blob: 3661c0bdb02575823f88e453543fd7a05534fafc [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"
Charles Davis4e786dd2010-05-25 19:52:27 +000037
38using namespace clang;
John McCall475999d2010-08-22 00:05:51 +000039using namespace CodeGen;
Charles Davis4e786dd2010-05-25 19:52:27 +000040
41namespace {
Charles Davis53c59df2010-08-16 03:33:14 +000042class ItaniumCXXABI : public CodeGen::CGCXXABI {
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +000043 /// VTables - All the vtables which have been defined.
44 llvm::DenseMap<const CXXRecordDecl *, llvm::GlobalVariable *> VTables;
45
John McCall475999d2010-08-22 00:05:51 +000046protected:
Mark Seabornedf0d382013-07-24 16:25:13 +000047 bool UseARMMethodPtrABI;
48 bool UseARMGuardVarABI;
John McCalld23b27e2016-09-16 02:40:45 +000049 bool Use32BitVTableOffsetABI;
John McCall7a9aac22010-08-23 01:21:21 +000050
Timur Iskhodzhanov67455222013-10-03 06:26:13 +000051 ItaniumMangleContext &getMangleContext() {
52 return cast<ItaniumMangleContext>(CodeGen::CGCXXABI::getMangleContext());
53 }
54
Charles Davis4e786dd2010-05-25 19:52:27 +000055public:
Mark Seabornedf0d382013-07-24 16:25:13 +000056 ItaniumCXXABI(CodeGen::CodeGenModule &CGM,
57 bool UseARMMethodPtrABI = false,
58 bool UseARMGuardVarABI = false) :
59 CGCXXABI(CGM), UseARMMethodPtrABI(UseARMMethodPtrABI),
John McCalld23b27e2016-09-16 02:40:45 +000060 UseARMGuardVarABI(UseARMGuardVarABI),
Richard Smithb17d6fa2016-12-01 03:04:07 +000061 Use32BitVTableOffsetABI(false) { }
John McCall475999d2010-08-22 00:05:51 +000062
Reid Kleckner40ca9132014-05-13 22:05:45 +000063 bool classifyReturnType(CGFunctionInfo &FI) const override;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000064
Richard Smithf667ad52017-08-26 01:04:35 +000065 bool passClassIndirect(const CXXRecordDecl *RD) const {
66 // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
67 // The PS4 platform ABI follows the behavior of Clang 3.2.
68 if (CGM.getCodeGenOpts().getClangABICompat() <=
69 CodeGenOptions::ClangABI::Ver4 ||
70 CGM.getTriple().getOS() == llvm::Triple::PS4)
Akira Hatanaka02914dc2018-02-05 20:23:22 +000071 return RD->hasNonTrivialDestructorForCall() ||
72 RD->hasNonTrivialCopyConstructorForCall();
Richard Smithf667ad52017-08-26 01:04:35 +000073 return !canCopyArgument(RD);
74 }
75
Craig Topper4f12f102014-03-12 06:41:41 +000076 RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const override {
Richard Smith96cd6712017-08-16 01:49:53 +000077 // If C++ prohibits us from making a copy, pass by address.
Richard Smithf667ad52017-08-26 01:04:35 +000078 if (passClassIndirect(RD))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000079 return RAA_Indirect;
80 return RAA_Default;
81 }
82
John McCall7f416cc2015-09-08 08:05:57 +000083 bool isThisCompleteObject(GlobalDecl GD) const override {
84 // The Itanium ABI has separate complete-object vs. base-object
85 // variants of both constructors and destructors.
86 if (isa<CXXDestructorDecl>(GD.getDecl())) {
87 switch (GD.getDtorType()) {
88 case Dtor_Complete:
89 case Dtor_Deleting:
90 return true;
91
92 case Dtor_Base:
93 return false;
94
95 case Dtor_Comdat:
96 llvm_unreachable("emitting dtor comdat as function?");
97 }
98 llvm_unreachable("bad dtor kind");
99 }
100 if (isa<CXXConstructorDecl>(GD.getDecl())) {
101 switch (GD.getCtorType()) {
102 case Ctor_Complete:
103 return true;
104
105 case Ctor_Base:
106 return false;
107
108 case Ctor_CopyingClosure:
109 case Ctor_DefaultClosure:
110 llvm_unreachable("closure ctors in Itanium ABI?");
111
112 case Ctor_Comdat:
113 llvm_unreachable("emitting ctor comdat as function?");
114 }
115 llvm_unreachable("bad dtor kind");
116 }
117
118 // No other kinds.
119 return false;
120 }
121
Craig Topper4f12f102014-03-12 06:41:41 +0000122 bool isZeroInitializable(const MemberPointerType *MPT) override;
John McCall84fa5102010-08-22 04:16:24 +0000123
Craig Topper4f12f102014-03-12 06:41:41 +0000124 llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT) override;
John McCall7a9aac22010-08-23 01:21:21 +0000125
John McCallb92ab1a2016-10-26 23:46:34 +0000126 CGCallee
Craig Topper4f12f102014-03-12 06:41:41 +0000127 EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
128 const Expr *E,
John McCall7f416cc2015-09-08 08:05:57 +0000129 Address This,
130 llvm::Value *&ThisPtrForCall,
Craig Topper4f12f102014-03-12 06:41:41 +0000131 llvm::Value *MemFnPtr,
132 const MemberPointerType *MPT) override;
John McCalla8bbb822010-08-22 03:04:22 +0000133
Craig Topper4f12f102014-03-12 06:41:41 +0000134 llvm::Value *
135 EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E,
John McCall7f416cc2015-09-08 08:05:57 +0000136 Address Base,
Craig Topper4f12f102014-03-12 06:41:41 +0000137 llvm::Value *MemPtr,
138 const MemberPointerType *MPT) override;
John McCallc134eb52010-08-31 21:07:20 +0000139
John McCall7a9aac22010-08-23 01:21:21 +0000140 llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
141 const CastExpr *E,
Craig Topper4f12f102014-03-12 06:41:41 +0000142 llvm::Value *Src) override;
John McCallc62bb392012-02-15 01:22:51 +0000143 llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
Craig Topper4f12f102014-03-12 06:41:41 +0000144 llvm::Constant *Src) override;
John McCall84fa5102010-08-22 04:16:24 +0000145
Craig Topper4f12f102014-03-12 06:41:41 +0000146 llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT) override;
John McCall84fa5102010-08-22 04:16:24 +0000147
David Majnemere2be95b2015-06-23 07:31:01 +0000148 llvm::Constant *EmitMemberFunctionPointer(const CXXMethodDecl *MD) override;
John McCallf3a88602011-02-03 08:15:49 +0000149 llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
Craig Topper4f12f102014-03-12 06:41:41 +0000150 CharUnits offset) override;
151 llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT) override;
Richard Smithdafff942012-01-14 04:30:29 +0000152 llvm::Constant *BuildMemberPointer(const CXXMethodDecl *MD,
153 CharUnits ThisAdjustment);
John McCall1c456c82010-08-22 06:43:33 +0000154
John McCall7a9aac22010-08-23 01:21:21 +0000155 llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000156 llvm::Value *L, llvm::Value *R,
John McCall7a9aac22010-08-23 01:21:21 +0000157 const MemberPointerType *MPT,
Craig Topper4f12f102014-03-12 06:41:41 +0000158 bool Inequality) override;
John McCall131d97d2010-08-22 08:30:07 +0000159
John McCall7a9aac22010-08-23 01:21:21 +0000160 llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000161 llvm::Value *Addr,
162 const MemberPointerType *MPT) override;
John McCall5d865c322010-08-31 07:33:07 +0000163
David Majnemer08681372014-11-01 07:37:17 +0000164 void emitVirtualObjectDelete(CodeGenFunction &CGF, const CXXDeleteExpr *DE,
John McCall7f416cc2015-09-08 08:05:57 +0000165 Address Ptr, QualType ElementType,
David Majnemer0c0b6d92014-10-31 20:09:12 +0000166 const CXXDestructorDecl *Dtor) override;
John McCall82fb8922012-09-25 10:10:39 +0000167
Akira Hatanakac47fcf02017-07-27 18:52:44 +0000168 /// Itanium says that an _Unwind_Exception has to be "double-word"
169 /// aligned (and thus the end of it is also so-aligned), meaning 16
170 /// bytes. Of course, that was written for the actual Itanium,
171 /// which is a 64-bit platform. Classically, the ABI doesn't really
172 /// specify the alignment on other platforms, but in practice
173 /// libUnwind declares the struct with __attribute__((aligned)), so
174 /// we assume that alignment here. (It's generally 16 bytes, but
175 /// some targets overwrite it.)
John McCall7f416cc2015-09-08 08:05:57 +0000176 CharUnits getAlignmentOfExnObject() {
Akira Hatanakac47fcf02017-07-27 18:52:44 +0000177 auto align = CGM.getContext().getTargetDefaultAlignForAttributeAligned();
178 return CGM.getContext().toCharUnitsFromBits(align);
John McCall7f416cc2015-09-08 08:05:57 +0000179 }
180
David Majnemer442d0a22014-11-25 07:20:20 +0000181 void emitRethrow(CodeGenFunction &CGF, bool isNoReturn) override;
David Majnemer7c237072015-03-05 00:46:22 +0000182 void emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) override;
David Majnemer442d0a22014-11-25 07:20:20 +0000183
Reid Klecknerfff8e7f2015-03-03 19:21:04 +0000184 void emitBeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *C) override;
185
186 llvm::CallInst *
187 emitTerminateForUnexpectedException(CodeGenFunction &CGF,
188 llvm::Value *Exn) override;
189
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +0000190 void EmitFundamentalRTTIDescriptor(QualType Type, bool DLLExport);
191 void EmitFundamentalRTTIDescriptors(bool DLLExport);
David Majnemer443250f2015-03-17 20:35:00 +0000192 llvm::Constant *getAddrOfRTTIDescriptor(QualType Ty) override;
Reid Kleckner10aa7702015-09-16 20:15:55 +0000193 CatchTypeInfo
David Majnemer37b417f2015-03-29 21:55:10 +0000194 getAddrOfCXXCatchHandlerType(QualType Ty,
195 QualType CatchHandlerType) override {
Reid Kleckner10aa7702015-09-16 20:15:55 +0000196 return CatchTypeInfo{getAddrOfRTTIDescriptor(Ty), 0};
David Majnemer443250f2015-03-17 20:35:00 +0000197 }
David Majnemere2cb8d12014-07-07 06:20:47 +0000198
David Majnemer1162d252014-06-22 19:05:33 +0000199 bool shouldTypeidBeNullChecked(bool IsDeref, QualType SrcRecordTy) override;
200 void EmitBadTypeidCall(CodeGenFunction &CGF) override;
201 llvm::Value *EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy,
John McCall7f416cc2015-09-08 08:05:57 +0000202 Address ThisPtr,
David Majnemer1162d252014-06-22 19:05:33 +0000203 llvm::Type *StdTypeInfoPtrTy) override;
204
205 bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
206 QualType SrcRecordTy) override;
207
John McCall7f416cc2015-09-08 08:05:57 +0000208 llvm::Value *EmitDynamicCastCall(CodeGenFunction &CGF, Address Value,
David Majnemer1162d252014-06-22 19:05:33 +0000209 QualType SrcRecordTy, QualType DestTy,
210 QualType DestRecordTy,
211 llvm::BasicBlock *CastEnd) override;
212
John McCall7f416cc2015-09-08 08:05:57 +0000213 llvm::Value *EmitDynamicCastToVoid(CodeGenFunction &CGF, Address Value,
David Majnemer1162d252014-06-22 19:05:33 +0000214 QualType SrcRecordTy,
215 QualType DestTy) override;
216
217 bool EmitBadCastCall(CodeGenFunction &CGF) override;
218
Craig Topper4f12f102014-03-12 06:41:41 +0000219 llvm::Value *
John McCall7f416cc2015-09-08 08:05:57 +0000220 GetVirtualBaseClassOffset(CodeGenFunction &CGF, Address This,
Craig Topper4f12f102014-03-12 06:41:41 +0000221 const CXXRecordDecl *ClassDecl,
222 const CXXRecordDecl *BaseClassDecl) override;
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000223
Craig Topper4f12f102014-03-12 06:41:41 +0000224 void EmitCXXConstructors(const CXXConstructorDecl *D) override;
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +0000225
George Burgess IVf203dbf2017-02-22 20:28:02 +0000226 AddedStructorArgs
227 buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
228 SmallVectorImpl<CanQualType> &ArgTys) override;
John McCall5d865c322010-08-31 07:33:07 +0000229
Reid Klecknere7de47e2013-07-22 13:51:44 +0000230 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
Craig Topper4f12f102014-03-12 06:41:41 +0000231 CXXDtorType DT) const override {
Reid Klecknere7de47e2013-07-22 13:51:44 +0000232 // Itanium does not emit any destructor variant as an inline thunk.
233 // Delegating may occur as an optimization, but all variants are either
234 // emitted with external linkage or as linkonce if they are inline and used.
235 return false;
236 }
237
Craig Topper4f12f102014-03-12 06:41:41 +0000238 void EmitCXXDestructors(const CXXDestructorDecl *D) override;
Reid Klecknere7de47e2013-07-22 13:51:44 +0000239
Reid Kleckner89077a12013-12-17 19:46:40 +0000240 void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
Craig Topper4f12f102014-03-12 06:41:41 +0000241 FunctionArgList &Params) override;
John McCall5d865c322010-08-31 07:33:07 +0000242
Craig Topper4f12f102014-03-12 06:41:41 +0000243 void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override;
John McCall8ed55a52010-09-02 09:58:18 +0000244
George Burgess IVf203dbf2017-02-22 20:28:02 +0000245 AddedStructorArgs
246 addImplicitConstructorArgs(CodeGenFunction &CGF, const CXXConstructorDecl *D,
247 CXXCtorType Type, bool ForVirtualBase,
248 bool Delegating, CallArgList &Args) override;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000249
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000250 void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD,
251 CXXDtorType Type, bool ForVirtualBase,
John McCall7f416cc2015-09-08 08:05:57 +0000252 bool Delegating, Address This) override;
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000253
Craig Topper4f12f102014-03-12 06:41:41 +0000254 void emitVTableDefinitions(CodeGenVTables &CGVT,
255 const CXXRecordDecl *RD) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000256
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000257 bool isVirtualOffsetNeededForVTableField(CodeGenFunction &CGF,
258 CodeGenFunction::VPtr Vptr) override;
259
260 bool doStructorsInitializeVPtrs(const CXXRecordDecl *VTableClass) override {
261 return true;
262 }
263
264 llvm::Constant *
265 getVTableAddressPoint(BaseSubobject Base,
266 const CXXRecordDecl *VTableClass) override;
267
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000268 llvm::Value *getVTableAddressPointInStructor(
269 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000270 BaseSubobject Base, const CXXRecordDecl *NearestVBase) override;
271
272 llvm::Value *getVTableAddressPointInStructorWithVTT(
273 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
274 BaseSubobject Base, const CXXRecordDecl *NearestVBase);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000275
276 llvm::Constant *
277 getVTableAddressPointForConstExpr(BaseSubobject Base,
Craig Topper4f12f102014-03-12 06:41:41 +0000278 const CXXRecordDecl *VTableClass) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000279
280 llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
Craig Topper4f12f102014-03-12 06:41:41 +0000281 CharUnits VPtrOffset) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000282
John McCall9831b842018-02-06 18:52:44 +0000283 CGCallee getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
284 Address This, llvm::Type *Ty,
285 SourceLocation Loc) override;
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000286
David Majnemer0c0b6d92014-10-31 20:09:12 +0000287 llvm::Value *EmitVirtualDestructorCall(CodeGenFunction &CGF,
288 const CXXDestructorDecl *Dtor,
289 CXXDtorType DtorType,
John McCall7f416cc2015-09-08 08:05:57 +0000290 Address This,
David Majnemer0c0b6d92014-10-31 20:09:12 +0000291 const CXXMemberCallExpr *CE) override;
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000292
Craig Topper4f12f102014-03-12 06:41:41 +0000293 void emitVirtualInheritanceTables(const CXXRecordDecl *RD) override;
Reid Kleckner7810af02013-06-19 15:20:38 +0000294
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000295 bool canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const override;
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000296
Hans Wennborgc94391d2014-06-06 20:04:01 +0000297 void setThunkLinkage(llvm::Function *Thunk, bool ForVTable, GlobalDecl GD,
298 bool ReturnAdjustment) override {
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000299 // Allow inlining of thunks by emitting them with available_externally
300 // linkage together with vtables when needed.
Peter Collingbourne8fabc1b2015-07-01 02:10:26 +0000301 if (ForVTable && !Thunk->hasLocalLinkage())
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000302 Thunk->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
Shoaib Meenaicef66e52017-07-24 17:16:27 +0000303
304 // Propagate dllexport storage, to enable the linker to generate import
305 // thunks as necessary (e.g. when a parent class has a key function and a
306 // child class doesn't, and the construction vtable for the parent in the
307 // child needs to reference the parent's thunks).
308 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
309 if (MD->hasAttr<DLLExportAttr>())
310 Thunk->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000311 }
312
John McCall7f416cc2015-09-08 08:05:57 +0000313 llvm::Value *performThisAdjustment(CodeGenFunction &CGF, Address This,
Craig Topper4f12f102014-03-12 06:41:41 +0000314 const ThisAdjustment &TA) override;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000315
John McCall7f416cc2015-09-08 08:05:57 +0000316 llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
Craig Topper4f12f102014-03-12 06:41:41 +0000317 const ReturnAdjustment &RA) override;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000318
David Majnemer196ac332014-09-11 23:05:02 +0000319 size_t getSrcArgforCopyCtor(const CXXConstructorDecl *,
320 FunctionArgList &Args) const override {
321 assert(!Args.empty() && "expected the arglist to not be empty!");
322 return Args.size() - 1;
323 }
324
Craig Topper4f12f102014-03-12 06:41:41 +0000325 StringRef GetPureVirtualCallName() override { return "__cxa_pure_virtual"; }
326 StringRef GetDeletedVirtualCallName() override
327 { return "__cxa_deleted_virtual"; }
Joao Matos2ce88ef2012-07-17 17:10:11 +0000328
Craig Topper4f12f102014-03-12 06:41:41 +0000329 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
John McCall7f416cc2015-09-08 08:05:57 +0000330 Address InitializeArrayCookie(CodeGenFunction &CGF,
331 Address NewPtr,
332 llvm::Value *NumElements,
333 const CXXNewExpr *expr,
334 QualType ElementType) override;
John McCallb91cd662012-05-01 05:23:51 +0000335 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000336 Address allocPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000337 CharUnits cookieSize) override;
John McCall68ff0372010-09-08 01:44:27 +0000338
John McCallcdf7ef52010-11-06 09:44:32 +0000339 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
Craig Topper4f12f102014-03-12 06:41:41 +0000340 llvm::GlobalVariable *DeclPtr,
341 bool PerformInit) override;
Richard Smithdbf74ba2013-04-14 23:01:42 +0000342 void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
Craig Topper4f12f102014-03-12 06:41:41 +0000343 llvm::Constant *dtor, llvm::Constant *addr) override;
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000344
345 llvm::Function *getOrCreateThreadLocalWrapper(const VarDecl *VD,
Alexander Musmanf94c3182014-09-26 06:28:25 +0000346 llvm::Value *Val);
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000347 void EmitThreadLocalInitFuncs(
David Majnemerb3341ea2014-10-05 05:05:40 +0000348 CodeGenModule &CGM,
Richard Smith5a99c492015-12-01 01:10:48 +0000349 ArrayRef<const VarDecl *> CXXThreadLocals,
David Majnemerb3341ea2014-10-05 05:05:40 +0000350 ArrayRef<llvm::Function *> CXXThreadLocalInits,
Richard Smith5a99c492015-12-01 01:10:48 +0000351 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) override;
David Majnemerb3341ea2014-10-05 05:05:40 +0000352
353 bool usesThreadWrapperFunction() const override { return true; }
Richard Smith0f383742014-03-26 22:48:22 +0000354 LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD,
355 QualType LValType) override;
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000356
Craig Topper4f12f102014-03-12 06:41:41 +0000357 bool NeedsVTTParameter(GlobalDecl GD) override;
David Majnemere2cb8d12014-07-07 06:20:47 +0000358
359 /**************************** RTTI Uniqueness ******************************/
360
361protected:
362 /// Returns true if the ABI requires RTTI type_info objects to be unique
363 /// across a program.
364 virtual bool shouldRTTIBeUnique() const { return true; }
365
366public:
367 /// What sort of unique-RTTI behavior should we use?
368 enum RTTIUniquenessKind {
369 /// We are guaranteeing, or need to guarantee, that the RTTI string
370 /// is unique.
371 RUK_Unique,
372
373 /// We are not guaranteeing uniqueness for the RTTI string, so we
374 /// can demote to hidden visibility but must use string comparisons.
375 RUK_NonUniqueHidden,
376
377 /// We are not guaranteeing uniqueness for the RTTI string, so we
378 /// have to use string comparisons, but we also have to emit it with
379 /// non-hidden visibility.
380 RUK_NonUniqueVisible
381 };
382
383 /// Return the required visibility status for the given type and linkage in
384 /// the current ABI.
385 RTTIUniquenessKind
386 classifyRTTIUniqueness(QualType CanTy,
387 llvm::GlobalValue::LinkageTypes Linkage) const;
388 friend class ItaniumRTTIBuilder;
Rafael Espindola91f68b42014-09-15 19:20:10 +0000389
390 void emitCXXStructor(const CXXMethodDecl *MD, StructorType Type) override;
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000391
Peter Collingbourne60108802017-12-13 21:53:04 +0000392 std::pair<llvm::Value *, const CXXRecordDecl *>
393 LoadVTablePtr(CodeGenFunction &CGF, Address This,
394 const CXXRecordDecl *RD) override;
395
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000396 private:
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +0000397 bool hasAnyUnusedVirtualInlineFunction(const CXXRecordDecl *RD) const {
398 const auto &VtableLayout =
399 CGM.getItaniumVTableContext().getVTableLayout(RD);
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000400
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +0000401 for (const auto &VtableComponent : VtableLayout.vtable_components()) {
402 // Skip empty slot.
403 if (!VtableComponent.isUsedFunctionPointerKind())
404 continue;
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000405
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +0000406 const CXXMethodDecl *Method = VtableComponent.getFunctionDecl();
407 if (!Method->getCanonicalDecl()->isInlined())
408 continue;
409
410 StringRef Name = CGM.getMangledName(VtableComponent.getGlobalDecl());
411 auto *Entry = CGM.GetGlobalValue(Name);
412 // This checks if virtual inline function has already been emitted.
413 // Note that it is possible that this inline function would be emitted
414 // after trying to emit vtable speculatively. Because of this we do
415 // an extra pass after emitting all deferred vtables to find and emit
416 // these vtables opportunistically.
417 if (!Entry || Entry->isDeclaration())
418 return true;
419 }
420 return false;
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000421 }
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000422
423 bool isVTableHidden(const CXXRecordDecl *RD) const {
424 const auto &VtableLayout =
425 CGM.getItaniumVTableContext().getVTableLayout(RD);
426
427 for (const auto &VtableComponent : VtableLayout.vtable_components()) {
428 if (VtableComponent.isRTTIKind()) {
429 const CXXRecordDecl *RTTIDecl = VtableComponent.getRTTIDecl();
430 if (RTTIDecl->getVisibility() == Visibility::HiddenVisibility)
431 return true;
432 } else if (VtableComponent.isUsedFunctionPointerKind()) {
433 const CXXMethodDecl *Method = VtableComponent.getFunctionDecl();
434 if (Method->getVisibility() == Visibility::HiddenVisibility &&
435 !Method->isDefined())
436 return true;
437 }
438 }
439 return false;
440 }
Charles Davis4e786dd2010-05-25 19:52:27 +0000441};
John McCall86353412010-08-21 22:46:04 +0000442
443class ARMCXXABI : public ItaniumCXXABI {
444public:
Mark Seabornedf0d382013-07-24 16:25:13 +0000445 ARMCXXABI(CodeGen::CodeGenModule &CGM) :
446 ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
447 /* UseARMGuardVarABI = */ true) {}
John McCall5d865c322010-08-31 07:33:07 +0000448
Craig Topper4f12f102014-03-12 06:41:41 +0000449 bool HasThisReturn(GlobalDecl GD) const override {
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000450 return (isa<CXXConstructorDecl>(GD.getDecl()) || (
451 isa<CXXDestructorDecl>(GD.getDecl()) &&
452 GD.getDtorType() != Dtor_Deleting));
453 }
John McCall5d865c322010-08-31 07:33:07 +0000454
Craig Topper4f12f102014-03-12 06:41:41 +0000455 void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV,
456 QualType ResTy) override;
John McCall5d865c322010-08-31 07:33:07 +0000457
Craig Topper4f12f102014-03-12 06:41:41 +0000458 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
John McCall7f416cc2015-09-08 08:05:57 +0000459 Address InitializeArrayCookie(CodeGenFunction &CGF,
460 Address NewPtr,
461 llvm::Value *NumElements,
462 const CXXNewExpr *expr,
463 QualType ElementType) override;
464 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, Address allocPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000465 CharUnits cookieSize) override;
John McCall86353412010-08-21 22:46:04 +0000466};
Tim Northovera2ee4332014-03-29 15:09:45 +0000467
468class iOS64CXXABI : public ARMCXXABI {
469public:
John McCalld23b27e2016-09-16 02:40:45 +0000470 iOS64CXXABI(CodeGen::CodeGenModule &CGM) : ARMCXXABI(CGM) {
471 Use32BitVTableOffsetABI = true;
472 }
Tim Northover65f582f2014-03-30 17:32:48 +0000473
474 // ARM64 libraries are prepared for non-unique RTTI.
David Majnemere2cb8d12014-07-07 06:20:47 +0000475 bool shouldRTTIBeUnique() const override { return false; }
Tim Northovera2ee4332014-03-29 15:09:45 +0000476};
Dan Gohmanc2853072015-09-03 22:51:53 +0000477
478class WebAssemblyCXXABI final : public ItaniumCXXABI {
479public:
480 explicit WebAssemblyCXXABI(CodeGen::CodeGenModule &CGM)
481 : ItaniumCXXABI(CGM, /*UseARMMethodPtrABI=*/true,
482 /*UseARMGuardVarABI=*/true) {}
483
484private:
485 bool HasThisReturn(GlobalDecl GD) const override {
486 return isa<CXXConstructorDecl>(GD.getDecl()) ||
487 (isa<CXXDestructorDecl>(GD.getDecl()) &&
488 GD.getDtorType() != Dtor_Deleting);
489 }
Derek Schuff8179be42016-05-10 17:44:55 +0000490 bool canCallMismatchedFunctionType() const override { return false; }
Dan Gohmanc2853072015-09-03 22:51:53 +0000491};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000492}
Charles Davis4e786dd2010-05-25 19:52:27 +0000493
Charles Davis53c59df2010-08-16 03:33:14 +0000494CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
John McCallc8e01702013-04-16 22:48:15 +0000495 switch (CGM.getTarget().getCXXABI().getKind()) {
John McCall57625922013-01-25 23:36:14 +0000496 // For IR-generation purposes, there's no significant difference
497 // between the ARM and iOS ABIs.
498 case TargetCXXABI::GenericARM:
499 case TargetCXXABI::iOS:
Tim Northover756447a2015-10-30 16:30:36 +0000500 case TargetCXXABI::WatchOS:
John McCall57625922013-01-25 23:36:14 +0000501 return new ARMCXXABI(CGM);
Charles Davis4e786dd2010-05-25 19:52:27 +0000502
Tim Northovera2ee4332014-03-29 15:09:45 +0000503 case TargetCXXABI::iOS64:
504 return new iOS64CXXABI(CGM);
505
Tim Northover9bb857a2013-01-31 12:13:10 +0000506 // Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't
507 // include the other 32-bit ARM oddities: constructor/destructor return values
508 // and array cookies.
509 case TargetCXXABI::GenericAArch64:
Mark Seabornedf0d382013-07-24 16:25:13 +0000510 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
511 /* UseARMGuardVarABI = */ true);
Tim Northover9bb857a2013-01-31 12:13:10 +0000512
Zoran Jovanovic26a12162015-02-18 15:21:35 +0000513 case TargetCXXABI::GenericMIPS:
514 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true);
515
Dan Gohmanc2853072015-09-03 22:51:53 +0000516 case TargetCXXABI::WebAssembly:
517 return new WebAssemblyCXXABI(CGM);
518
John McCall57625922013-01-25 23:36:14 +0000519 case TargetCXXABI::GenericItanium:
Mark Seabornedf0d382013-07-24 16:25:13 +0000520 if (CGM.getContext().getTargetInfo().getTriple().getArch()
521 == llvm::Triple::le32) {
522 // For PNaCl, use ARM-style method pointers so that PNaCl code
523 // does not assume anything about the alignment of function
524 // pointers.
525 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
526 /* UseARMGuardVarABI = */ false);
527 }
John McCall57625922013-01-25 23:36:14 +0000528 return new ItaniumCXXABI(CGM);
529
530 case TargetCXXABI::Microsoft:
531 llvm_unreachable("Microsoft ABI is not Itanium-based");
532 }
533 llvm_unreachable("bad ABI kind");
John McCall86353412010-08-21 22:46:04 +0000534}
535
Chris Lattnera5f58b02011-07-09 17:41:47 +0000536llvm::Type *
John McCall7a9aac22010-08-23 01:21:21 +0000537ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
538 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000539 return CGM.PtrDiffTy;
Serge Guelton1d993272017-05-09 19:31:30 +0000540 return llvm::StructType::get(CGM.PtrDiffTy, CGM.PtrDiffTy);
John McCall1c456c82010-08-22 06:43:33 +0000541}
542
John McCalld9c6c0b2010-08-22 00:59:17 +0000543/// In the Itanium and ARM ABIs, method pointers have the form:
544/// struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
545///
546/// In the Itanium ABI:
547/// - method pointers are virtual if (memptr.ptr & 1) is nonzero
548/// - the this-adjustment is (memptr.adj)
549/// - the virtual offset is (memptr.ptr - 1)
550///
551/// In the ARM ABI:
552/// - method pointers are virtual if (memptr.adj & 1) is nonzero
553/// - the this-adjustment is (memptr.adj >> 1)
554/// - the virtual offset is (memptr.ptr)
555/// ARM uses 'adj' for the virtual flag because Thumb functions
556/// may be only single-byte aligned.
557///
558/// If the member is virtual, the adjusted 'this' pointer points
559/// to a vtable pointer from which the virtual offset is applied.
560///
561/// If the member is non-virtual, memptr.ptr is the address of
562/// the function to call.
John McCallb92ab1a2016-10-26 23:46:34 +0000563CGCallee ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(
John McCall7f416cc2015-09-08 08:05:57 +0000564 CodeGenFunction &CGF, const Expr *E, Address ThisAddr,
565 llvm::Value *&ThisPtrForCall,
David Majnemer2b0d66d2014-02-20 23:22:07 +0000566 llvm::Value *MemFnPtr, const MemberPointerType *MPT) {
John McCall475999d2010-08-22 00:05:51 +0000567 CGBuilderTy &Builder = CGF.Builder;
568
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000569 const FunctionProtoType *FPT =
John McCall475999d2010-08-22 00:05:51 +0000570 MPT->getPointeeType()->getAs<FunctionProtoType>();
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000571 const CXXRecordDecl *RD =
John McCall475999d2010-08-22 00:05:51 +0000572 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
573
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000574 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(
575 CGM.getTypes().arrangeCXXMethodType(RD, FPT, /*FD=*/nullptr));
John McCall475999d2010-08-22 00:05:51 +0000576
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000577 llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(CGM.PtrDiffTy, 1);
John McCall475999d2010-08-22 00:05:51 +0000578
John McCalld9c6c0b2010-08-22 00:59:17 +0000579 llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
580 llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
581 llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
582
John McCalla1dee5302010-08-22 10:59:02 +0000583 // Extract memptr.adj, which is in the second field.
584 llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
John McCalld9c6c0b2010-08-22 00:59:17 +0000585
586 // Compute the true adjustment.
587 llvm::Value *Adj = RawAdj;
Mark Seabornedf0d382013-07-24 16:25:13 +0000588 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000589 Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
John McCall475999d2010-08-22 00:05:51 +0000590
591 // Apply the adjustment and cast back to the original struct type
592 // for consistency.
John McCall7f416cc2015-09-08 08:05:57 +0000593 llvm::Value *This = ThisAddr.getPointer();
John McCalld9c6c0b2010-08-22 00:59:17 +0000594 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
595 Ptr = Builder.CreateInBoundsGEP(Ptr, Adj);
596 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
John McCall7f416cc2015-09-08 08:05:57 +0000597 ThisPtrForCall = This;
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000598
John McCall475999d2010-08-22 00:05:51 +0000599 // Load the function pointer.
John McCalla1dee5302010-08-22 10:59:02 +0000600 llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000601
John McCall475999d2010-08-22 00:05:51 +0000602 // If the LSB in the function pointer is 1, the function pointer points to
603 // a virtual function.
John McCalld9c6c0b2010-08-22 00:59:17 +0000604 llvm::Value *IsVirtual;
Mark Seabornedf0d382013-07-24 16:25:13 +0000605 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000606 IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
607 else
608 IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
609 IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
John McCall475999d2010-08-22 00:05:51 +0000610 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
611
612 // In the virtual path, the adjustment left 'This' pointing to the
613 // vtable of the correct base subobject. The "function pointer" is an
John McCalld9c6c0b2010-08-22 00:59:17 +0000614 // offset within the vtable (+1 for the virtual flag on non-ARM).
John McCall475999d2010-08-22 00:05:51 +0000615 CGF.EmitBlock(FnVirtual);
616
617 // Cast the adjusted this to a pointer to vtable pointer and load.
Chris Lattner2192fe52011-07-18 04:24:23 +0000618 llvm::Type *VTableTy = Builder.getInt8PtrTy();
John McCall7f416cc2015-09-08 08:05:57 +0000619 CharUnits VTablePtrAlign =
620 CGF.CGM.getDynamicOffsetAlignment(ThisAddr.getAlignment(), RD,
621 CGF.getPointerAlign());
622 llvm::Value *VTable =
Piotr Padlewski4b1ac722015-09-15 21:46:55 +0000623 CGF.GetVTablePtr(Address(This, VTablePtrAlign), VTableTy, RD);
John McCall475999d2010-08-22 00:05:51 +0000624
625 // Apply the offset.
John McCalld23b27e2016-09-16 02:40:45 +0000626 // On ARM64, to reserve extra space in virtual member function pointers,
627 // we only pay attention to the low 32 bits of the offset.
John McCalld9c6c0b2010-08-22 00:59:17 +0000628 llvm::Value *VTableOffset = FnAsInt;
Mark Seabornedf0d382013-07-24 16:25:13 +0000629 if (!UseARMMethodPtrABI)
630 VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
John McCalld23b27e2016-09-16 02:40:45 +0000631 if (Use32BitVTableOffsetABI) {
632 VTableOffset = Builder.CreateTrunc(VTableOffset, CGF.Int32Ty);
633 VTableOffset = Builder.CreateZExt(VTableOffset, CGM.PtrDiffTy);
634 }
John McCalld9c6c0b2010-08-22 00:59:17 +0000635 VTable = Builder.CreateGEP(VTable, VTableOffset);
John McCall475999d2010-08-22 00:05:51 +0000636
637 // Load the virtual function to call.
638 VTable = Builder.CreateBitCast(VTable, FTy->getPointerTo()->getPointerTo());
John McCall7f416cc2015-09-08 08:05:57 +0000639 llvm::Value *VirtualFn =
640 Builder.CreateAlignedLoad(VTable, CGF.getPointerAlign(),
641 "memptr.virtualfn");
John McCall475999d2010-08-22 00:05:51 +0000642 CGF.EmitBranch(FnEnd);
643
644 // In the non-virtual path, the function pointer is actually a
645 // function pointer.
646 CGF.EmitBlock(FnNonVirtual);
647 llvm::Value *NonVirtualFn =
John McCalld9c6c0b2010-08-22 00:59:17 +0000648 Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn");
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000649
John McCall475999d2010-08-22 00:05:51 +0000650 // We're done.
651 CGF.EmitBlock(FnEnd);
John McCallb92ab1a2016-10-26 23:46:34 +0000652 llvm::PHINode *CalleePtr = Builder.CreatePHI(FTy->getPointerTo(), 2);
653 CalleePtr->addIncoming(VirtualFn, FnVirtual);
654 CalleePtr->addIncoming(NonVirtualFn, FnNonVirtual);
655
656 CGCallee Callee(FPT, CalleePtr);
John McCall475999d2010-08-22 00:05:51 +0000657 return Callee;
658}
John McCalla8bbb822010-08-22 03:04:22 +0000659
John McCallc134eb52010-08-31 21:07:20 +0000660/// Compute an l-value by applying the given pointer-to-member to a
661/// base object.
David Majnemer2b0d66d2014-02-20 23:22:07 +0000662llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(
John McCall7f416cc2015-09-08 08:05:57 +0000663 CodeGenFunction &CGF, const Expr *E, Address Base, llvm::Value *MemPtr,
David Majnemer2b0d66d2014-02-20 23:22:07 +0000664 const MemberPointerType *MPT) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000665 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCallc134eb52010-08-31 21:07:20 +0000666
667 CGBuilderTy &Builder = CGF.Builder;
668
John McCallc134eb52010-08-31 21:07:20 +0000669 // Cast to char*.
John McCall7f416cc2015-09-08 08:05:57 +0000670 Base = Builder.CreateElementBitCast(Base, CGF.Int8Ty);
John McCallc134eb52010-08-31 21:07:20 +0000671
672 // Apply the offset, which we assume is non-null.
John McCall7f416cc2015-09-08 08:05:57 +0000673 llvm::Value *Addr =
674 Builder.CreateInBoundsGEP(Base.getPointer(), MemPtr, "memptr.offset");
John McCallc134eb52010-08-31 21:07:20 +0000675
676 // Cast the address to the appropriate pointer type, adopting the
677 // address space of the base pointer.
John McCall7f416cc2015-09-08 08:05:57 +0000678 llvm::Type *PType = CGF.ConvertTypeForMem(MPT->getPointeeType())
679 ->getPointerTo(Base.getAddressSpace());
John McCallc134eb52010-08-31 21:07:20 +0000680 return Builder.CreateBitCast(Addr, PType);
681}
682
John McCallc62bb392012-02-15 01:22:51 +0000683/// Perform a bitcast, derived-to-base, or base-to-derived member pointer
684/// conversion.
685///
686/// Bitcast conversions are always a no-op under Itanium.
John McCall7a9aac22010-08-23 01:21:21 +0000687///
688/// Obligatory offset/adjustment diagram:
689/// <-- offset --> <-- adjustment -->
690/// |--------------------------|----------------------|--------------------|
691/// ^Derived address point ^Base address point ^Member address point
692///
693/// So when converting a base member pointer to a derived member pointer,
694/// we add the offset to the adjustment because the address point has
695/// decreased; and conversely, when converting a derived MP to a base MP
696/// we subtract the offset from the adjustment because the address point
697/// has increased.
698///
699/// The standard forbids (at compile time) conversion to and from
700/// virtual bases, which is why we don't have to consider them here.
701///
702/// The standard forbids (at run time) casting a derived MP to a base
703/// MP when the derived MP does not point to a member of the base.
704/// This is why -1 is a reasonable choice for null data member
705/// pointers.
John McCalla1dee5302010-08-22 10:59:02 +0000706llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000707ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
708 const CastExpr *E,
John McCallc62bb392012-02-15 01:22:51 +0000709 llvm::Value *src) {
John McCalle3027922010-08-25 11:45:40 +0000710 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
John McCallc62bb392012-02-15 01:22:51 +0000711 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
712 E->getCastKind() == CK_ReinterpretMemberPointer);
713
714 // Under Itanium, reinterprets don't require any additional processing.
715 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
716
717 // Use constant emission if we can.
718 if (isa<llvm::Constant>(src))
719 return EmitMemberPointerConversion(E, cast<llvm::Constant>(src));
720
721 llvm::Constant *adj = getMemberPointerAdjustment(E);
722 if (!adj) return src;
John McCalla8bbb822010-08-22 03:04:22 +0000723
724 CGBuilderTy &Builder = CGF.Builder;
John McCallc62bb392012-02-15 01:22:51 +0000725 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
John McCalla8bbb822010-08-22 03:04:22 +0000726
John McCallc62bb392012-02-15 01:22:51 +0000727 const MemberPointerType *destTy =
728 E->getType()->castAs<MemberPointerType>();
John McCall1c456c82010-08-22 06:43:33 +0000729
John McCall7a9aac22010-08-23 01:21:21 +0000730 // For member data pointers, this is just a matter of adding the
731 // offset if the source is non-null.
John McCallc62bb392012-02-15 01:22:51 +0000732 if (destTy->isMemberDataPointer()) {
733 llvm::Value *dst;
734 if (isDerivedToBase)
735 dst = Builder.CreateNSWSub(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000736 else
John McCallc62bb392012-02-15 01:22:51 +0000737 dst = Builder.CreateNSWAdd(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000738
739 // Null check.
John McCallc62bb392012-02-15 01:22:51 +0000740 llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType());
741 llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull");
742 return Builder.CreateSelect(isNull, src, dst);
John McCall7a9aac22010-08-23 01:21:21 +0000743 }
744
John McCalla1dee5302010-08-22 10:59:02 +0000745 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000746 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000747 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
748 offset <<= 1;
749 adj = llvm::ConstantInt::get(adj->getType(), offset);
John McCalla1dee5302010-08-22 10:59:02 +0000750 }
751
John McCallc62bb392012-02-15 01:22:51 +0000752 llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj");
753 llvm::Value *dstAdj;
754 if (isDerivedToBase)
755 dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000756 else
John McCallc62bb392012-02-15 01:22:51 +0000757 dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000758
John McCallc62bb392012-02-15 01:22:51 +0000759 return Builder.CreateInsertValue(src, dstAdj, 1);
760}
761
762llvm::Constant *
763ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E,
764 llvm::Constant *src) {
765 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
766 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
767 E->getCastKind() == CK_ReinterpretMemberPointer);
768
769 // Under Itanium, reinterprets don't require any additional processing.
770 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
771
772 // If the adjustment is trivial, we don't need to do anything.
773 llvm::Constant *adj = getMemberPointerAdjustment(E);
774 if (!adj) return src;
775
776 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
777
778 const MemberPointerType *destTy =
779 E->getType()->castAs<MemberPointerType>();
780
781 // For member data pointers, this is just a matter of adding the
782 // offset if the source is non-null.
783 if (destTy->isMemberDataPointer()) {
784 // null maps to null.
785 if (src->isAllOnesValue()) return src;
786
787 if (isDerivedToBase)
788 return llvm::ConstantExpr::getNSWSub(src, adj);
789 else
790 return llvm::ConstantExpr::getNSWAdd(src, adj);
791 }
792
793 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000794 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000795 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
796 offset <<= 1;
797 adj = llvm::ConstantInt::get(adj->getType(), offset);
798 }
799
800 llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1);
801 llvm::Constant *dstAdj;
802 if (isDerivedToBase)
803 dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj);
804 else
805 dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj);
806
807 return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1);
John McCalla8bbb822010-08-22 03:04:22 +0000808}
John McCall84fa5102010-08-22 04:16:24 +0000809
810llvm::Constant *
John McCall7a9aac22010-08-23 01:21:21 +0000811ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
John McCall7a9aac22010-08-23 01:21:21 +0000812 // Itanium C++ ABI 2.3:
813 // A NULL pointer is represented as -1.
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000814 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000815 return llvm::ConstantInt::get(CGM.PtrDiffTy, -1ULL, /*isSigned=*/true);
John McCalla1dee5302010-08-22 10:59:02 +0000816
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000817 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.PtrDiffTy, 0);
John McCalla1dee5302010-08-22 10:59:02 +0000818 llvm::Constant *Values[2] = { Zero, Zero };
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000819 return llvm::ConstantStruct::getAnon(Values);
John McCall84fa5102010-08-22 04:16:24 +0000820}
821
John McCallf3a88602011-02-03 08:15:49 +0000822llvm::Constant *
823ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
824 CharUnits offset) {
John McCall7a9aac22010-08-23 01:21:21 +0000825 // Itanium C++ ABI 2.3:
826 // A pointer to data member is an offset from the base address of
827 // the class object containing it, represented as a ptrdiff_t
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000828 return llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity());
John McCall7a9aac22010-08-23 01:21:21 +0000829}
830
David Majnemere2be95b2015-06-23 07:31:01 +0000831llvm::Constant *
832ItaniumCXXABI::EmitMemberFunctionPointer(const CXXMethodDecl *MD) {
Richard Smithdafff942012-01-14 04:30:29 +0000833 return BuildMemberPointer(MD, CharUnits::Zero());
834}
835
836llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD,
837 CharUnits ThisAdjustment) {
John McCalla1dee5302010-08-22 10:59:02 +0000838 assert(MD->isInstance() && "Member function must not be static!");
839 MD = MD->getCanonicalDecl();
840
841 CodeGenTypes &Types = CGM.getTypes();
John McCalla1dee5302010-08-22 10:59:02 +0000842
843 // Get the function pointer (or index if this is a virtual function).
844 llvm::Constant *MemPtr[2];
845 if (MD->isVirtual()) {
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000846 uint64_t Index = CGM.getItaniumVTableContext().getMethodVTableIndex(MD);
John McCalla1dee5302010-08-22 10:59:02 +0000847
Ken Dyckdf016282011-04-09 01:30:02 +0000848 const ASTContext &Context = getContext();
849 CharUnits PointerWidth =
Douglas Gregore8bbc122011-09-02 00:18:52 +0000850 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Ken Dyckdf016282011-04-09 01:30:02 +0000851 uint64_t VTableOffset = (Index * PointerWidth.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000852
Mark Seabornedf0d382013-07-24 16:25:13 +0000853 if (UseARMMethodPtrABI) {
John McCalla1dee5302010-08-22 10:59:02 +0000854 // ARM C++ ABI 3.2.1:
855 // This ABI specifies that adj contains twice the this
856 // adjustment, plus 1 if the member function is virtual. The
857 // least significant bit of adj then makes exactly the same
858 // discrimination as the least significant bit of ptr does for
859 // Itanium.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000860 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset);
861 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000862 2 * ThisAdjustment.getQuantity() + 1);
John McCalla1dee5302010-08-22 10:59:02 +0000863 } else {
864 // Itanium C++ ABI 2.3:
865 // For a virtual function, [the pointer field] is 1 plus the
866 // virtual table offset (in bytes) of the function,
867 // represented as a ptrdiff_t.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000868 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset + 1);
869 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000870 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000871 }
872 } else {
John McCall2979fe02011-04-12 00:42:48 +0000873 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
Chris Lattner2192fe52011-07-18 04:24:23 +0000874 llvm::Type *Ty;
John McCall2979fe02011-04-12 00:42:48 +0000875 // Check whether the function has a computable LLVM signature.
Chris Lattner8806e322011-07-10 00:18:59 +0000876 if (Types.isFuncTypeConvertible(FPT)) {
John McCall2979fe02011-04-12 00:42:48 +0000877 // The function has a computable LLVM signature; use the correct type.
John McCalla729c622012-02-17 03:33:10 +0000878 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
John McCalla1dee5302010-08-22 10:59:02 +0000879 } else {
John McCall2979fe02011-04-12 00:42:48 +0000880 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
881 // function type is incomplete.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000882 Ty = CGM.PtrDiffTy;
John McCalla1dee5302010-08-22 10:59:02 +0000883 }
John McCall2979fe02011-04-12 00:42:48 +0000884 llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty);
John McCalla1dee5302010-08-22 10:59:02 +0000885
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000886 MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, CGM.PtrDiffTy);
Mark Seabornedf0d382013-07-24 16:25:13 +0000887 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
888 (UseARMMethodPtrABI ? 2 : 1) *
Richard Smithdafff942012-01-14 04:30:29 +0000889 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000890 }
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000891
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000892 return llvm::ConstantStruct::getAnon(MemPtr);
John McCall1c456c82010-08-22 06:43:33 +0000893}
894
Richard Smithdafff942012-01-14 04:30:29 +0000895llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP,
896 QualType MPType) {
897 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
898 const ValueDecl *MPD = MP.getMemberPointerDecl();
899 if (!MPD)
900 return EmitNullMemberPointer(MPT);
901
Reid Kleckner452abac2013-05-09 21:01:17 +0000902 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
Richard Smithdafff942012-01-14 04:30:29 +0000903
904 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
905 return BuildMemberPointer(MD, ThisAdjustment);
906
907 CharUnits FieldOffset =
908 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
909 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
910}
911
John McCall131d97d2010-08-22 08:30:07 +0000912/// The comparison algorithm is pretty easy: the member pointers are
913/// the same if they're either bitwise identical *or* both null.
914///
915/// ARM is different here only because null-ness is more complicated.
916llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000917ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
918 llvm::Value *L,
919 llvm::Value *R,
920 const MemberPointerType *MPT,
921 bool Inequality) {
John McCall131d97d2010-08-22 08:30:07 +0000922 CGBuilderTy &Builder = CGF.Builder;
923
John McCall131d97d2010-08-22 08:30:07 +0000924 llvm::ICmpInst::Predicate Eq;
925 llvm::Instruction::BinaryOps And, Or;
926 if (Inequality) {
927 Eq = llvm::ICmpInst::ICMP_NE;
928 And = llvm::Instruction::Or;
929 Or = llvm::Instruction::And;
930 } else {
931 Eq = llvm::ICmpInst::ICMP_EQ;
932 And = llvm::Instruction::And;
933 Or = llvm::Instruction::Or;
934 }
935
John McCall7a9aac22010-08-23 01:21:21 +0000936 // Member data pointers are easy because there's a unique null
937 // value, so it just comes down to bitwise equality.
938 if (MPT->isMemberDataPointer())
939 return Builder.CreateICmp(Eq, L, R);
940
941 // For member function pointers, the tautologies are more complex.
942 // The Itanium tautology is:
John McCall61a14882010-08-23 06:56:36 +0000943 // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
John McCall7a9aac22010-08-23 01:21:21 +0000944 // The ARM tautology is:
John McCall61a14882010-08-23 06:56:36 +0000945 // (L == R) <==> (L.ptr == R.ptr &&
946 // (L.adj == R.adj ||
947 // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
John McCall7a9aac22010-08-23 01:21:21 +0000948 // The inequality tautologies have exactly the same structure, except
949 // applying De Morgan's laws.
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000950
John McCall7a9aac22010-08-23 01:21:21 +0000951 llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
952 llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
953
John McCall131d97d2010-08-22 08:30:07 +0000954 // This condition tests whether L.ptr == R.ptr. This must always be
955 // true for equality to hold.
956 llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
957
958 // This condition, together with the assumption that L.ptr == R.ptr,
959 // tests whether the pointers are both null. ARM imposes an extra
960 // condition.
961 llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
962 llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
963
964 // This condition tests whether L.adj == R.adj. If this isn't
965 // true, the pointers are unequal unless they're both null.
John McCalla1dee5302010-08-22 10:59:02 +0000966 llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
967 llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000968 llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
969
970 // Null member function pointers on ARM clear the low bit of Adj,
971 // so the zero condition has to check that neither low bit is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000972 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000973 llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
974
975 // Compute (l.adj | r.adj) & 1 and test it against zero.
976 llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
977 llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
978 llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
979 "cmp.or.adj");
980 EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
981 }
982
983 // Tie together all our conditions.
984 llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
985 Result = Builder.CreateBinOp(And, PtrEq, Result,
986 Inequality ? "memptr.ne" : "memptr.eq");
987 return Result;
988}
989
990llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000991ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
992 llvm::Value *MemPtr,
993 const MemberPointerType *MPT) {
John McCall131d97d2010-08-22 08:30:07 +0000994 CGBuilderTy &Builder = CGF.Builder;
John McCall7a9aac22010-08-23 01:21:21 +0000995
996 /// For member data pointers, this is just a check against -1.
997 if (MPT->isMemberDataPointer()) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000998 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCall7a9aac22010-08-23 01:21:21 +0000999 llvm::Value *NegativeOne =
1000 llvm::Constant::getAllOnesValue(MemPtr->getType());
1001 return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
1002 }
Jake Ehrlichc451cf22017-11-11 01:15:41 +00001003
Daniel Dunbar914bc412011-04-19 23:10:47 +00001004 // In Itanium, a member function pointer is not null if 'ptr' is not null.
John McCalla1dee5302010-08-22 10:59:02 +00001005 llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
John McCall131d97d2010-08-22 08:30:07 +00001006
1007 llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
1008 llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
1009
Daniel Dunbar914bc412011-04-19 23:10:47 +00001010 // On ARM, a member function pointer is also non-null if the low bit of 'adj'
1011 // (the virtual bit) is set.
Mark Seabornedf0d382013-07-24 16:25:13 +00001012 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +00001013 llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
John McCalla1dee5302010-08-22 10:59:02 +00001014 llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +00001015 llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
Daniel Dunbar914bc412011-04-19 23:10:47 +00001016 llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero,
1017 "memptr.isvirtual");
1018 Result = Builder.CreateOr(Result, IsVirtual);
John McCall131d97d2010-08-22 08:30:07 +00001019 }
1020
1021 return Result;
1022}
John McCall1c456c82010-08-22 06:43:33 +00001023
Reid Kleckner40ca9132014-05-13 22:05:45 +00001024bool ItaniumCXXABI::classifyReturnType(CGFunctionInfo &FI) const {
1025 const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl();
1026 if (!RD)
1027 return false;
1028
Richard Smith96cd6712017-08-16 01:49:53 +00001029 // If C++ prohibits us from making a copy, return by address.
Richard Smithf667ad52017-08-26 01:04:35 +00001030 if (passClassIndirect(RD)) {
John McCall7f416cc2015-09-08 08:05:57 +00001031 auto Align = CGM.getContext().getTypeAlignInChars(FI.getReturnType());
1032 FI.getReturnInfo() = ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
Reid Kleckner40ca9132014-05-13 22:05:45 +00001033 return true;
1034 }
Reid Kleckner40ca9132014-05-13 22:05:45 +00001035 return false;
1036}
1037
John McCall614dbdc2010-08-22 21:01:12 +00001038/// The Itanium ABI requires non-zero initialization only for data
1039/// member pointers, for which '0' is a valid offset.
1040bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
David Majnemer5fd33e02015-04-24 01:25:08 +00001041 return MPT->isMemberFunctionPointer();
John McCall84fa5102010-08-22 04:16:24 +00001042}
John McCall5d865c322010-08-31 07:33:07 +00001043
John McCall82fb8922012-09-25 10:10:39 +00001044/// The Itanium ABI always places an offset to the complete object
1045/// at entry -2 in the vtable.
David Majnemer08681372014-11-01 07:37:17 +00001046void ItaniumCXXABI::emitVirtualObjectDelete(CodeGenFunction &CGF,
1047 const CXXDeleteExpr *DE,
John McCall7f416cc2015-09-08 08:05:57 +00001048 Address Ptr,
David Majnemer08681372014-11-01 07:37:17 +00001049 QualType ElementType,
1050 const CXXDestructorDecl *Dtor) {
1051 bool UseGlobalDelete = DE->isGlobalDelete();
David Majnemer0c0b6d92014-10-31 20:09:12 +00001052 if (UseGlobalDelete) {
1053 // Derive the complete-object pointer, which is what we need
1054 // to pass to the deallocation function.
John McCall82fb8922012-09-25 10:10:39 +00001055
David Majnemer0c0b6d92014-10-31 20:09:12 +00001056 // Grab the vtable pointer as an intptr_t*.
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001057 auto *ClassDecl =
1058 cast<CXXRecordDecl>(ElementType->getAs<RecordType>()->getDecl());
1059 llvm::Value *VTable =
1060 CGF.GetVTablePtr(Ptr, CGF.IntPtrTy->getPointerTo(), ClassDecl);
John McCall82fb8922012-09-25 10:10:39 +00001061
David Majnemer0c0b6d92014-10-31 20:09:12 +00001062 // Track back to entry -2 and pull out the offset there.
1063 llvm::Value *OffsetPtr = CGF.Builder.CreateConstInBoundsGEP1_64(
1064 VTable, -2, "complete-offset.ptr");
John McCall7f416cc2015-09-08 08:05:57 +00001065 llvm::Value *Offset =
1066 CGF.Builder.CreateAlignedLoad(OffsetPtr, CGF.getPointerAlign());
David Majnemer0c0b6d92014-10-31 20:09:12 +00001067
1068 // Apply the offset.
John McCall7f416cc2015-09-08 08:05:57 +00001069 llvm::Value *CompletePtr =
1070 CGF.Builder.CreateBitCast(Ptr.getPointer(), CGF.Int8PtrTy);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001071 CompletePtr = CGF.Builder.CreateInBoundsGEP(CompletePtr, Offset);
1072
1073 // If we're supposed to call the global delete, make sure we do so
1074 // even if the destructor throws.
David Majnemer08681372014-11-01 07:37:17 +00001075 CGF.pushCallObjectDeleteCleanup(DE->getOperatorDelete(), CompletePtr,
1076 ElementType);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001077 }
1078
1079 // FIXME: Provide a source location here even though there's no
1080 // CXXMemberCallExpr for dtor call.
1081 CXXDtorType DtorType = UseGlobalDelete ? Dtor_Complete : Dtor_Deleting;
1082 EmitVirtualDestructorCall(CGF, Dtor, DtorType, Ptr, /*CE=*/nullptr);
1083
1084 if (UseGlobalDelete)
1085 CGF.PopCleanupBlock();
John McCall82fb8922012-09-25 10:10:39 +00001086}
1087
David Majnemer442d0a22014-11-25 07:20:20 +00001088void ItaniumCXXABI::emitRethrow(CodeGenFunction &CGF, bool isNoReturn) {
1089 // void __cxa_rethrow();
1090
1091 llvm::FunctionType *FTy =
1092 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
1093
1094 llvm::Constant *Fn = CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow");
1095
1096 if (isNoReturn)
1097 CGF.EmitNoreturnRuntimeCallOrInvoke(Fn, None);
1098 else
1099 CGF.EmitRuntimeCallOrInvoke(Fn);
1100}
1101
David Majnemer7c237072015-03-05 00:46:22 +00001102static llvm::Constant *getAllocateExceptionFn(CodeGenModule &CGM) {
1103 // void *__cxa_allocate_exception(size_t thrown_size);
1104
1105 llvm::FunctionType *FTy =
1106 llvm::FunctionType::get(CGM.Int8PtrTy, CGM.SizeTy, /*IsVarArgs=*/false);
1107
1108 return CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
1109}
1110
1111static llvm::Constant *getThrowFn(CodeGenModule &CGM) {
1112 // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
1113 // void (*dest) (void *));
1114
1115 llvm::Type *Args[3] = { CGM.Int8PtrTy, CGM.Int8PtrTy, CGM.Int8PtrTy };
1116 llvm::FunctionType *FTy =
1117 llvm::FunctionType::get(CGM.VoidTy, Args, /*IsVarArgs=*/false);
1118
1119 return CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
1120}
1121
1122void ItaniumCXXABI::emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) {
1123 QualType ThrowType = E->getSubExpr()->getType();
1124 // Now allocate the exception object.
1125 llvm::Type *SizeTy = CGF.ConvertType(getContext().getSizeType());
1126 uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
1127
1128 llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(CGM);
1129 llvm::CallInst *ExceptionPtr = CGF.EmitNounwindRuntimeCall(
1130 AllocExceptionFn, llvm::ConstantInt::get(SizeTy, TypeSize), "exception");
1131
John McCall7f416cc2015-09-08 08:05:57 +00001132 CharUnits ExnAlign = getAlignmentOfExnObject();
1133 CGF.EmitAnyExprToExn(E->getSubExpr(), Address(ExceptionPtr, ExnAlign));
David Majnemer7c237072015-03-05 00:46:22 +00001134
1135 // Now throw the exception.
1136 llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType,
1137 /*ForEH=*/true);
1138
1139 // The address of the destructor. If the exception type has a
1140 // trivial destructor (or isn't a record), we just pass null.
1141 llvm::Constant *Dtor = nullptr;
1142 if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
1143 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
1144 if (!Record->hasTrivialDestructor()) {
1145 CXXDestructorDecl *DtorD = Record->getDestructor();
1146 Dtor = CGM.getAddrOfCXXStructor(DtorD, StructorType::Complete);
1147 Dtor = llvm::ConstantExpr::getBitCast(Dtor, CGM.Int8PtrTy);
1148 }
1149 }
1150 if (!Dtor) Dtor = llvm::Constant::getNullValue(CGM.Int8PtrTy);
1151
1152 llvm::Value *args[] = { ExceptionPtr, TypeInfo, Dtor };
1153 CGF.EmitNoreturnRuntimeCallOrInvoke(getThrowFn(CGM), args);
1154}
1155
David Majnemer1162d252014-06-22 19:05:33 +00001156static llvm::Constant *getItaniumDynamicCastFn(CodeGenFunction &CGF) {
1157 // void *__dynamic_cast(const void *sub,
1158 // const abi::__class_type_info *src,
1159 // const abi::__class_type_info *dst,
1160 // std::ptrdiff_t src2dst_offset);
Jake Ehrlichc451cf22017-11-11 01:15:41 +00001161
David Majnemer1162d252014-06-22 19:05:33 +00001162 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
Jake Ehrlichc451cf22017-11-11 01:15:41 +00001163 llvm::Type *PtrDiffTy =
David Majnemer1162d252014-06-22 19:05:33 +00001164 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1165
1166 llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
1167
1168 llvm::FunctionType *FTy = llvm::FunctionType::get(Int8PtrTy, Args, false);
1169
1170 // Mark the function as nounwind readonly.
1171 llvm::Attribute::AttrKind FuncAttrs[] = { llvm::Attribute::NoUnwind,
1172 llvm::Attribute::ReadOnly };
Reid Klecknerde864822017-03-21 16:57:30 +00001173 llvm::AttributeList Attrs = llvm::AttributeList::get(
1174 CGF.getLLVMContext(), llvm::AttributeList::FunctionIndex, FuncAttrs);
David Majnemer1162d252014-06-22 19:05:33 +00001175
1176 return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast", Attrs);
1177}
1178
1179static llvm::Constant *getBadCastFn(CodeGenFunction &CGF) {
1180 // void __cxa_bad_cast();
1181 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1182 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
1183}
1184
1185/// \brief Compute the src2dst_offset hint as described in the
1186/// Itanium C++ ABI [2.9.7]
1187static CharUnits computeOffsetHint(ASTContext &Context,
1188 const CXXRecordDecl *Src,
1189 const CXXRecordDecl *Dst) {
1190 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1191 /*DetectVirtual=*/false);
1192
1193 // If Dst is not derived from Src we can skip the whole computation below and
1194 // return that Src is not a public base of Dst. Record all inheritance paths.
1195 if (!Dst->isDerivedFrom(Src, Paths))
1196 return CharUnits::fromQuantity(-2ULL);
1197
1198 unsigned NumPublicPaths = 0;
1199 CharUnits Offset;
1200
1201 // Now walk all possible inheritance paths.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001202 for (const CXXBasePath &Path : Paths) {
1203 if (Path.Access != AS_public) // Ignore non-public inheritance.
David Majnemer1162d252014-06-22 19:05:33 +00001204 continue;
1205
1206 ++NumPublicPaths;
1207
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001208 for (const CXXBasePathElement &PathElement : Path) {
David Majnemer1162d252014-06-22 19:05:33 +00001209 // If the path contains a virtual base class we can't give any hint.
1210 // -1: no hint.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001211 if (PathElement.Base->isVirtual())
David Majnemer1162d252014-06-22 19:05:33 +00001212 return CharUnits::fromQuantity(-1ULL);
1213
1214 if (NumPublicPaths > 1) // Won't use offsets, skip computation.
1215 continue;
1216
1217 // Accumulate the base class offsets.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001218 const ASTRecordLayout &L = Context.getASTRecordLayout(PathElement.Class);
1219 Offset += L.getBaseClassOffset(
1220 PathElement.Base->getType()->getAsCXXRecordDecl());
David Majnemer1162d252014-06-22 19:05:33 +00001221 }
1222 }
1223
1224 // -2: Src is not a public base of Dst.
1225 if (NumPublicPaths == 0)
1226 return CharUnits::fromQuantity(-2ULL);
1227
1228 // -3: Src is a multiple public base type but never a virtual base type.
1229 if (NumPublicPaths > 1)
1230 return CharUnits::fromQuantity(-3ULL);
1231
1232 // Otherwise, the Src type is a unique public nonvirtual base type of Dst.
1233 // Return the offset of Src from the origin of Dst.
1234 return Offset;
1235}
1236
1237static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) {
1238 // void __cxa_bad_typeid();
1239 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1240
1241 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
1242}
1243
1244bool ItaniumCXXABI::shouldTypeidBeNullChecked(bool IsDeref,
1245 QualType SrcRecordTy) {
1246 return IsDeref;
1247}
1248
1249void ItaniumCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) {
1250 llvm::Value *Fn = getBadTypeidFn(CGF);
1251 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
1252 CGF.Builder.CreateUnreachable();
1253}
1254
1255llvm::Value *ItaniumCXXABI::EmitTypeid(CodeGenFunction &CGF,
1256 QualType SrcRecordTy,
John McCall7f416cc2015-09-08 08:05:57 +00001257 Address ThisPtr,
David Majnemer1162d252014-06-22 19:05:33 +00001258 llvm::Type *StdTypeInfoPtrTy) {
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001259 auto *ClassDecl =
1260 cast<CXXRecordDecl>(SrcRecordTy->getAs<RecordType>()->getDecl());
David Majnemer1162d252014-06-22 19:05:33 +00001261 llvm::Value *Value =
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001262 CGF.GetVTablePtr(ThisPtr, StdTypeInfoPtrTy->getPointerTo(), ClassDecl);
David Majnemer1162d252014-06-22 19:05:33 +00001263
1264 // Load the type info.
1265 Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL);
John McCall7f416cc2015-09-08 08:05:57 +00001266 return CGF.Builder.CreateAlignedLoad(Value, CGF.getPointerAlign());
David Majnemer1162d252014-06-22 19:05:33 +00001267}
1268
1269bool ItaniumCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
1270 QualType SrcRecordTy) {
1271 return SrcIsPtr;
1272}
1273
1274llvm::Value *ItaniumCXXABI::EmitDynamicCastCall(
John McCall7f416cc2015-09-08 08:05:57 +00001275 CodeGenFunction &CGF, Address ThisAddr, QualType SrcRecordTy,
David Majnemer1162d252014-06-22 19:05:33 +00001276 QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) {
1277 llvm::Type *PtrDiffLTy =
1278 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1279 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1280
1281 llvm::Value *SrcRTTI =
1282 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
1283 llvm::Value *DestRTTI =
1284 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
1285
1286 // Compute the offset hint.
1287 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
1288 const CXXRecordDecl *DestDecl = DestRecordTy->getAsCXXRecordDecl();
1289 llvm::Value *OffsetHint = llvm::ConstantInt::get(
1290 PtrDiffLTy,
1291 computeOffsetHint(CGF.getContext(), SrcDecl, DestDecl).getQuantity());
1292
1293 // Emit the call to __dynamic_cast.
John McCall7f416cc2015-09-08 08:05:57 +00001294 llvm::Value *Value = ThisAddr.getPointer();
David Majnemer1162d252014-06-22 19:05:33 +00001295 Value = CGF.EmitCastToVoidPtr(Value);
1296
1297 llvm::Value *args[] = {Value, SrcRTTI, DestRTTI, OffsetHint};
1298 Value = CGF.EmitNounwindRuntimeCall(getItaniumDynamicCastFn(CGF), args);
1299 Value = CGF.Builder.CreateBitCast(Value, DestLTy);
1300
1301 /// C++ [expr.dynamic.cast]p9:
1302 /// A failed cast to reference type throws std::bad_cast
1303 if (DestTy->isReferenceType()) {
1304 llvm::BasicBlock *BadCastBlock =
1305 CGF.createBasicBlock("dynamic_cast.bad_cast");
1306
1307 llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
1308 CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
1309
1310 CGF.EmitBlock(BadCastBlock);
1311 EmitBadCastCall(CGF);
1312 }
1313
1314 return Value;
1315}
1316
1317llvm::Value *ItaniumCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001318 Address ThisAddr,
David Majnemer1162d252014-06-22 19:05:33 +00001319 QualType SrcRecordTy,
1320 QualType DestTy) {
1321 llvm::Type *PtrDiffLTy =
1322 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1323 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1324
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001325 auto *ClassDecl =
1326 cast<CXXRecordDecl>(SrcRecordTy->getAs<RecordType>()->getDecl());
David Majnemer1162d252014-06-22 19:05:33 +00001327 // Get the vtable pointer.
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001328 llvm::Value *VTable = CGF.GetVTablePtr(ThisAddr, PtrDiffLTy->getPointerTo(),
1329 ClassDecl);
David Majnemer1162d252014-06-22 19:05:33 +00001330
1331 // Get the offset-to-top from the vtable.
1332 llvm::Value *OffsetToTop =
1333 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL);
John McCall7f416cc2015-09-08 08:05:57 +00001334 OffsetToTop =
1335 CGF.Builder.CreateAlignedLoad(OffsetToTop, CGF.getPointerAlign(),
1336 "offset.to.top");
David Majnemer1162d252014-06-22 19:05:33 +00001337
1338 // Finally, add the offset to the pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001339 llvm::Value *Value = ThisAddr.getPointer();
David Majnemer1162d252014-06-22 19:05:33 +00001340 Value = CGF.EmitCastToVoidPtr(Value);
1341 Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop);
1342
1343 return CGF.Builder.CreateBitCast(Value, DestLTy);
1344}
1345
1346bool ItaniumCXXABI::EmitBadCastCall(CodeGenFunction &CGF) {
1347 llvm::Value *Fn = getBadCastFn(CGF);
1348 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
1349 CGF.Builder.CreateUnreachable();
1350 return true;
1351}
1352
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001353llvm::Value *
1354ItaniumCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001355 Address This,
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001356 const CXXRecordDecl *ClassDecl,
1357 const CXXRecordDecl *BaseClassDecl) {
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001358 llvm::Value *VTablePtr = CGF.GetVTablePtr(This, CGM.Int8PtrTy, ClassDecl);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001359 CharUnits VBaseOffsetOffset =
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001360 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(ClassDecl,
1361 BaseClassDecl);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001362
1363 llvm::Value *VBaseOffsetPtr =
1364 CGF.Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
1365 "vbase.offset.ptr");
1366 VBaseOffsetPtr = CGF.Builder.CreateBitCast(VBaseOffsetPtr,
1367 CGM.PtrDiffTy->getPointerTo());
1368
1369 llvm::Value *VBaseOffset =
John McCall7f416cc2015-09-08 08:05:57 +00001370 CGF.Builder.CreateAlignedLoad(VBaseOffsetPtr, CGF.getPointerAlign(),
1371 "vbase.offset");
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001372
1373 return VBaseOffset;
1374}
1375
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001376void ItaniumCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
1377 // Just make sure we're in sync with TargetCXXABI.
1378 assert(CGM.getTarget().getCXXABI().hasConstructorVariants());
1379
Rafael Espindolac3cde362013-12-09 14:51:17 +00001380 // The constructor used for constructing this as a base class;
1381 // ignores virtual bases.
1382 CGM.EmitGlobal(GlobalDecl(D, Ctor_Base));
1383
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001384 // The constructor used for constructing this as a complete class;
Nico Weber4c2ffb22015-01-07 05:25:05 +00001385 // constructs the virtual bases, then calls the base constructor.
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001386 if (!D->getParent()->isAbstract()) {
1387 // We don't need to emit the complete ctor if the class is abstract.
1388 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
1389 }
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001390}
1391
George Burgess IVf203dbf2017-02-22 20:28:02 +00001392CGCXXABI::AddedStructorArgs
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001393ItaniumCXXABI::buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
1394 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9bca9232010-09-02 10:25:57 +00001395 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001396
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001397 // All parameters are already in place except VTT, which goes after 'this'.
1398 // These are Clang types, so we don't need to worry about sret yet.
John McCall5d865c322010-08-31 07:33:07 +00001399
1400 // Check if we need to add a VTT parameter (which has type void **).
George Burgess IVf203dbf2017-02-22 20:28:02 +00001401 if (T == StructorType::Base && MD->getParent()->getNumVBases() != 0) {
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001402 ArgTys.insert(ArgTys.begin() + 1,
1403 Context.getPointerType(Context.VoidPtrTy));
George Burgess IVf203dbf2017-02-22 20:28:02 +00001404 return AddedStructorArgs::prefix(1);
1405 }
1406 return AddedStructorArgs{};
John McCall5d865c322010-08-31 07:33:07 +00001407}
1408
Reid Klecknere7de47e2013-07-22 13:51:44 +00001409void ItaniumCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
Rafael Espindolac3cde362013-12-09 14:51:17 +00001410 // The destructor used for destructing this as a base class; ignores
1411 // virtual bases.
1412 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001413
1414 // The destructor used for destructing this as a most-derived class;
1415 // call the base destructor and then destructs any virtual bases.
1416 CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));
1417
Rafael Espindolac3cde362013-12-09 14:51:17 +00001418 // The destructor in a virtual table is always a 'deleting'
1419 // destructor, which calls the complete destructor and then uses the
1420 // appropriate operator delete.
1421 if (D->isVirtual())
1422 CGM.EmitGlobal(GlobalDecl(D, Dtor_Deleting));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001423}
1424
Reid Kleckner89077a12013-12-17 19:46:40 +00001425void ItaniumCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
1426 QualType &ResTy,
1427 FunctionArgList &Params) {
John McCall5d865c322010-08-31 07:33:07 +00001428 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
Reid Kleckner89077a12013-12-17 19:46:40 +00001429 assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
John McCall5d865c322010-08-31 07:33:07 +00001430
1431 // Check if we need a VTT parameter as well.
Peter Collingbourne66f82e62013-06-28 20:45:28 +00001432 if (NeedsVTTParameter(CGF.CurGD)) {
John McCall9bca9232010-09-02 10:25:57 +00001433 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001434
1435 // FIXME: avoid the fake decl
1436 QualType T = Context.getPointerType(Context.VoidPtrTy);
Alexey Bataev56223232017-06-09 13:40:18 +00001437 auto *VTTDecl = ImplicitParamDecl::Create(
1438 Context, /*DC=*/nullptr, MD->getLocation(), &Context.Idents.get("vtt"),
1439 T, ImplicitParamDecl::CXXVTT);
Reid Kleckner89077a12013-12-17 19:46:40 +00001440 Params.insert(Params.begin() + 1, VTTDecl);
Reid Kleckner2af6d732013-12-13 00:09:59 +00001441 getStructorImplicitParamDecl(CGF) = VTTDecl;
John McCall5d865c322010-08-31 07:33:07 +00001442 }
1443}
1444
John McCall5d865c322010-08-31 07:33:07 +00001445void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
Justin Lebared4f1722016-07-27 22:04:24 +00001446 // Naked functions have no prolog.
1447 if (CGF.CurFuncDecl && CGF.CurFuncDecl->hasAttr<NakedAttr>())
1448 return;
1449
Reid Kleckner06239e42017-11-16 19:09:36 +00001450 /// Initialize the 'this' slot. In the Itanium C++ ABI, no prologue
1451 /// adjustments are required, becuase they are all handled by thunks.
1452 setCXXABIThisValue(CGF, loadIncomingCXXThis(CGF));
John McCall5d865c322010-08-31 07:33:07 +00001453
1454 /// Initialize the 'vtt' slot if needed.
Reid Kleckner2af6d732013-12-13 00:09:59 +00001455 if (getStructorImplicitParamDecl(CGF)) {
1456 getStructorImplicitParamValue(CGF) = CGF.Builder.CreateLoad(
1457 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), "vtt");
John McCall5d865c322010-08-31 07:33:07 +00001458 }
John McCall5d865c322010-08-31 07:33:07 +00001459
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001460 /// If this is a function that the ABI specifies returns 'this', initialize
1461 /// the return slot to 'this' at the start of the function.
1462 ///
1463 /// Unlike the setting of return types, this is done within the ABI
1464 /// implementation instead of by clients of CGCXXABI because:
1465 /// 1) getThisValue is currently protected
1466 /// 2) in theory, an ABI could implement 'this' returns some other way;
1467 /// HasThisReturn only specifies a contract, not the implementation
John McCall5d865c322010-08-31 07:33:07 +00001468 if (HasThisReturn(CGF.CurGD))
Eli Friedman9fbeba02012-02-11 02:57:39 +00001469 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
John McCall5d865c322010-08-31 07:33:07 +00001470}
1471
George Burgess IVf203dbf2017-02-22 20:28:02 +00001472CGCXXABI::AddedStructorArgs ItaniumCXXABI::addImplicitConstructorArgs(
Reid Kleckner89077a12013-12-17 19:46:40 +00001473 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
1474 bool ForVirtualBase, bool Delegating, CallArgList &Args) {
1475 if (!NeedsVTTParameter(GlobalDecl(D, Type)))
George Burgess IVf203dbf2017-02-22 20:28:02 +00001476 return AddedStructorArgs{};
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001477
Reid Kleckner89077a12013-12-17 19:46:40 +00001478 // Insert the implicit 'vtt' argument as the second argument.
1479 llvm::Value *VTT =
1480 CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase, Delegating);
1481 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1482 Args.insert(Args.begin() + 1,
1483 CallArg(RValue::get(VTT), VTTTy, /*needscopy=*/false));
George Burgess IVf203dbf2017-02-22 20:28:02 +00001484 return AddedStructorArgs::prefix(1); // Added one arg.
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001485}
1486
1487void ItaniumCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
1488 const CXXDestructorDecl *DD,
1489 CXXDtorType Type, bool ForVirtualBase,
John McCall7f416cc2015-09-08 08:05:57 +00001490 bool Delegating, Address This) {
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001491 GlobalDecl GD(DD, Type);
1492 llvm::Value *VTT = CGF.GetVTTParameter(GD, ForVirtualBase, Delegating);
1493 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1494
John McCallb92ab1a2016-10-26 23:46:34 +00001495 CGCallee Callee;
1496 if (getContext().getLangOpts().AppleKext &&
1497 Type != Dtor_Base && DD->isVirtual())
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001498 Callee = CGF.BuildAppleKextVirtualDestructorCall(DD, Type, DD->getParent());
John McCallb92ab1a2016-10-26 23:46:34 +00001499 else
1500 Callee =
1501 CGCallee::forDirect(CGM.getAddrOfCXXStructor(DD, getFromDtorType(Type)),
1502 DD);
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001503
John McCall7f416cc2015-09-08 08:05:57 +00001504 CGF.EmitCXXMemberOrOperatorCall(DD, Callee, ReturnValueSlot(),
Richard Smith762672a2016-09-28 19:09:10 +00001505 This.getPointer(), VTT, VTTTy,
1506 nullptr, nullptr);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001507}
1508
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001509void ItaniumCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
1510 const CXXRecordDecl *RD) {
1511 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, CharUnits());
1512 if (VTable->hasInitializer())
1513 return;
1514
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001515 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001516 const VTableLayout &VTLayout = VTContext.getVTableLayout(RD);
1517 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
David Majnemerd905da42014-07-01 20:30:31 +00001518 llvm::Constant *RTTI =
1519 CGM.GetAddrOfRTTIDescriptor(CGM.getContext().getTagDeclType(RD));
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001520
1521 // Create and set the initializer.
John McCall9c6cb762016-11-28 22:18:33 +00001522 ConstantInitBuilder Builder(CGM);
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001523 auto Components = Builder.beginStruct();
John McCall9c6cb762016-11-28 22:18:33 +00001524 CGVT.createVTableInitializer(Components, VTLayout, RTTI);
1525 Components.finishAndSetAsInitializer(VTable);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001526
1527 // Set the correct linkage.
1528 VTable->setLinkage(Linkage);
1529
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00001530 if (CGM.supportsCOMDAT() && VTable->isWeakForLinker())
1531 VTable->setComdat(CGM.getModule().getOrInsertComdat(VTable->getName()));
Rafael Espindolacb92c192015-01-15 23:18:01 +00001532
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001533 // Set the right visibility.
Rafael Espindola880c3b22018-02-07 19:44:15 +00001534 CGM.setGlobalVisibility(VTable, RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001535
Benjamin Kramer5d34a2b2014-09-10 12:50:59 +00001536 // Use pointer alignment for the vtable. Otherwise we would align them based
1537 // on the size of the initializer which doesn't make sense as only single
1538 // values are read.
1539 unsigned PAlign = CGM.getTarget().getPointerAlign(0);
1540 VTable->setAlignment(getContext().toCharUnitsFromBits(PAlign).getQuantity());
1541
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001542 // If this is the magic class __cxxabiv1::__fundamental_type_info,
1543 // we will emit the typeinfo for the fundamental types. This is the
1544 // same behaviour as GCC.
1545 const DeclContext *DC = RD->getDeclContext();
1546 if (RD->getIdentifier() &&
1547 RD->getIdentifier()->isStr("__fundamental_type_info") &&
1548 isa<NamespaceDecl>(DC) && cast<NamespaceDecl>(DC)->getIdentifier() &&
1549 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
1550 DC->getParent()->isTranslationUnit())
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00001551 EmitFundamentalRTTIDescriptors(RD->hasAttr<DLLExportAttr>());
Peter Collingbournea4ccff32015-02-20 20:30:56 +00001552
Evgeniy Stepanov93987df2016-01-23 01:20:18 +00001553 if (!VTable->isDeclarationForLinker())
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00001554 CGM.EmitVTableTypeMetadata(VTable, VTLayout);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001555}
1556
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001557bool ItaniumCXXABI::isVirtualOffsetNeededForVTableField(
1558 CodeGenFunction &CGF, CodeGenFunction::VPtr Vptr) {
1559 if (Vptr.NearestVBase == nullptr)
1560 return false;
1561 return NeedsVTTParameter(CGF.CurGD);
Piotr Padlewski255652e2015-09-09 22:20:28 +00001562}
1563
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001564llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructor(
1565 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1566 const CXXRecordDecl *NearestVBase) {
1567
1568 if ((Base.getBase()->getNumVBases() || NearestVBase != nullptr) &&
1569 NeedsVTTParameter(CGF.CurGD)) {
1570 return getVTableAddressPointInStructorWithVTT(CGF, VTableClass, Base,
1571 NearestVBase);
1572 }
1573 return getVTableAddressPoint(Base, VTableClass);
1574}
1575
1576llvm::Constant *
1577ItaniumCXXABI::getVTableAddressPoint(BaseSubobject Base,
1578 const CXXRecordDecl *VTableClass) {
1579 llvm::GlobalValue *VTable = getAddrOfVTable(VTableClass, CharUnits());
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001580
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001581 // Find the appropriate vtable within the vtable group, and the address point
1582 // within that vtable.
1583 VTableLayout::AddressPointLocation AddressPoint =
1584 CGM.getItaniumVTableContext()
1585 .getVTableLayout(VTableClass)
1586 .getAddressPoint(Base);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001587 llvm::Value *Indices[] = {
Peter Collingbourne4e6a5402016-03-14 19:07:10 +00001588 llvm::ConstantInt::get(CGM.Int32Ty, 0),
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001589 llvm::ConstantInt::get(CGM.Int32Ty, AddressPoint.VTableIndex),
1590 llvm::ConstantInt::get(CGM.Int32Ty, AddressPoint.AddressPointIndex),
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001591 };
1592
Peter Collingbourne25a2b702016-12-13 20:50:44 +00001593 return llvm::ConstantExpr::getGetElementPtr(VTable->getValueType(), VTable,
1594 Indices, /*InBounds=*/true,
1595 /*InRangeIndex=*/1);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001596}
1597
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001598llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructorWithVTT(
1599 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1600 const CXXRecordDecl *NearestVBase) {
1601 assert((Base.getBase()->getNumVBases() || NearestVBase != nullptr) &&
1602 NeedsVTTParameter(CGF.CurGD) && "This class doesn't have VTT");
1603
1604 // Get the secondary vpointer index.
1605 uint64_t VirtualPointerIndex =
1606 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1607
1608 /// Load the VTT.
1609 llvm::Value *VTT = CGF.LoadCXXVTT();
1610 if (VirtualPointerIndex)
1611 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1612
1613 // And load the address point from the VTT.
1614 return CGF.Builder.CreateAlignedLoad(VTT, CGF.getPointerAlign());
1615}
1616
1617llvm::Constant *ItaniumCXXABI::getVTableAddressPointForConstExpr(
1618 BaseSubobject Base, const CXXRecordDecl *VTableClass) {
1619 return getVTableAddressPoint(Base, VTableClass);
1620}
1621
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001622llvm::GlobalVariable *ItaniumCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
1623 CharUnits VPtrOffset) {
1624 assert(VPtrOffset.isZero() && "Itanium ABI only supports zero vptr offsets");
1625
1626 llvm::GlobalVariable *&VTable = VTables[RD];
1627 if (VTable)
1628 return VTable;
1629
Eric Christopherd160c502016-01-29 01:35:53 +00001630 // Queue up this vtable for possible deferred emission.
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001631 CGM.addDeferredVTable(RD);
1632
Yaron Kerene46f7ed2015-07-29 14:21:47 +00001633 SmallString<256> Name;
1634 llvm::raw_svector_ostream Out(Name);
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00001635 getMangleContext().mangleCXXVTable(RD, Out);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001636
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001637 const VTableLayout &VTLayout =
1638 CGM.getItaniumVTableContext().getVTableLayout(RD);
1639 llvm::Type *VTableType = CGM.getVTables().getVTableType(VTLayout);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001640
1641 VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001642 Name, VTableType, llvm::GlobalValue::ExternalLinkage);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00001643 VTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Rafael Espindola880c3b22018-02-07 19:44:15 +00001644 CGM.setGlobalVisibility(VTable, RD);
Hans Wennborgda24e9c2014-06-02 23:13:03 +00001645
1646 if (RD->hasAttr<DLLImportAttr>())
1647 VTable->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1648 else if (RD->hasAttr<DLLExportAttr>())
1649 VTable->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1650
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001651 return VTable;
1652}
1653
John McCall9831b842018-02-06 18:52:44 +00001654CGCallee ItaniumCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
1655 GlobalDecl GD,
1656 Address This,
1657 llvm::Type *Ty,
1658 SourceLocation Loc) {
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001659 GD = GD.getCanonicalDecl();
1660 Ty = Ty->getPointerTo()->getPointerTo();
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001661 auto *MethodDecl = cast<CXXMethodDecl>(GD.getDecl());
1662 llvm::Value *VTable = CGF.GetVTablePtr(This, Ty, MethodDecl->getParent());
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001663
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001664 uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
John McCall9831b842018-02-06 18:52:44 +00001665 llvm::Value *VFunc;
1666 if (CGF.ShouldEmitVTableTypeCheckedLoad(MethodDecl->getParent())) {
1667 VFunc = CGF.EmitVTableTypeCheckedLoad(
Peter Collingbourne0ca03632016-06-25 00:24:06 +00001668 MethodDecl->getParent(), VTable,
1669 VTableIndex * CGM.getContext().getTargetInfo().getPointerWidth(0) / 8);
John McCall9831b842018-02-06 18:52:44 +00001670 } else {
1671 CGF.EmitTypeMetadataCodeForVCall(MethodDecl->getParent(), VTable, Loc);
Peter Collingbourne0ca03632016-06-25 00:24:06 +00001672
John McCall9831b842018-02-06 18:52:44 +00001673 llvm::Value *VFuncPtr =
1674 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfn");
1675 auto *VFuncLoad =
1676 CGF.Builder.CreateAlignedLoad(VFuncPtr, CGF.getPointerAlign());
Piotr Padlewski77cc9622016-10-29 15:28:30 +00001677
John McCall9831b842018-02-06 18:52:44 +00001678 // Add !invariant.load md to virtual function load to indicate that
1679 // function didn't change inside vtable.
1680 // It's safe to add it without -fstrict-vtable-pointers, but it would not
1681 // help in devirtualization because it will only matter if we will have 2
1682 // the same virtual function loads from the same vtable load, which won't
1683 // happen without enabled devirtualization with -fstrict-vtable-pointers.
1684 if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1685 CGM.getCodeGenOpts().StrictVTablePointers)
1686 VFuncLoad->setMetadata(
1687 llvm::LLVMContext::MD_invariant_load,
1688 llvm::MDNode::get(CGM.getLLVMContext(),
1689 llvm::ArrayRef<llvm::Metadata *>()));
1690 VFunc = VFuncLoad;
1691 }
John McCallb92ab1a2016-10-26 23:46:34 +00001692
John McCall9831b842018-02-06 18:52:44 +00001693 CGCallee Callee(MethodDecl, VFunc);
1694 return Callee;
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001695}
1696
David Majnemer0c0b6d92014-10-31 20:09:12 +00001697llvm::Value *ItaniumCXXABI::EmitVirtualDestructorCall(
1698 CodeGenFunction &CGF, const CXXDestructorDecl *Dtor, CXXDtorType DtorType,
John McCall7f416cc2015-09-08 08:05:57 +00001699 Address This, const CXXMemberCallExpr *CE) {
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001700 assert(CE == nullptr || CE->arg_begin() == CE->arg_end());
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001701 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
1702
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001703 const CGFunctionInfo *FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
1704 Dtor, getFromDtorType(DtorType));
Peter Collingbourneea211002018-02-05 23:09:13 +00001705 auto *Ty =
1706 cast<llvm::FunctionType>(CGF.CGM.getTypes().GetFunctionType(*FInfo));
John McCallb92ab1a2016-10-26 23:46:34 +00001707 CGCallee Callee =
Peter Collingbourneea211002018-02-05 23:09:13 +00001708 CGCallee::forVirtual(CE, GlobalDecl(Dtor, DtorType), This, Ty);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001709
John McCall7f416cc2015-09-08 08:05:57 +00001710 CGF.EmitCXXMemberOrOperatorCall(Dtor, Callee, ReturnValueSlot(),
1711 This.getPointer(), /*ImplicitParam=*/nullptr,
Richard Smith762672a2016-09-28 19:09:10 +00001712 QualType(), CE, nullptr);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001713 return nullptr;
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001714}
1715
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001716void ItaniumCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
Reid Kleckner7810af02013-06-19 15:20:38 +00001717 CodeGenVTables &VTables = CGM.getVTables();
1718 llvm::GlobalVariable *VTT = VTables.GetAddrOfVTT(RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001719 VTables.EmitVTTDefinition(VTT, CGM.getVTableLinkage(RD), RD);
Reid Kleckner7810af02013-06-19 15:20:38 +00001720}
1721
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001722bool ItaniumCXXABI::canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const {
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001723 // We don't emit available_externally vtables if we are in -fapple-kext mode
1724 // because kext mode does not permit devirtualization.
1725 if (CGM.getLangOpts().AppleKext)
1726 return false;
1727
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +00001728 // If we don't have any not emitted inline virtual function, and if vtable is
1729 // not hidden, then we are safe to emit available_externally copy of vtable.
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001730 // FIXME we can still emit a copy of the vtable if we
1731 // can emit definition of the inline functions.
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +00001732 return !hasAnyUnusedVirtualInlineFunction(RD) && !isVTableHidden(RD);
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001733}
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001734static llvm::Value *performTypeAdjustment(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001735 Address InitialPtr,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001736 int64_t NonVirtualAdjustment,
1737 int64_t VirtualAdjustment,
1738 bool IsReturnAdjustment) {
1739 if (!NonVirtualAdjustment && !VirtualAdjustment)
John McCall7f416cc2015-09-08 08:05:57 +00001740 return InitialPtr.getPointer();
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001741
John McCall7f416cc2015-09-08 08:05:57 +00001742 Address V = CGF.Builder.CreateElementBitCast(InitialPtr, CGF.Int8Ty);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001743
John McCall7f416cc2015-09-08 08:05:57 +00001744 // In a base-to-derived cast, the non-virtual adjustment is applied first.
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001745 if (NonVirtualAdjustment && !IsReturnAdjustment) {
John McCall7f416cc2015-09-08 08:05:57 +00001746 V = CGF.Builder.CreateConstInBoundsByteGEP(V,
1747 CharUnits::fromQuantity(NonVirtualAdjustment));
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001748 }
1749
John McCall7f416cc2015-09-08 08:05:57 +00001750 // Perform the virtual adjustment if we have one.
1751 llvm::Value *ResultPtr;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001752 if (VirtualAdjustment) {
1753 llvm::Type *PtrDiffTy =
1754 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1755
John McCall7f416cc2015-09-08 08:05:57 +00001756 Address VTablePtrPtr = CGF.Builder.CreateElementBitCast(V, CGF.Int8PtrTy);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001757 llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr);
1758
1759 llvm::Value *OffsetPtr =
1760 CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
1761
1762 OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo());
1763
1764 // Load the adjustment offset from the vtable.
John McCall7f416cc2015-09-08 08:05:57 +00001765 llvm::Value *Offset =
1766 CGF.Builder.CreateAlignedLoad(OffsetPtr, CGF.getPointerAlign());
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001767
1768 // Adjust our pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001769 ResultPtr = CGF.Builder.CreateInBoundsGEP(V.getPointer(), Offset);
1770 } else {
1771 ResultPtr = V.getPointer();
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001772 }
1773
John McCall7f416cc2015-09-08 08:05:57 +00001774 // In a derived-to-base conversion, the non-virtual adjustment is
1775 // applied second.
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001776 if (NonVirtualAdjustment && IsReturnAdjustment) {
John McCall7f416cc2015-09-08 08:05:57 +00001777 ResultPtr = CGF.Builder.CreateConstInBoundsGEP1_64(ResultPtr,
1778 NonVirtualAdjustment);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001779 }
1780
1781 // Cast back to the original type.
John McCall7f416cc2015-09-08 08:05:57 +00001782 return CGF.Builder.CreateBitCast(ResultPtr, InitialPtr.getType());
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001783}
1784
1785llvm::Value *ItaniumCXXABI::performThisAdjustment(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001786 Address This,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001787 const ThisAdjustment &TA) {
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00001788 return performTypeAdjustment(CGF, This, TA.NonVirtual,
1789 TA.Virtual.Itanium.VCallOffsetOffset,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001790 /*IsReturnAdjustment=*/false);
1791}
1792
1793llvm::Value *
John McCall7f416cc2015-09-08 08:05:57 +00001794ItaniumCXXABI::performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001795 const ReturnAdjustment &RA) {
1796 return performTypeAdjustment(CGF, Ret, RA.NonVirtual,
1797 RA.Virtual.Itanium.VBaseOffsetOffset,
1798 /*IsReturnAdjustment=*/true);
1799}
1800
John McCall5d865c322010-08-31 07:33:07 +00001801void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
1802 RValue RV, QualType ResultType) {
1803 if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
1804 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
1805
1806 // Destructor thunks in the ARM ABI have indeterminate results.
John McCall7f416cc2015-09-08 08:05:57 +00001807 llvm::Type *T = CGF.ReturnValue.getElementType();
John McCall5d865c322010-08-31 07:33:07 +00001808 RValue Undef = RValue::get(llvm::UndefValue::get(T));
1809 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
1810}
John McCall8ed55a52010-09-02 09:58:18 +00001811
1812/************************** Array allocation cookies **************************/
1813
John McCallb91cd662012-05-01 05:23:51 +00001814CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
1815 // The array cookie is a size_t; pad that up to the element alignment.
1816 // The cookie is actually right-justified in that space.
1817 return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
1818 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001819}
1820
John McCall7f416cc2015-09-08 08:05:57 +00001821Address ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1822 Address NewPtr,
1823 llvm::Value *NumElements,
1824 const CXXNewExpr *expr,
1825 QualType ElementType) {
John McCallb91cd662012-05-01 05:23:51 +00001826 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001827
John McCall7f416cc2015-09-08 08:05:57 +00001828 unsigned AS = NewPtr.getAddressSpace();
John McCall8ed55a52010-09-02 09:58:18 +00001829
John McCall9bca9232010-09-02 10:25:57 +00001830 ASTContext &Ctx = getContext();
John McCall7f416cc2015-09-08 08:05:57 +00001831 CharUnits SizeSize = CGF.getSizeSize();
John McCall8ed55a52010-09-02 09:58:18 +00001832
1833 // The size of the cookie.
1834 CharUnits CookieSize =
1835 std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
John McCallb91cd662012-05-01 05:23:51 +00001836 assert(CookieSize == getArrayCookieSizeImpl(ElementType));
John McCall8ed55a52010-09-02 09:58:18 +00001837
1838 // Compute an offset to the cookie.
John McCall7f416cc2015-09-08 08:05:57 +00001839 Address CookiePtr = NewPtr;
John McCall8ed55a52010-09-02 09:58:18 +00001840 CharUnits CookieOffset = CookieSize - SizeSize;
1841 if (!CookieOffset.isZero())
John McCall7f416cc2015-09-08 08:05:57 +00001842 CookiePtr = CGF.Builder.CreateConstInBoundsByteGEP(CookiePtr, CookieOffset);
John McCall8ed55a52010-09-02 09:58:18 +00001843
1844 // Write the number of elements into the appropriate slot.
John McCall7f416cc2015-09-08 08:05:57 +00001845 Address NumElementsPtr =
1846 CGF.Builder.CreateElementBitCast(CookiePtr, CGF.SizeTy);
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001847 llvm::Instruction *SI = CGF.Builder.CreateStore(NumElements, NumElementsPtr);
John McCall7f416cc2015-09-08 08:05:57 +00001848
1849 // Handle the array cookie specially in ASan.
Filipe Cabecinhas6f83fa92018-01-02 13:46:12 +00001850 if (CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) && AS == 0 &&
1851 expr->getOperatorNew()->isReplaceableGlobalAllocationFunction()) {
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001852 // The store to the CookiePtr does not need to be instrumented.
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001853 CGM.getSanitizerMetadata()->disableSanitizerForInstruction(SI);
1854 llvm::FunctionType *FTy =
John McCall7f416cc2015-09-08 08:05:57 +00001855 llvm::FunctionType::get(CGM.VoidTy, NumElementsPtr.getType(), false);
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001856 llvm::Constant *F =
1857 CGM.CreateRuntimeFunction(FTy, "__asan_poison_cxx_array_cookie");
John McCall7f416cc2015-09-08 08:05:57 +00001858 CGF.Builder.CreateCall(F, NumElementsPtr.getPointer());
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001859 }
John McCall8ed55a52010-09-02 09:58:18 +00001860
1861 // Finally, compute a pointer to the actual data buffer by skipping
1862 // over the cookie completely.
John McCall7f416cc2015-09-08 08:05:57 +00001863 return CGF.Builder.CreateConstInBoundsByteGEP(NewPtr, CookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001864}
1865
John McCallb91cd662012-05-01 05:23:51 +00001866llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001867 Address allocPtr,
John McCallb91cd662012-05-01 05:23:51 +00001868 CharUnits cookieSize) {
1869 // The element size is right-justified in the cookie.
John McCall7f416cc2015-09-08 08:05:57 +00001870 Address numElementsPtr = allocPtr;
1871 CharUnits numElementsOffset = cookieSize - CGF.getSizeSize();
John McCallb91cd662012-05-01 05:23:51 +00001872 if (!numElementsOffset.isZero())
1873 numElementsPtr =
John McCall7f416cc2015-09-08 08:05:57 +00001874 CGF.Builder.CreateConstInBoundsByteGEP(numElementsPtr, numElementsOffset);
John McCall8ed55a52010-09-02 09:58:18 +00001875
John McCall7f416cc2015-09-08 08:05:57 +00001876 unsigned AS = allocPtr.getAddressSpace();
1877 numElementsPtr = CGF.Builder.CreateElementBitCast(numElementsPtr, CGF.SizeTy);
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001878 if (!CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) || AS != 0)
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001879 return CGF.Builder.CreateLoad(numElementsPtr);
1880 // In asan mode emit a function call instead of a regular load and let the
1881 // run-time deal with it: if the shadow is properly poisoned return the
1882 // cookie, otherwise return 0 to avoid an infinite loop calling DTORs.
1883 // We can't simply ignore this load using nosanitize metadata because
1884 // the metadata may be lost.
1885 llvm::FunctionType *FTy =
1886 llvm::FunctionType::get(CGF.SizeTy, CGF.SizeTy->getPointerTo(0), false);
1887 llvm::Constant *F =
1888 CGM.CreateRuntimeFunction(FTy, "__asan_load_cxx_array_cookie");
John McCall7f416cc2015-09-08 08:05:57 +00001889 return CGF.Builder.CreateCall(F, numElementsPtr.getPointer());
John McCall8ed55a52010-09-02 09:58:18 +00001890}
1891
John McCallb91cd662012-05-01 05:23:51 +00001892CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
John McCallc19c7062013-01-25 23:36:19 +00001893 // ARM says that the cookie is always:
John McCall8ed55a52010-09-02 09:58:18 +00001894 // struct array_cookie {
1895 // std::size_t element_size; // element_size != 0
1896 // std::size_t element_count;
1897 // };
John McCallc19c7062013-01-25 23:36:19 +00001898 // But the base ABI doesn't give anything an alignment greater than
1899 // 8, so we can dismiss this as typical ABI-author blindness to
1900 // actual language complexity and round up to the element alignment.
1901 return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes),
1902 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001903}
1904
John McCall7f416cc2015-09-08 08:05:57 +00001905Address ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1906 Address newPtr,
1907 llvm::Value *numElements,
1908 const CXXNewExpr *expr,
1909 QualType elementType) {
John McCallb91cd662012-05-01 05:23:51 +00001910 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001911
John McCall8ed55a52010-09-02 09:58:18 +00001912 // The cookie is always at the start of the buffer.
John McCall7f416cc2015-09-08 08:05:57 +00001913 Address cookie = newPtr;
John McCall8ed55a52010-09-02 09:58:18 +00001914
1915 // The first element is the element size.
John McCall7f416cc2015-09-08 08:05:57 +00001916 cookie = CGF.Builder.CreateElementBitCast(cookie, CGF.SizeTy);
John McCallc19c7062013-01-25 23:36:19 +00001917 llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy,
1918 getContext().getTypeSizeInChars(elementType).getQuantity());
1919 CGF.Builder.CreateStore(elementSize, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001920
1921 // The second element is the element count.
John McCall7f416cc2015-09-08 08:05:57 +00001922 cookie = CGF.Builder.CreateConstInBoundsGEP(cookie, 1, CGF.getSizeSize());
John McCallc19c7062013-01-25 23:36:19 +00001923 CGF.Builder.CreateStore(numElements, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001924
1925 // Finally, compute a pointer to the actual data buffer by skipping
1926 // over the cookie completely.
John McCallc19c7062013-01-25 23:36:19 +00001927 CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType);
John McCall7f416cc2015-09-08 08:05:57 +00001928 return CGF.Builder.CreateConstInBoundsByteGEP(newPtr, cookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001929}
1930
John McCallb91cd662012-05-01 05:23:51 +00001931llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001932 Address allocPtr,
John McCallb91cd662012-05-01 05:23:51 +00001933 CharUnits cookieSize) {
1934 // The number of elements is at offset sizeof(size_t) relative to
1935 // the allocated pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001936 Address numElementsPtr
1937 = CGF.Builder.CreateConstInBoundsByteGEP(allocPtr, CGF.getSizeSize());
John McCall8ed55a52010-09-02 09:58:18 +00001938
John McCall7f416cc2015-09-08 08:05:57 +00001939 numElementsPtr = CGF.Builder.CreateElementBitCast(numElementsPtr, CGF.SizeTy);
John McCallb91cd662012-05-01 05:23:51 +00001940 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall8ed55a52010-09-02 09:58:18 +00001941}
1942
John McCall68ff0372010-09-08 01:44:27 +00001943/*********************** Static local initialization **************************/
1944
1945static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001946 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001947 // int __cxa_guard_acquire(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001948 llvm::FunctionType *FTy =
John McCall68ff0372010-09-08 01:44:27 +00001949 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
Jay Foad5709f7c2011-07-29 13:56:53 +00001950 GuardPtrTy, /*isVarArg=*/false);
Reid Klecknerde864822017-03-21 16:57:30 +00001951 return CGM.CreateRuntimeFunction(
1952 FTy, "__cxa_guard_acquire",
1953 llvm::AttributeList::get(CGM.getLLVMContext(),
1954 llvm::AttributeList::FunctionIndex,
1955 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001956}
1957
1958static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001959 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001960 // void __cxa_guard_release(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001961 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001962 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Reid Klecknerde864822017-03-21 16:57:30 +00001963 return CGM.CreateRuntimeFunction(
1964 FTy, "__cxa_guard_release",
1965 llvm::AttributeList::get(CGM.getLLVMContext(),
1966 llvm::AttributeList::FunctionIndex,
1967 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001968}
1969
1970static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001971 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001972 // void __cxa_guard_abort(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001973 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001974 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Reid Klecknerde864822017-03-21 16:57:30 +00001975 return CGM.CreateRuntimeFunction(
1976 FTy, "__cxa_guard_abort",
1977 llvm::AttributeList::get(CGM.getLLVMContext(),
1978 llvm::AttributeList::FunctionIndex,
1979 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001980}
1981
1982namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001983 struct CallGuardAbort final : EHScopeStack::Cleanup {
John McCall68ff0372010-09-08 01:44:27 +00001984 llvm::GlobalVariable *Guard;
Chandler Carruth84537952012-03-30 19:44:53 +00001985 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
John McCall68ff0372010-09-08 01:44:27 +00001986
Craig Topper4f12f102014-03-12 06:41:41 +00001987 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall882987f2013-02-28 19:01:20 +00001988 CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()),
1989 Guard);
John McCall68ff0372010-09-08 01:44:27 +00001990 }
1991 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001992}
John McCall68ff0372010-09-08 01:44:27 +00001993
1994/// The ARM code here follows the Itanium code closely enough that we
1995/// just special-case it at particular places.
John McCallcdf7ef52010-11-06 09:44:32 +00001996void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
1997 const VarDecl &D,
John McCallb88a5662012-03-30 21:00:39 +00001998 llvm::GlobalVariable *var,
1999 bool shouldPerformInit) {
John McCall68ff0372010-09-08 01:44:27 +00002000 CGBuilderTy &Builder = CGF.Builder;
John McCallcdf7ef52010-11-06 09:44:32 +00002001
Richard Smith62f19e72016-06-25 00:15:56 +00002002 // Inline variables that weren't instantiated from variable templates have
2003 // partially-ordered initialization within their translation unit.
2004 bool NonTemplateInline =
2005 D.isInline() &&
2006 !isTemplateInstantiation(D.getTemplateSpecializationKind());
2007
2008 // We only need to use thread-safe statics for local non-TLS variables and
2009 // inline variables; other global initialization is always single-threaded
2010 // or (through lazy dynamic loading in multiple threads) unsequenced.
Richard Smithdbf74ba2013-04-14 23:01:42 +00002011 bool threadsafe = getContext().getLangOpts().ThreadsafeStatics &&
Richard Smith62f19e72016-06-25 00:15:56 +00002012 (D.isLocalVarDecl() || NonTemplateInline) &&
2013 !D.getTLSKind();
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00002014
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00002015 // If we have a global variable with internal linkage and thread-safe statics
2016 // are disabled, we can just let the guard variable be of type i8.
John McCallb88a5662012-03-30 21:00:39 +00002017 bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
2018
2019 llvm::IntegerType *guardTy;
John McCall7f416cc2015-09-08 08:05:57 +00002020 CharUnits guardAlignment;
John McCall5aa52592011-06-17 07:33:57 +00002021 if (useInt8GuardVariable) {
John McCallb88a5662012-03-30 21:00:39 +00002022 guardTy = CGF.Int8Ty;
John McCall7f416cc2015-09-08 08:05:57 +00002023 guardAlignment = CharUnits::One();
John McCall5aa52592011-06-17 07:33:57 +00002024 } else {
Tim Northover9bb857a2013-01-31 12:13:10 +00002025 // Guard variables are 64 bits in the generic ABI and size width on ARM
2026 // (i.e. 32-bit on AArch32, 64-bit on AArch64).
John McCall7f416cc2015-09-08 08:05:57 +00002027 if (UseARMGuardVarABI) {
2028 guardTy = CGF.SizeTy;
2029 guardAlignment = CGF.getSizeAlign();
2030 } else {
2031 guardTy = CGF.Int64Ty;
2032 guardAlignment = CharUnits::fromQuantity(
2033 CGM.getDataLayout().getABITypeAlignment(guardTy));
2034 }
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00002035 }
John McCallb88a5662012-03-30 21:00:39 +00002036 llvm::PointerType *guardPtrTy = guardTy->getPointerTo();
John McCall68ff0372010-09-08 01:44:27 +00002037
John McCallb88a5662012-03-30 21:00:39 +00002038 // Create the guard variable if we don't already have it (as we
2039 // might if we're double-emitting this function body).
2040 llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
2041 if (!guard) {
2042 // Mangle the name for the guard.
2043 SmallString<256> guardName;
2044 {
2045 llvm::raw_svector_ostream out(guardName);
Reid Klecknerd8110b62013-09-10 20:14:30 +00002046 getMangleContext().mangleStaticGuardVariable(&D, out);
John McCallb88a5662012-03-30 21:00:39 +00002047 }
John McCall8e7cb6d2010-11-02 21:04:24 +00002048
John McCallb88a5662012-03-30 21:00:39 +00002049 // Create the guard variable with a zero-initializer.
2050 // Just absorb linkage and visibility from the guarded variable.
2051 guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
2052 false, var->getLinkage(),
2053 llvm::ConstantInt::get(guardTy, 0),
2054 guardName.str());
2055 guard->setVisibility(var->getVisibility());
Richard Smithdbf74ba2013-04-14 23:01:42 +00002056 // If the variable is thread-local, so is its guard variable.
2057 guard->setThreadLocalMode(var->getThreadLocalMode());
John McCall7f416cc2015-09-08 08:05:57 +00002058 guard->setAlignment(guardAlignment.getQuantity());
John McCallb88a5662012-03-30 21:00:39 +00002059
Yaron Keren5bfa1082015-09-03 20:33:29 +00002060 // The ABI says: "It is suggested that it be emitted in the same COMDAT
2061 // group as the associated data object." In practice, this doesn't work for
Dan Gohman839f2152017-01-17 21:46:38 +00002062 // non-ELF and non-Wasm object formats, so only do it for ELF and Wasm.
Rafael Espindola0d4fb982015-01-12 22:13:53 +00002063 llvm::Comdat *C = var->getComdat();
Yaron Keren5bfa1082015-09-03 20:33:29 +00002064 if (!D.isLocalVarDecl() && C &&
Dan Gohman839f2152017-01-17 21:46:38 +00002065 (CGM.getTarget().getTriple().isOSBinFormatELF() ||
2066 CGM.getTarget().getTriple().isOSBinFormatWasm())) {
Rafael Espindola2ae4b632014-09-19 19:43:18 +00002067 guard->setComdat(C);
Richard Smith62f19e72016-06-25 00:15:56 +00002068 // An inline variable's guard function is run from the per-TU
2069 // initialization function, not via a dedicated global ctor function, so
2070 // we can't put it in a comdat.
2071 if (!NonTemplateInline)
2072 CGF.CurFn->setComdat(C);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00002073 } else if (CGM.supportsCOMDAT() && guard->isWeakForLinker()) {
2074 guard->setComdat(CGM.getModule().getOrInsertComdat(guard->getName()));
Rafael Espindola2ae4b632014-09-19 19:43:18 +00002075 }
2076
John McCallb88a5662012-03-30 21:00:39 +00002077 CGM.setStaticLocalDeclGuardAddress(&D, guard);
2078 }
John McCall87590e62012-03-30 07:09:50 +00002079
John McCall7f416cc2015-09-08 08:05:57 +00002080 Address guardAddr = Address(guard, guardAlignment);
2081
John McCall68ff0372010-09-08 01:44:27 +00002082 // Test whether the variable has completed initialization.
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002083 //
John McCall68ff0372010-09-08 01:44:27 +00002084 // Itanium C++ ABI 3.3.2:
2085 // The following is pseudo-code showing how these functions can be used:
2086 // if (obj_guard.first_byte == 0) {
2087 // if ( __cxa_guard_acquire (&obj_guard) ) {
2088 // try {
2089 // ... initialize the object ...;
2090 // } catch (...) {
2091 // __cxa_guard_abort (&obj_guard);
2092 // throw;
2093 // }
2094 // ... queue object destructor with __cxa_atexit() ...;
2095 // __cxa_guard_release (&obj_guard);
2096 // }
2097 // }
Tim Northovera2ee4332014-03-29 15:09:45 +00002098
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002099 // Load the first byte of the guard variable.
2100 llvm::LoadInst *LI =
John McCall7f416cc2015-09-08 08:05:57 +00002101 Builder.CreateLoad(Builder.CreateElementBitCast(guardAddr, CGM.Int8Ty));
John McCall68ff0372010-09-08 01:44:27 +00002102
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002103 // Itanium ABI:
2104 // An implementation supporting thread-safety on multiprocessor
2105 // systems must also guarantee that references to the initialized
2106 // object do not occur before the load of the initialization flag.
2107 //
2108 // In LLVM, we do this by marking the load Acquire.
2109 if (threadsafe)
JF Bastien92f4ef12016-04-06 17:26:42 +00002110 LI->setAtomic(llvm::AtomicOrdering::Acquire);
Eli Friedman84d28122011-09-13 22:21:56 +00002111
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002112 // For ARM, we should only check the first bit, rather than the entire byte:
2113 //
2114 // ARM C++ ABI 3.2.3.1:
2115 // To support the potential use of initialization guard variables
2116 // as semaphores that are the target of ARM SWP and LDREX/STREX
2117 // synchronizing instructions we define a static initialization
2118 // guard variable to be a 4-byte aligned, 4-byte word with the
2119 // following inline access protocol.
2120 // #define INITIALIZED 1
2121 // if ((obj_guard & INITIALIZED) != INITIALIZED) {
2122 // if (__cxa_guard_acquire(&obj_guard))
2123 // ...
2124 // }
2125 //
2126 // and similarly for ARM64:
2127 //
2128 // ARM64 C++ ABI 3.2.2:
2129 // This ABI instead only specifies the value bit 0 of the static guard
2130 // variable; all other bits are platform defined. Bit 0 shall be 0 when the
2131 // variable is not initialized and 1 when it is.
2132 llvm::Value *V =
2133 (UseARMGuardVarABI && !useInt8GuardVariable)
2134 ? Builder.CreateAnd(LI, llvm::ConstantInt::get(CGM.Int8Ty, 1))
2135 : LI;
Richard Smithae8d62c2017-07-26 22:01:09 +00002136 llvm::Value *NeedsInit = Builder.CreateIsNull(V, "guard.uninitialized");
John McCall68ff0372010-09-08 01:44:27 +00002137
2138 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
2139 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
2140
2141 // Check if the first byte of the guard variable is zero.
Richard Smithae8d62c2017-07-26 22:01:09 +00002142 CGF.EmitCXXGuardedInitBranch(NeedsInit, InitCheckBlock, EndBlock,
2143 CodeGenFunction::GuardKind::VariableGuard, &D);
John McCall68ff0372010-09-08 01:44:27 +00002144
2145 CGF.EmitBlock(InitCheckBlock);
2146
2147 // Variables used when coping with thread-safe statics and exceptions.
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002148 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00002149 // Call __cxa_guard_acquire.
2150 llvm::Value *V
John McCall882987f2013-02-28 19:01:20 +00002151 = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002152
John McCall68ff0372010-09-08 01:44:27 +00002153 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002154
John McCall68ff0372010-09-08 01:44:27 +00002155 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
2156 InitBlock, EndBlock);
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002157
John McCall68ff0372010-09-08 01:44:27 +00002158 // Call __cxa_guard_abort along the exceptional edge.
John McCallb88a5662012-03-30 21:00:39 +00002159 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002160
John McCall68ff0372010-09-08 01:44:27 +00002161 CGF.EmitBlock(InitBlock);
2162 }
2163
2164 // Emit the initializer and add a global destructor if appropriate.
John McCallb88a5662012-03-30 21:00:39 +00002165 CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
John McCall68ff0372010-09-08 01:44:27 +00002166
John McCall5aa52592011-06-17 07:33:57 +00002167 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00002168 // Pop the guard-abort cleanup if we pushed one.
2169 CGF.PopCleanupBlock();
2170
2171 // Call __cxa_guard_release. This cannot throw.
John McCall7f416cc2015-09-08 08:05:57 +00002172 CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy),
2173 guardAddr.getPointer());
John McCall68ff0372010-09-08 01:44:27 +00002174 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002175 Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guardAddr);
John McCall68ff0372010-09-08 01:44:27 +00002176 }
2177
2178 CGF.EmitBlock(EndBlock);
2179}
John McCallc84ed6a2012-05-01 06:13:13 +00002180
2181/// Register a global destructor using __cxa_atexit.
2182static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
2183 llvm::Constant *dtor,
Richard Smithdbf74ba2013-04-14 23:01:42 +00002184 llvm::Constant *addr,
2185 bool TLS) {
Bill Wendling95cae882013-05-02 19:18:03 +00002186 const char *Name = "__cxa_atexit";
2187 if (TLS) {
2188 const llvm::Triple &T = CGF.getTarget().getTriple();
Manman Renf93fff22015-11-11 23:08:18 +00002189 Name = T.isOSDarwin() ? "_tlv_atexit" : "__cxa_thread_atexit";
Bill Wendling95cae882013-05-02 19:18:03 +00002190 }
Richard Smithdbf74ba2013-04-14 23:01:42 +00002191
John McCallc84ed6a2012-05-01 06:13:13 +00002192 // We're assuming that the destructor function is something we can
2193 // reasonably call with the default CC. Go ahead and cast it to the
2194 // right prototype.
2195 llvm::Type *dtorTy =
2196 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo();
2197
2198 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
2199 llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
2200 llvm::FunctionType *atexitTy =
2201 llvm::FunctionType::get(CGF.IntTy, paramTys, false);
2202
2203 // Fetch the actual function.
Richard Smithdbf74ba2013-04-14 23:01:42 +00002204 llvm::Constant *atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name);
John McCallc84ed6a2012-05-01 06:13:13 +00002205 if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit))
2206 fn->setDoesNotThrow();
2207
2208 // Create a variable that binds the atexit to this shared object.
2209 llvm::Constant *handle =
Reid Kleckner9de92142017-02-13 18:49:21 +00002210 CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
2211 auto *GV = cast<llvm::GlobalValue>(handle->stripPointerCasts());
2212 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
John McCallc84ed6a2012-05-01 06:13:13 +00002213
2214 llvm::Value *args[] = {
2215 llvm::ConstantExpr::getBitCast(dtor, dtorTy),
2216 llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy),
2217 handle
2218 };
John McCall882987f2013-02-28 19:01:20 +00002219 CGF.EmitNounwindRuntimeCall(atexit, args);
John McCallc84ed6a2012-05-01 06:13:13 +00002220}
2221
2222/// Register a global destructor as best as we know how.
2223void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF,
Richard Smithdbf74ba2013-04-14 23:01:42 +00002224 const VarDecl &D,
John McCallc84ed6a2012-05-01 06:13:13 +00002225 llvm::Constant *dtor,
2226 llvm::Constant *addr) {
2227 // Use __cxa_atexit if available.
Richard Smithdbf74ba2013-04-14 23:01:42 +00002228 if (CGM.getCodeGenOpts().CXAAtExit)
2229 return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind());
2230
2231 if (D.getTLSKind())
2232 CGM.ErrorUnsupported(&D, "non-trivial TLS destruction");
John McCallc84ed6a2012-05-01 06:13:13 +00002233
2234 // In Apple kexts, we want to add a global destructor entry.
2235 // FIXME: shouldn't this be guarded by some variable?
Richard Smith9c6890a2012-11-01 22:30:59 +00002236 if (CGM.getLangOpts().AppleKext) {
John McCallc84ed6a2012-05-01 06:13:13 +00002237 // Generate a global destructor entry.
2238 return CGM.AddCXXDtorEntry(dtor, addr);
2239 }
2240
David Blaikieebe87e12013-08-27 23:57:18 +00002241 CGF.registerGlobalDtorWithAtExit(D, dtor, addr);
John McCallc84ed6a2012-05-01 06:13:13 +00002242}
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002243
David Majnemer9b21c332014-07-11 20:28:10 +00002244static bool isThreadWrapperReplaceable(const VarDecl *VD,
2245 CodeGen::CodeGenModule &CGM) {
2246 assert(!VD->isStaticLocal() && "static local VarDecls don't need wrappers!");
Manman Renf93fff22015-11-11 23:08:18 +00002247 // Darwin prefers to have references to thread local variables to go through
David Majnemer9b21c332014-07-11 20:28:10 +00002248 // the thread wrapper instead of directly referencing the backing variable.
2249 return VD->getTLSKind() == VarDecl::TLS_Dynamic &&
Manman Renf93fff22015-11-11 23:08:18 +00002250 CGM.getTarget().getTriple().isOSDarwin();
David Majnemer9b21c332014-07-11 20:28:10 +00002251}
2252
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002253/// Get the appropriate linkage for the wrapper function. This is essentially
David Majnemer4632e1e2014-06-27 16:56:27 +00002254/// the weak form of the variable's linkage; every translation unit which needs
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002255/// the wrapper emits a copy, and we want the linker to merge them.
David Majnemer35ab3282014-06-11 04:08:55 +00002256static llvm::GlobalValue::LinkageTypes
2257getThreadLocalWrapperLinkage(const VarDecl *VD, CodeGen::CodeGenModule &CGM) {
2258 llvm::GlobalValue::LinkageTypes VarLinkage =
2259 CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false);
2260
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002261 // For internal linkage variables, we don't need an external or weak wrapper.
2262 if (llvm::GlobalValue::isLocalLinkage(VarLinkage))
2263 return VarLinkage;
David Majnemer35ab3282014-06-11 04:08:55 +00002264
David Majnemer9b21c332014-07-11 20:28:10 +00002265 // If the thread wrapper is replaceable, give it appropriate linkage.
Manman Ren68150262015-11-11 22:42:31 +00002266 if (isThreadWrapperReplaceable(VD, CGM))
2267 if (!llvm::GlobalVariable::isLinkOnceLinkage(VarLinkage) &&
2268 !llvm::GlobalVariable::isWeakODRLinkage(VarLinkage))
2269 return VarLinkage;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002270 return llvm::GlobalValue::WeakODRLinkage;
2271}
2272
2273llvm::Function *
2274ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD,
Alexander Musmanf94c3182014-09-26 06:28:25 +00002275 llvm::Value *Val) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002276 // Mangle the name for the thread_local wrapper function.
2277 SmallString<256> WrapperName;
2278 {
2279 llvm::raw_svector_ostream Out(WrapperName);
2280 getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002281 }
2282
Akira Hatanaka26907f92016-01-15 03:34:06 +00002283 // FIXME: If VD is a definition, we should regenerate the function attributes
2284 // before returning.
Alexander Musmanf94c3182014-09-26 06:28:25 +00002285 if (llvm::Value *V = CGM.getModule().getNamedValue(WrapperName))
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002286 return cast<llvm::Function>(V);
2287
Akira Hatanaka26907f92016-01-15 03:34:06 +00002288 QualType RetQT = VD->getType();
2289 if (RetQT->isReferenceType())
2290 RetQT = RetQT.getNonReferenceType();
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002291
John McCallc56a8b32016-03-11 04:30:31 +00002292 const CGFunctionInfo &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
2293 getContext().getPointerType(RetQT), FunctionArgList());
Akira Hatanaka26907f92016-01-15 03:34:06 +00002294
2295 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FI);
David Majnemer35ab3282014-06-11 04:08:55 +00002296 llvm::Function *Wrapper =
2297 llvm::Function::Create(FnTy, getThreadLocalWrapperLinkage(VD, CGM),
2298 WrapperName.str(), &CGM.getModule());
Akira Hatanaka26907f92016-01-15 03:34:06 +00002299
2300 CGM.SetLLVMFunctionAttributes(nullptr, FI, Wrapper);
2301
2302 if (VD->hasDefinition())
2303 CGM.SetLLVMFunctionAttributesForDefinition(nullptr, Wrapper);
2304
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002305 // Always resolve references to the wrapper at link time.
Manman Ren68150262015-11-11 22:42:31 +00002306 if (!Wrapper->hasLocalLinkage() && !(isThreadWrapperReplaceable(VD, CGM) &&
2307 !llvm::GlobalVariable::isLinkOnceLinkage(Wrapper->getLinkage()) &&
2308 !llvm::GlobalVariable::isWeakODRLinkage(Wrapper->getLinkage())))
Duncan P. N. Exon Smith4434d362014-05-07 22:36:11 +00002309 Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
Manman Renb0b3af72015-12-17 00:42:36 +00002310
2311 if (isThreadWrapperReplaceable(VD, CGM)) {
2312 Wrapper->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2313 Wrapper->addFnAttr(llvm::Attribute::NoUnwind);
2314 }
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002315 return Wrapper;
2316}
2317
2318void ItaniumCXXABI::EmitThreadLocalInitFuncs(
Richard Smith5a99c492015-12-01 01:10:48 +00002319 CodeGenModule &CGM, ArrayRef<const VarDecl *> CXXThreadLocals,
2320 ArrayRef<llvm::Function *> CXXThreadLocalInits,
2321 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) {
David Majnemerb3341ea2014-10-05 05:05:40 +00002322 llvm::Function *InitFunc = nullptr;
Richard Smithfbe23692017-01-13 00:43:31 +00002323
2324 // Separate initializers into those with ordered (or partially-ordered)
2325 // initialization and those with unordered initialization.
2326 llvm::SmallVector<llvm::Function *, 8> OrderedInits;
2327 llvm::SmallDenseMap<const VarDecl *, llvm::Function *> UnorderedInits;
2328 for (unsigned I = 0; I != CXXThreadLocalInits.size(); ++I) {
2329 if (isTemplateInstantiation(
2330 CXXThreadLocalInitVars[I]->getTemplateSpecializationKind()))
2331 UnorderedInits[CXXThreadLocalInitVars[I]->getCanonicalDecl()] =
2332 CXXThreadLocalInits[I];
2333 else
2334 OrderedInits.push_back(CXXThreadLocalInits[I]);
2335 }
2336
2337 if (!OrderedInits.empty()) {
David Majnemerb3341ea2014-10-05 05:05:40 +00002338 // Generate a guarded initialization function.
2339 llvm::FunctionType *FTy =
2340 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002341 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
2342 InitFunc = CGM.CreateGlobalInitOrDestructFunction(FTy, "__tls_init", FI,
Alexey Samsonov1444bb92014-10-17 00:20:19 +00002343 SourceLocation(),
David Majnemerb3341ea2014-10-05 05:05:40 +00002344 /*TLS=*/true);
2345 llvm::GlobalVariable *Guard = new llvm::GlobalVariable(
2346 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false,
2347 llvm::GlobalVariable::InternalLinkage,
2348 llvm::ConstantInt::get(CGM.Int8Ty, 0), "__tls_guard");
2349 Guard->setThreadLocal(true);
John McCall7f416cc2015-09-08 08:05:57 +00002350
2351 CharUnits GuardAlign = CharUnits::One();
2352 Guard->setAlignment(GuardAlign.getQuantity());
2353
Richard Smithfbe23692017-01-13 00:43:31 +00002354 CodeGenFunction(CGM).GenerateCXXGlobalInitFunc(InitFunc, OrderedInits,
2355 Address(Guard, GuardAlign));
Manman Ren5e5d0462016-03-18 23:35:21 +00002356 // On Darwin platforms, use CXX_FAST_TLS calling convention.
2357 if (CGM.getTarget().getTriple().isOSDarwin()) {
2358 InitFunc->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2359 InitFunc->addFnAttr(llvm::Attribute::NoUnwind);
2360 }
David Majnemerb3341ea2014-10-05 05:05:40 +00002361 }
Richard Smithfbe23692017-01-13 00:43:31 +00002362
2363 // Emit thread wrappers.
Richard Smith5a99c492015-12-01 01:10:48 +00002364 for (const VarDecl *VD : CXXThreadLocals) {
2365 llvm::GlobalVariable *Var =
2366 cast<llvm::GlobalVariable>(CGM.GetGlobalValue(CGM.getMangledName(VD)));
Richard Smithfbe23692017-01-13 00:43:31 +00002367 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Var);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002368
David Majnemer9b21c332014-07-11 20:28:10 +00002369 // Some targets require that all access to thread local variables go through
2370 // the thread wrapper. This means that we cannot attempt to create a thread
2371 // wrapper or a thread helper.
Richard Smithfbe23692017-01-13 00:43:31 +00002372 if (isThreadWrapperReplaceable(VD, CGM) && !VD->hasDefinition()) {
2373 Wrapper->setLinkage(llvm::Function::ExternalLinkage);
David Majnemer9b21c332014-07-11 20:28:10 +00002374 continue;
Richard Smithfbe23692017-01-13 00:43:31 +00002375 }
David Majnemer9b21c332014-07-11 20:28:10 +00002376
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002377 // Mangle the name for the thread_local initialization function.
2378 SmallString<256> InitFnName;
2379 {
2380 llvm::raw_svector_ostream Out(InitFnName);
2381 getMangleContext().mangleItaniumThreadLocalInit(VD, Out);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002382 }
2383
2384 // If we have a definition for the variable, emit the initialization
2385 // function as an alias to the global Init function (if any). Otherwise,
2386 // produce a declaration of the initialization function.
Craig Topper8a13c412014-05-21 05:09:00 +00002387 llvm::GlobalValue *Init = nullptr;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002388 bool InitIsInitFunc = false;
2389 if (VD->hasDefinition()) {
2390 InitIsInitFunc = true;
Richard Smithfbe23692017-01-13 00:43:31 +00002391 llvm::Function *InitFuncToUse = InitFunc;
2392 if (isTemplateInstantiation(VD->getTemplateSpecializationKind()))
2393 InitFuncToUse = UnorderedInits.lookup(VD->getCanonicalDecl());
2394 if (InitFuncToUse)
Rafael Espindola234405b2014-05-17 21:30:14 +00002395 Init = llvm::GlobalAlias::create(Var->getLinkage(), InitFnName.str(),
Richard Smithfbe23692017-01-13 00:43:31 +00002396 InitFuncToUse);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002397 } else {
2398 // Emit a weak global function referring to the initialization function.
2399 // This function will not exist if the TU defining the thread_local
2400 // variable in question does not need any dynamic initialization for
2401 // its thread_local variables.
2402 llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, false);
Richard Smithfbe23692017-01-13 00:43:31 +00002403 Init = llvm::Function::Create(FnTy,
2404 llvm::GlobalVariable::ExternalWeakLinkage,
2405 InitFnName.str(), &CGM.getModule());
John McCallc56a8b32016-03-11 04:30:31 +00002406 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
Akira Hatanaka26907f92016-01-15 03:34:06 +00002407 CGM.SetLLVMFunctionAttributes(nullptr, FI, cast<llvm::Function>(Init));
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002408 }
2409
2410 if (Init)
2411 Init->setVisibility(Var->getVisibility());
2412
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002413 llvm::LLVMContext &Context = CGM.getModule().getContext();
2414 llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper);
John McCall7f416cc2015-09-08 08:05:57 +00002415 CGBuilderTy Builder(CGM, Entry);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002416 if (InitIsInitFunc) {
Manman Ren5e5d0462016-03-18 23:35:21 +00002417 if (Init) {
2418 llvm::CallInst *CallVal = Builder.CreateCall(Init);
2419 if (isThreadWrapperReplaceable(VD, CGM))
2420 CallVal->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2421 }
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002422 } else {
2423 // Don't know whether we have an init function. Call it if it exists.
2424 llvm::Value *Have = Builder.CreateIsNotNull(Init);
2425 llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2426 llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2427 Builder.CreateCondBr(Have, InitBB, ExitBB);
2428
2429 Builder.SetInsertPoint(InitBB);
David Blaikie4ba525b2015-07-14 17:27:39 +00002430 Builder.CreateCall(Init);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002431 Builder.CreateBr(ExitBB);
2432
2433 Builder.SetInsertPoint(ExitBB);
2434 }
2435
2436 // For a reference, the result of the wrapper function is a pointer to
2437 // the referenced object.
2438 llvm::Value *Val = Var;
2439 if (VD->getType()->isReferenceType()) {
John McCall7f416cc2015-09-08 08:05:57 +00002440 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2441 Val = Builder.CreateAlignedLoad(Val, Align);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002442 }
Alexander Musmanf94c3182014-09-26 06:28:25 +00002443 if (Val->getType() != Wrapper->getReturnType())
2444 Val = Builder.CreatePointerBitCastOrAddrSpaceCast(
2445 Val, Wrapper->getReturnType(), "");
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002446 Builder.CreateRet(Val);
2447 }
2448}
2449
Richard Smith0f383742014-03-26 22:48:22 +00002450LValue ItaniumCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
2451 const VarDecl *VD,
2452 QualType LValType) {
Richard Smith5a99c492015-12-01 01:10:48 +00002453 llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD);
Alexander Musmanf94c3182014-09-26 06:28:25 +00002454 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Val);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002455
Manman Renb0b3af72015-12-17 00:42:36 +00002456 llvm::CallInst *CallVal = CGF.Builder.CreateCall(Wrapper);
Saleem Abdulrasool4a7130a2016-08-01 21:31:24 +00002457 CallVal->setCallingConv(Wrapper->getCallingConv());
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002458
2459 LValue LV;
2460 if (VD->getType()->isReferenceType())
Manman Renb0b3af72015-12-17 00:42:36 +00002461 LV = CGF.MakeNaturalAlignAddrLValue(CallVal, LValType);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002462 else
Manman Renb0b3af72015-12-17 00:42:36 +00002463 LV = CGF.MakeAddrLValue(CallVal, LValType,
2464 CGF.getContext().getDeclAlign(VD));
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002465 // FIXME: need setObjCGCLValueClass?
2466 return LV;
2467}
Peter Collingbourne66f82e62013-06-28 20:45:28 +00002468
2469/// Return whether the given global decl needs a VTT parameter, which it does
2470/// if it's a base constructor or destructor with virtual bases.
2471bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) {
2472 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002473
Peter Collingbourne66f82e62013-06-28 20:45:28 +00002474 // We don't have any virtual bases, just return early.
2475 if (!MD->getParent()->getNumVBases())
2476 return false;
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002477
Peter Collingbourne66f82e62013-06-28 20:45:28 +00002478 // Check if we have a base constructor.
2479 if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base)
2480 return true;
2481
2482 // Check if we have a base destructor.
2483 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
2484 return true;
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002485
Peter Collingbourne66f82e62013-06-28 20:45:28 +00002486 return false;
2487}
David Majnemere2cb8d12014-07-07 06:20:47 +00002488
2489namespace {
2490class ItaniumRTTIBuilder {
2491 CodeGenModule &CGM; // Per-module state.
2492 llvm::LLVMContext &VMContext;
2493 const ItaniumCXXABI &CXXABI; // Per-module state.
2494
2495 /// Fields - The fields of the RTTI descriptor currently being built.
2496 SmallVector<llvm::Constant *, 16> Fields;
2497
2498 /// GetAddrOfTypeName - Returns the mangled type name of the given type.
2499 llvm::GlobalVariable *
2500 GetAddrOfTypeName(QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage);
2501
2502 /// GetAddrOfExternalRTTIDescriptor - Returns the constant for the RTTI
2503 /// descriptor of the given type.
2504 llvm::Constant *GetAddrOfExternalRTTIDescriptor(QualType Ty);
2505
2506 /// BuildVTablePointer - Build the vtable pointer for the given type.
2507 void BuildVTablePointer(const Type *Ty);
2508
2509 /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
2510 /// inheritance, according to the Itanium C++ ABI, 2.9.5p6b.
2511 void BuildSIClassTypeInfo(const CXXRecordDecl *RD);
2512
2513 /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
2514 /// classes with bases that do not satisfy the abi::__si_class_type_info
2515 /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
2516 void BuildVMIClassTypeInfo(const CXXRecordDecl *RD);
2517
2518 /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct, used
2519 /// for pointer types.
2520 void BuildPointerTypeInfo(QualType PointeeTy);
2521
2522 /// BuildObjCObjectTypeInfo - Build the appropriate kind of
2523 /// type_info for an object type.
2524 void BuildObjCObjectTypeInfo(const ObjCObjectType *Ty);
2525
2526 /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
2527 /// struct, used for member pointer types.
2528 void BuildPointerToMemberTypeInfo(const MemberPointerType *Ty);
2529
2530public:
2531 ItaniumRTTIBuilder(const ItaniumCXXABI &ABI)
2532 : CGM(ABI.CGM), VMContext(CGM.getModule().getContext()), CXXABI(ABI) {}
2533
2534 // Pointer type info flags.
2535 enum {
2536 /// PTI_Const - Type has const qualifier.
2537 PTI_Const = 0x1,
2538
2539 /// PTI_Volatile - Type has volatile qualifier.
2540 PTI_Volatile = 0x2,
2541
2542 /// PTI_Restrict - Type has restrict qualifier.
2543 PTI_Restrict = 0x4,
2544
2545 /// PTI_Incomplete - Type is incomplete.
2546 PTI_Incomplete = 0x8,
2547
2548 /// PTI_ContainingClassIncomplete - Containing class is incomplete.
2549 /// (in pointer to member).
Richard Smitha7d93782016-12-01 03:32:42 +00002550 PTI_ContainingClassIncomplete = 0x10,
2551
2552 /// PTI_TransactionSafe - Pointee is transaction_safe function (C++ TM TS).
2553 //PTI_TransactionSafe = 0x20,
2554
2555 /// PTI_Noexcept - Pointee is noexcept function (C++1z).
2556 PTI_Noexcept = 0x40,
David Majnemere2cb8d12014-07-07 06:20:47 +00002557 };
2558
2559 // VMI type info flags.
2560 enum {
2561 /// VMI_NonDiamondRepeat - Class has non-diamond repeated inheritance.
2562 VMI_NonDiamondRepeat = 0x1,
2563
2564 /// VMI_DiamondShaped - Class is diamond shaped.
2565 VMI_DiamondShaped = 0x2
2566 };
2567
2568 // Base class type info flags.
2569 enum {
2570 /// BCTI_Virtual - Base class is virtual.
2571 BCTI_Virtual = 0x1,
2572
2573 /// BCTI_Public - Base class is public.
2574 BCTI_Public = 0x2
2575 };
2576
2577 /// BuildTypeInfo - Build the RTTI type info struct for the given type.
2578 ///
2579 /// \param Force - true to force the creation of this RTTI value
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00002580 /// \param DLLExport - true to mark the RTTI value as DLLExport
2581 llvm::Constant *BuildTypeInfo(QualType Ty, bool Force = false,
2582 bool DLLExport = false);
David Majnemere2cb8d12014-07-07 06:20:47 +00002583};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002584}
David Majnemere2cb8d12014-07-07 06:20:47 +00002585
2586llvm::GlobalVariable *ItaniumRTTIBuilder::GetAddrOfTypeName(
2587 QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage) {
Yaron Kerene46f7ed2015-07-29 14:21:47 +00002588 SmallString<256> Name;
2589 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00002590 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00002591
2592 // We know that the mangled name of the type starts at index 4 of the
2593 // mangled name of the typename, so we can just index into it in order to
2594 // get the mangled name of the type.
2595 llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,
2596 Name.substr(4));
2597
2598 llvm::GlobalVariable *GV =
2599 CGM.CreateOrReplaceCXXRuntimeVariable(Name, Init->getType(), Linkage);
2600
2601 GV->setInitializer(Init);
2602
2603 return GV;
2604}
2605
2606llvm::Constant *
2607ItaniumRTTIBuilder::GetAddrOfExternalRTTIDescriptor(QualType Ty) {
2608 // Mangle the RTTI name.
Yaron Kerene46f7ed2015-07-29 14:21:47 +00002609 SmallString<256> Name;
2610 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00002611 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00002612
2613 // Look for an existing global.
2614 llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name);
2615
2616 if (!GV) {
2617 // Create a new global variable.
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +00002618 // Note for the future: If we would ever like to do deferred emission of
2619 // RTTI, check if emitting vtables opportunistically need any adjustment.
2620
David Majnemere2cb8d12014-07-07 06:20:47 +00002621 GV = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
2622 /*Constant=*/true,
2623 llvm::GlobalValue::ExternalLinkage, nullptr,
2624 Name);
David Majnemer1fb1a042014-11-07 07:26:38 +00002625 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2626 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
2627 if (RD->hasAttr<DLLImportAttr>())
2628 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
2629 }
David Majnemere2cb8d12014-07-07 06:20:47 +00002630 }
2631
2632 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
2633}
2634
2635/// TypeInfoIsInStandardLibrary - Given a builtin type, returns whether the type
2636/// info for that type is defined in the standard library.
2637static bool TypeInfoIsInStandardLibrary(const BuiltinType *Ty) {
2638 // Itanium C++ ABI 2.9.2:
2639 // Basic type information (e.g. for "int", "bool", etc.) will be kept in
2640 // the run-time support library. Specifically, the run-time support
2641 // library should contain type_info objects for the types X, X* and
2642 // X const*, for every X in: void, std::nullptr_t, bool, wchar_t, char,
2643 // unsigned char, signed char, short, unsigned short, int, unsigned int,
2644 // long, unsigned long, long long, unsigned long long, float, double,
2645 // long double, char16_t, char32_t, and the IEEE 754r decimal and
2646 // half-precision floating point types.
Richard Smith4a382012016-02-03 01:32:42 +00002647 //
2648 // GCC also emits RTTI for __int128.
2649 // FIXME: We do not emit RTTI information for decimal types here.
2650
2651 // Types added here must also be added to EmitFundamentalRTTIDescriptors.
David Majnemere2cb8d12014-07-07 06:20:47 +00002652 switch (Ty->getKind()) {
2653 case BuiltinType::Void:
2654 case BuiltinType::NullPtr:
2655 case BuiltinType::Bool:
2656 case BuiltinType::WChar_S:
2657 case BuiltinType::WChar_U:
2658 case BuiltinType::Char_U:
2659 case BuiltinType::Char_S:
2660 case BuiltinType::UChar:
2661 case BuiltinType::SChar:
2662 case BuiltinType::Short:
2663 case BuiltinType::UShort:
2664 case BuiltinType::Int:
2665 case BuiltinType::UInt:
2666 case BuiltinType::Long:
2667 case BuiltinType::ULong:
2668 case BuiltinType::LongLong:
2669 case BuiltinType::ULongLong:
2670 case BuiltinType::Half:
2671 case BuiltinType::Float:
2672 case BuiltinType::Double:
2673 case BuiltinType::LongDouble:
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00002674 case BuiltinType::Float16:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002675 case BuiltinType::Float128:
David Majnemere2cb8d12014-07-07 06:20:47 +00002676 case BuiltinType::Char16:
2677 case BuiltinType::Char32:
2678 case BuiltinType::Int128:
2679 case BuiltinType::UInt128:
Richard Smith4a382012016-02-03 01:32:42 +00002680 return true;
2681
Alexey Bader954ba212016-04-08 13:40:33 +00002682#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2683 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00002684#include "clang/Basic/OpenCLImageTypes.def"
David Majnemere2cb8d12014-07-07 06:20:47 +00002685 case BuiltinType::OCLSampler:
2686 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00002687 case BuiltinType::OCLClkEvent:
2688 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00002689 case BuiltinType::OCLReserveID:
Richard Smith4a382012016-02-03 01:32:42 +00002690 return false;
David Majnemere2cb8d12014-07-07 06:20:47 +00002691
2692 case BuiltinType::Dependent:
2693#define BUILTIN_TYPE(Id, SingletonId)
2694#define PLACEHOLDER_TYPE(Id, SingletonId) \
2695 case BuiltinType::Id:
2696#include "clang/AST/BuiltinTypes.def"
2697 llvm_unreachable("asking for RRTI for a placeholder type!");
2698
2699 case BuiltinType::ObjCId:
2700 case BuiltinType::ObjCClass:
2701 case BuiltinType::ObjCSel:
2702 llvm_unreachable("FIXME: Objective-C types are unsupported!");
2703 }
2704
2705 llvm_unreachable("Invalid BuiltinType Kind!");
2706}
2707
2708static bool TypeInfoIsInStandardLibrary(const PointerType *PointerTy) {
2709 QualType PointeeTy = PointerTy->getPointeeType();
2710 const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(PointeeTy);
2711 if (!BuiltinTy)
2712 return false;
2713
2714 // Check the qualifiers.
2715 Qualifiers Quals = PointeeTy.getQualifiers();
2716 Quals.removeConst();
2717
2718 if (!Quals.empty())
2719 return false;
2720
2721 return TypeInfoIsInStandardLibrary(BuiltinTy);
2722}
2723
2724/// IsStandardLibraryRTTIDescriptor - Returns whether the type
2725/// information for the given type exists in the standard library.
2726static bool IsStandardLibraryRTTIDescriptor(QualType Ty) {
2727 // Type info for builtin types is defined in the standard library.
2728 if (const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(Ty))
2729 return TypeInfoIsInStandardLibrary(BuiltinTy);
2730
2731 // Type info for some pointer types to builtin types is defined in the
2732 // standard library.
2733 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2734 return TypeInfoIsInStandardLibrary(PointerTy);
2735
2736 return false;
2737}
2738
2739/// ShouldUseExternalRTTIDescriptor - Returns whether the type information for
2740/// the given type exists somewhere else, and that we should not emit the type
2741/// information in this translation unit. Assumes that it is not a
2742/// standard-library type.
2743static bool ShouldUseExternalRTTIDescriptor(CodeGenModule &CGM,
2744 QualType Ty) {
2745 ASTContext &Context = CGM.getContext();
2746
2747 // If RTTI is disabled, assume it might be disabled in the
2748 // translation unit that defines any potential key function, too.
2749 if (!Context.getLangOpts().RTTI) return false;
2750
2751 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2752 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
2753 if (!RD->hasDefinition())
2754 return false;
2755
2756 if (!RD->isDynamicClass())
2757 return false;
2758
2759 // FIXME: this may need to be reconsidered if the key function
2760 // changes.
David Majnemerbe9022c2015-08-06 20:56:55 +00002761 // N.B. We must always emit the RTTI data ourselves if there exists a key
2762 // function.
2763 bool IsDLLImport = RD->hasAttr<DLLImportAttr>();
Martin Storsjo3b528942018-02-02 06:22:35 +00002764
2765 // Don't import the RTTI but emit it locally.
2766 if (CGM.getTriple().isWindowsGNUEnvironment() && IsDLLImport)
2767 return false;
2768
David Majnemer1fb1a042014-11-07 07:26:38 +00002769 if (CGM.getVTables().isVTableExternal(RD))
Shoaib Meenai61118e72017-07-04 01:02:19 +00002770 return IsDLLImport && !CGM.getTriple().isWindowsItaniumEnvironment()
2771 ? false
2772 : true;
David Majnemer1fb1a042014-11-07 07:26:38 +00002773
David Majnemerbe9022c2015-08-06 20:56:55 +00002774 if (IsDLLImport)
David Majnemer1fb1a042014-11-07 07:26:38 +00002775 return true;
David Majnemere2cb8d12014-07-07 06:20:47 +00002776 }
2777
2778 return false;
2779}
2780
2781/// IsIncompleteClassType - Returns whether the given record type is incomplete.
2782static bool IsIncompleteClassType(const RecordType *RecordTy) {
2783 return !RecordTy->getDecl()->isCompleteDefinition();
2784}
2785
2786/// ContainsIncompleteClassType - Returns whether the given type contains an
2787/// incomplete class type. This is true if
2788///
2789/// * The given type is an incomplete class type.
2790/// * The given type is a pointer type whose pointee type contains an
2791/// incomplete class type.
2792/// * The given type is a member pointer type whose class is an incomplete
2793/// class type.
2794/// * The given type is a member pointer type whoise pointee type contains an
2795/// incomplete class type.
2796/// is an indirect or direct pointer to an incomplete class type.
2797static bool ContainsIncompleteClassType(QualType Ty) {
2798 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2799 if (IsIncompleteClassType(RecordTy))
2800 return true;
2801 }
2802
2803 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2804 return ContainsIncompleteClassType(PointerTy->getPointeeType());
2805
2806 if (const MemberPointerType *MemberPointerTy =
2807 dyn_cast<MemberPointerType>(Ty)) {
2808 // Check if the class type is incomplete.
2809 const RecordType *ClassType = cast<RecordType>(MemberPointerTy->getClass());
2810 if (IsIncompleteClassType(ClassType))
2811 return true;
2812
2813 return ContainsIncompleteClassType(MemberPointerTy->getPointeeType());
2814 }
2815
2816 return false;
2817}
2818
2819// CanUseSingleInheritance - Return whether the given record decl has a "single,
2820// public, non-virtual base at offset zero (i.e. the derived class is dynamic
2821// iff the base is)", according to Itanium C++ ABI, 2.95p6b.
2822static bool CanUseSingleInheritance(const CXXRecordDecl *RD) {
2823 // Check the number of bases.
2824 if (RD->getNumBases() != 1)
2825 return false;
2826
2827 // Get the base.
2828 CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin();
2829
2830 // Check that the base is not virtual.
2831 if (Base->isVirtual())
2832 return false;
2833
2834 // Check that the base is public.
2835 if (Base->getAccessSpecifier() != AS_public)
2836 return false;
2837
2838 // Check that the class is dynamic iff the base is.
2839 const CXXRecordDecl *BaseDecl =
2840 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2841 if (!BaseDecl->isEmpty() &&
2842 BaseDecl->isDynamicClass() != RD->isDynamicClass())
2843 return false;
2844
2845 return true;
2846}
2847
2848void ItaniumRTTIBuilder::BuildVTablePointer(const Type *Ty) {
2849 // abi::__class_type_info.
2850 static const char * const ClassTypeInfo =
2851 "_ZTVN10__cxxabiv117__class_type_infoE";
2852 // abi::__si_class_type_info.
2853 static const char * const SIClassTypeInfo =
2854 "_ZTVN10__cxxabiv120__si_class_type_infoE";
2855 // abi::__vmi_class_type_info.
2856 static const char * const VMIClassTypeInfo =
2857 "_ZTVN10__cxxabiv121__vmi_class_type_infoE";
2858
2859 const char *VTableName = nullptr;
2860
2861 switch (Ty->getTypeClass()) {
2862#define TYPE(Class, Base)
2863#define ABSTRACT_TYPE(Class, Base)
2864#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2865#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2866#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2867#include "clang/AST/TypeNodes.def"
2868 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
2869
2870 case Type::LValueReference:
2871 case Type::RValueReference:
2872 llvm_unreachable("References shouldn't get here");
2873
2874 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00002875 case Type::DeducedTemplateSpecialization:
2876 llvm_unreachable("Undeduced type shouldn't get here");
David Majnemere2cb8d12014-07-07 06:20:47 +00002877
Xiuli Pan9c14e282016-01-09 12:53:17 +00002878 case Type::Pipe:
2879 llvm_unreachable("Pipe types shouldn't get here");
2880
David Majnemere2cb8d12014-07-07 06:20:47 +00002881 case Type::Builtin:
2882 // GCC treats vector and complex types as fundamental types.
2883 case Type::Vector:
2884 case Type::ExtVector:
2885 case Type::Complex:
2886 case Type::Atomic:
2887 // FIXME: GCC treats block pointers as fundamental types?!
2888 case Type::BlockPointer:
2889 // abi::__fundamental_type_info.
2890 VTableName = "_ZTVN10__cxxabiv123__fundamental_type_infoE";
2891 break;
2892
2893 case Type::ConstantArray:
2894 case Type::IncompleteArray:
2895 case Type::VariableArray:
2896 // abi::__array_type_info.
2897 VTableName = "_ZTVN10__cxxabiv117__array_type_infoE";
2898 break;
2899
2900 case Type::FunctionNoProto:
2901 case Type::FunctionProto:
Richard Smithb17d6fa2016-12-01 03:04:07 +00002902 // abi::__function_type_info.
2903 VTableName = "_ZTVN10__cxxabiv120__function_type_infoE";
David Majnemere2cb8d12014-07-07 06:20:47 +00002904 break;
2905
2906 case Type::Enum:
2907 // abi::__enum_type_info.
2908 VTableName = "_ZTVN10__cxxabiv116__enum_type_infoE";
2909 break;
2910
2911 case Type::Record: {
2912 const CXXRecordDecl *RD =
2913 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
2914
2915 if (!RD->hasDefinition() || !RD->getNumBases()) {
2916 VTableName = ClassTypeInfo;
2917 } else if (CanUseSingleInheritance(RD)) {
2918 VTableName = SIClassTypeInfo;
2919 } else {
2920 VTableName = VMIClassTypeInfo;
2921 }
2922
2923 break;
2924 }
2925
2926 case Type::ObjCObject:
2927 // Ignore protocol qualifiers.
2928 Ty = cast<ObjCObjectType>(Ty)->getBaseType().getTypePtr();
2929
2930 // Handle id and Class.
2931 if (isa<BuiltinType>(Ty)) {
2932 VTableName = ClassTypeInfo;
2933 break;
2934 }
2935
2936 assert(isa<ObjCInterfaceType>(Ty));
2937 // Fall through.
2938
2939 case Type::ObjCInterface:
2940 if (cast<ObjCInterfaceType>(Ty)->getDecl()->getSuperClass()) {
2941 VTableName = SIClassTypeInfo;
2942 } else {
2943 VTableName = ClassTypeInfo;
2944 }
2945 break;
2946
2947 case Type::ObjCObjectPointer:
2948 case Type::Pointer:
2949 // abi::__pointer_type_info.
2950 VTableName = "_ZTVN10__cxxabiv119__pointer_type_infoE";
2951 break;
2952
2953 case Type::MemberPointer:
2954 // abi::__pointer_to_member_type_info.
2955 VTableName = "_ZTVN10__cxxabiv129__pointer_to_member_type_infoE";
2956 break;
2957 }
2958
2959 llvm::Constant *VTable =
2960 CGM.getModule().getOrInsertGlobal(VTableName, CGM.Int8PtrTy);
2961
2962 llvm::Type *PtrDiffTy =
2963 CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
2964
2965 // The vtable address point is 2.
2966 llvm::Constant *Two = llvm::ConstantInt::get(PtrDiffTy, 2);
David Blaikiee3b172a2015-04-02 18:55:21 +00002967 VTable =
2968 llvm::ConstantExpr::getInBoundsGetElementPtr(CGM.Int8PtrTy, VTable, Two);
David Majnemere2cb8d12014-07-07 06:20:47 +00002969 VTable = llvm::ConstantExpr::getBitCast(VTable, CGM.Int8PtrTy);
2970
2971 Fields.push_back(VTable);
2972}
2973
2974/// \brief Return the linkage that the type info and type info name constants
2975/// should have for the given type.
2976static llvm::GlobalVariable::LinkageTypes getTypeInfoLinkage(CodeGenModule &CGM,
2977 QualType Ty) {
2978 // Itanium C++ ABI 2.9.5p7:
2979 // In addition, it and all of the intermediate abi::__pointer_type_info
2980 // structs in the chain down to the abi::__class_type_info for the
2981 // incomplete class type must be prevented from resolving to the
2982 // corresponding type_info structs for the complete class type, possibly
2983 // by making them local static objects. Finally, a dummy class RTTI is
2984 // generated for the incomplete type that will not resolve to the final
2985 // complete class RTTI (because the latter need not exist), possibly by
2986 // making it a local static object.
2987 if (ContainsIncompleteClassType(Ty))
2988 return llvm::GlobalValue::InternalLinkage;
2989
2990 switch (Ty->getLinkage()) {
2991 case NoLinkage:
2992 case InternalLinkage:
2993 case UniqueExternalLinkage:
2994 return llvm::GlobalValue::InternalLinkage;
2995
2996 case VisibleNoLinkage:
Richard Smith1283e982017-07-07 20:04:28 +00002997 case ModuleInternalLinkage:
2998 case ModuleLinkage:
David Majnemere2cb8d12014-07-07 06:20:47 +00002999 case ExternalLinkage:
Saleem Abdulrasool18820022016-12-02 22:46:18 +00003000 // RTTI is not enabled, which means that this type info struct is going
3001 // to be used for exception handling. Give it linkonce_odr linkage.
3002 if (!CGM.getLangOpts().RTTI)
David Majnemere2cb8d12014-07-07 06:20:47 +00003003 return llvm::GlobalValue::LinkOnceODRLinkage;
David Majnemere2cb8d12014-07-07 06:20:47 +00003004
3005 if (const RecordType *Record = dyn_cast<RecordType>(Ty)) {
3006 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
3007 if (RD->hasAttr<WeakAttr>())
3008 return llvm::GlobalValue::WeakODRLinkage;
Saleem Abdulrasool18820022016-12-02 22:46:18 +00003009 if (CGM.getTriple().isWindowsItaniumEnvironment())
Shoaib Meenai61118e72017-07-04 01:02:19 +00003010 if (RD->hasAttr<DLLImportAttr>() &&
3011 ShouldUseExternalRTTIDescriptor(CGM, Ty))
Saleem Abdulrasool18820022016-12-02 22:46:18 +00003012 return llvm::GlobalValue::ExternalLinkage;
Martin Storsjoc6c5af72017-09-01 06:41:55 +00003013 // MinGW always uses LinkOnceODRLinkage for type info.
3014 if (RD->isDynamicClass() &&
3015 !CGM.getContext()
3016 .getTargetInfo()
3017 .getTriple()
3018 .isWindowsGNUEnvironment())
3019 return CGM.getVTableLinkage(RD);
David Majnemere2cb8d12014-07-07 06:20:47 +00003020 }
3021
3022 return llvm::GlobalValue::LinkOnceODRLinkage;
3023 }
3024
3025 llvm_unreachable("Invalid linkage!");
3026}
3027
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00003028llvm::Constant *ItaniumRTTIBuilder::BuildTypeInfo(QualType Ty, bool Force,
3029 bool DLLExport) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003030 // We want to operate on the canonical type.
Yaron Kerenebd14262016-03-16 12:14:43 +00003031 Ty = Ty.getCanonicalType();
David Majnemere2cb8d12014-07-07 06:20:47 +00003032
3033 // Check if we've already emitted an RTTI descriptor for this type.
Yaron Kerene46f7ed2015-07-29 14:21:47 +00003034 SmallString<256> Name;
3035 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00003036 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00003037
3038 llvm::GlobalVariable *OldGV = CGM.getModule().getNamedGlobal(Name);
3039 if (OldGV && !OldGV->isDeclaration()) {
3040 assert(!OldGV->hasAvailableExternallyLinkage() &&
3041 "available_externally typeinfos not yet implemented");
3042
3043 return llvm::ConstantExpr::getBitCast(OldGV, CGM.Int8PtrTy);
3044 }
3045
3046 // Check if there is already an external RTTI descriptor for this type.
3047 bool IsStdLib = IsStandardLibraryRTTIDescriptor(Ty);
3048 if (!Force && (IsStdLib || ShouldUseExternalRTTIDescriptor(CGM, Ty)))
3049 return GetAddrOfExternalRTTIDescriptor(Ty);
3050
3051 // Emit the standard library with external linkage.
3052 llvm::GlobalVariable::LinkageTypes Linkage;
3053 if (IsStdLib)
3054 Linkage = llvm::GlobalValue::ExternalLinkage;
3055 else
3056 Linkage = getTypeInfoLinkage(CGM, Ty);
3057
3058 // Add the vtable pointer.
3059 BuildVTablePointer(cast<Type>(Ty));
3060
3061 // And the name.
3062 llvm::GlobalVariable *TypeName = GetAddrOfTypeName(Ty, Linkage);
3063 llvm::Constant *TypeNameField;
3064
3065 // If we're supposed to demote the visibility, be sure to set a flag
3066 // to use a string comparison for type_info comparisons.
3067 ItaniumCXXABI::RTTIUniquenessKind RTTIUniqueness =
3068 CXXABI.classifyRTTIUniqueness(Ty, Linkage);
3069 if (RTTIUniqueness != ItaniumCXXABI::RUK_Unique) {
3070 // The flag is the sign bit, which on ARM64 is defined to be clear
3071 // for global pointers. This is very ARM64-specific.
3072 TypeNameField = llvm::ConstantExpr::getPtrToInt(TypeName, CGM.Int64Ty);
3073 llvm::Constant *flag =
3074 llvm::ConstantInt::get(CGM.Int64Ty, ((uint64_t)1) << 63);
3075 TypeNameField = llvm::ConstantExpr::getAdd(TypeNameField, flag);
3076 TypeNameField =
3077 llvm::ConstantExpr::getIntToPtr(TypeNameField, CGM.Int8PtrTy);
3078 } else {
3079 TypeNameField = llvm::ConstantExpr::getBitCast(TypeName, CGM.Int8PtrTy);
3080 }
3081 Fields.push_back(TypeNameField);
3082
3083 switch (Ty->getTypeClass()) {
3084#define TYPE(Class, Base)
3085#define ABSTRACT_TYPE(Class, Base)
3086#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
3087#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3088#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3089#include "clang/AST/TypeNodes.def"
3090 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
3091
3092 // GCC treats vector types as fundamental types.
3093 case Type::Builtin:
3094 case Type::Vector:
3095 case Type::ExtVector:
3096 case Type::Complex:
3097 case Type::BlockPointer:
3098 // Itanium C++ ABI 2.9.5p4:
3099 // abi::__fundamental_type_info adds no data members to std::type_info.
3100 break;
3101
3102 case Type::LValueReference:
3103 case Type::RValueReference:
3104 llvm_unreachable("References shouldn't get here");
3105
3106 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00003107 case Type::DeducedTemplateSpecialization:
3108 llvm_unreachable("Undeduced type shouldn't get here");
David Majnemere2cb8d12014-07-07 06:20:47 +00003109
Xiuli Pan9c14e282016-01-09 12:53:17 +00003110 case Type::Pipe:
3111 llvm_unreachable("Pipe type shouldn't get here");
3112
David Majnemere2cb8d12014-07-07 06:20:47 +00003113 case Type::ConstantArray:
3114 case Type::IncompleteArray:
3115 case Type::VariableArray:
3116 // Itanium C++ ABI 2.9.5p5:
3117 // abi::__array_type_info adds no data members to std::type_info.
3118 break;
3119
3120 case Type::FunctionNoProto:
Richard Smithb17d6fa2016-12-01 03:04:07 +00003121 case Type::FunctionProto:
David Majnemere2cb8d12014-07-07 06:20:47 +00003122 // Itanium C++ ABI 2.9.5p5:
3123 // abi::__function_type_info adds no data members to std::type_info.
3124 break;
3125
3126 case Type::Enum:
3127 // Itanium C++ ABI 2.9.5p5:
3128 // abi::__enum_type_info adds no data members to std::type_info.
3129 break;
3130
3131 case Type::Record: {
3132 const CXXRecordDecl *RD =
3133 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
3134 if (!RD->hasDefinition() || !RD->getNumBases()) {
3135 // We don't need to emit any fields.
3136 break;
3137 }
3138
3139 if (CanUseSingleInheritance(RD))
3140 BuildSIClassTypeInfo(RD);
3141 else
3142 BuildVMIClassTypeInfo(RD);
3143
3144 break;
3145 }
3146
3147 case Type::ObjCObject:
3148 case Type::ObjCInterface:
3149 BuildObjCObjectTypeInfo(cast<ObjCObjectType>(Ty));
3150 break;
3151
3152 case Type::ObjCObjectPointer:
3153 BuildPointerTypeInfo(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
3154 break;
3155
3156 case Type::Pointer:
3157 BuildPointerTypeInfo(cast<PointerType>(Ty)->getPointeeType());
3158 break;
3159
3160 case Type::MemberPointer:
3161 BuildPointerToMemberTypeInfo(cast<MemberPointerType>(Ty));
3162 break;
3163
3164 case Type::Atomic:
3165 // No fields, at least for the moment.
3166 break;
3167 }
3168
3169 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Fields);
3170
Rafael Espindolacb92c192015-01-15 23:18:01 +00003171 llvm::Module &M = CGM.getModule();
David Majnemere2cb8d12014-07-07 06:20:47 +00003172 llvm::GlobalVariable *GV =
Rafael Espindolacb92c192015-01-15 23:18:01 +00003173 new llvm::GlobalVariable(M, Init->getType(),
3174 /*Constant=*/true, Linkage, Init, Name);
3175
David Majnemere2cb8d12014-07-07 06:20:47 +00003176 // If there's already an old global variable, replace it with the new one.
3177 if (OldGV) {
3178 GV->takeName(OldGV);
3179 llvm::Constant *NewPtr =
3180 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
3181 OldGV->replaceAllUsesWith(NewPtr);
3182 OldGV->eraseFromParent();
3183 }
3184
Yaron Keren04da2382015-07-29 15:42:28 +00003185 if (CGM.supportsCOMDAT() && GV->isWeakForLinker())
3186 GV->setComdat(M.getOrInsertComdat(GV->getName()));
3187
David Majnemere2cb8d12014-07-07 06:20:47 +00003188 // The Itanium ABI specifies that type_info objects must be globally
3189 // unique, with one exception: if the type is an incomplete class
3190 // type or a (possibly indirect) pointer to one. That exception
3191 // affects the general case of comparing type_info objects produced
3192 // by the typeid operator, which is why the comparison operators on
3193 // std::type_info generally use the type_info name pointers instead
3194 // of the object addresses. However, the language's built-in uses
3195 // of RTTI generally require class types to be complete, even when
3196 // manipulating pointers to those class types. This allows the
3197 // implementation of dynamic_cast to rely on address equality tests,
3198 // which is much faster.
3199
3200 // All of this is to say that it's important that both the type_info
3201 // object and the type_info name be uniqued when weakly emitted.
3202
3203 // Give the type_info object and name the formal visibility of the
3204 // type itself.
3205 llvm::GlobalValue::VisibilityTypes llvmVisibility;
3206 if (llvm::GlobalValue::isLocalLinkage(Linkage))
3207 // If the linkage is local, only default visibility makes sense.
3208 llvmVisibility = llvm::GlobalValue::DefaultVisibility;
3209 else if (RTTIUniqueness == ItaniumCXXABI::RUK_NonUniqueHidden)
3210 llvmVisibility = llvm::GlobalValue::HiddenVisibility;
3211 else
3212 llvmVisibility = CodeGenModule::GetLLVMVisibility(Ty->getVisibility());
Saleem Abdulrasool18820022016-12-02 22:46:18 +00003213
David Majnemere2cb8d12014-07-07 06:20:47 +00003214 TypeName->setVisibility(llvmVisibility);
3215 GV->setVisibility(llvmVisibility);
Saleem Abdulrasool18820022016-12-02 22:46:18 +00003216
3217 if (CGM.getTriple().isWindowsItaniumEnvironment()) {
3218 auto RD = Ty->getAsCXXRecordDecl();
3219 if (DLLExport || (RD && RD->hasAttr<DLLExportAttr>())) {
3220 TypeName->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
3221 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
Shoaib Meenai61118e72017-07-04 01:02:19 +00003222 } else if (RD && RD->hasAttr<DLLImportAttr>() &&
3223 ShouldUseExternalRTTIDescriptor(CGM, Ty)) {
Saleem Abdulrasool18820022016-12-02 22:46:18 +00003224 TypeName->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
3225 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
3226
3227 // Because the typename and the typeinfo are DLL import, convert them to
3228 // declarations rather than definitions. The initializers still need to
3229 // be constructed to calculate the type for the declarations.
3230 TypeName->setInitializer(nullptr);
3231 GV->setInitializer(nullptr);
3232 }
3233 }
David Majnemere2cb8d12014-07-07 06:20:47 +00003234
3235 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
3236}
3237
David Majnemere2cb8d12014-07-07 06:20:47 +00003238/// BuildObjCObjectTypeInfo - Build the appropriate kind of type_info
3239/// for the given Objective-C object type.
3240void ItaniumRTTIBuilder::BuildObjCObjectTypeInfo(const ObjCObjectType *OT) {
3241 // Drop qualifiers.
3242 const Type *T = OT->getBaseType().getTypePtr();
3243 assert(isa<BuiltinType>(T) || isa<ObjCInterfaceType>(T));
3244
3245 // The builtin types are abi::__class_type_infos and don't require
3246 // extra fields.
3247 if (isa<BuiltinType>(T)) return;
3248
3249 ObjCInterfaceDecl *Class = cast<ObjCInterfaceType>(T)->getDecl();
3250 ObjCInterfaceDecl *Super = Class->getSuperClass();
3251
3252 // Root classes are also __class_type_info.
3253 if (!Super) return;
3254
3255 QualType SuperTy = CGM.getContext().getObjCInterfaceType(Super);
3256
3257 // Everything else is single inheritance.
3258 llvm::Constant *BaseTypeInfo =
3259 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(SuperTy);
3260 Fields.push_back(BaseTypeInfo);
3261}
3262
3263/// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
3264/// inheritance, according to the Itanium C++ ABI, 2.95p6b.
3265void ItaniumRTTIBuilder::BuildSIClassTypeInfo(const CXXRecordDecl *RD) {
3266 // Itanium C++ ABI 2.9.5p6b:
3267 // It adds to abi::__class_type_info a single member pointing to the
3268 // type_info structure for the base type,
3269 llvm::Constant *BaseTypeInfo =
3270 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(RD->bases_begin()->getType());
3271 Fields.push_back(BaseTypeInfo);
3272}
3273
3274namespace {
3275 /// SeenBases - Contains virtual and non-virtual bases seen when traversing
3276 /// a class hierarchy.
3277 struct SeenBases {
3278 llvm::SmallPtrSet<const CXXRecordDecl *, 16> NonVirtualBases;
3279 llvm::SmallPtrSet<const CXXRecordDecl *, 16> VirtualBases;
3280 };
3281}
3282
3283/// ComputeVMIClassTypeInfoFlags - Compute the value of the flags member in
3284/// abi::__vmi_class_type_info.
3285///
3286static unsigned ComputeVMIClassTypeInfoFlags(const CXXBaseSpecifier *Base,
3287 SeenBases &Bases) {
3288
3289 unsigned Flags = 0;
3290
3291 const CXXRecordDecl *BaseDecl =
3292 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
3293
3294 if (Base->isVirtual()) {
3295 // Mark the virtual base as seen.
David Blaikie82e95a32014-11-19 07:49:47 +00003296 if (!Bases.VirtualBases.insert(BaseDecl).second) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003297 // If this virtual base has been seen before, then the class is diamond
3298 // shaped.
3299 Flags |= ItaniumRTTIBuilder::VMI_DiamondShaped;
3300 } else {
3301 if (Bases.NonVirtualBases.count(BaseDecl))
3302 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3303 }
3304 } else {
3305 // Mark the non-virtual base as seen.
David Blaikie82e95a32014-11-19 07:49:47 +00003306 if (!Bases.NonVirtualBases.insert(BaseDecl).second) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003307 // If this non-virtual base has been seen before, then the class has non-
3308 // diamond shaped repeated inheritance.
3309 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3310 } else {
3311 if (Bases.VirtualBases.count(BaseDecl))
3312 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3313 }
3314 }
3315
3316 // Walk all bases.
3317 for (const auto &I : BaseDecl->bases())
3318 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
3319
3320 return Flags;
3321}
3322
3323static unsigned ComputeVMIClassTypeInfoFlags(const CXXRecordDecl *RD) {
3324 unsigned Flags = 0;
3325 SeenBases Bases;
3326
3327 // Walk all bases.
3328 for (const auto &I : RD->bases())
3329 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
3330
3331 return Flags;
3332}
3333
3334/// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
3335/// classes with bases that do not satisfy the abi::__si_class_type_info
3336/// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
3337void ItaniumRTTIBuilder::BuildVMIClassTypeInfo(const CXXRecordDecl *RD) {
3338 llvm::Type *UnsignedIntLTy =
3339 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3340
3341 // Itanium C++ ABI 2.9.5p6c:
3342 // __flags is a word with flags describing details about the class
3343 // structure, which may be referenced by using the __flags_masks
3344 // enumeration. These flags refer to both direct and indirect bases.
3345 unsigned Flags = ComputeVMIClassTypeInfoFlags(RD);
3346 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3347
3348 // Itanium C++ ABI 2.9.5p6c:
3349 // __base_count is a word with the number of direct proper base class
3350 // descriptions that follow.
3351 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, RD->getNumBases()));
3352
3353 if (!RD->getNumBases())
3354 return;
3355
David Majnemere2cb8d12014-07-07 06:20:47 +00003356 // Now add the base class descriptions.
3357
3358 // Itanium C++ ABI 2.9.5p6c:
3359 // __base_info[] is an array of base class descriptions -- one for every
3360 // direct proper base. Each description is of the type:
3361 //
3362 // struct abi::__base_class_type_info {
3363 // public:
3364 // const __class_type_info *__base_type;
3365 // long __offset_flags;
3366 //
3367 // enum __offset_flags_masks {
3368 // __virtual_mask = 0x1,
3369 // __public_mask = 0x2,
3370 // __offset_shift = 8
3371 // };
3372 // };
Reid Klecknerd8b04662016-08-25 22:16:30 +00003373
3374 // If we're in mingw and 'long' isn't wide enough for a pointer, use 'long
3375 // long' instead of 'long' for __offset_flags. libstdc++abi uses long long on
3376 // LLP64 platforms.
3377 // FIXME: Consider updating libc++abi to match, and extend this logic to all
3378 // LLP64 platforms.
3379 QualType OffsetFlagsTy = CGM.getContext().LongTy;
3380 const TargetInfo &TI = CGM.getContext().getTargetInfo();
3381 if (TI.getTriple().isOSCygMing() && TI.getPointerWidth(0) > TI.getLongWidth())
3382 OffsetFlagsTy = CGM.getContext().LongLongTy;
3383 llvm::Type *OffsetFlagsLTy =
3384 CGM.getTypes().ConvertType(OffsetFlagsTy);
3385
David Majnemere2cb8d12014-07-07 06:20:47 +00003386 for (const auto &Base : RD->bases()) {
3387 // The __base_type member points to the RTTI for the base type.
3388 Fields.push_back(ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(Base.getType()));
3389
3390 const CXXRecordDecl *BaseDecl =
3391 cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
3392
3393 int64_t OffsetFlags = 0;
3394
3395 // All but the lower 8 bits of __offset_flags are a signed offset.
3396 // For a non-virtual base, this is the offset in the object of the base
3397 // subobject. For a virtual base, this is the offset in the virtual table of
3398 // the virtual base offset for the virtual base referenced (negative).
3399 CharUnits Offset;
3400 if (Base.isVirtual())
3401 Offset =
3402 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(RD, BaseDecl);
3403 else {
3404 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
3405 Offset = Layout.getBaseClassOffset(BaseDecl);
3406 };
3407
3408 OffsetFlags = uint64_t(Offset.getQuantity()) << 8;
3409
3410 // The low-order byte of __offset_flags contains flags, as given by the
3411 // masks from the enumeration __offset_flags_masks.
3412 if (Base.isVirtual())
3413 OffsetFlags |= BCTI_Virtual;
3414 if (Base.getAccessSpecifier() == AS_public)
3415 OffsetFlags |= BCTI_Public;
3416
Reid Klecknerd8b04662016-08-25 22:16:30 +00003417 Fields.push_back(llvm::ConstantInt::get(OffsetFlagsLTy, OffsetFlags));
David Majnemere2cb8d12014-07-07 06:20:47 +00003418 }
3419}
3420
Richard Smitha7d93782016-12-01 03:32:42 +00003421/// Compute the flags for a __pbase_type_info, and remove the corresponding
3422/// pieces from \p Type.
3423static unsigned extractPBaseFlags(ASTContext &Ctx, QualType &Type) {
3424 unsigned Flags = 0;
David Majnemere2cb8d12014-07-07 06:20:47 +00003425
Richard Smitha7d93782016-12-01 03:32:42 +00003426 if (Type.isConstQualified())
3427 Flags |= ItaniumRTTIBuilder::PTI_Const;
3428 if (Type.isVolatileQualified())
3429 Flags |= ItaniumRTTIBuilder::PTI_Volatile;
3430 if (Type.isRestrictQualified())
3431 Flags |= ItaniumRTTIBuilder::PTI_Restrict;
3432 Type = Type.getUnqualifiedType();
David Majnemere2cb8d12014-07-07 06:20:47 +00003433
3434 // Itanium C++ ABI 2.9.5p7:
3435 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
3436 // incomplete class type, the incomplete target type flag is set.
Richard Smitha7d93782016-12-01 03:32:42 +00003437 if (ContainsIncompleteClassType(Type))
3438 Flags |= ItaniumRTTIBuilder::PTI_Incomplete;
3439
3440 if (auto *Proto = Type->getAs<FunctionProtoType>()) {
3441 if (Proto->isNothrow(Ctx)) {
3442 Flags |= ItaniumRTTIBuilder::PTI_Noexcept;
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00003443 Type = Ctx.getFunctionTypeWithExceptionSpec(Type, EST_None);
Richard Smitha7d93782016-12-01 03:32:42 +00003444 }
3445 }
3446
3447 return Flags;
3448}
3449
3450/// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct,
3451/// used for pointer types.
3452void ItaniumRTTIBuilder::BuildPointerTypeInfo(QualType PointeeTy) {
3453 // Itanium C++ ABI 2.9.5p7:
3454 // __flags is a flag word describing the cv-qualification and other
3455 // attributes of the type pointed to
3456 unsigned Flags = extractPBaseFlags(CGM.getContext(), PointeeTy);
David Majnemere2cb8d12014-07-07 06:20:47 +00003457
3458 llvm::Type *UnsignedIntLTy =
3459 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3460 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3461
3462 // Itanium C++ ABI 2.9.5p7:
3463 // __pointee is a pointer to the std::type_info derivation for the
3464 // unqualified type being pointed to.
3465 llvm::Constant *PointeeTypeInfo =
Richard Smitha7d93782016-12-01 03:32:42 +00003466 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(PointeeTy);
David Majnemere2cb8d12014-07-07 06:20:47 +00003467 Fields.push_back(PointeeTypeInfo);
3468}
3469
3470/// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
3471/// struct, used for member pointer types.
3472void
3473ItaniumRTTIBuilder::BuildPointerToMemberTypeInfo(const MemberPointerType *Ty) {
3474 QualType PointeeTy = Ty->getPointeeType();
3475
David Majnemere2cb8d12014-07-07 06:20:47 +00003476 // Itanium C++ ABI 2.9.5p7:
3477 // __flags is a flag word describing the cv-qualification and other
3478 // attributes of the type pointed to.
Richard Smitha7d93782016-12-01 03:32:42 +00003479 unsigned Flags = extractPBaseFlags(CGM.getContext(), PointeeTy);
David Majnemere2cb8d12014-07-07 06:20:47 +00003480
3481 const RecordType *ClassType = cast<RecordType>(Ty->getClass());
David Majnemere2cb8d12014-07-07 06:20:47 +00003482 if (IsIncompleteClassType(ClassType))
3483 Flags |= PTI_ContainingClassIncomplete;
3484
3485 llvm::Type *UnsignedIntLTy =
3486 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3487 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3488
3489 // Itanium C++ ABI 2.9.5p7:
3490 // __pointee is a pointer to the std::type_info derivation for the
3491 // unqualified type being pointed to.
3492 llvm::Constant *PointeeTypeInfo =
Richard Smitha7d93782016-12-01 03:32:42 +00003493 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(PointeeTy);
David Majnemere2cb8d12014-07-07 06:20:47 +00003494 Fields.push_back(PointeeTypeInfo);
3495
3496 // Itanium C++ ABI 2.9.5p9:
3497 // __context is a pointer to an abi::__class_type_info corresponding to the
3498 // class type containing the member pointed to
3499 // (e.g., the "A" in "int A::*").
3500 Fields.push_back(
3501 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(QualType(ClassType, 0)));
3502}
3503
David Majnemer443250f2015-03-17 20:35:00 +00003504llvm::Constant *ItaniumCXXABI::getAddrOfRTTIDescriptor(QualType Ty) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003505 return ItaniumRTTIBuilder(*this).BuildTypeInfo(Ty);
3506}
3507
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00003508void ItaniumCXXABI::EmitFundamentalRTTIDescriptor(QualType Type,
3509 bool DLLExport) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003510 QualType PointerType = getContext().getPointerType(Type);
3511 QualType PointerTypeConst = getContext().getPointerType(Type.withConst());
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00003512 ItaniumRTTIBuilder(*this).BuildTypeInfo(Type, /*Force=*/true, DLLExport);
3513 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerType, /*Force=*/true,
3514 DLLExport);
3515 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerTypeConst, /*Force=*/true,
3516 DLLExport);
David Majnemere2cb8d12014-07-07 06:20:47 +00003517}
3518
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00003519void ItaniumCXXABI::EmitFundamentalRTTIDescriptors(bool DLLExport) {
Richard Smith4a382012016-02-03 01:32:42 +00003520 // Types added here must also be added to TypeInfoIsInStandardLibrary.
David Majnemere2cb8d12014-07-07 06:20:47 +00003521 QualType FundamentalTypes[] = {
3522 getContext().VoidTy, getContext().NullPtrTy,
3523 getContext().BoolTy, getContext().WCharTy,
3524 getContext().CharTy, getContext().UnsignedCharTy,
3525 getContext().SignedCharTy, getContext().ShortTy,
3526 getContext().UnsignedShortTy, getContext().IntTy,
3527 getContext().UnsignedIntTy, getContext().LongTy,
3528 getContext().UnsignedLongTy, getContext().LongLongTy,
Richard Smith4a382012016-02-03 01:32:42 +00003529 getContext().UnsignedLongLongTy, getContext().Int128Ty,
3530 getContext().UnsignedInt128Ty, getContext().HalfTy,
David Majnemere2cb8d12014-07-07 06:20:47 +00003531 getContext().FloatTy, getContext().DoubleTy,
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00003532 getContext().LongDoubleTy, getContext().Float128Ty,
3533 getContext().Char16Ty, getContext().Char32Ty
David Majnemere2cb8d12014-07-07 06:20:47 +00003534 };
3535 for (const QualType &FundamentalType : FundamentalTypes)
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00003536 EmitFundamentalRTTIDescriptor(FundamentalType, DLLExport);
David Majnemere2cb8d12014-07-07 06:20:47 +00003537}
3538
3539/// What sort of uniqueness rules should we use for the RTTI for the
3540/// given type?
3541ItaniumCXXABI::RTTIUniquenessKind ItaniumCXXABI::classifyRTTIUniqueness(
3542 QualType CanTy, llvm::GlobalValue::LinkageTypes Linkage) const {
3543 if (shouldRTTIBeUnique())
3544 return RUK_Unique;
3545
3546 // It's only necessary for linkonce_odr or weak_odr linkage.
3547 if (Linkage != llvm::GlobalValue::LinkOnceODRLinkage &&
3548 Linkage != llvm::GlobalValue::WeakODRLinkage)
3549 return RUK_Unique;
3550
3551 // It's only necessary with default visibility.
3552 if (CanTy->getVisibility() != DefaultVisibility)
3553 return RUK_Unique;
3554
3555 // If we're not required to publish this symbol, hide it.
3556 if (Linkage == llvm::GlobalValue::LinkOnceODRLinkage)
3557 return RUK_NonUniqueHidden;
3558
3559 // If we're required to publish this symbol, as we might be under an
3560 // explicit instantiation, leave it with default visibility but
3561 // enable string-comparisons.
3562 assert(Linkage == llvm::GlobalValue::WeakODRLinkage);
3563 return RUK_NonUniqueVisible;
3564}
Rafael Espindola91f68b42014-09-15 19:20:10 +00003565
Rafael Espindola1e4df922014-09-16 15:18:21 +00003566// Find out how to codegen the complete destructor and constructor
3567namespace {
3568enum class StructorCodegen { Emit, RAUW, Alias, COMDAT };
3569}
3570static StructorCodegen getCodegenToUse(CodeGenModule &CGM,
3571 const CXXMethodDecl *MD) {
3572 if (!CGM.getCodeGenOpts().CXXCtorDtorAliases)
3573 return StructorCodegen::Emit;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003574
Rafael Espindola1e4df922014-09-16 15:18:21 +00003575 // The complete and base structors are not equivalent if there are any virtual
3576 // bases, so emit separate functions.
3577 if (MD->getParent()->getNumVBases())
3578 return StructorCodegen::Emit;
3579
3580 GlobalDecl AliasDecl;
3581 if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) {
3582 AliasDecl = GlobalDecl(DD, Dtor_Complete);
3583 } else {
3584 const auto *CD = cast<CXXConstructorDecl>(MD);
3585 AliasDecl = GlobalDecl(CD, Ctor_Complete);
3586 }
3587 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3588
3589 if (llvm::GlobalValue::isDiscardableIfUnused(Linkage))
3590 return StructorCodegen::RAUW;
3591
3592 // FIXME: Should we allow available_externally aliases?
3593 if (!llvm::GlobalAlias::isValidLinkage(Linkage))
3594 return StructorCodegen::RAUW;
3595
Rafael Espindola0806f982014-09-16 20:19:43 +00003596 if (llvm::GlobalValue::isWeakForLinker(Linkage)) {
Dan Gohman839f2152017-01-17 21:46:38 +00003597 // Only ELF and wasm support COMDATs with arbitrary names (C5/D5).
3598 if (CGM.getTarget().getTriple().isOSBinFormatELF() ||
3599 CGM.getTarget().getTriple().isOSBinFormatWasm())
Rafael Espindola0806f982014-09-16 20:19:43 +00003600 return StructorCodegen::COMDAT;
3601 return StructorCodegen::Emit;
3602 }
Rafael Espindola1e4df922014-09-16 15:18:21 +00003603
3604 return StructorCodegen::Alias;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003605}
3606
Rafael Espindola1e4df922014-09-16 15:18:21 +00003607static void emitConstructorDestructorAlias(CodeGenModule &CGM,
3608 GlobalDecl AliasDecl,
3609 GlobalDecl TargetDecl) {
3610 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3611
3612 StringRef MangledName = CGM.getMangledName(AliasDecl);
3613 llvm::GlobalValue *Entry = CGM.GetGlobalValue(MangledName);
3614 if (Entry && !Entry->isDeclaration())
3615 return;
3616
3617 auto *Aliasee = cast<llvm::GlobalValue>(CGM.GetAddrOfGlobal(TargetDecl));
Rafael Espindola1e4df922014-09-16 15:18:21 +00003618
3619 // Create the alias with no name.
David Blaikie2a791d72015-09-14 18:38:22 +00003620 auto *Alias = llvm::GlobalAlias::create(Linkage, "", Aliasee);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003621
3622 // Switch any previous uses to the alias.
3623 if (Entry) {
NAKAMURA Takumie9621042015-09-15 01:39:27 +00003624 assert(Entry->getType() == Aliasee->getType() &&
Rafael Espindola1e4df922014-09-16 15:18:21 +00003625 "declaration exists with different type");
3626 Alias->takeName(Entry);
3627 Entry->replaceAllUsesWith(Alias);
3628 Entry->eraseFromParent();
3629 } else {
3630 Alias->setName(MangledName);
3631 }
3632
3633 // Finally, set up the alias with its proper name and attributes.
Dario Domiziolic4fb8ca72014-09-19 22:06:24 +00003634 CGM.setAliasAttributes(cast<NamedDecl>(AliasDecl.getDecl()), Alias);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003635}
3636
3637void ItaniumCXXABI::emitCXXStructor(const CXXMethodDecl *MD,
3638 StructorType Type) {
3639 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
3640 const CXXDestructorDecl *DD = CD ? nullptr : cast<CXXDestructorDecl>(MD);
3641
3642 StructorCodegen CGType = getCodegenToUse(CGM, MD);
3643
3644 if (Type == StructorType::Complete) {
3645 GlobalDecl CompleteDecl;
3646 GlobalDecl BaseDecl;
3647 if (CD) {
3648 CompleteDecl = GlobalDecl(CD, Ctor_Complete);
3649 BaseDecl = GlobalDecl(CD, Ctor_Base);
3650 } else {
3651 CompleteDecl = GlobalDecl(DD, Dtor_Complete);
3652 BaseDecl = GlobalDecl(DD, Dtor_Base);
3653 }
3654
3655 if (CGType == StructorCodegen::Alias || CGType == StructorCodegen::COMDAT) {
3656 emitConstructorDestructorAlias(CGM, CompleteDecl, BaseDecl);
3657 return;
3658 }
3659
3660 if (CGType == StructorCodegen::RAUW) {
3661 StringRef MangledName = CGM.getMangledName(CompleteDecl);
Andrey Bokhankocab58582015-08-31 13:20:44 +00003662 auto *Aliasee = CGM.GetAddrOfGlobal(BaseDecl);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003663 CGM.addReplacement(MangledName, Aliasee);
3664 return;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003665 }
3666 }
3667
3668 // The base destructor is equivalent to the base destructor of its
3669 // base class if there is exactly one non-virtual base class with a
3670 // non-trivial destructor, there are no fields with a non-trivial
3671 // destructor, and the body of the destructor is trivial.
Rafael Espindola1e4df922014-09-16 15:18:21 +00003672 if (DD && Type == StructorType::Base && CGType != StructorCodegen::COMDAT &&
3673 !CGM.TryEmitBaseDestructorAsAlias(DD))
Rafael Espindola91f68b42014-09-15 19:20:10 +00003674 return;
3675
Richard Smith5b349582017-10-13 01:55:36 +00003676 // FIXME: The deleting destructor is equivalent to the selected operator
3677 // delete if:
3678 // * either the delete is a destroying operator delete or the destructor
3679 // would be trivial if it weren't virtual,
3680 // * the conversion from the 'this' parameter to the first parameter of the
3681 // destructor is equivalent to a bitcast,
3682 // * the destructor does not have an implicit "this" return, and
3683 // * the operator delete has the same calling convention and IR function type
3684 // as the destructor.
3685 // In such cases we should try to emit the deleting dtor as an alias to the
3686 // selected 'operator delete'.
3687
Rafael Espindola1e4df922014-09-16 15:18:21 +00003688 llvm::Function *Fn = CGM.codegenCXXStructor(MD, Type);
Rafael Espindola91f68b42014-09-15 19:20:10 +00003689
Rafael Espindola1e4df922014-09-16 15:18:21 +00003690 if (CGType == StructorCodegen::COMDAT) {
3691 SmallString<256> Buffer;
3692 llvm::raw_svector_ostream Out(Buffer);
3693 if (DD)
3694 getMangleContext().mangleCXXDtorComdat(DD, Out);
3695 else
3696 getMangleContext().mangleCXXCtorComdat(CD, Out);
3697 llvm::Comdat *C = CGM.getModule().getOrInsertComdat(Out.str());
3698 Fn->setComdat(C);
Rafael Espindoladbee8a72015-01-15 21:36:08 +00003699 } else {
3700 CGM.maybeSetTrivialComdat(*MD, *Fn);
Rafael Espindola91f68b42014-09-15 19:20:10 +00003701 }
Rafael Espindola91f68b42014-09-15 19:20:10 +00003702}
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003703
3704static llvm::Constant *getBeginCatchFn(CodeGenModule &CGM) {
3705 // void *__cxa_begin_catch(void*);
3706 llvm::FunctionType *FTy = llvm::FunctionType::get(
3707 CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3708
3709 return CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
3710}
3711
3712static llvm::Constant *getEndCatchFn(CodeGenModule &CGM) {
3713 // void __cxa_end_catch();
3714 llvm::FunctionType *FTy =
3715 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
3716
3717 return CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
3718}
3719
3720static llvm::Constant *getGetExceptionPtrFn(CodeGenModule &CGM) {
3721 // void *__cxa_get_exception_ptr(void*);
3722 llvm::FunctionType *FTy = llvm::FunctionType::get(
3723 CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3724
3725 return CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
3726}
3727
3728namespace {
3729 /// A cleanup to call __cxa_end_catch. In many cases, the caught
3730 /// exception type lets us state definitively that the thrown exception
3731 /// type does not have a destructor. In particular:
3732 /// - Catch-alls tell us nothing, so we have to conservatively
3733 /// assume that the thrown exception might have a destructor.
3734 /// - Catches by reference behave according to their base types.
3735 /// - Catches of non-record types will only trigger for exceptions
3736 /// of non-record types, which never have destructors.
3737 /// - Catches of record types can trigger for arbitrary subclasses
3738 /// of the caught type, so we have to assume the actual thrown
3739 /// exception type might have a throwing destructor, even if the
3740 /// caught type's destructor is trivial or nothrow.
David Blaikie7e70d682015-08-18 22:40:54 +00003741 struct CallEndCatch final : EHScopeStack::Cleanup {
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003742 CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
3743 bool MightThrow;
3744
3745 void Emit(CodeGenFunction &CGF, Flags flags) override {
3746 if (!MightThrow) {
3747 CGF.EmitNounwindRuntimeCall(getEndCatchFn(CGF.CGM));
3748 return;
3749 }
3750
3751 CGF.EmitRuntimeCallOrInvoke(getEndCatchFn(CGF.CGM));
3752 }
3753 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003754}
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003755
3756/// Emits a call to __cxa_begin_catch and enters a cleanup to call
3757/// __cxa_end_catch.
3758///
3759/// \param EndMightThrow - true if __cxa_end_catch might throw
3760static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
3761 llvm::Value *Exn,
3762 bool EndMightThrow) {
3763 llvm::CallInst *call =
3764 CGF.EmitNounwindRuntimeCall(getBeginCatchFn(CGF.CGM), Exn);
3765
3766 CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
3767
3768 return call;
3769}
3770
3771/// A "special initializer" callback for initializing a catch
3772/// parameter during catch initialization.
3773static void InitCatchParam(CodeGenFunction &CGF,
3774 const VarDecl &CatchParam,
John McCall7f416cc2015-09-08 08:05:57 +00003775 Address ParamAddr,
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003776 SourceLocation Loc) {
3777 // Load the exception from where the landing pad saved it.
3778 llvm::Value *Exn = CGF.getExceptionFromSlot();
3779
3780 CanQualType CatchType =
3781 CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
3782 llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
3783
3784 // If we're catching by reference, we can just cast the object
3785 // pointer to the appropriate pointer.
3786 if (isa<ReferenceType>(CatchType)) {
3787 QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
3788 bool EndCatchMightThrow = CaughtType->isRecordType();
3789
3790 // __cxa_begin_catch returns the adjusted object pointer.
3791 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
3792
3793 // We have no way to tell the personality function that we're
3794 // catching by reference, so if we're catching a pointer,
3795 // __cxa_begin_catch will actually return that pointer by value.
3796 if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
3797 QualType PointeeType = PT->getPointeeType();
3798
3799 // When catching by reference, generally we should just ignore
3800 // this by-value pointer and use the exception object instead.
3801 if (!PointeeType->isRecordType()) {
3802
3803 // Exn points to the struct _Unwind_Exception header, which
3804 // we have to skip past in order to reach the exception data.
3805 unsigned HeaderSize =
3806 CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
3807 AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
3808
3809 // However, if we're catching a pointer-to-record type that won't
3810 // work, because the personality function might have adjusted
3811 // the pointer. There's actually no way for us to fully satisfy
3812 // the language/ABI contract here: we can't use Exn because it
3813 // might have the wrong adjustment, but we can't use the by-value
3814 // pointer because it's off by a level of abstraction.
3815 //
3816 // The current solution is to dump the adjusted pointer into an
3817 // alloca, which breaks language semantics (because changing the
3818 // pointer doesn't change the exception) but at least works.
3819 // The better solution would be to filter out non-exact matches
3820 // and rethrow them, but this is tricky because the rethrow
3821 // really needs to be catchable by other sites at this landing
3822 // pad. The best solution is to fix the personality function.
3823 } else {
3824 // Pull the pointer for the reference type off.
3825 llvm::Type *PtrTy =
3826 cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
3827
3828 // Create the temporary and write the adjusted pointer into it.
John McCall7f416cc2015-09-08 08:05:57 +00003829 Address ExnPtrTmp =
3830 CGF.CreateTempAlloca(PtrTy, CGF.getPointerAlign(), "exn.byref.tmp");
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003831 llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
3832 CGF.Builder.CreateStore(Casted, ExnPtrTmp);
3833
3834 // Bind the reference to the temporary.
John McCall7f416cc2015-09-08 08:05:57 +00003835 AdjustedExn = ExnPtrTmp.getPointer();
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003836 }
3837 }
3838
3839 llvm::Value *ExnCast =
3840 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
3841 CGF.Builder.CreateStore(ExnCast, ParamAddr);
3842 return;
3843 }
3844
3845 // Scalars and complexes.
3846 TypeEvaluationKind TEK = CGF.getEvaluationKind(CatchType);
3847 if (TEK != TEK_Aggregate) {
3848 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
3849
3850 // If the catch type is a pointer type, __cxa_begin_catch returns
3851 // the pointer by value.
3852 if (CatchType->hasPointerRepresentation()) {
3853 llvm::Value *CastExn =
3854 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
3855
3856 switch (CatchType.getQualifiers().getObjCLifetime()) {
3857 case Qualifiers::OCL_Strong:
3858 CastExn = CGF.EmitARCRetainNonBlock(CastExn);
3859 // fallthrough
3860
3861 case Qualifiers::OCL_None:
3862 case Qualifiers::OCL_ExplicitNone:
3863 case Qualifiers::OCL_Autoreleasing:
3864 CGF.Builder.CreateStore(CastExn, ParamAddr);
3865 return;
3866
3867 case Qualifiers::OCL_Weak:
3868 CGF.EmitARCInitWeak(ParamAddr, CastExn);
3869 return;
3870 }
3871 llvm_unreachable("bad ownership qualifier!");
3872 }
3873
3874 // Otherwise, it returns a pointer into the exception object.
3875
3876 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
3877 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
3878
3879 LValue srcLV = CGF.MakeNaturalAlignAddrLValue(Cast, CatchType);
John McCall7f416cc2015-09-08 08:05:57 +00003880 LValue destLV = CGF.MakeAddrLValue(ParamAddr, CatchType);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003881 switch (TEK) {
3882 case TEK_Complex:
3883 CGF.EmitStoreOfComplex(CGF.EmitLoadOfComplex(srcLV, Loc), destLV,
3884 /*init*/ true);
3885 return;
3886 case TEK_Scalar: {
3887 llvm::Value *ExnLoad = CGF.EmitLoadOfScalar(srcLV, Loc);
3888 CGF.EmitStoreOfScalar(ExnLoad, destLV, /*init*/ true);
3889 return;
3890 }
3891 case TEK_Aggregate:
3892 llvm_unreachable("evaluation kind filtered out!");
3893 }
3894 llvm_unreachable("bad evaluation kind");
3895 }
3896
3897 assert(isa<RecordType>(CatchType) && "unexpected catch type!");
John McCall7f416cc2015-09-08 08:05:57 +00003898 auto catchRD = CatchType->getAsCXXRecordDecl();
3899 CharUnits caughtExnAlignment = CGF.CGM.getClassPointerAlignment(catchRD);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003900
3901 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
3902
3903 // Check for a copy expression. If we don't have a copy expression,
3904 // that means a trivial copy is okay.
3905 const Expr *copyExpr = CatchParam.getInit();
3906 if (!copyExpr) {
3907 llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true);
John McCall7f416cc2015-09-08 08:05:57 +00003908 Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy),
3909 caughtExnAlignment);
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00003910 LValue Dest = CGF.MakeAddrLValue(ParamAddr, CatchType);
3911 LValue Src = CGF.MakeAddrLValue(adjustedExn, CatchType);
3912 CGF.EmitAggregateCopy(Dest, Src, CatchType);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003913 return;
3914 }
3915
3916 // We have to call __cxa_get_exception_ptr to get the adjusted
3917 // pointer before copying.
3918 llvm::CallInst *rawAdjustedExn =
3919 CGF.EmitNounwindRuntimeCall(getGetExceptionPtrFn(CGF.CGM), Exn);
3920
3921 // Cast that to the appropriate type.
John McCall7f416cc2015-09-08 08:05:57 +00003922 Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy),
3923 caughtExnAlignment);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003924
3925 // The copy expression is defined in terms of an OpaqueValueExpr.
3926 // Find it and map it to the adjusted expression.
3927 CodeGenFunction::OpaqueValueMapping
3928 opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr),
3929 CGF.MakeAddrLValue(adjustedExn, CatchParam.getType()));
3930
3931 // Call the copy ctor in a terminate scope.
3932 CGF.EHStack.pushTerminate();
3933
3934 // Perform the copy construction.
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003935 CGF.EmitAggExpr(copyExpr,
John McCall7f416cc2015-09-08 08:05:57 +00003936 AggValueSlot::forAddr(ParamAddr, Qualifiers(),
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003937 AggValueSlot::IsNotDestructed,
3938 AggValueSlot::DoesNotNeedGCBarriers,
3939 AggValueSlot::IsNotAliased));
3940
3941 // Leave the terminate scope.
3942 CGF.EHStack.popTerminate();
3943
3944 // Undo the opaque value mapping.
3945 opaque.pop();
3946
3947 // Finally we can call __cxa_begin_catch.
3948 CallBeginCatch(CGF, Exn, true);
3949}
3950
3951/// Begins a catch statement by initializing the catch variable and
3952/// calling __cxa_begin_catch.
3953void ItaniumCXXABI::emitBeginCatch(CodeGenFunction &CGF,
3954 const CXXCatchStmt *S) {
3955 // We have to be very careful with the ordering of cleanups here:
3956 // C++ [except.throw]p4:
3957 // The destruction [of the exception temporary] occurs
3958 // immediately after the destruction of the object declared in
3959 // the exception-declaration in the handler.
3960 //
3961 // So the precise ordering is:
3962 // 1. Construct catch variable.
3963 // 2. __cxa_begin_catch
3964 // 3. Enter __cxa_end_catch cleanup
3965 // 4. Enter dtor cleanup
3966 //
3967 // We do this by using a slightly abnormal initialization process.
3968 // Delegation sequence:
3969 // - ExitCXXTryStmt opens a RunCleanupsScope
3970 // - EmitAutoVarAlloca creates the variable and debug info
3971 // - InitCatchParam initializes the variable from the exception
3972 // - CallBeginCatch calls __cxa_begin_catch
3973 // - CallBeginCatch enters the __cxa_end_catch cleanup
3974 // - EmitAutoVarCleanups enters the variable destructor cleanup
3975 // - EmitCXXTryStmt emits the code for the catch body
3976 // - EmitCXXTryStmt close the RunCleanupsScope
3977
3978 VarDecl *CatchParam = S->getExceptionDecl();
3979 if (!CatchParam) {
3980 llvm::Value *Exn = CGF.getExceptionFromSlot();
3981 CallBeginCatch(CGF, Exn, true);
3982 return;
3983 }
3984
3985 // Emit the local.
3986 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
3987 InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF), S->getLocStart());
3988 CGF.EmitAutoVarCleanups(var);
3989}
3990
3991/// Get or define the following function:
3992/// void @__clang_call_terminate(i8* %exn) nounwind noreturn
3993/// This code is used only in C++.
3994static llvm::Constant *getClangCallTerminateFn(CodeGenModule &CGM) {
3995 llvm::FunctionType *fnTy =
3996 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
Reid Klecknerde864822017-03-21 16:57:30 +00003997 llvm::Constant *fnRef = CGM.CreateRuntimeFunction(
3998 fnTy, "__clang_call_terminate", llvm::AttributeList(), /*Local=*/true);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003999
4000 llvm::Function *fn = dyn_cast<llvm::Function>(fnRef);
4001 if (fn && fn->empty()) {
4002 fn->setDoesNotThrow();
4003 fn->setDoesNotReturn();
4004
4005 // What we really want is to massively penalize inlining without
4006 // forbidding it completely. The difference between that and
4007 // 'noinline' is negligible.
4008 fn->addFnAttr(llvm::Attribute::NoInline);
4009
4010 // Allow this function to be shared across translation units, but
4011 // we don't want it to turn into an exported symbol.
4012 fn->setLinkage(llvm::Function::LinkOnceODRLinkage);
4013 fn->setVisibility(llvm::Function::HiddenVisibility);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00004014 if (CGM.supportsCOMDAT())
4015 fn->setComdat(CGM.getModule().getOrInsertComdat(fn->getName()));
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004016
4017 // Set up the function.
4018 llvm::BasicBlock *entry =
4019 llvm::BasicBlock::Create(CGM.getLLVMContext(), "", fn);
John McCall7f416cc2015-09-08 08:05:57 +00004020 CGBuilderTy builder(CGM, entry);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004021
4022 // Pull the exception pointer out of the parameter list.
4023 llvm::Value *exn = &*fn->arg_begin();
4024
4025 // Call __cxa_begin_catch(exn).
4026 llvm::CallInst *catchCall = builder.CreateCall(getBeginCatchFn(CGM), exn);
4027 catchCall->setDoesNotThrow();
4028 catchCall->setCallingConv(CGM.getRuntimeCC());
4029
4030 // Call std::terminate().
David Blaikie4ba525b2015-07-14 17:27:39 +00004031 llvm::CallInst *termCall = builder.CreateCall(CGM.getTerminateFn());
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004032 termCall->setDoesNotThrow();
4033 termCall->setDoesNotReturn();
4034 termCall->setCallingConv(CGM.getRuntimeCC());
4035
4036 // std::terminate cannot return.
4037 builder.CreateUnreachable();
4038 }
4039
4040 return fnRef;
4041}
4042
4043llvm::CallInst *
4044ItaniumCXXABI::emitTerminateForUnexpectedException(CodeGenFunction &CGF,
4045 llvm::Value *Exn) {
4046 // In C++, we want to call __cxa_begin_catch() before terminating.
4047 if (Exn) {
4048 assert(CGF.CGM.getLangOpts().CPlusPlus);
4049 return CGF.EmitNounwindRuntimeCall(getClangCallTerminateFn(CGF.CGM), Exn);
4050 }
4051 return CGF.EmitNounwindRuntimeCall(CGF.CGM.getTerminateFn());
4052}
Peter Collingbourne60108802017-12-13 21:53:04 +00004053
4054std::pair<llvm::Value *, const CXXRecordDecl *>
4055ItaniumCXXABI::LoadVTablePtr(CodeGenFunction &CGF, Address This,
4056 const CXXRecordDecl *RD) {
4057 return {CGF.GetVTablePtr(This, CGM.Int8PtrTy, RD), RD};
4058}