blob: 173bc4d8df3498e33b6435dcb1ac8c2878476bc9 [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)
71 return RD->hasNonTrivialDestructor() ||
72 RD->hasNonTrivialCopyConstructor();
73 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 McCallb92ab1a2016-10-26 23:46:34 +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
392 private:
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +0000393 bool hasAnyUnusedVirtualInlineFunction(const CXXRecordDecl *RD) const {
394 const auto &VtableLayout =
395 CGM.getItaniumVTableContext().getVTableLayout(RD);
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000396
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +0000397 for (const auto &VtableComponent : VtableLayout.vtable_components()) {
398 // Skip empty slot.
399 if (!VtableComponent.isUsedFunctionPointerKind())
400 continue;
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000401
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +0000402 const CXXMethodDecl *Method = VtableComponent.getFunctionDecl();
403 if (!Method->getCanonicalDecl()->isInlined())
404 continue;
405
406 StringRef Name = CGM.getMangledName(VtableComponent.getGlobalDecl());
407 auto *Entry = CGM.GetGlobalValue(Name);
408 // This checks if virtual inline function has already been emitted.
409 // Note that it is possible that this inline function would be emitted
410 // after trying to emit vtable speculatively. Because of this we do
411 // an extra pass after emitting all deferred vtables to find and emit
412 // these vtables opportunistically.
413 if (!Entry || Entry->isDeclaration())
414 return true;
415 }
416 return false;
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000417 }
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000418
419 bool isVTableHidden(const CXXRecordDecl *RD) const {
420 const auto &VtableLayout =
421 CGM.getItaniumVTableContext().getVTableLayout(RD);
422
423 for (const auto &VtableComponent : VtableLayout.vtable_components()) {
424 if (VtableComponent.isRTTIKind()) {
425 const CXXRecordDecl *RTTIDecl = VtableComponent.getRTTIDecl();
426 if (RTTIDecl->getVisibility() == Visibility::HiddenVisibility)
427 return true;
428 } else if (VtableComponent.isUsedFunctionPointerKind()) {
429 const CXXMethodDecl *Method = VtableComponent.getFunctionDecl();
430 if (Method->getVisibility() == Visibility::HiddenVisibility &&
431 !Method->isDefined())
432 return true;
433 }
434 }
435 return false;
436 }
Charles Davis4e786dd2010-05-25 19:52:27 +0000437};
John McCall86353412010-08-21 22:46:04 +0000438
439class ARMCXXABI : public ItaniumCXXABI {
440public:
Mark Seabornedf0d382013-07-24 16:25:13 +0000441 ARMCXXABI(CodeGen::CodeGenModule &CGM) :
442 ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
443 /* UseARMGuardVarABI = */ true) {}
John McCall5d865c322010-08-31 07:33:07 +0000444
Craig Topper4f12f102014-03-12 06:41:41 +0000445 bool HasThisReturn(GlobalDecl GD) const override {
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000446 return (isa<CXXConstructorDecl>(GD.getDecl()) || (
447 isa<CXXDestructorDecl>(GD.getDecl()) &&
448 GD.getDtorType() != Dtor_Deleting));
449 }
John McCall5d865c322010-08-31 07:33:07 +0000450
Craig Topper4f12f102014-03-12 06:41:41 +0000451 void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV,
452 QualType ResTy) override;
John McCall5d865c322010-08-31 07:33:07 +0000453
Craig Topper4f12f102014-03-12 06:41:41 +0000454 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
John McCall7f416cc2015-09-08 08:05:57 +0000455 Address InitializeArrayCookie(CodeGenFunction &CGF,
456 Address NewPtr,
457 llvm::Value *NumElements,
458 const CXXNewExpr *expr,
459 QualType ElementType) override;
460 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, Address allocPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000461 CharUnits cookieSize) override;
John McCall86353412010-08-21 22:46:04 +0000462};
Tim Northovera2ee4332014-03-29 15:09:45 +0000463
464class iOS64CXXABI : public ARMCXXABI {
465public:
John McCalld23b27e2016-09-16 02:40:45 +0000466 iOS64CXXABI(CodeGen::CodeGenModule &CGM) : ARMCXXABI(CGM) {
467 Use32BitVTableOffsetABI = true;
468 }
Tim Northover65f582f2014-03-30 17:32:48 +0000469
470 // ARM64 libraries are prepared for non-unique RTTI.
David Majnemere2cb8d12014-07-07 06:20:47 +0000471 bool shouldRTTIBeUnique() const override { return false; }
Tim Northovera2ee4332014-03-29 15:09:45 +0000472};
Dan Gohmanc2853072015-09-03 22:51:53 +0000473
474class WebAssemblyCXXABI final : public ItaniumCXXABI {
475public:
476 explicit WebAssemblyCXXABI(CodeGen::CodeGenModule &CGM)
477 : ItaniumCXXABI(CGM, /*UseARMMethodPtrABI=*/true,
478 /*UseARMGuardVarABI=*/true) {}
479
480private:
481 bool HasThisReturn(GlobalDecl GD) const override {
482 return isa<CXXConstructorDecl>(GD.getDecl()) ||
483 (isa<CXXDestructorDecl>(GD.getDecl()) &&
484 GD.getDtorType() != Dtor_Deleting);
485 }
Derek Schuff8179be42016-05-10 17:44:55 +0000486 bool canCallMismatchedFunctionType() const override { return false; }
Dan Gohmanc2853072015-09-03 22:51:53 +0000487};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000488}
Charles Davis4e786dd2010-05-25 19:52:27 +0000489
Charles Davis53c59df2010-08-16 03:33:14 +0000490CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
John McCallc8e01702013-04-16 22:48:15 +0000491 switch (CGM.getTarget().getCXXABI().getKind()) {
John McCall57625922013-01-25 23:36:14 +0000492 // For IR-generation purposes, there's no significant difference
493 // between the ARM and iOS ABIs.
494 case TargetCXXABI::GenericARM:
495 case TargetCXXABI::iOS:
Tim Northover756447a2015-10-30 16:30:36 +0000496 case TargetCXXABI::WatchOS:
John McCall57625922013-01-25 23:36:14 +0000497 return new ARMCXXABI(CGM);
Charles Davis4e786dd2010-05-25 19:52:27 +0000498
Tim Northovera2ee4332014-03-29 15:09:45 +0000499 case TargetCXXABI::iOS64:
500 return new iOS64CXXABI(CGM);
501
Tim Northover9bb857a2013-01-31 12:13:10 +0000502 // Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't
503 // include the other 32-bit ARM oddities: constructor/destructor return values
504 // and array cookies.
505 case TargetCXXABI::GenericAArch64:
Mark Seabornedf0d382013-07-24 16:25:13 +0000506 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
507 /* UseARMGuardVarABI = */ true);
Tim Northover9bb857a2013-01-31 12:13:10 +0000508
Zoran Jovanovic26a12162015-02-18 15:21:35 +0000509 case TargetCXXABI::GenericMIPS:
510 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true);
511
Dan Gohmanc2853072015-09-03 22:51:53 +0000512 case TargetCXXABI::WebAssembly:
513 return new WebAssemblyCXXABI(CGM);
514
John McCall57625922013-01-25 23:36:14 +0000515 case TargetCXXABI::GenericItanium:
Mark Seabornedf0d382013-07-24 16:25:13 +0000516 if (CGM.getContext().getTargetInfo().getTriple().getArch()
517 == llvm::Triple::le32) {
518 // For PNaCl, use ARM-style method pointers so that PNaCl code
519 // does not assume anything about the alignment of function
520 // pointers.
521 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
522 /* UseARMGuardVarABI = */ false);
523 }
John McCall57625922013-01-25 23:36:14 +0000524 return new ItaniumCXXABI(CGM);
525
526 case TargetCXXABI::Microsoft:
527 llvm_unreachable("Microsoft ABI is not Itanium-based");
528 }
529 llvm_unreachable("bad ABI kind");
John McCall86353412010-08-21 22:46:04 +0000530}
531
Chris Lattnera5f58b02011-07-09 17:41:47 +0000532llvm::Type *
John McCall7a9aac22010-08-23 01:21:21 +0000533ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
534 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000535 return CGM.PtrDiffTy;
Serge Guelton1d993272017-05-09 19:31:30 +0000536 return llvm::StructType::get(CGM.PtrDiffTy, CGM.PtrDiffTy);
John McCall1c456c82010-08-22 06:43:33 +0000537}
538
John McCalld9c6c0b2010-08-22 00:59:17 +0000539/// In the Itanium and ARM ABIs, method pointers have the form:
540/// struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
541///
542/// In the Itanium ABI:
543/// - method pointers are virtual if (memptr.ptr & 1) is nonzero
544/// - the this-adjustment is (memptr.adj)
545/// - the virtual offset is (memptr.ptr - 1)
546///
547/// In the ARM ABI:
548/// - method pointers are virtual if (memptr.adj & 1) is nonzero
549/// - the this-adjustment is (memptr.adj >> 1)
550/// - the virtual offset is (memptr.ptr)
551/// ARM uses 'adj' for the virtual flag because Thumb functions
552/// may be only single-byte aligned.
553///
554/// If the member is virtual, the adjusted 'this' pointer points
555/// to a vtable pointer from which the virtual offset is applied.
556///
557/// If the member is non-virtual, memptr.ptr is the address of
558/// the function to call.
John McCallb92ab1a2016-10-26 23:46:34 +0000559CGCallee ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(
John McCall7f416cc2015-09-08 08:05:57 +0000560 CodeGenFunction &CGF, const Expr *E, Address ThisAddr,
561 llvm::Value *&ThisPtrForCall,
David Majnemer2b0d66d2014-02-20 23:22:07 +0000562 llvm::Value *MemFnPtr, const MemberPointerType *MPT) {
John McCall475999d2010-08-22 00:05:51 +0000563 CGBuilderTy &Builder = CGF.Builder;
564
565 const FunctionProtoType *FPT =
566 MPT->getPointeeType()->getAs<FunctionProtoType>();
567 const CXXRecordDecl *RD =
568 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
569
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000570 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(
571 CGM.getTypes().arrangeCXXMethodType(RD, FPT, /*FD=*/nullptr));
John McCall475999d2010-08-22 00:05:51 +0000572
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000573 llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(CGM.PtrDiffTy, 1);
John McCall475999d2010-08-22 00:05:51 +0000574
John McCalld9c6c0b2010-08-22 00:59:17 +0000575 llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
576 llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
577 llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
578
John McCalla1dee5302010-08-22 10:59:02 +0000579 // Extract memptr.adj, which is in the second field.
580 llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
John McCalld9c6c0b2010-08-22 00:59:17 +0000581
582 // Compute the true adjustment.
583 llvm::Value *Adj = RawAdj;
Mark Seabornedf0d382013-07-24 16:25:13 +0000584 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000585 Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
John McCall475999d2010-08-22 00:05:51 +0000586
587 // Apply the adjustment and cast back to the original struct type
588 // for consistency.
John McCall7f416cc2015-09-08 08:05:57 +0000589 llvm::Value *This = ThisAddr.getPointer();
John McCalld9c6c0b2010-08-22 00:59:17 +0000590 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
591 Ptr = Builder.CreateInBoundsGEP(Ptr, Adj);
592 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
John McCall7f416cc2015-09-08 08:05:57 +0000593 ThisPtrForCall = This;
John McCall475999d2010-08-22 00:05:51 +0000594
595 // Load the function pointer.
John McCalla1dee5302010-08-22 10:59:02 +0000596 llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
John McCall475999d2010-08-22 00:05:51 +0000597
598 // If the LSB in the function pointer is 1, the function pointer points to
599 // a virtual function.
John McCalld9c6c0b2010-08-22 00:59:17 +0000600 llvm::Value *IsVirtual;
Mark Seabornedf0d382013-07-24 16:25:13 +0000601 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000602 IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
603 else
604 IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
605 IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
John McCall475999d2010-08-22 00:05:51 +0000606 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
607
608 // In the virtual path, the adjustment left 'This' pointing to the
609 // vtable of the correct base subobject. The "function pointer" is an
John McCalld9c6c0b2010-08-22 00:59:17 +0000610 // offset within the vtable (+1 for the virtual flag on non-ARM).
John McCall475999d2010-08-22 00:05:51 +0000611 CGF.EmitBlock(FnVirtual);
612
613 // Cast the adjusted this to a pointer to vtable pointer and load.
Chris Lattner2192fe52011-07-18 04:24:23 +0000614 llvm::Type *VTableTy = Builder.getInt8PtrTy();
John McCall7f416cc2015-09-08 08:05:57 +0000615 CharUnits VTablePtrAlign =
616 CGF.CGM.getDynamicOffsetAlignment(ThisAddr.getAlignment(), RD,
617 CGF.getPointerAlign());
618 llvm::Value *VTable =
Piotr Padlewski4b1ac722015-09-15 21:46:55 +0000619 CGF.GetVTablePtr(Address(This, VTablePtrAlign), VTableTy, RD);
John McCall475999d2010-08-22 00:05:51 +0000620
621 // Apply the offset.
John McCalld23b27e2016-09-16 02:40:45 +0000622 // On ARM64, to reserve extra space in virtual member function pointers,
623 // we only pay attention to the low 32 bits of the offset.
John McCalld9c6c0b2010-08-22 00:59:17 +0000624 llvm::Value *VTableOffset = FnAsInt;
Mark Seabornedf0d382013-07-24 16:25:13 +0000625 if (!UseARMMethodPtrABI)
626 VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
John McCalld23b27e2016-09-16 02:40:45 +0000627 if (Use32BitVTableOffsetABI) {
628 VTableOffset = Builder.CreateTrunc(VTableOffset, CGF.Int32Ty);
629 VTableOffset = Builder.CreateZExt(VTableOffset, CGM.PtrDiffTy);
630 }
John McCalld9c6c0b2010-08-22 00:59:17 +0000631 VTable = Builder.CreateGEP(VTable, VTableOffset);
John McCall475999d2010-08-22 00:05:51 +0000632
633 // Load the virtual function to call.
634 VTable = Builder.CreateBitCast(VTable, FTy->getPointerTo()->getPointerTo());
John McCall7f416cc2015-09-08 08:05:57 +0000635 llvm::Value *VirtualFn =
636 Builder.CreateAlignedLoad(VTable, CGF.getPointerAlign(),
637 "memptr.virtualfn");
John McCall475999d2010-08-22 00:05:51 +0000638 CGF.EmitBranch(FnEnd);
639
640 // In the non-virtual path, the function pointer is actually a
641 // function pointer.
642 CGF.EmitBlock(FnNonVirtual);
643 llvm::Value *NonVirtualFn =
John McCalld9c6c0b2010-08-22 00:59:17 +0000644 Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn");
John McCall475999d2010-08-22 00:05:51 +0000645
646 // We're done.
647 CGF.EmitBlock(FnEnd);
John McCallb92ab1a2016-10-26 23:46:34 +0000648 llvm::PHINode *CalleePtr = Builder.CreatePHI(FTy->getPointerTo(), 2);
649 CalleePtr->addIncoming(VirtualFn, FnVirtual);
650 CalleePtr->addIncoming(NonVirtualFn, FnNonVirtual);
651
652 CGCallee Callee(FPT, CalleePtr);
John McCall475999d2010-08-22 00:05:51 +0000653 return Callee;
654}
John McCalla8bbb822010-08-22 03:04:22 +0000655
John McCallc134eb52010-08-31 21:07:20 +0000656/// Compute an l-value by applying the given pointer-to-member to a
657/// base object.
David Majnemer2b0d66d2014-02-20 23:22:07 +0000658llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(
John McCall7f416cc2015-09-08 08:05:57 +0000659 CodeGenFunction &CGF, const Expr *E, Address Base, llvm::Value *MemPtr,
David Majnemer2b0d66d2014-02-20 23:22:07 +0000660 const MemberPointerType *MPT) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000661 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCallc134eb52010-08-31 21:07:20 +0000662
663 CGBuilderTy &Builder = CGF.Builder;
664
John McCallc134eb52010-08-31 21:07:20 +0000665 // Cast to char*.
John McCall7f416cc2015-09-08 08:05:57 +0000666 Base = Builder.CreateElementBitCast(Base, CGF.Int8Ty);
John McCallc134eb52010-08-31 21:07:20 +0000667
668 // Apply the offset, which we assume is non-null.
John McCall7f416cc2015-09-08 08:05:57 +0000669 llvm::Value *Addr =
670 Builder.CreateInBoundsGEP(Base.getPointer(), MemPtr, "memptr.offset");
John McCallc134eb52010-08-31 21:07:20 +0000671
672 // Cast the address to the appropriate pointer type, adopting the
673 // address space of the base pointer.
John McCall7f416cc2015-09-08 08:05:57 +0000674 llvm::Type *PType = CGF.ConvertTypeForMem(MPT->getPointeeType())
675 ->getPointerTo(Base.getAddressSpace());
John McCallc134eb52010-08-31 21:07:20 +0000676 return Builder.CreateBitCast(Addr, PType);
677}
678
John McCallc62bb392012-02-15 01:22:51 +0000679/// Perform a bitcast, derived-to-base, or base-to-derived member pointer
680/// conversion.
681///
682/// Bitcast conversions are always a no-op under Itanium.
John McCall7a9aac22010-08-23 01:21:21 +0000683///
684/// Obligatory offset/adjustment diagram:
685/// <-- offset --> <-- adjustment -->
686/// |--------------------------|----------------------|--------------------|
687/// ^Derived address point ^Base address point ^Member address point
688///
689/// So when converting a base member pointer to a derived member pointer,
690/// we add the offset to the adjustment because the address point has
691/// decreased; and conversely, when converting a derived MP to a base MP
692/// we subtract the offset from the adjustment because the address point
693/// has increased.
694///
695/// The standard forbids (at compile time) conversion to and from
696/// virtual bases, which is why we don't have to consider them here.
697///
698/// The standard forbids (at run time) casting a derived MP to a base
699/// MP when the derived MP does not point to a member of the base.
700/// This is why -1 is a reasonable choice for null data member
701/// pointers.
John McCalla1dee5302010-08-22 10:59:02 +0000702llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000703ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
704 const CastExpr *E,
John McCallc62bb392012-02-15 01:22:51 +0000705 llvm::Value *src) {
John McCalle3027922010-08-25 11:45:40 +0000706 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
John McCallc62bb392012-02-15 01:22:51 +0000707 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
708 E->getCastKind() == CK_ReinterpretMemberPointer);
709
710 // Under Itanium, reinterprets don't require any additional processing.
711 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
712
713 // Use constant emission if we can.
714 if (isa<llvm::Constant>(src))
715 return EmitMemberPointerConversion(E, cast<llvm::Constant>(src));
716
717 llvm::Constant *adj = getMemberPointerAdjustment(E);
718 if (!adj) return src;
John McCalla8bbb822010-08-22 03:04:22 +0000719
720 CGBuilderTy &Builder = CGF.Builder;
John McCallc62bb392012-02-15 01:22:51 +0000721 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
John McCalla8bbb822010-08-22 03:04:22 +0000722
John McCallc62bb392012-02-15 01:22:51 +0000723 const MemberPointerType *destTy =
724 E->getType()->castAs<MemberPointerType>();
John McCall1c456c82010-08-22 06:43:33 +0000725
John McCall7a9aac22010-08-23 01:21:21 +0000726 // For member data pointers, this is just a matter of adding the
727 // offset if the source is non-null.
John McCallc62bb392012-02-15 01:22:51 +0000728 if (destTy->isMemberDataPointer()) {
729 llvm::Value *dst;
730 if (isDerivedToBase)
731 dst = Builder.CreateNSWSub(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000732 else
John McCallc62bb392012-02-15 01:22:51 +0000733 dst = Builder.CreateNSWAdd(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000734
735 // Null check.
John McCallc62bb392012-02-15 01:22:51 +0000736 llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType());
737 llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull");
738 return Builder.CreateSelect(isNull, src, dst);
John McCall7a9aac22010-08-23 01:21:21 +0000739 }
740
John McCalla1dee5302010-08-22 10:59:02 +0000741 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000742 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000743 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
744 offset <<= 1;
745 adj = llvm::ConstantInt::get(adj->getType(), offset);
John McCalla1dee5302010-08-22 10:59:02 +0000746 }
747
John McCallc62bb392012-02-15 01:22:51 +0000748 llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj");
749 llvm::Value *dstAdj;
750 if (isDerivedToBase)
751 dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000752 else
John McCallc62bb392012-02-15 01:22:51 +0000753 dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000754
John McCallc62bb392012-02-15 01:22:51 +0000755 return Builder.CreateInsertValue(src, dstAdj, 1);
756}
757
758llvm::Constant *
759ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E,
760 llvm::Constant *src) {
761 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
762 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
763 E->getCastKind() == CK_ReinterpretMemberPointer);
764
765 // Under Itanium, reinterprets don't require any additional processing.
766 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
767
768 // If the adjustment is trivial, we don't need to do anything.
769 llvm::Constant *adj = getMemberPointerAdjustment(E);
770 if (!adj) return src;
771
772 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
773
774 const MemberPointerType *destTy =
775 E->getType()->castAs<MemberPointerType>();
776
777 // For member data pointers, this is just a matter of adding the
778 // offset if the source is non-null.
779 if (destTy->isMemberDataPointer()) {
780 // null maps to null.
781 if (src->isAllOnesValue()) return src;
782
783 if (isDerivedToBase)
784 return llvm::ConstantExpr::getNSWSub(src, adj);
785 else
786 return llvm::ConstantExpr::getNSWAdd(src, adj);
787 }
788
789 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000790 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000791 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
792 offset <<= 1;
793 adj = llvm::ConstantInt::get(adj->getType(), offset);
794 }
795
796 llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1);
797 llvm::Constant *dstAdj;
798 if (isDerivedToBase)
799 dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj);
800 else
801 dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj);
802
803 return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1);
John McCalla8bbb822010-08-22 03:04:22 +0000804}
John McCall84fa5102010-08-22 04:16:24 +0000805
806llvm::Constant *
John McCall7a9aac22010-08-23 01:21:21 +0000807ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
John McCall7a9aac22010-08-23 01:21:21 +0000808 // Itanium C++ ABI 2.3:
809 // A NULL pointer is represented as -1.
810 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000811 return llvm::ConstantInt::get(CGM.PtrDiffTy, -1ULL, /*isSigned=*/true);
John McCalla1dee5302010-08-22 10:59:02 +0000812
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000813 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.PtrDiffTy, 0);
John McCalla1dee5302010-08-22 10:59:02 +0000814 llvm::Constant *Values[2] = { Zero, Zero };
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000815 return llvm::ConstantStruct::getAnon(Values);
John McCall84fa5102010-08-22 04:16:24 +0000816}
817
John McCallf3a88602011-02-03 08:15:49 +0000818llvm::Constant *
819ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
820 CharUnits offset) {
John McCall7a9aac22010-08-23 01:21:21 +0000821 // Itanium C++ ABI 2.3:
822 // A pointer to data member is an offset from the base address of
823 // the class object containing it, represented as a ptrdiff_t
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000824 return llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity());
John McCall7a9aac22010-08-23 01:21:21 +0000825}
826
David Majnemere2be95b2015-06-23 07:31:01 +0000827llvm::Constant *
828ItaniumCXXABI::EmitMemberFunctionPointer(const CXXMethodDecl *MD) {
Richard Smithdafff942012-01-14 04:30:29 +0000829 return BuildMemberPointer(MD, CharUnits::Zero());
830}
831
832llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD,
833 CharUnits ThisAdjustment) {
John McCalla1dee5302010-08-22 10:59:02 +0000834 assert(MD->isInstance() && "Member function must not be static!");
835 MD = MD->getCanonicalDecl();
836
837 CodeGenTypes &Types = CGM.getTypes();
John McCalla1dee5302010-08-22 10:59:02 +0000838
839 // Get the function pointer (or index if this is a virtual function).
840 llvm::Constant *MemPtr[2];
841 if (MD->isVirtual()) {
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000842 uint64_t Index = CGM.getItaniumVTableContext().getMethodVTableIndex(MD);
John McCalla1dee5302010-08-22 10:59:02 +0000843
Ken Dyckdf016282011-04-09 01:30:02 +0000844 const ASTContext &Context = getContext();
845 CharUnits PointerWidth =
Douglas Gregore8bbc122011-09-02 00:18:52 +0000846 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Ken Dyckdf016282011-04-09 01:30:02 +0000847 uint64_t VTableOffset = (Index * PointerWidth.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000848
Mark Seabornedf0d382013-07-24 16:25:13 +0000849 if (UseARMMethodPtrABI) {
John McCalla1dee5302010-08-22 10:59:02 +0000850 // ARM C++ ABI 3.2.1:
851 // This ABI specifies that adj contains twice the this
852 // adjustment, plus 1 if the member function is virtual. The
853 // least significant bit of adj then makes exactly the same
854 // discrimination as the least significant bit of ptr does for
855 // Itanium.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000856 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset);
857 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000858 2 * ThisAdjustment.getQuantity() + 1);
John McCalla1dee5302010-08-22 10:59:02 +0000859 } else {
860 // Itanium C++ ABI 2.3:
861 // For a virtual function, [the pointer field] is 1 plus the
862 // virtual table offset (in bytes) of the function,
863 // represented as a ptrdiff_t.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000864 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset + 1);
865 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000866 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000867 }
868 } else {
John McCall2979fe02011-04-12 00:42:48 +0000869 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
Chris Lattner2192fe52011-07-18 04:24:23 +0000870 llvm::Type *Ty;
John McCall2979fe02011-04-12 00:42:48 +0000871 // Check whether the function has a computable LLVM signature.
Chris Lattner8806e322011-07-10 00:18:59 +0000872 if (Types.isFuncTypeConvertible(FPT)) {
John McCall2979fe02011-04-12 00:42:48 +0000873 // The function has a computable LLVM signature; use the correct type.
John McCalla729c622012-02-17 03:33:10 +0000874 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
John McCalla1dee5302010-08-22 10:59:02 +0000875 } else {
John McCall2979fe02011-04-12 00:42:48 +0000876 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
877 // function type is incomplete.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000878 Ty = CGM.PtrDiffTy;
John McCalla1dee5302010-08-22 10:59:02 +0000879 }
John McCall2979fe02011-04-12 00:42:48 +0000880 llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty);
John McCalla1dee5302010-08-22 10:59:02 +0000881
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000882 MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, CGM.PtrDiffTy);
Mark Seabornedf0d382013-07-24 16:25:13 +0000883 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
884 (UseARMMethodPtrABI ? 2 : 1) *
Richard Smithdafff942012-01-14 04:30:29 +0000885 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000886 }
John McCall1c456c82010-08-22 06:43:33 +0000887
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000888 return llvm::ConstantStruct::getAnon(MemPtr);
John McCall1c456c82010-08-22 06:43:33 +0000889}
890
Richard Smithdafff942012-01-14 04:30:29 +0000891llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP,
892 QualType MPType) {
893 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
894 const ValueDecl *MPD = MP.getMemberPointerDecl();
895 if (!MPD)
896 return EmitNullMemberPointer(MPT);
897
Reid Kleckner452abac2013-05-09 21:01:17 +0000898 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
Richard Smithdafff942012-01-14 04:30:29 +0000899
900 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
901 return BuildMemberPointer(MD, ThisAdjustment);
902
903 CharUnits FieldOffset =
904 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
905 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
906}
907
John McCall131d97d2010-08-22 08:30:07 +0000908/// The comparison algorithm is pretty easy: the member pointers are
909/// the same if they're either bitwise identical *or* both null.
910///
911/// ARM is different here only because null-ness is more complicated.
912llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000913ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
914 llvm::Value *L,
915 llvm::Value *R,
916 const MemberPointerType *MPT,
917 bool Inequality) {
John McCall131d97d2010-08-22 08:30:07 +0000918 CGBuilderTy &Builder = CGF.Builder;
919
John McCall131d97d2010-08-22 08:30:07 +0000920 llvm::ICmpInst::Predicate Eq;
921 llvm::Instruction::BinaryOps And, Or;
922 if (Inequality) {
923 Eq = llvm::ICmpInst::ICMP_NE;
924 And = llvm::Instruction::Or;
925 Or = llvm::Instruction::And;
926 } else {
927 Eq = llvm::ICmpInst::ICMP_EQ;
928 And = llvm::Instruction::And;
929 Or = llvm::Instruction::Or;
930 }
931
John McCall7a9aac22010-08-23 01:21:21 +0000932 // Member data pointers are easy because there's a unique null
933 // value, so it just comes down to bitwise equality.
934 if (MPT->isMemberDataPointer())
935 return Builder.CreateICmp(Eq, L, R);
936
937 // For member function pointers, the tautologies are more complex.
938 // The Itanium tautology is:
John McCall61a14882010-08-23 06:56:36 +0000939 // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
John McCall7a9aac22010-08-23 01:21:21 +0000940 // The ARM tautology is:
John McCall61a14882010-08-23 06:56:36 +0000941 // (L == R) <==> (L.ptr == R.ptr &&
942 // (L.adj == R.adj ||
943 // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
John McCall7a9aac22010-08-23 01:21:21 +0000944 // The inequality tautologies have exactly the same structure, except
945 // applying De Morgan's laws.
946
947 llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
948 llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
949
John McCall131d97d2010-08-22 08:30:07 +0000950 // This condition tests whether L.ptr == R.ptr. This must always be
951 // true for equality to hold.
952 llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
953
954 // This condition, together with the assumption that L.ptr == R.ptr,
955 // tests whether the pointers are both null. ARM imposes an extra
956 // condition.
957 llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
958 llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
959
960 // This condition tests whether L.adj == R.adj. If this isn't
961 // true, the pointers are unequal unless they're both null.
John McCalla1dee5302010-08-22 10:59:02 +0000962 llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
963 llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000964 llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
965
966 // Null member function pointers on ARM clear the low bit of Adj,
967 // so the zero condition has to check that neither low bit is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000968 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000969 llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
970
971 // Compute (l.adj | r.adj) & 1 and test it against zero.
972 llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
973 llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
974 llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
975 "cmp.or.adj");
976 EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
977 }
978
979 // Tie together all our conditions.
980 llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
981 Result = Builder.CreateBinOp(And, PtrEq, Result,
982 Inequality ? "memptr.ne" : "memptr.eq");
983 return Result;
984}
985
986llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000987ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
988 llvm::Value *MemPtr,
989 const MemberPointerType *MPT) {
John McCall131d97d2010-08-22 08:30:07 +0000990 CGBuilderTy &Builder = CGF.Builder;
John McCall7a9aac22010-08-23 01:21:21 +0000991
992 /// For member data pointers, this is just a check against -1.
993 if (MPT->isMemberDataPointer()) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000994 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCall7a9aac22010-08-23 01:21:21 +0000995 llvm::Value *NegativeOne =
996 llvm::Constant::getAllOnesValue(MemPtr->getType());
997 return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
998 }
John McCall131d97d2010-08-22 08:30:07 +0000999
Daniel Dunbar914bc412011-04-19 23:10:47 +00001000 // In Itanium, a member function pointer is not null if 'ptr' is not null.
John McCalla1dee5302010-08-22 10:59:02 +00001001 llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
John McCall131d97d2010-08-22 08:30:07 +00001002
1003 llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
1004 llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
1005
Daniel Dunbar914bc412011-04-19 23:10:47 +00001006 // On ARM, a member function pointer is also non-null if the low bit of 'adj'
1007 // (the virtual bit) is set.
Mark Seabornedf0d382013-07-24 16:25:13 +00001008 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +00001009 llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
John McCalla1dee5302010-08-22 10:59:02 +00001010 llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +00001011 llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
Daniel Dunbar914bc412011-04-19 23:10:47 +00001012 llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero,
1013 "memptr.isvirtual");
1014 Result = Builder.CreateOr(Result, IsVirtual);
John McCall131d97d2010-08-22 08:30:07 +00001015 }
1016
1017 return Result;
1018}
John McCall1c456c82010-08-22 06:43:33 +00001019
Reid Kleckner40ca9132014-05-13 22:05:45 +00001020bool ItaniumCXXABI::classifyReturnType(CGFunctionInfo &FI) const {
1021 const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl();
1022 if (!RD)
1023 return false;
1024
Richard Smith96cd6712017-08-16 01:49:53 +00001025 // If C++ prohibits us from making a copy, return by address.
Richard Smithf667ad52017-08-26 01:04:35 +00001026 if (passClassIndirect(RD)) {
John McCall7f416cc2015-09-08 08:05:57 +00001027 auto Align = CGM.getContext().getTypeAlignInChars(FI.getReturnType());
1028 FI.getReturnInfo() = ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
Reid Kleckner40ca9132014-05-13 22:05:45 +00001029 return true;
1030 }
Reid Kleckner40ca9132014-05-13 22:05:45 +00001031 return false;
1032}
1033
John McCall614dbdc2010-08-22 21:01:12 +00001034/// The Itanium ABI requires non-zero initialization only for data
1035/// member pointers, for which '0' is a valid offset.
1036bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
David Majnemer5fd33e02015-04-24 01:25:08 +00001037 return MPT->isMemberFunctionPointer();
John McCall84fa5102010-08-22 04:16:24 +00001038}
John McCall5d865c322010-08-31 07:33:07 +00001039
John McCall82fb8922012-09-25 10:10:39 +00001040/// The Itanium ABI always places an offset to the complete object
1041/// at entry -2 in the vtable.
David Majnemer08681372014-11-01 07:37:17 +00001042void ItaniumCXXABI::emitVirtualObjectDelete(CodeGenFunction &CGF,
1043 const CXXDeleteExpr *DE,
John McCall7f416cc2015-09-08 08:05:57 +00001044 Address Ptr,
David Majnemer08681372014-11-01 07:37:17 +00001045 QualType ElementType,
1046 const CXXDestructorDecl *Dtor) {
1047 bool UseGlobalDelete = DE->isGlobalDelete();
David Majnemer0c0b6d92014-10-31 20:09:12 +00001048 if (UseGlobalDelete) {
1049 // Derive the complete-object pointer, which is what we need
1050 // to pass to the deallocation function.
John McCall82fb8922012-09-25 10:10:39 +00001051
David Majnemer0c0b6d92014-10-31 20:09:12 +00001052 // Grab the vtable pointer as an intptr_t*.
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001053 auto *ClassDecl =
1054 cast<CXXRecordDecl>(ElementType->getAs<RecordType>()->getDecl());
1055 llvm::Value *VTable =
1056 CGF.GetVTablePtr(Ptr, CGF.IntPtrTy->getPointerTo(), ClassDecl);
John McCall82fb8922012-09-25 10:10:39 +00001057
David Majnemer0c0b6d92014-10-31 20:09:12 +00001058 // Track back to entry -2 and pull out the offset there.
1059 llvm::Value *OffsetPtr = CGF.Builder.CreateConstInBoundsGEP1_64(
1060 VTable, -2, "complete-offset.ptr");
John McCall7f416cc2015-09-08 08:05:57 +00001061 llvm::Value *Offset =
1062 CGF.Builder.CreateAlignedLoad(OffsetPtr, CGF.getPointerAlign());
David Majnemer0c0b6d92014-10-31 20:09:12 +00001063
1064 // Apply the offset.
John McCall7f416cc2015-09-08 08:05:57 +00001065 llvm::Value *CompletePtr =
1066 CGF.Builder.CreateBitCast(Ptr.getPointer(), CGF.Int8PtrTy);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001067 CompletePtr = CGF.Builder.CreateInBoundsGEP(CompletePtr, Offset);
1068
1069 // If we're supposed to call the global delete, make sure we do so
1070 // even if the destructor throws.
David Majnemer08681372014-11-01 07:37:17 +00001071 CGF.pushCallObjectDeleteCleanup(DE->getOperatorDelete(), CompletePtr,
1072 ElementType);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001073 }
1074
1075 // FIXME: Provide a source location here even though there's no
1076 // CXXMemberCallExpr for dtor call.
1077 CXXDtorType DtorType = UseGlobalDelete ? Dtor_Complete : Dtor_Deleting;
1078 EmitVirtualDestructorCall(CGF, Dtor, DtorType, Ptr, /*CE=*/nullptr);
1079
1080 if (UseGlobalDelete)
1081 CGF.PopCleanupBlock();
John McCall82fb8922012-09-25 10:10:39 +00001082}
1083
David Majnemer442d0a22014-11-25 07:20:20 +00001084void ItaniumCXXABI::emitRethrow(CodeGenFunction &CGF, bool isNoReturn) {
1085 // void __cxa_rethrow();
1086
1087 llvm::FunctionType *FTy =
1088 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
1089
1090 llvm::Constant *Fn = CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow");
1091
1092 if (isNoReturn)
1093 CGF.EmitNoreturnRuntimeCallOrInvoke(Fn, None);
1094 else
1095 CGF.EmitRuntimeCallOrInvoke(Fn);
1096}
1097
David Majnemer7c237072015-03-05 00:46:22 +00001098static llvm::Constant *getAllocateExceptionFn(CodeGenModule &CGM) {
1099 // void *__cxa_allocate_exception(size_t thrown_size);
1100
1101 llvm::FunctionType *FTy =
1102 llvm::FunctionType::get(CGM.Int8PtrTy, CGM.SizeTy, /*IsVarArgs=*/false);
1103
1104 return CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
1105}
1106
1107static llvm::Constant *getThrowFn(CodeGenModule &CGM) {
1108 // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
1109 // void (*dest) (void *));
1110
1111 llvm::Type *Args[3] = { CGM.Int8PtrTy, CGM.Int8PtrTy, CGM.Int8PtrTy };
1112 llvm::FunctionType *FTy =
1113 llvm::FunctionType::get(CGM.VoidTy, Args, /*IsVarArgs=*/false);
1114
1115 return CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
1116}
1117
1118void ItaniumCXXABI::emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) {
1119 QualType ThrowType = E->getSubExpr()->getType();
1120 // Now allocate the exception object.
1121 llvm::Type *SizeTy = CGF.ConvertType(getContext().getSizeType());
1122 uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
1123
1124 llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(CGM);
1125 llvm::CallInst *ExceptionPtr = CGF.EmitNounwindRuntimeCall(
1126 AllocExceptionFn, llvm::ConstantInt::get(SizeTy, TypeSize), "exception");
1127
John McCall7f416cc2015-09-08 08:05:57 +00001128 CharUnits ExnAlign = getAlignmentOfExnObject();
1129 CGF.EmitAnyExprToExn(E->getSubExpr(), Address(ExceptionPtr, ExnAlign));
David Majnemer7c237072015-03-05 00:46:22 +00001130
1131 // Now throw the exception.
1132 llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType,
1133 /*ForEH=*/true);
1134
1135 // The address of the destructor. If the exception type has a
1136 // trivial destructor (or isn't a record), we just pass null.
1137 llvm::Constant *Dtor = nullptr;
1138 if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
1139 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
1140 if (!Record->hasTrivialDestructor()) {
1141 CXXDestructorDecl *DtorD = Record->getDestructor();
1142 Dtor = CGM.getAddrOfCXXStructor(DtorD, StructorType::Complete);
1143 Dtor = llvm::ConstantExpr::getBitCast(Dtor, CGM.Int8PtrTy);
1144 }
1145 }
1146 if (!Dtor) Dtor = llvm::Constant::getNullValue(CGM.Int8PtrTy);
1147
1148 llvm::Value *args[] = { ExceptionPtr, TypeInfo, Dtor };
1149 CGF.EmitNoreturnRuntimeCallOrInvoke(getThrowFn(CGM), args);
1150}
1151
David Majnemer1162d252014-06-22 19:05:33 +00001152static llvm::Constant *getItaniumDynamicCastFn(CodeGenFunction &CGF) {
1153 // void *__dynamic_cast(const void *sub,
1154 // const abi::__class_type_info *src,
1155 // const abi::__class_type_info *dst,
1156 // std::ptrdiff_t src2dst_offset);
1157
1158 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
1159 llvm::Type *PtrDiffTy =
1160 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1161
1162 llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
1163
1164 llvm::FunctionType *FTy = llvm::FunctionType::get(Int8PtrTy, Args, false);
1165
1166 // Mark the function as nounwind readonly.
1167 llvm::Attribute::AttrKind FuncAttrs[] = { llvm::Attribute::NoUnwind,
1168 llvm::Attribute::ReadOnly };
Reid Klecknerde864822017-03-21 16:57:30 +00001169 llvm::AttributeList Attrs = llvm::AttributeList::get(
1170 CGF.getLLVMContext(), llvm::AttributeList::FunctionIndex, FuncAttrs);
David Majnemer1162d252014-06-22 19:05:33 +00001171
1172 return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast", Attrs);
1173}
1174
1175static llvm::Constant *getBadCastFn(CodeGenFunction &CGF) {
1176 // void __cxa_bad_cast();
1177 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1178 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
1179}
1180
1181/// \brief Compute the src2dst_offset hint as described in the
1182/// Itanium C++ ABI [2.9.7]
1183static CharUnits computeOffsetHint(ASTContext &Context,
1184 const CXXRecordDecl *Src,
1185 const CXXRecordDecl *Dst) {
1186 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1187 /*DetectVirtual=*/false);
1188
1189 // If Dst is not derived from Src we can skip the whole computation below and
1190 // return that Src is not a public base of Dst. Record all inheritance paths.
1191 if (!Dst->isDerivedFrom(Src, Paths))
1192 return CharUnits::fromQuantity(-2ULL);
1193
1194 unsigned NumPublicPaths = 0;
1195 CharUnits Offset;
1196
1197 // Now walk all possible inheritance paths.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001198 for (const CXXBasePath &Path : Paths) {
1199 if (Path.Access != AS_public) // Ignore non-public inheritance.
David Majnemer1162d252014-06-22 19:05:33 +00001200 continue;
1201
1202 ++NumPublicPaths;
1203
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001204 for (const CXXBasePathElement &PathElement : Path) {
David Majnemer1162d252014-06-22 19:05:33 +00001205 // If the path contains a virtual base class we can't give any hint.
1206 // -1: no hint.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001207 if (PathElement.Base->isVirtual())
David Majnemer1162d252014-06-22 19:05:33 +00001208 return CharUnits::fromQuantity(-1ULL);
1209
1210 if (NumPublicPaths > 1) // Won't use offsets, skip computation.
1211 continue;
1212
1213 // Accumulate the base class offsets.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001214 const ASTRecordLayout &L = Context.getASTRecordLayout(PathElement.Class);
1215 Offset += L.getBaseClassOffset(
1216 PathElement.Base->getType()->getAsCXXRecordDecl());
David Majnemer1162d252014-06-22 19:05:33 +00001217 }
1218 }
1219
1220 // -2: Src is not a public base of Dst.
1221 if (NumPublicPaths == 0)
1222 return CharUnits::fromQuantity(-2ULL);
1223
1224 // -3: Src is a multiple public base type but never a virtual base type.
1225 if (NumPublicPaths > 1)
1226 return CharUnits::fromQuantity(-3ULL);
1227
1228 // Otherwise, the Src type is a unique public nonvirtual base type of Dst.
1229 // Return the offset of Src from the origin of Dst.
1230 return Offset;
1231}
1232
1233static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) {
1234 // void __cxa_bad_typeid();
1235 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1236
1237 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
1238}
1239
1240bool ItaniumCXXABI::shouldTypeidBeNullChecked(bool IsDeref,
1241 QualType SrcRecordTy) {
1242 return IsDeref;
1243}
1244
1245void ItaniumCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) {
1246 llvm::Value *Fn = getBadTypeidFn(CGF);
1247 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
1248 CGF.Builder.CreateUnreachable();
1249}
1250
1251llvm::Value *ItaniumCXXABI::EmitTypeid(CodeGenFunction &CGF,
1252 QualType SrcRecordTy,
John McCall7f416cc2015-09-08 08:05:57 +00001253 Address ThisPtr,
David Majnemer1162d252014-06-22 19:05:33 +00001254 llvm::Type *StdTypeInfoPtrTy) {
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001255 auto *ClassDecl =
1256 cast<CXXRecordDecl>(SrcRecordTy->getAs<RecordType>()->getDecl());
David Majnemer1162d252014-06-22 19:05:33 +00001257 llvm::Value *Value =
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001258 CGF.GetVTablePtr(ThisPtr, StdTypeInfoPtrTy->getPointerTo(), ClassDecl);
David Majnemer1162d252014-06-22 19:05:33 +00001259
1260 // Load the type info.
1261 Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL);
John McCall7f416cc2015-09-08 08:05:57 +00001262 return CGF.Builder.CreateAlignedLoad(Value, CGF.getPointerAlign());
David Majnemer1162d252014-06-22 19:05:33 +00001263}
1264
1265bool ItaniumCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
1266 QualType SrcRecordTy) {
1267 return SrcIsPtr;
1268}
1269
1270llvm::Value *ItaniumCXXABI::EmitDynamicCastCall(
John McCall7f416cc2015-09-08 08:05:57 +00001271 CodeGenFunction &CGF, Address ThisAddr, QualType SrcRecordTy,
David Majnemer1162d252014-06-22 19:05:33 +00001272 QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) {
1273 llvm::Type *PtrDiffLTy =
1274 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1275 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1276
1277 llvm::Value *SrcRTTI =
1278 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
1279 llvm::Value *DestRTTI =
1280 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
1281
1282 // Compute the offset hint.
1283 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
1284 const CXXRecordDecl *DestDecl = DestRecordTy->getAsCXXRecordDecl();
1285 llvm::Value *OffsetHint = llvm::ConstantInt::get(
1286 PtrDiffLTy,
1287 computeOffsetHint(CGF.getContext(), SrcDecl, DestDecl).getQuantity());
1288
1289 // Emit the call to __dynamic_cast.
John McCall7f416cc2015-09-08 08:05:57 +00001290 llvm::Value *Value = ThisAddr.getPointer();
David Majnemer1162d252014-06-22 19:05:33 +00001291 Value = CGF.EmitCastToVoidPtr(Value);
1292
1293 llvm::Value *args[] = {Value, SrcRTTI, DestRTTI, OffsetHint};
1294 Value = CGF.EmitNounwindRuntimeCall(getItaniumDynamicCastFn(CGF), args);
1295 Value = CGF.Builder.CreateBitCast(Value, DestLTy);
1296
1297 /// C++ [expr.dynamic.cast]p9:
1298 /// A failed cast to reference type throws std::bad_cast
1299 if (DestTy->isReferenceType()) {
1300 llvm::BasicBlock *BadCastBlock =
1301 CGF.createBasicBlock("dynamic_cast.bad_cast");
1302
1303 llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
1304 CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
1305
1306 CGF.EmitBlock(BadCastBlock);
1307 EmitBadCastCall(CGF);
1308 }
1309
1310 return Value;
1311}
1312
1313llvm::Value *ItaniumCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001314 Address ThisAddr,
David Majnemer1162d252014-06-22 19:05:33 +00001315 QualType SrcRecordTy,
1316 QualType DestTy) {
1317 llvm::Type *PtrDiffLTy =
1318 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1319 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1320
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001321 auto *ClassDecl =
1322 cast<CXXRecordDecl>(SrcRecordTy->getAs<RecordType>()->getDecl());
David Majnemer1162d252014-06-22 19:05:33 +00001323 // Get the vtable pointer.
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001324 llvm::Value *VTable = CGF.GetVTablePtr(ThisAddr, PtrDiffLTy->getPointerTo(),
1325 ClassDecl);
David Majnemer1162d252014-06-22 19:05:33 +00001326
1327 // Get the offset-to-top from the vtable.
1328 llvm::Value *OffsetToTop =
1329 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL);
John McCall7f416cc2015-09-08 08:05:57 +00001330 OffsetToTop =
1331 CGF.Builder.CreateAlignedLoad(OffsetToTop, CGF.getPointerAlign(),
1332 "offset.to.top");
David Majnemer1162d252014-06-22 19:05:33 +00001333
1334 // Finally, add the offset to the pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001335 llvm::Value *Value = ThisAddr.getPointer();
David Majnemer1162d252014-06-22 19:05:33 +00001336 Value = CGF.EmitCastToVoidPtr(Value);
1337 Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop);
1338
1339 return CGF.Builder.CreateBitCast(Value, DestLTy);
1340}
1341
1342bool ItaniumCXXABI::EmitBadCastCall(CodeGenFunction &CGF) {
1343 llvm::Value *Fn = getBadCastFn(CGF);
1344 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
1345 CGF.Builder.CreateUnreachable();
1346 return true;
1347}
1348
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001349llvm::Value *
1350ItaniumCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001351 Address This,
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001352 const CXXRecordDecl *ClassDecl,
1353 const CXXRecordDecl *BaseClassDecl) {
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001354 llvm::Value *VTablePtr = CGF.GetVTablePtr(This, CGM.Int8PtrTy, ClassDecl);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001355 CharUnits VBaseOffsetOffset =
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001356 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(ClassDecl,
1357 BaseClassDecl);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001358
1359 llvm::Value *VBaseOffsetPtr =
1360 CGF.Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
1361 "vbase.offset.ptr");
1362 VBaseOffsetPtr = CGF.Builder.CreateBitCast(VBaseOffsetPtr,
1363 CGM.PtrDiffTy->getPointerTo());
1364
1365 llvm::Value *VBaseOffset =
John McCall7f416cc2015-09-08 08:05:57 +00001366 CGF.Builder.CreateAlignedLoad(VBaseOffsetPtr, CGF.getPointerAlign(),
1367 "vbase.offset");
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001368
1369 return VBaseOffset;
1370}
1371
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001372void ItaniumCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
1373 // Just make sure we're in sync with TargetCXXABI.
1374 assert(CGM.getTarget().getCXXABI().hasConstructorVariants());
1375
Rafael Espindolac3cde362013-12-09 14:51:17 +00001376 // The constructor used for constructing this as a base class;
1377 // ignores virtual bases.
1378 CGM.EmitGlobal(GlobalDecl(D, Ctor_Base));
1379
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001380 // The constructor used for constructing this as a complete class;
Nico Weber4c2ffb22015-01-07 05:25:05 +00001381 // constructs the virtual bases, then calls the base constructor.
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001382 if (!D->getParent()->isAbstract()) {
1383 // We don't need to emit the complete ctor if the class is abstract.
1384 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
1385 }
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001386}
1387
George Burgess IVf203dbf2017-02-22 20:28:02 +00001388CGCXXABI::AddedStructorArgs
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001389ItaniumCXXABI::buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
1390 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9bca9232010-09-02 10:25:57 +00001391 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001392
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001393 // All parameters are already in place except VTT, which goes after 'this'.
1394 // These are Clang types, so we don't need to worry about sret yet.
John McCall5d865c322010-08-31 07:33:07 +00001395
1396 // Check if we need to add a VTT parameter (which has type void **).
George Burgess IVf203dbf2017-02-22 20:28:02 +00001397 if (T == StructorType::Base && MD->getParent()->getNumVBases() != 0) {
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001398 ArgTys.insert(ArgTys.begin() + 1,
1399 Context.getPointerType(Context.VoidPtrTy));
George Burgess IVf203dbf2017-02-22 20:28:02 +00001400 return AddedStructorArgs::prefix(1);
1401 }
1402 return AddedStructorArgs{};
John McCall5d865c322010-08-31 07:33:07 +00001403}
1404
Reid Klecknere7de47e2013-07-22 13:51:44 +00001405void ItaniumCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
Rafael Espindolac3cde362013-12-09 14:51:17 +00001406 // The destructor used for destructing this as a base class; ignores
1407 // virtual bases.
1408 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001409
1410 // The destructor used for destructing this as a most-derived class;
1411 // call the base destructor and then destructs any virtual bases.
1412 CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));
1413
Rafael Espindolac3cde362013-12-09 14:51:17 +00001414 // The destructor in a virtual table is always a 'deleting'
1415 // destructor, which calls the complete destructor and then uses the
1416 // appropriate operator delete.
1417 if (D->isVirtual())
1418 CGM.EmitGlobal(GlobalDecl(D, Dtor_Deleting));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001419}
1420
Reid Kleckner89077a12013-12-17 19:46:40 +00001421void ItaniumCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
1422 QualType &ResTy,
1423 FunctionArgList &Params) {
John McCall5d865c322010-08-31 07:33:07 +00001424 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
Reid Kleckner89077a12013-12-17 19:46:40 +00001425 assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
John McCall5d865c322010-08-31 07:33:07 +00001426
1427 // Check if we need a VTT parameter as well.
Peter Collingbourne66f82e62013-06-28 20:45:28 +00001428 if (NeedsVTTParameter(CGF.CurGD)) {
John McCall9bca9232010-09-02 10:25:57 +00001429 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001430
1431 // FIXME: avoid the fake decl
1432 QualType T = Context.getPointerType(Context.VoidPtrTy);
Alexey Bataev56223232017-06-09 13:40:18 +00001433 auto *VTTDecl = ImplicitParamDecl::Create(
1434 Context, /*DC=*/nullptr, MD->getLocation(), &Context.Idents.get("vtt"),
1435 T, ImplicitParamDecl::CXXVTT);
Reid Kleckner89077a12013-12-17 19:46:40 +00001436 Params.insert(Params.begin() + 1, VTTDecl);
Reid Kleckner2af6d732013-12-13 00:09:59 +00001437 getStructorImplicitParamDecl(CGF) = VTTDecl;
John McCall5d865c322010-08-31 07:33:07 +00001438 }
1439}
1440
John McCall5d865c322010-08-31 07:33:07 +00001441void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
Justin Lebared4f1722016-07-27 22:04:24 +00001442 // Naked functions have no prolog.
1443 if (CGF.CurFuncDecl && CGF.CurFuncDecl->hasAttr<NakedAttr>())
1444 return;
1445
John McCall5d865c322010-08-31 07:33:07 +00001446 /// Initialize the 'this' slot.
1447 EmitThisParam(CGF);
1448
1449 /// Initialize the 'vtt' slot if needed.
Reid Kleckner2af6d732013-12-13 00:09:59 +00001450 if (getStructorImplicitParamDecl(CGF)) {
1451 getStructorImplicitParamValue(CGF) = CGF.Builder.CreateLoad(
1452 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), "vtt");
John McCall5d865c322010-08-31 07:33:07 +00001453 }
John McCall5d865c322010-08-31 07:33:07 +00001454
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001455 /// If this is a function that the ABI specifies returns 'this', initialize
1456 /// the return slot to 'this' at the start of the function.
1457 ///
1458 /// Unlike the setting of return types, this is done within the ABI
1459 /// implementation instead of by clients of CGCXXABI because:
1460 /// 1) getThisValue is currently protected
1461 /// 2) in theory, an ABI could implement 'this' returns some other way;
1462 /// HasThisReturn only specifies a contract, not the implementation
John McCall5d865c322010-08-31 07:33:07 +00001463 if (HasThisReturn(CGF.CurGD))
Eli Friedman9fbeba02012-02-11 02:57:39 +00001464 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
John McCall5d865c322010-08-31 07:33:07 +00001465}
1466
George Burgess IVf203dbf2017-02-22 20:28:02 +00001467CGCXXABI::AddedStructorArgs ItaniumCXXABI::addImplicitConstructorArgs(
Reid Kleckner89077a12013-12-17 19:46:40 +00001468 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
1469 bool ForVirtualBase, bool Delegating, CallArgList &Args) {
1470 if (!NeedsVTTParameter(GlobalDecl(D, Type)))
George Burgess IVf203dbf2017-02-22 20:28:02 +00001471 return AddedStructorArgs{};
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001472
Reid Kleckner89077a12013-12-17 19:46:40 +00001473 // Insert the implicit 'vtt' argument as the second argument.
1474 llvm::Value *VTT =
1475 CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase, Delegating);
1476 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1477 Args.insert(Args.begin() + 1,
1478 CallArg(RValue::get(VTT), VTTTy, /*needscopy=*/false));
George Burgess IVf203dbf2017-02-22 20:28:02 +00001479 return AddedStructorArgs::prefix(1); // Added one arg.
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001480}
1481
1482void ItaniumCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
1483 const CXXDestructorDecl *DD,
1484 CXXDtorType Type, bool ForVirtualBase,
John McCall7f416cc2015-09-08 08:05:57 +00001485 bool Delegating, Address This) {
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001486 GlobalDecl GD(DD, Type);
1487 llvm::Value *VTT = CGF.GetVTTParameter(GD, ForVirtualBase, Delegating);
1488 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1489
John McCallb92ab1a2016-10-26 23:46:34 +00001490 CGCallee Callee;
1491 if (getContext().getLangOpts().AppleKext &&
1492 Type != Dtor_Base && DD->isVirtual())
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001493 Callee = CGF.BuildAppleKextVirtualDestructorCall(DD, Type, DD->getParent());
John McCallb92ab1a2016-10-26 23:46:34 +00001494 else
1495 Callee =
1496 CGCallee::forDirect(CGM.getAddrOfCXXStructor(DD, getFromDtorType(Type)),
1497 DD);
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001498
John McCall7f416cc2015-09-08 08:05:57 +00001499 CGF.EmitCXXMemberOrOperatorCall(DD, Callee, ReturnValueSlot(),
Richard Smith762672a2016-09-28 19:09:10 +00001500 This.getPointer(), VTT, VTTTy,
1501 nullptr, nullptr);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001502}
1503
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001504void ItaniumCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
1505 const CXXRecordDecl *RD) {
1506 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, CharUnits());
1507 if (VTable->hasInitializer())
1508 return;
1509
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001510 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001511 const VTableLayout &VTLayout = VTContext.getVTableLayout(RD);
1512 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
David Majnemerd905da42014-07-01 20:30:31 +00001513 llvm::Constant *RTTI =
1514 CGM.GetAddrOfRTTIDescriptor(CGM.getContext().getTagDeclType(RD));
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001515
1516 // Create and set the initializer.
John McCall9c6cb762016-11-28 22:18:33 +00001517 ConstantInitBuilder Builder(CGM);
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001518 auto Components = Builder.beginStruct();
John McCall9c6cb762016-11-28 22:18:33 +00001519 CGVT.createVTableInitializer(Components, VTLayout, RTTI);
1520 Components.finishAndSetAsInitializer(VTable);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001521
1522 // Set the correct linkage.
1523 VTable->setLinkage(Linkage);
1524
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00001525 if (CGM.supportsCOMDAT() && VTable->isWeakForLinker())
1526 VTable->setComdat(CGM.getModule().getOrInsertComdat(VTable->getName()));
Rafael Espindolacb92c192015-01-15 23:18:01 +00001527
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001528 // Set the right visibility.
John McCall8f80a612014-02-08 00:41:16 +00001529 CGM.setGlobalVisibility(VTable, RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001530
Benjamin Kramer5d34a2b2014-09-10 12:50:59 +00001531 // Use pointer alignment for the vtable. Otherwise we would align them based
1532 // on the size of the initializer which doesn't make sense as only single
1533 // values are read.
1534 unsigned PAlign = CGM.getTarget().getPointerAlign(0);
1535 VTable->setAlignment(getContext().toCharUnitsFromBits(PAlign).getQuantity());
1536
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001537 // If this is the magic class __cxxabiv1::__fundamental_type_info,
1538 // we will emit the typeinfo for the fundamental types. This is the
1539 // same behaviour as GCC.
1540 const DeclContext *DC = RD->getDeclContext();
1541 if (RD->getIdentifier() &&
1542 RD->getIdentifier()->isStr("__fundamental_type_info") &&
1543 isa<NamespaceDecl>(DC) && cast<NamespaceDecl>(DC)->getIdentifier() &&
1544 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
1545 DC->getParent()->isTranslationUnit())
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00001546 EmitFundamentalRTTIDescriptors(RD->hasAttr<DLLExportAttr>());
Peter Collingbournea4ccff32015-02-20 20:30:56 +00001547
Evgeniy Stepanov93987df2016-01-23 01:20:18 +00001548 if (!VTable->isDeclarationForLinker())
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00001549 CGM.EmitVTableTypeMetadata(VTable, VTLayout);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001550}
1551
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001552bool ItaniumCXXABI::isVirtualOffsetNeededForVTableField(
1553 CodeGenFunction &CGF, CodeGenFunction::VPtr Vptr) {
1554 if (Vptr.NearestVBase == nullptr)
1555 return false;
1556 return NeedsVTTParameter(CGF.CurGD);
Piotr Padlewski255652e2015-09-09 22:20:28 +00001557}
1558
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001559llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructor(
1560 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1561 const CXXRecordDecl *NearestVBase) {
1562
1563 if ((Base.getBase()->getNumVBases() || NearestVBase != nullptr) &&
1564 NeedsVTTParameter(CGF.CurGD)) {
1565 return getVTableAddressPointInStructorWithVTT(CGF, VTableClass, Base,
1566 NearestVBase);
1567 }
1568 return getVTableAddressPoint(Base, VTableClass);
1569}
1570
1571llvm::Constant *
1572ItaniumCXXABI::getVTableAddressPoint(BaseSubobject Base,
1573 const CXXRecordDecl *VTableClass) {
1574 llvm::GlobalValue *VTable = getAddrOfVTable(VTableClass, CharUnits());
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001575
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001576 // Find the appropriate vtable within the vtable group, and the address point
1577 // within that vtable.
1578 VTableLayout::AddressPointLocation AddressPoint =
1579 CGM.getItaniumVTableContext()
1580 .getVTableLayout(VTableClass)
1581 .getAddressPoint(Base);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001582 llvm::Value *Indices[] = {
Peter Collingbourne4e6a5402016-03-14 19:07:10 +00001583 llvm::ConstantInt::get(CGM.Int32Ty, 0),
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001584 llvm::ConstantInt::get(CGM.Int32Ty, AddressPoint.VTableIndex),
1585 llvm::ConstantInt::get(CGM.Int32Ty, AddressPoint.AddressPointIndex),
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001586 };
1587
Peter Collingbourne25a2b702016-12-13 20:50:44 +00001588 return llvm::ConstantExpr::getGetElementPtr(VTable->getValueType(), VTable,
1589 Indices, /*InBounds=*/true,
1590 /*InRangeIndex=*/1);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001591}
1592
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001593llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructorWithVTT(
1594 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1595 const CXXRecordDecl *NearestVBase) {
1596 assert((Base.getBase()->getNumVBases() || NearestVBase != nullptr) &&
1597 NeedsVTTParameter(CGF.CurGD) && "This class doesn't have VTT");
1598
1599 // Get the secondary vpointer index.
1600 uint64_t VirtualPointerIndex =
1601 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1602
1603 /// Load the VTT.
1604 llvm::Value *VTT = CGF.LoadCXXVTT();
1605 if (VirtualPointerIndex)
1606 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1607
1608 // And load the address point from the VTT.
1609 return CGF.Builder.CreateAlignedLoad(VTT, CGF.getPointerAlign());
1610}
1611
1612llvm::Constant *ItaniumCXXABI::getVTableAddressPointForConstExpr(
1613 BaseSubobject Base, const CXXRecordDecl *VTableClass) {
1614 return getVTableAddressPoint(Base, VTableClass);
1615}
1616
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001617llvm::GlobalVariable *ItaniumCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
1618 CharUnits VPtrOffset) {
1619 assert(VPtrOffset.isZero() && "Itanium ABI only supports zero vptr offsets");
1620
1621 llvm::GlobalVariable *&VTable = VTables[RD];
1622 if (VTable)
1623 return VTable;
1624
Eric Christopherd160c502016-01-29 01:35:53 +00001625 // Queue up this vtable for possible deferred emission.
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001626 CGM.addDeferredVTable(RD);
1627
Yaron Kerene46f7ed2015-07-29 14:21:47 +00001628 SmallString<256> Name;
1629 llvm::raw_svector_ostream Out(Name);
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00001630 getMangleContext().mangleCXXVTable(RD, Out);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001631
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001632 const VTableLayout &VTLayout =
1633 CGM.getItaniumVTableContext().getVTableLayout(RD);
1634 llvm::Type *VTableType = CGM.getVTables().getVTableType(VTLayout);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001635
1636 VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001637 Name, VTableType, llvm::GlobalValue::ExternalLinkage);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00001638 VTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Hans Wennborgda24e9c2014-06-02 23:13:03 +00001639
1640 if (RD->hasAttr<DLLImportAttr>())
1641 VTable->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1642 else if (RD->hasAttr<DLLExportAttr>())
1643 VTable->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1644
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001645 return VTable;
1646}
1647
John McCallb92ab1a2016-10-26 23:46:34 +00001648CGCallee ItaniumCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
1649 GlobalDecl GD,
1650 Address This,
1651 llvm::Type *Ty,
1652 SourceLocation Loc) {
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001653 GD = GD.getCanonicalDecl();
1654 Ty = Ty->getPointerTo()->getPointerTo();
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001655 auto *MethodDecl = cast<CXXMethodDecl>(GD.getDecl());
1656 llvm::Value *VTable = CGF.GetVTablePtr(This, Ty, MethodDecl->getParent());
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001657
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001658 uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
John McCallb92ab1a2016-10-26 23:46:34 +00001659 llvm::Value *VFunc;
Peter Collingbourne0ca03632016-06-25 00:24:06 +00001660 if (CGF.ShouldEmitVTableTypeCheckedLoad(MethodDecl->getParent())) {
John McCallb92ab1a2016-10-26 23:46:34 +00001661 VFunc = CGF.EmitVTableTypeCheckedLoad(
Peter Collingbourne0ca03632016-06-25 00:24:06 +00001662 MethodDecl->getParent(), VTable,
1663 VTableIndex * CGM.getContext().getTargetInfo().getPointerWidth(0) / 8);
1664 } else {
1665 CGF.EmitTypeMetadataCodeForVCall(MethodDecl->getParent(), VTable, Loc);
1666
1667 llvm::Value *VFuncPtr =
1668 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfn");
Piotr Padlewski77cc9622016-10-29 15:28:30 +00001669 auto *VFuncLoad =
1670 CGF.Builder.CreateAlignedLoad(VFuncPtr, CGF.getPointerAlign());
1671
1672 // Add !invariant.load md to virtual function load to indicate that
1673 // function didn't change inside vtable.
1674 // It's safe to add it without -fstrict-vtable-pointers, but it would not
1675 // help in devirtualization because it will only matter if we will have 2
1676 // the same virtual function loads from the same vtable load, which won't
1677 // happen without enabled devirtualization with -fstrict-vtable-pointers.
1678 if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1679 CGM.getCodeGenOpts().StrictVTablePointers)
1680 VFuncLoad->setMetadata(
1681 llvm::LLVMContext::MD_invariant_load,
1682 llvm::MDNode::get(CGM.getLLVMContext(),
1683 llvm::ArrayRef<llvm::Metadata *>()));
1684 VFunc = VFuncLoad;
Peter Collingbourne0ca03632016-06-25 00:24:06 +00001685 }
John McCallb92ab1a2016-10-26 23:46:34 +00001686
1687 CGCallee Callee(MethodDecl, VFunc);
1688 return Callee;
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001689}
1690
David Majnemer0c0b6d92014-10-31 20:09:12 +00001691llvm::Value *ItaniumCXXABI::EmitVirtualDestructorCall(
1692 CodeGenFunction &CGF, const CXXDestructorDecl *Dtor, CXXDtorType DtorType,
John McCall7f416cc2015-09-08 08:05:57 +00001693 Address This, const CXXMemberCallExpr *CE) {
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001694 assert(CE == nullptr || CE->arg_begin() == CE->arg_end());
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001695 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
1696
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001697 const CGFunctionInfo *FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
1698 Dtor, getFromDtorType(DtorType));
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001699 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
John McCallb92ab1a2016-10-26 23:46:34 +00001700 CGCallee Callee =
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00001701 getVirtualFunctionPointer(CGF, GlobalDecl(Dtor, DtorType), This, Ty,
1702 CE ? CE->getLocStart() : SourceLocation());
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001703
John McCall7f416cc2015-09-08 08:05:57 +00001704 CGF.EmitCXXMemberOrOperatorCall(Dtor, Callee, ReturnValueSlot(),
1705 This.getPointer(), /*ImplicitParam=*/nullptr,
Richard Smith762672a2016-09-28 19:09:10 +00001706 QualType(), CE, nullptr);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001707 return nullptr;
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001708}
1709
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001710void ItaniumCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
Reid Kleckner7810af02013-06-19 15:20:38 +00001711 CodeGenVTables &VTables = CGM.getVTables();
1712 llvm::GlobalVariable *VTT = VTables.GetAddrOfVTT(RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001713 VTables.EmitVTTDefinition(VTT, CGM.getVTableLinkage(RD), RD);
Reid Kleckner7810af02013-06-19 15:20:38 +00001714}
1715
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001716bool ItaniumCXXABI::canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const {
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001717 // We don't emit available_externally vtables if we are in -fapple-kext mode
1718 // because kext mode does not permit devirtualization.
1719 if (CGM.getLangOpts().AppleKext)
1720 return false;
1721
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +00001722 // If we don't have any not emitted inline virtual function, and if vtable is
1723 // not hidden, then we are safe to emit available_externally copy of vtable.
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001724 // FIXME we can still emit a copy of the vtable if we
1725 // can emit definition of the inline functions.
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +00001726 return !hasAnyUnusedVirtualInlineFunction(RD) && !isVTableHidden(RD);
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001727}
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001728static llvm::Value *performTypeAdjustment(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001729 Address InitialPtr,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001730 int64_t NonVirtualAdjustment,
1731 int64_t VirtualAdjustment,
1732 bool IsReturnAdjustment) {
1733 if (!NonVirtualAdjustment && !VirtualAdjustment)
John McCall7f416cc2015-09-08 08:05:57 +00001734 return InitialPtr.getPointer();
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001735
John McCall7f416cc2015-09-08 08:05:57 +00001736 Address V = CGF.Builder.CreateElementBitCast(InitialPtr, CGF.Int8Ty);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001737
John McCall7f416cc2015-09-08 08:05:57 +00001738 // In a base-to-derived cast, the non-virtual adjustment is applied first.
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001739 if (NonVirtualAdjustment && !IsReturnAdjustment) {
John McCall7f416cc2015-09-08 08:05:57 +00001740 V = CGF.Builder.CreateConstInBoundsByteGEP(V,
1741 CharUnits::fromQuantity(NonVirtualAdjustment));
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001742 }
1743
John McCall7f416cc2015-09-08 08:05:57 +00001744 // Perform the virtual adjustment if we have one.
1745 llvm::Value *ResultPtr;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001746 if (VirtualAdjustment) {
1747 llvm::Type *PtrDiffTy =
1748 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1749
John McCall7f416cc2015-09-08 08:05:57 +00001750 Address VTablePtrPtr = CGF.Builder.CreateElementBitCast(V, CGF.Int8PtrTy);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001751 llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr);
1752
1753 llvm::Value *OffsetPtr =
1754 CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
1755
1756 OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo());
1757
1758 // Load the adjustment offset from the vtable.
John McCall7f416cc2015-09-08 08:05:57 +00001759 llvm::Value *Offset =
1760 CGF.Builder.CreateAlignedLoad(OffsetPtr, CGF.getPointerAlign());
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001761
1762 // Adjust our pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001763 ResultPtr = CGF.Builder.CreateInBoundsGEP(V.getPointer(), Offset);
1764 } else {
1765 ResultPtr = V.getPointer();
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001766 }
1767
John McCall7f416cc2015-09-08 08:05:57 +00001768 // In a derived-to-base conversion, the non-virtual adjustment is
1769 // applied second.
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001770 if (NonVirtualAdjustment && IsReturnAdjustment) {
John McCall7f416cc2015-09-08 08:05:57 +00001771 ResultPtr = CGF.Builder.CreateConstInBoundsGEP1_64(ResultPtr,
1772 NonVirtualAdjustment);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001773 }
1774
1775 // Cast back to the original type.
John McCall7f416cc2015-09-08 08:05:57 +00001776 return CGF.Builder.CreateBitCast(ResultPtr, InitialPtr.getType());
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001777}
1778
1779llvm::Value *ItaniumCXXABI::performThisAdjustment(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001780 Address This,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001781 const ThisAdjustment &TA) {
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00001782 return performTypeAdjustment(CGF, This, TA.NonVirtual,
1783 TA.Virtual.Itanium.VCallOffsetOffset,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001784 /*IsReturnAdjustment=*/false);
1785}
1786
1787llvm::Value *
John McCall7f416cc2015-09-08 08:05:57 +00001788ItaniumCXXABI::performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001789 const ReturnAdjustment &RA) {
1790 return performTypeAdjustment(CGF, Ret, RA.NonVirtual,
1791 RA.Virtual.Itanium.VBaseOffsetOffset,
1792 /*IsReturnAdjustment=*/true);
1793}
1794
John McCall5d865c322010-08-31 07:33:07 +00001795void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
1796 RValue RV, QualType ResultType) {
1797 if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
1798 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
1799
1800 // Destructor thunks in the ARM ABI have indeterminate results.
John McCall7f416cc2015-09-08 08:05:57 +00001801 llvm::Type *T = CGF.ReturnValue.getElementType();
John McCall5d865c322010-08-31 07:33:07 +00001802 RValue Undef = RValue::get(llvm::UndefValue::get(T));
1803 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
1804}
John McCall8ed55a52010-09-02 09:58:18 +00001805
1806/************************** Array allocation cookies **************************/
1807
John McCallb91cd662012-05-01 05:23:51 +00001808CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
1809 // The array cookie is a size_t; pad that up to the element alignment.
1810 // The cookie is actually right-justified in that space.
1811 return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
1812 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001813}
1814
John McCall7f416cc2015-09-08 08:05:57 +00001815Address ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1816 Address NewPtr,
1817 llvm::Value *NumElements,
1818 const CXXNewExpr *expr,
1819 QualType ElementType) {
John McCallb91cd662012-05-01 05:23:51 +00001820 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001821
John McCall7f416cc2015-09-08 08:05:57 +00001822 unsigned AS = NewPtr.getAddressSpace();
John McCall8ed55a52010-09-02 09:58:18 +00001823
John McCall9bca9232010-09-02 10:25:57 +00001824 ASTContext &Ctx = getContext();
John McCall7f416cc2015-09-08 08:05:57 +00001825 CharUnits SizeSize = CGF.getSizeSize();
John McCall8ed55a52010-09-02 09:58:18 +00001826
1827 // The size of the cookie.
1828 CharUnits CookieSize =
1829 std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
John McCallb91cd662012-05-01 05:23:51 +00001830 assert(CookieSize == getArrayCookieSizeImpl(ElementType));
John McCall8ed55a52010-09-02 09:58:18 +00001831
1832 // Compute an offset to the cookie.
John McCall7f416cc2015-09-08 08:05:57 +00001833 Address CookiePtr = NewPtr;
John McCall8ed55a52010-09-02 09:58:18 +00001834 CharUnits CookieOffset = CookieSize - SizeSize;
1835 if (!CookieOffset.isZero())
John McCall7f416cc2015-09-08 08:05:57 +00001836 CookiePtr = CGF.Builder.CreateConstInBoundsByteGEP(CookiePtr, CookieOffset);
John McCall8ed55a52010-09-02 09:58:18 +00001837
1838 // Write the number of elements into the appropriate slot.
John McCall7f416cc2015-09-08 08:05:57 +00001839 Address NumElementsPtr =
1840 CGF.Builder.CreateElementBitCast(CookiePtr, CGF.SizeTy);
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001841 llvm::Instruction *SI = CGF.Builder.CreateStore(NumElements, NumElementsPtr);
John McCall7f416cc2015-09-08 08:05:57 +00001842
1843 // Handle the array cookie specially in ASan.
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001844 if (CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) && AS == 0 &&
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001845 expr->getOperatorNew()->isReplaceableGlobalAllocationFunction()) {
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001846 // The store to the CookiePtr does not need to be instrumented.
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001847 CGM.getSanitizerMetadata()->disableSanitizerForInstruction(SI);
1848 llvm::FunctionType *FTy =
John McCall7f416cc2015-09-08 08:05:57 +00001849 llvm::FunctionType::get(CGM.VoidTy, NumElementsPtr.getType(), false);
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001850 llvm::Constant *F =
1851 CGM.CreateRuntimeFunction(FTy, "__asan_poison_cxx_array_cookie");
John McCall7f416cc2015-09-08 08:05:57 +00001852 CGF.Builder.CreateCall(F, NumElementsPtr.getPointer());
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001853 }
John McCall8ed55a52010-09-02 09:58:18 +00001854
1855 // Finally, compute a pointer to the actual data buffer by skipping
1856 // over the cookie completely.
John McCall7f416cc2015-09-08 08:05:57 +00001857 return CGF.Builder.CreateConstInBoundsByteGEP(NewPtr, CookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001858}
1859
John McCallb91cd662012-05-01 05:23:51 +00001860llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001861 Address allocPtr,
John McCallb91cd662012-05-01 05:23:51 +00001862 CharUnits cookieSize) {
1863 // The element size is right-justified in the cookie.
John McCall7f416cc2015-09-08 08:05:57 +00001864 Address numElementsPtr = allocPtr;
1865 CharUnits numElementsOffset = cookieSize - CGF.getSizeSize();
John McCallb91cd662012-05-01 05:23:51 +00001866 if (!numElementsOffset.isZero())
1867 numElementsPtr =
John McCall7f416cc2015-09-08 08:05:57 +00001868 CGF.Builder.CreateConstInBoundsByteGEP(numElementsPtr, numElementsOffset);
John McCall8ed55a52010-09-02 09:58:18 +00001869
John McCall7f416cc2015-09-08 08:05:57 +00001870 unsigned AS = allocPtr.getAddressSpace();
1871 numElementsPtr = CGF.Builder.CreateElementBitCast(numElementsPtr, CGF.SizeTy);
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001872 if (!CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) || AS != 0)
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001873 return CGF.Builder.CreateLoad(numElementsPtr);
1874 // In asan mode emit a function call instead of a regular load and let the
1875 // run-time deal with it: if the shadow is properly poisoned return the
1876 // cookie, otherwise return 0 to avoid an infinite loop calling DTORs.
1877 // We can't simply ignore this load using nosanitize metadata because
1878 // the metadata may be lost.
1879 llvm::FunctionType *FTy =
1880 llvm::FunctionType::get(CGF.SizeTy, CGF.SizeTy->getPointerTo(0), false);
1881 llvm::Constant *F =
1882 CGM.CreateRuntimeFunction(FTy, "__asan_load_cxx_array_cookie");
John McCall7f416cc2015-09-08 08:05:57 +00001883 return CGF.Builder.CreateCall(F, numElementsPtr.getPointer());
John McCall8ed55a52010-09-02 09:58:18 +00001884}
1885
John McCallb91cd662012-05-01 05:23:51 +00001886CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
John McCallc19c7062013-01-25 23:36:19 +00001887 // ARM says that the cookie is always:
John McCall8ed55a52010-09-02 09:58:18 +00001888 // struct array_cookie {
1889 // std::size_t element_size; // element_size != 0
1890 // std::size_t element_count;
1891 // };
John McCallc19c7062013-01-25 23:36:19 +00001892 // But the base ABI doesn't give anything an alignment greater than
1893 // 8, so we can dismiss this as typical ABI-author blindness to
1894 // actual language complexity and round up to the element alignment.
1895 return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes),
1896 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001897}
1898
John McCall7f416cc2015-09-08 08:05:57 +00001899Address ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1900 Address newPtr,
1901 llvm::Value *numElements,
1902 const CXXNewExpr *expr,
1903 QualType elementType) {
John McCallb91cd662012-05-01 05:23:51 +00001904 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001905
John McCall8ed55a52010-09-02 09:58:18 +00001906 // The cookie is always at the start of the buffer.
John McCall7f416cc2015-09-08 08:05:57 +00001907 Address cookie = newPtr;
John McCall8ed55a52010-09-02 09:58:18 +00001908
1909 // The first element is the element size.
John McCall7f416cc2015-09-08 08:05:57 +00001910 cookie = CGF.Builder.CreateElementBitCast(cookie, CGF.SizeTy);
John McCallc19c7062013-01-25 23:36:19 +00001911 llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy,
1912 getContext().getTypeSizeInChars(elementType).getQuantity());
1913 CGF.Builder.CreateStore(elementSize, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001914
1915 // The second element is the element count.
John McCall7f416cc2015-09-08 08:05:57 +00001916 cookie = CGF.Builder.CreateConstInBoundsGEP(cookie, 1, CGF.getSizeSize());
John McCallc19c7062013-01-25 23:36:19 +00001917 CGF.Builder.CreateStore(numElements, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001918
1919 // Finally, compute a pointer to the actual data buffer by skipping
1920 // over the cookie completely.
John McCallc19c7062013-01-25 23:36:19 +00001921 CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType);
John McCall7f416cc2015-09-08 08:05:57 +00001922 return CGF.Builder.CreateConstInBoundsByteGEP(newPtr, cookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001923}
1924
John McCallb91cd662012-05-01 05:23:51 +00001925llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001926 Address allocPtr,
John McCallb91cd662012-05-01 05:23:51 +00001927 CharUnits cookieSize) {
1928 // The number of elements is at offset sizeof(size_t) relative to
1929 // the allocated pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001930 Address numElementsPtr
1931 = CGF.Builder.CreateConstInBoundsByteGEP(allocPtr, CGF.getSizeSize());
John McCall8ed55a52010-09-02 09:58:18 +00001932
John McCall7f416cc2015-09-08 08:05:57 +00001933 numElementsPtr = CGF.Builder.CreateElementBitCast(numElementsPtr, CGF.SizeTy);
John McCallb91cd662012-05-01 05:23:51 +00001934 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall8ed55a52010-09-02 09:58:18 +00001935}
1936
John McCall68ff0372010-09-08 01:44:27 +00001937/*********************** Static local initialization **************************/
1938
1939static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001940 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001941 // int __cxa_guard_acquire(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001942 llvm::FunctionType *FTy =
John McCall68ff0372010-09-08 01:44:27 +00001943 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
Jay Foad5709f7c2011-07-29 13:56:53 +00001944 GuardPtrTy, /*isVarArg=*/false);
Reid Klecknerde864822017-03-21 16:57:30 +00001945 return CGM.CreateRuntimeFunction(
1946 FTy, "__cxa_guard_acquire",
1947 llvm::AttributeList::get(CGM.getLLVMContext(),
1948 llvm::AttributeList::FunctionIndex,
1949 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001950}
1951
1952static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001953 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001954 // void __cxa_guard_release(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001955 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001956 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Reid Klecknerde864822017-03-21 16:57:30 +00001957 return CGM.CreateRuntimeFunction(
1958 FTy, "__cxa_guard_release",
1959 llvm::AttributeList::get(CGM.getLLVMContext(),
1960 llvm::AttributeList::FunctionIndex,
1961 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001962}
1963
1964static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001965 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001966 // void __cxa_guard_abort(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001967 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001968 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Reid Klecknerde864822017-03-21 16:57:30 +00001969 return CGM.CreateRuntimeFunction(
1970 FTy, "__cxa_guard_abort",
1971 llvm::AttributeList::get(CGM.getLLVMContext(),
1972 llvm::AttributeList::FunctionIndex,
1973 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001974}
1975
1976namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001977 struct CallGuardAbort final : EHScopeStack::Cleanup {
John McCall68ff0372010-09-08 01:44:27 +00001978 llvm::GlobalVariable *Guard;
Chandler Carruth84537952012-03-30 19:44:53 +00001979 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
John McCall68ff0372010-09-08 01:44:27 +00001980
Craig Topper4f12f102014-03-12 06:41:41 +00001981 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall882987f2013-02-28 19:01:20 +00001982 CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()),
1983 Guard);
John McCall68ff0372010-09-08 01:44:27 +00001984 }
1985 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001986}
John McCall68ff0372010-09-08 01:44:27 +00001987
1988/// The ARM code here follows the Itanium code closely enough that we
1989/// just special-case it at particular places.
John McCallcdf7ef52010-11-06 09:44:32 +00001990void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
1991 const VarDecl &D,
John McCallb88a5662012-03-30 21:00:39 +00001992 llvm::GlobalVariable *var,
1993 bool shouldPerformInit) {
John McCall68ff0372010-09-08 01:44:27 +00001994 CGBuilderTy &Builder = CGF.Builder;
John McCallcdf7ef52010-11-06 09:44:32 +00001995
Richard Smith62f19e72016-06-25 00:15:56 +00001996 // Inline variables that weren't instantiated from variable templates have
1997 // partially-ordered initialization within their translation unit.
1998 bool NonTemplateInline =
1999 D.isInline() &&
2000 !isTemplateInstantiation(D.getTemplateSpecializationKind());
2001
2002 // We only need to use thread-safe statics for local non-TLS variables and
2003 // inline variables; other global initialization is always single-threaded
2004 // or (through lazy dynamic loading in multiple threads) unsequenced.
Richard Smithdbf74ba2013-04-14 23:01:42 +00002005 bool threadsafe = getContext().getLangOpts().ThreadsafeStatics &&
Richard Smith62f19e72016-06-25 00:15:56 +00002006 (D.isLocalVarDecl() || NonTemplateInline) &&
2007 !D.getTLSKind();
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00002008
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00002009 // If we have a global variable with internal linkage and thread-safe statics
2010 // are disabled, we can just let the guard variable be of type i8.
John McCallb88a5662012-03-30 21:00:39 +00002011 bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
2012
2013 llvm::IntegerType *guardTy;
John McCall7f416cc2015-09-08 08:05:57 +00002014 CharUnits guardAlignment;
John McCall5aa52592011-06-17 07:33:57 +00002015 if (useInt8GuardVariable) {
John McCallb88a5662012-03-30 21:00:39 +00002016 guardTy = CGF.Int8Ty;
John McCall7f416cc2015-09-08 08:05:57 +00002017 guardAlignment = CharUnits::One();
John McCall5aa52592011-06-17 07:33:57 +00002018 } else {
Tim Northover9bb857a2013-01-31 12:13:10 +00002019 // Guard variables are 64 bits in the generic ABI and size width on ARM
2020 // (i.e. 32-bit on AArch32, 64-bit on AArch64).
John McCall7f416cc2015-09-08 08:05:57 +00002021 if (UseARMGuardVarABI) {
2022 guardTy = CGF.SizeTy;
2023 guardAlignment = CGF.getSizeAlign();
2024 } else {
2025 guardTy = CGF.Int64Ty;
2026 guardAlignment = CharUnits::fromQuantity(
2027 CGM.getDataLayout().getABITypeAlignment(guardTy));
2028 }
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00002029 }
John McCallb88a5662012-03-30 21:00:39 +00002030 llvm::PointerType *guardPtrTy = guardTy->getPointerTo();
John McCall68ff0372010-09-08 01:44:27 +00002031
John McCallb88a5662012-03-30 21:00:39 +00002032 // Create the guard variable if we don't already have it (as we
2033 // might if we're double-emitting this function body).
2034 llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
2035 if (!guard) {
2036 // Mangle the name for the guard.
2037 SmallString<256> guardName;
2038 {
2039 llvm::raw_svector_ostream out(guardName);
Reid Klecknerd8110b62013-09-10 20:14:30 +00002040 getMangleContext().mangleStaticGuardVariable(&D, out);
John McCallb88a5662012-03-30 21:00:39 +00002041 }
John McCall8e7cb6d2010-11-02 21:04:24 +00002042
John McCallb88a5662012-03-30 21:00:39 +00002043 // Create the guard variable with a zero-initializer.
2044 // Just absorb linkage and visibility from the guarded variable.
2045 guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
2046 false, var->getLinkage(),
2047 llvm::ConstantInt::get(guardTy, 0),
2048 guardName.str());
2049 guard->setVisibility(var->getVisibility());
Richard Smithdbf74ba2013-04-14 23:01:42 +00002050 // If the variable is thread-local, so is its guard variable.
2051 guard->setThreadLocalMode(var->getThreadLocalMode());
John McCall7f416cc2015-09-08 08:05:57 +00002052 guard->setAlignment(guardAlignment.getQuantity());
John McCallb88a5662012-03-30 21:00:39 +00002053
Yaron Keren5bfa1082015-09-03 20:33:29 +00002054 // The ABI says: "It is suggested that it be emitted in the same COMDAT
2055 // group as the associated data object." In practice, this doesn't work for
Dan Gohman839f2152017-01-17 21:46:38 +00002056 // non-ELF and non-Wasm object formats, so only do it for ELF and Wasm.
Rafael Espindola0d4fb982015-01-12 22:13:53 +00002057 llvm::Comdat *C = var->getComdat();
Yaron Keren5bfa1082015-09-03 20:33:29 +00002058 if (!D.isLocalVarDecl() && C &&
Dan Gohman839f2152017-01-17 21:46:38 +00002059 (CGM.getTarget().getTriple().isOSBinFormatELF() ||
2060 CGM.getTarget().getTriple().isOSBinFormatWasm())) {
Rafael Espindola2ae4b632014-09-19 19:43:18 +00002061 guard->setComdat(C);
Richard Smith62f19e72016-06-25 00:15:56 +00002062 // An inline variable's guard function is run from the per-TU
2063 // initialization function, not via a dedicated global ctor function, so
2064 // we can't put it in a comdat.
2065 if (!NonTemplateInline)
2066 CGF.CurFn->setComdat(C);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00002067 } else if (CGM.supportsCOMDAT() && guard->isWeakForLinker()) {
2068 guard->setComdat(CGM.getModule().getOrInsertComdat(guard->getName()));
Rafael Espindola2ae4b632014-09-19 19:43:18 +00002069 }
2070
John McCallb88a5662012-03-30 21:00:39 +00002071 CGM.setStaticLocalDeclGuardAddress(&D, guard);
2072 }
John McCall87590e62012-03-30 07:09:50 +00002073
John McCall7f416cc2015-09-08 08:05:57 +00002074 Address guardAddr = Address(guard, guardAlignment);
2075
John McCall68ff0372010-09-08 01:44:27 +00002076 // Test whether the variable has completed initialization.
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002077 //
John McCall68ff0372010-09-08 01:44:27 +00002078 // Itanium C++ ABI 3.3.2:
2079 // The following is pseudo-code showing how these functions can be used:
2080 // if (obj_guard.first_byte == 0) {
2081 // if ( __cxa_guard_acquire (&obj_guard) ) {
2082 // try {
2083 // ... initialize the object ...;
2084 // } catch (...) {
2085 // __cxa_guard_abort (&obj_guard);
2086 // throw;
2087 // }
2088 // ... queue object destructor with __cxa_atexit() ...;
2089 // __cxa_guard_release (&obj_guard);
2090 // }
2091 // }
Tim Northovera2ee4332014-03-29 15:09:45 +00002092
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002093 // Load the first byte of the guard variable.
2094 llvm::LoadInst *LI =
John McCall7f416cc2015-09-08 08:05:57 +00002095 Builder.CreateLoad(Builder.CreateElementBitCast(guardAddr, CGM.Int8Ty));
John McCall68ff0372010-09-08 01:44:27 +00002096
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002097 // Itanium ABI:
2098 // An implementation supporting thread-safety on multiprocessor
2099 // systems must also guarantee that references to the initialized
2100 // object do not occur before the load of the initialization flag.
2101 //
2102 // In LLVM, we do this by marking the load Acquire.
2103 if (threadsafe)
JF Bastien92f4ef12016-04-06 17:26:42 +00002104 LI->setAtomic(llvm::AtomicOrdering::Acquire);
Eli Friedman84d28122011-09-13 22:21:56 +00002105
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002106 // For ARM, we should only check the first bit, rather than the entire byte:
2107 //
2108 // ARM C++ ABI 3.2.3.1:
2109 // To support the potential use of initialization guard variables
2110 // as semaphores that are the target of ARM SWP and LDREX/STREX
2111 // synchronizing instructions we define a static initialization
2112 // guard variable to be a 4-byte aligned, 4-byte word with the
2113 // following inline access protocol.
2114 // #define INITIALIZED 1
2115 // if ((obj_guard & INITIALIZED) != INITIALIZED) {
2116 // if (__cxa_guard_acquire(&obj_guard))
2117 // ...
2118 // }
2119 //
2120 // and similarly for ARM64:
2121 //
2122 // ARM64 C++ ABI 3.2.2:
2123 // This ABI instead only specifies the value bit 0 of the static guard
2124 // variable; all other bits are platform defined. Bit 0 shall be 0 when the
2125 // variable is not initialized and 1 when it is.
2126 llvm::Value *V =
2127 (UseARMGuardVarABI && !useInt8GuardVariable)
2128 ? Builder.CreateAnd(LI, llvm::ConstantInt::get(CGM.Int8Ty, 1))
2129 : LI;
Richard Smithae8d62c2017-07-26 22:01:09 +00002130 llvm::Value *NeedsInit = Builder.CreateIsNull(V, "guard.uninitialized");
John McCall68ff0372010-09-08 01:44:27 +00002131
2132 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
2133 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
2134
2135 // Check if the first byte of the guard variable is zero.
Richard Smithae8d62c2017-07-26 22:01:09 +00002136 CGF.EmitCXXGuardedInitBranch(NeedsInit, InitCheckBlock, EndBlock,
2137 CodeGenFunction::GuardKind::VariableGuard, &D);
John McCall68ff0372010-09-08 01:44:27 +00002138
2139 CGF.EmitBlock(InitCheckBlock);
2140
2141 // Variables used when coping with thread-safe statics and exceptions.
John McCall5aa52592011-06-17 07:33:57 +00002142 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00002143 // Call __cxa_guard_acquire.
2144 llvm::Value *V
John McCall882987f2013-02-28 19:01:20 +00002145 = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
John McCall68ff0372010-09-08 01:44:27 +00002146
2147 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
2148
2149 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
2150 InitBlock, EndBlock);
2151
2152 // Call __cxa_guard_abort along the exceptional edge.
John McCallb88a5662012-03-30 21:00:39 +00002153 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
John McCall68ff0372010-09-08 01:44:27 +00002154
2155 CGF.EmitBlock(InitBlock);
2156 }
2157
2158 // Emit the initializer and add a global destructor if appropriate.
John McCallb88a5662012-03-30 21:00:39 +00002159 CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
John McCall68ff0372010-09-08 01:44:27 +00002160
John McCall5aa52592011-06-17 07:33:57 +00002161 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00002162 // Pop the guard-abort cleanup if we pushed one.
2163 CGF.PopCleanupBlock();
2164
2165 // Call __cxa_guard_release. This cannot throw.
John McCall7f416cc2015-09-08 08:05:57 +00002166 CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy),
2167 guardAddr.getPointer());
John McCall68ff0372010-09-08 01:44:27 +00002168 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002169 Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guardAddr);
John McCall68ff0372010-09-08 01:44:27 +00002170 }
2171
2172 CGF.EmitBlock(EndBlock);
2173}
John McCallc84ed6a2012-05-01 06:13:13 +00002174
2175/// Register a global destructor using __cxa_atexit.
2176static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
2177 llvm::Constant *dtor,
Richard Smithdbf74ba2013-04-14 23:01:42 +00002178 llvm::Constant *addr,
2179 bool TLS) {
Bill Wendling95cae882013-05-02 19:18:03 +00002180 const char *Name = "__cxa_atexit";
2181 if (TLS) {
2182 const llvm::Triple &T = CGF.getTarget().getTriple();
Manman Renf93fff22015-11-11 23:08:18 +00002183 Name = T.isOSDarwin() ? "_tlv_atexit" : "__cxa_thread_atexit";
Bill Wendling95cae882013-05-02 19:18:03 +00002184 }
Richard Smithdbf74ba2013-04-14 23:01:42 +00002185
John McCallc84ed6a2012-05-01 06:13:13 +00002186 // We're assuming that the destructor function is something we can
2187 // reasonably call with the default CC. Go ahead and cast it to the
2188 // right prototype.
2189 llvm::Type *dtorTy =
2190 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo();
2191
2192 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
2193 llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
2194 llvm::FunctionType *atexitTy =
2195 llvm::FunctionType::get(CGF.IntTy, paramTys, false);
2196
2197 // Fetch the actual function.
Richard Smithdbf74ba2013-04-14 23:01:42 +00002198 llvm::Constant *atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name);
John McCallc84ed6a2012-05-01 06:13:13 +00002199 if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit))
2200 fn->setDoesNotThrow();
2201
2202 // Create a variable that binds the atexit to this shared object.
2203 llvm::Constant *handle =
Reid Kleckner9de92142017-02-13 18:49:21 +00002204 CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
2205 auto *GV = cast<llvm::GlobalValue>(handle->stripPointerCasts());
2206 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
John McCallc84ed6a2012-05-01 06:13:13 +00002207
2208 llvm::Value *args[] = {
2209 llvm::ConstantExpr::getBitCast(dtor, dtorTy),
2210 llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy),
2211 handle
2212 };
John McCall882987f2013-02-28 19:01:20 +00002213 CGF.EmitNounwindRuntimeCall(atexit, args);
John McCallc84ed6a2012-05-01 06:13:13 +00002214}
2215
2216/// Register a global destructor as best as we know how.
2217void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF,
Richard Smithdbf74ba2013-04-14 23:01:42 +00002218 const VarDecl &D,
John McCallc84ed6a2012-05-01 06:13:13 +00002219 llvm::Constant *dtor,
2220 llvm::Constant *addr) {
2221 // Use __cxa_atexit if available.
Richard Smithdbf74ba2013-04-14 23:01:42 +00002222 if (CGM.getCodeGenOpts().CXAAtExit)
2223 return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind());
2224
2225 if (D.getTLSKind())
2226 CGM.ErrorUnsupported(&D, "non-trivial TLS destruction");
John McCallc84ed6a2012-05-01 06:13:13 +00002227
2228 // In Apple kexts, we want to add a global destructor entry.
2229 // FIXME: shouldn't this be guarded by some variable?
Richard Smith9c6890a2012-11-01 22:30:59 +00002230 if (CGM.getLangOpts().AppleKext) {
John McCallc84ed6a2012-05-01 06:13:13 +00002231 // Generate a global destructor entry.
2232 return CGM.AddCXXDtorEntry(dtor, addr);
2233 }
2234
David Blaikieebe87e12013-08-27 23:57:18 +00002235 CGF.registerGlobalDtorWithAtExit(D, dtor, addr);
John McCallc84ed6a2012-05-01 06:13:13 +00002236}
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002237
David Majnemer9b21c332014-07-11 20:28:10 +00002238static bool isThreadWrapperReplaceable(const VarDecl *VD,
2239 CodeGen::CodeGenModule &CGM) {
2240 assert(!VD->isStaticLocal() && "static local VarDecls don't need wrappers!");
Manman Renf93fff22015-11-11 23:08:18 +00002241 // Darwin prefers to have references to thread local variables to go through
David Majnemer9b21c332014-07-11 20:28:10 +00002242 // the thread wrapper instead of directly referencing the backing variable.
2243 return VD->getTLSKind() == VarDecl::TLS_Dynamic &&
Manman Renf93fff22015-11-11 23:08:18 +00002244 CGM.getTarget().getTriple().isOSDarwin();
David Majnemer9b21c332014-07-11 20:28:10 +00002245}
2246
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002247/// Get the appropriate linkage for the wrapper function. This is essentially
David Majnemer4632e1e2014-06-27 16:56:27 +00002248/// the weak form of the variable's linkage; every translation unit which needs
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002249/// the wrapper emits a copy, and we want the linker to merge them.
David Majnemer35ab3282014-06-11 04:08:55 +00002250static llvm::GlobalValue::LinkageTypes
2251getThreadLocalWrapperLinkage(const VarDecl *VD, CodeGen::CodeGenModule &CGM) {
2252 llvm::GlobalValue::LinkageTypes VarLinkage =
2253 CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false);
2254
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002255 // For internal linkage variables, we don't need an external or weak wrapper.
2256 if (llvm::GlobalValue::isLocalLinkage(VarLinkage))
2257 return VarLinkage;
David Majnemer35ab3282014-06-11 04:08:55 +00002258
David Majnemer9b21c332014-07-11 20:28:10 +00002259 // If the thread wrapper is replaceable, give it appropriate linkage.
Manman Ren68150262015-11-11 22:42:31 +00002260 if (isThreadWrapperReplaceable(VD, CGM))
2261 if (!llvm::GlobalVariable::isLinkOnceLinkage(VarLinkage) &&
2262 !llvm::GlobalVariable::isWeakODRLinkage(VarLinkage))
2263 return VarLinkage;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002264 return llvm::GlobalValue::WeakODRLinkage;
2265}
2266
2267llvm::Function *
2268ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD,
Alexander Musmanf94c3182014-09-26 06:28:25 +00002269 llvm::Value *Val) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002270 // Mangle the name for the thread_local wrapper function.
2271 SmallString<256> WrapperName;
2272 {
2273 llvm::raw_svector_ostream Out(WrapperName);
2274 getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002275 }
2276
Akira Hatanaka26907f92016-01-15 03:34:06 +00002277 // FIXME: If VD is a definition, we should regenerate the function attributes
2278 // before returning.
Alexander Musmanf94c3182014-09-26 06:28:25 +00002279 if (llvm::Value *V = CGM.getModule().getNamedValue(WrapperName))
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002280 return cast<llvm::Function>(V);
2281
Akira Hatanaka26907f92016-01-15 03:34:06 +00002282 QualType RetQT = VD->getType();
2283 if (RetQT->isReferenceType())
2284 RetQT = RetQT.getNonReferenceType();
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002285
John McCallc56a8b32016-03-11 04:30:31 +00002286 const CGFunctionInfo &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
2287 getContext().getPointerType(RetQT), FunctionArgList());
Akira Hatanaka26907f92016-01-15 03:34:06 +00002288
2289 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FI);
David Majnemer35ab3282014-06-11 04:08:55 +00002290 llvm::Function *Wrapper =
2291 llvm::Function::Create(FnTy, getThreadLocalWrapperLinkage(VD, CGM),
2292 WrapperName.str(), &CGM.getModule());
Akira Hatanaka26907f92016-01-15 03:34:06 +00002293
2294 CGM.SetLLVMFunctionAttributes(nullptr, FI, Wrapper);
2295
2296 if (VD->hasDefinition())
2297 CGM.SetLLVMFunctionAttributesForDefinition(nullptr, Wrapper);
2298
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002299 // Always resolve references to the wrapper at link time.
Manman Ren68150262015-11-11 22:42:31 +00002300 if (!Wrapper->hasLocalLinkage() && !(isThreadWrapperReplaceable(VD, CGM) &&
2301 !llvm::GlobalVariable::isLinkOnceLinkage(Wrapper->getLinkage()) &&
2302 !llvm::GlobalVariable::isWeakODRLinkage(Wrapper->getLinkage())))
Duncan P. N. Exon Smith4434d362014-05-07 22:36:11 +00002303 Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
Manman Renb0b3af72015-12-17 00:42:36 +00002304
2305 if (isThreadWrapperReplaceable(VD, CGM)) {
2306 Wrapper->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2307 Wrapper->addFnAttr(llvm::Attribute::NoUnwind);
2308 }
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002309 return Wrapper;
2310}
2311
2312void ItaniumCXXABI::EmitThreadLocalInitFuncs(
Richard Smith5a99c492015-12-01 01:10:48 +00002313 CodeGenModule &CGM, ArrayRef<const VarDecl *> CXXThreadLocals,
2314 ArrayRef<llvm::Function *> CXXThreadLocalInits,
2315 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) {
David Majnemerb3341ea2014-10-05 05:05:40 +00002316 llvm::Function *InitFunc = nullptr;
Richard Smithfbe23692017-01-13 00:43:31 +00002317
2318 // Separate initializers into those with ordered (or partially-ordered)
2319 // initialization and those with unordered initialization.
2320 llvm::SmallVector<llvm::Function *, 8> OrderedInits;
2321 llvm::SmallDenseMap<const VarDecl *, llvm::Function *> UnorderedInits;
2322 for (unsigned I = 0; I != CXXThreadLocalInits.size(); ++I) {
2323 if (isTemplateInstantiation(
2324 CXXThreadLocalInitVars[I]->getTemplateSpecializationKind()))
2325 UnorderedInits[CXXThreadLocalInitVars[I]->getCanonicalDecl()] =
2326 CXXThreadLocalInits[I];
2327 else
2328 OrderedInits.push_back(CXXThreadLocalInits[I]);
2329 }
2330
2331 if (!OrderedInits.empty()) {
David Majnemerb3341ea2014-10-05 05:05:40 +00002332 // Generate a guarded initialization function.
2333 llvm::FunctionType *FTy =
2334 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002335 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
2336 InitFunc = CGM.CreateGlobalInitOrDestructFunction(FTy, "__tls_init", FI,
Alexey Samsonov1444bb92014-10-17 00:20:19 +00002337 SourceLocation(),
David Majnemerb3341ea2014-10-05 05:05:40 +00002338 /*TLS=*/true);
2339 llvm::GlobalVariable *Guard = new llvm::GlobalVariable(
2340 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false,
2341 llvm::GlobalVariable::InternalLinkage,
2342 llvm::ConstantInt::get(CGM.Int8Ty, 0), "__tls_guard");
2343 Guard->setThreadLocal(true);
John McCall7f416cc2015-09-08 08:05:57 +00002344
2345 CharUnits GuardAlign = CharUnits::One();
2346 Guard->setAlignment(GuardAlign.getQuantity());
2347
Richard Smithfbe23692017-01-13 00:43:31 +00002348 CodeGenFunction(CGM).GenerateCXXGlobalInitFunc(InitFunc, OrderedInits,
2349 Address(Guard, GuardAlign));
Manman Ren5e5d0462016-03-18 23:35:21 +00002350 // On Darwin platforms, use CXX_FAST_TLS calling convention.
2351 if (CGM.getTarget().getTriple().isOSDarwin()) {
2352 InitFunc->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2353 InitFunc->addFnAttr(llvm::Attribute::NoUnwind);
2354 }
David Majnemerb3341ea2014-10-05 05:05:40 +00002355 }
Richard Smithfbe23692017-01-13 00:43:31 +00002356
2357 // Emit thread wrappers.
Richard Smith5a99c492015-12-01 01:10:48 +00002358 for (const VarDecl *VD : CXXThreadLocals) {
2359 llvm::GlobalVariable *Var =
2360 cast<llvm::GlobalVariable>(CGM.GetGlobalValue(CGM.getMangledName(VD)));
Richard Smithfbe23692017-01-13 00:43:31 +00002361 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Var);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002362
David Majnemer9b21c332014-07-11 20:28:10 +00002363 // Some targets require that all access to thread local variables go through
2364 // the thread wrapper. This means that we cannot attempt to create a thread
2365 // wrapper or a thread helper.
Richard Smithfbe23692017-01-13 00:43:31 +00002366 if (isThreadWrapperReplaceable(VD, CGM) && !VD->hasDefinition()) {
2367 Wrapper->setLinkage(llvm::Function::ExternalLinkage);
David Majnemer9b21c332014-07-11 20:28:10 +00002368 continue;
Richard Smithfbe23692017-01-13 00:43:31 +00002369 }
David Majnemer9b21c332014-07-11 20:28:10 +00002370
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002371 // Mangle the name for the thread_local initialization function.
2372 SmallString<256> InitFnName;
2373 {
2374 llvm::raw_svector_ostream Out(InitFnName);
2375 getMangleContext().mangleItaniumThreadLocalInit(VD, Out);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002376 }
2377
2378 // If we have a definition for the variable, emit the initialization
2379 // function as an alias to the global Init function (if any). Otherwise,
2380 // produce a declaration of the initialization function.
Craig Topper8a13c412014-05-21 05:09:00 +00002381 llvm::GlobalValue *Init = nullptr;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002382 bool InitIsInitFunc = false;
2383 if (VD->hasDefinition()) {
2384 InitIsInitFunc = true;
Richard Smithfbe23692017-01-13 00:43:31 +00002385 llvm::Function *InitFuncToUse = InitFunc;
2386 if (isTemplateInstantiation(VD->getTemplateSpecializationKind()))
2387 InitFuncToUse = UnorderedInits.lookup(VD->getCanonicalDecl());
2388 if (InitFuncToUse)
Rafael Espindola234405b2014-05-17 21:30:14 +00002389 Init = llvm::GlobalAlias::create(Var->getLinkage(), InitFnName.str(),
Richard Smithfbe23692017-01-13 00:43:31 +00002390 InitFuncToUse);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002391 } else {
2392 // Emit a weak global function referring to the initialization function.
2393 // This function will not exist if the TU defining the thread_local
2394 // variable in question does not need any dynamic initialization for
2395 // its thread_local variables.
2396 llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, false);
Richard Smithfbe23692017-01-13 00:43:31 +00002397 Init = llvm::Function::Create(FnTy,
2398 llvm::GlobalVariable::ExternalWeakLinkage,
2399 InitFnName.str(), &CGM.getModule());
John McCallc56a8b32016-03-11 04:30:31 +00002400 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
Akira Hatanaka26907f92016-01-15 03:34:06 +00002401 CGM.SetLLVMFunctionAttributes(nullptr, FI, cast<llvm::Function>(Init));
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002402 }
2403
2404 if (Init)
2405 Init->setVisibility(Var->getVisibility());
2406
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002407 llvm::LLVMContext &Context = CGM.getModule().getContext();
2408 llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper);
John McCall7f416cc2015-09-08 08:05:57 +00002409 CGBuilderTy Builder(CGM, Entry);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002410 if (InitIsInitFunc) {
Manman Ren5e5d0462016-03-18 23:35:21 +00002411 if (Init) {
2412 llvm::CallInst *CallVal = Builder.CreateCall(Init);
2413 if (isThreadWrapperReplaceable(VD, CGM))
2414 CallVal->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2415 }
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002416 } else {
2417 // Don't know whether we have an init function. Call it if it exists.
2418 llvm::Value *Have = Builder.CreateIsNotNull(Init);
2419 llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2420 llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2421 Builder.CreateCondBr(Have, InitBB, ExitBB);
2422
2423 Builder.SetInsertPoint(InitBB);
David Blaikie4ba525b2015-07-14 17:27:39 +00002424 Builder.CreateCall(Init);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002425 Builder.CreateBr(ExitBB);
2426
2427 Builder.SetInsertPoint(ExitBB);
2428 }
2429
2430 // For a reference, the result of the wrapper function is a pointer to
2431 // the referenced object.
2432 llvm::Value *Val = Var;
2433 if (VD->getType()->isReferenceType()) {
John McCall7f416cc2015-09-08 08:05:57 +00002434 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2435 Val = Builder.CreateAlignedLoad(Val, Align);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002436 }
Alexander Musmanf94c3182014-09-26 06:28:25 +00002437 if (Val->getType() != Wrapper->getReturnType())
2438 Val = Builder.CreatePointerBitCastOrAddrSpaceCast(
2439 Val, Wrapper->getReturnType(), "");
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002440 Builder.CreateRet(Val);
2441 }
2442}
2443
Richard Smith0f383742014-03-26 22:48:22 +00002444LValue ItaniumCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
2445 const VarDecl *VD,
2446 QualType LValType) {
Richard Smith5a99c492015-12-01 01:10:48 +00002447 llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD);
Alexander Musmanf94c3182014-09-26 06:28:25 +00002448 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Val);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002449
Manman Renb0b3af72015-12-17 00:42:36 +00002450 llvm::CallInst *CallVal = CGF.Builder.CreateCall(Wrapper);
Saleem Abdulrasool4a7130a2016-08-01 21:31:24 +00002451 CallVal->setCallingConv(Wrapper->getCallingConv());
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002452
2453 LValue LV;
2454 if (VD->getType()->isReferenceType())
Manman Renb0b3af72015-12-17 00:42:36 +00002455 LV = CGF.MakeNaturalAlignAddrLValue(CallVal, LValType);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002456 else
Manman Renb0b3af72015-12-17 00:42:36 +00002457 LV = CGF.MakeAddrLValue(CallVal, LValType,
2458 CGF.getContext().getDeclAlign(VD));
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002459 // FIXME: need setObjCGCLValueClass?
2460 return LV;
2461}
Peter Collingbourne66f82e62013-06-28 20:45:28 +00002462
2463/// Return whether the given global decl needs a VTT parameter, which it does
2464/// if it's a base constructor or destructor with virtual bases.
2465bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) {
2466 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
2467
2468 // We don't have any virtual bases, just return early.
2469 if (!MD->getParent()->getNumVBases())
2470 return false;
2471
2472 // Check if we have a base constructor.
2473 if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base)
2474 return true;
2475
2476 // Check if we have a base destructor.
2477 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
2478 return true;
2479
2480 return false;
2481}
David Majnemere2cb8d12014-07-07 06:20:47 +00002482
2483namespace {
2484class ItaniumRTTIBuilder {
2485 CodeGenModule &CGM; // Per-module state.
2486 llvm::LLVMContext &VMContext;
2487 const ItaniumCXXABI &CXXABI; // Per-module state.
2488
2489 /// Fields - The fields of the RTTI descriptor currently being built.
2490 SmallVector<llvm::Constant *, 16> Fields;
2491
2492 /// GetAddrOfTypeName - Returns the mangled type name of the given type.
2493 llvm::GlobalVariable *
2494 GetAddrOfTypeName(QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage);
2495
2496 /// GetAddrOfExternalRTTIDescriptor - Returns the constant for the RTTI
2497 /// descriptor of the given type.
2498 llvm::Constant *GetAddrOfExternalRTTIDescriptor(QualType Ty);
2499
2500 /// BuildVTablePointer - Build the vtable pointer for the given type.
2501 void BuildVTablePointer(const Type *Ty);
2502
2503 /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
2504 /// inheritance, according to the Itanium C++ ABI, 2.9.5p6b.
2505 void BuildSIClassTypeInfo(const CXXRecordDecl *RD);
2506
2507 /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
2508 /// classes with bases that do not satisfy the abi::__si_class_type_info
2509 /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
2510 void BuildVMIClassTypeInfo(const CXXRecordDecl *RD);
2511
2512 /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct, used
2513 /// for pointer types.
2514 void BuildPointerTypeInfo(QualType PointeeTy);
2515
2516 /// BuildObjCObjectTypeInfo - Build the appropriate kind of
2517 /// type_info for an object type.
2518 void BuildObjCObjectTypeInfo(const ObjCObjectType *Ty);
2519
2520 /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
2521 /// struct, used for member pointer types.
2522 void BuildPointerToMemberTypeInfo(const MemberPointerType *Ty);
2523
2524public:
2525 ItaniumRTTIBuilder(const ItaniumCXXABI &ABI)
2526 : CGM(ABI.CGM), VMContext(CGM.getModule().getContext()), CXXABI(ABI) {}
2527
2528 // Pointer type info flags.
2529 enum {
2530 /// PTI_Const - Type has const qualifier.
2531 PTI_Const = 0x1,
2532
2533 /// PTI_Volatile - Type has volatile qualifier.
2534 PTI_Volatile = 0x2,
2535
2536 /// PTI_Restrict - Type has restrict qualifier.
2537 PTI_Restrict = 0x4,
2538
2539 /// PTI_Incomplete - Type is incomplete.
2540 PTI_Incomplete = 0x8,
2541
2542 /// PTI_ContainingClassIncomplete - Containing class is incomplete.
2543 /// (in pointer to member).
Richard Smitha7d93782016-12-01 03:32:42 +00002544 PTI_ContainingClassIncomplete = 0x10,
2545
2546 /// PTI_TransactionSafe - Pointee is transaction_safe function (C++ TM TS).
2547 //PTI_TransactionSafe = 0x20,
2548
2549 /// PTI_Noexcept - Pointee is noexcept function (C++1z).
2550 PTI_Noexcept = 0x40,
David Majnemere2cb8d12014-07-07 06:20:47 +00002551 };
2552
2553 // VMI type info flags.
2554 enum {
2555 /// VMI_NonDiamondRepeat - Class has non-diamond repeated inheritance.
2556 VMI_NonDiamondRepeat = 0x1,
2557
2558 /// VMI_DiamondShaped - Class is diamond shaped.
2559 VMI_DiamondShaped = 0x2
2560 };
2561
2562 // Base class type info flags.
2563 enum {
2564 /// BCTI_Virtual - Base class is virtual.
2565 BCTI_Virtual = 0x1,
2566
2567 /// BCTI_Public - Base class is public.
2568 BCTI_Public = 0x2
2569 };
2570
2571 /// BuildTypeInfo - Build the RTTI type info struct for the given type.
2572 ///
2573 /// \param Force - true to force the creation of this RTTI value
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00002574 /// \param DLLExport - true to mark the RTTI value as DLLExport
2575 llvm::Constant *BuildTypeInfo(QualType Ty, bool Force = false,
2576 bool DLLExport = false);
David Majnemere2cb8d12014-07-07 06:20:47 +00002577};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002578}
David Majnemere2cb8d12014-07-07 06:20:47 +00002579
2580llvm::GlobalVariable *ItaniumRTTIBuilder::GetAddrOfTypeName(
2581 QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage) {
Yaron Kerene46f7ed2015-07-29 14:21:47 +00002582 SmallString<256> Name;
2583 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00002584 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00002585
2586 // We know that the mangled name of the type starts at index 4 of the
2587 // mangled name of the typename, so we can just index into it in order to
2588 // get the mangled name of the type.
2589 llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,
2590 Name.substr(4));
2591
2592 llvm::GlobalVariable *GV =
2593 CGM.CreateOrReplaceCXXRuntimeVariable(Name, Init->getType(), Linkage);
2594
2595 GV->setInitializer(Init);
2596
2597 return GV;
2598}
2599
2600llvm::Constant *
2601ItaniumRTTIBuilder::GetAddrOfExternalRTTIDescriptor(QualType Ty) {
2602 // Mangle the RTTI name.
Yaron Kerene46f7ed2015-07-29 14:21:47 +00002603 SmallString<256> Name;
2604 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00002605 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00002606
2607 // Look for an existing global.
2608 llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name);
2609
2610 if (!GV) {
2611 // Create a new global variable.
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +00002612 // Note for the future: If we would ever like to do deferred emission of
2613 // RTTI, check if emitting vtables opportunistically need any adjustment.
2614
David Majnemere2cb8d12014-07-07 06:20:47 +00002615 GV = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
2616 /*Constant=*/true,
2617 llvm::GlobalValue::ExternalLinkage, nullptr,
2618 Name);
David Majnemer1fb1a042014-11-07 07:26:38 +00002619 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2620 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
2621 if (RD->hasAttr<DLLImportAttr>())
2622 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
2623 }
David Majnemere2cb8d12014-07-07 06:20:47 +00002624 }
2625
2626 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
2627}
2628
2629/// TypeInfoIsInStandardLibrary - Given a builtin type, returns whether the type
2630/// info for that type is defined in the standard library.
2631static bool TypeInfoIsInStandardLibrary(const BuiltinType *Ty) {
2632 // Itanium C++ ABI 2.9.2:
2633 // Basic type information (e.g. for "int", "bool", etc.) will be kept in
2634 // the run-time support library. Specifically, the run-time support
2635 // library should contain type_info objects for the types X, X* and
2636 // X const*, for every X in: void, std::nullptr_t, bool, wchar_t, char,
2637 // unsigned char, signed char, short, unsigned short, int, unsigned int,
2638 // long, unsigned long, long long, unsigned long long, float, double,
2639 // long double, char16_t, char32_t, and the IEEE 754r decimal and
2640 // half-precision floating point types.
Richard Smith4a382012016-02-03 01:32:42 +00002641 //
2642 // GCC also emits RTTI for __int128.
2643 // FIXME: We do not emit RTTI information for decimal types here.
2644
2645 // Types added here must also be added to EmitFundamentalRTTIDescriptors.
David Majnemere2cb8d12014-07-07 06:20:47 +00002646 switch (Ty->getKind()) {
2647 case BuiltinType::Void:
2648 case BuiltinType::NullPtr:
2649 case BuiltinType::Bool:
2650 case BuiltinType::WChar_S:
2651 case BuiltinType::WChar_U:
2652 case BuiltinType::Char_U:
2653 case BuiltinType::Char_S:
2654 case BuiltinType::UChar:
2655 case BuiltinType::SChar:
2656 case BuiltinType::Short:
2657 case BuiltinType::UShort:
2658 case BuiltinType::Int:
2659 case BuiltinType::UInt:
2660 case BuiltinType::Long:
2661 case BuiltinType::ULong:
2662 case BuiltinType::LongLong:
2663 case BuiltinType::ULongLong:
2664 case BuiltinType::Half:
2665 case BuiltinType::Float:
2666 case BuiltinType::Double:
2667 case BuiltinType::LongDouble:
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00002668 case BuiltinType::Float16:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002669 case BuiltinType::Float128:
David Majnemere2cb8d12014-07-07 06:20:47 +00002670 case BuiltinType::Char16:
2671 case BuiltinType::Char32:
2672 case BuiltinType::Int128:
2673 case BuiltinType::UInt128:
Richard Smith4a382012016-02-03 01:32:42 +00002674 return true;
2675
Alexey Bader954ba212016-04-08 13:40:33 +00002676#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2677 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00002678#include "clang/Basic/OpenCLImageTypes.def"
David Majnemere2cb8d12014-07-07 06:20:47 +00002679 case BuiltinType::OCLSampler:
2680 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00002681 case BuiltinType::OCLClkEvent:
2682 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00002683 case BuiltinType::OCLReserveID:
Richard Smith4a382012016-02-03 01:32:42 +00002684 return false;
David Majnemere2cb8d12014-07-07 06:20:47 +00002685
2686 case BuiltinType::Dependent:
2687#define BUILTIN_TYPE(Id, SingletonId)
2688#define PLACEHOLDER_TYPE(Id, SingletonId) \
2689 case BuiltinType::Id:
2690#include "clang/AST/BuiltinTypes.def"
2691 llvm_unreachable("asking for RRTI for a placeholder type!");
2692
2693 case BuiltinType::ObjCId:
2694 case BuiltinType::ObjCClass:
2695 case BuiltinType::ObjCSel:
2696 llvm_unreachable("FIXME: Objective-C types are unsupported!");
2697 }
2698
2699 llvm_unreachable("Invalid BuiltinType Kind!");
2700}
2701
2702static bool TypeInfoIsInStandardLibrary(const PointerType *PointerTy) {
2703 QualType PointeeTy = PointerTy->getPointeeType();
2704 const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(PointeeTy);
2705 if (!BuiltinTy)
2706 return false;
2707
2708 // Check the qualifiers.
2709 Qualifiers Quals = PointeeTy.getQualifiers();
2710 Quals.removeConst();
2711
2712 if (!Quals.empty())
2713 return false;
2714
2715 return TypeInfoIsInStandardLibrary(BuiltinTy);
2716}
2717
2718/// IsStandardLibraryRTTIDescriptor - Returns whether the type
2719/// information for the given type exists in the standard library.
2720static bool IsStandardLibraryRTTIDescriptor(QualType Ty) {
2721 // Type info for builtin types is defined in the standard library.
2722 if (const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(Ty))
2723 return TypeInfoIsInStandardLibrary(BuiltinTy);
2724
2725 // Type info for some pointer types to builtin types is defined in the
2726 // standard library.
2727 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2728 return TypeInfoIsInStandardLibrary(PointerTy);
2729
2730 return false;
2731}
2732
2733/// ShouldUseExternalRTTIDescriptor - Returns whether the type information for
2734/// the given type exists somewhere else, and that we should not emit the type
2735/// information in this translation unit. Assumes that it is not a
2736/// standard-library type.
2737static bool ShouldUseExternalRTTIDescriptor(CodeGenModule &CGM,
2738 QualType Ty) {
2739 ASTContext &Context = CGM.getContext();
2740
2741 // If RTTI is disabled, assume it might be disabled in the
2742 // translation unit that defines any potential key function, too.
2743 if (!Context.getLangOpts().RTTI) return false;
2744
2745 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2746 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
2747 if (!RD->hasDefinition())
2748 return false;
2749
2750 if (!RD->isDynamicClass())
2751 return false;
2752
2753 // FIXME: this may need to be reconsidered if the key function
2754 // changes.
David Majnemerbe9022c2015-08-06 20:56:55 +00002755 // N.B. We must always emit the RTTI data ourselves if there exists a key
2756 // function.
2757 bool IsDLLImport = RD->hasAttr<DLLImportAttr>();
David Majnemer1fb1a042014-11-07 07:26:38 +00002758 if (CGM.getVTables().isVTableExternal(RD))
Shoaib Meenai61118e72017-07-04 01:02:19 +00002759 return IsDLLImport && !CGM.getTriple().isWindowsItaniumEnvironment()
2760 ? false
2761 : true;
David Majnemer1fb1a042014-11-07 07:26:38 +00002762
David Majnemerbe9022c2015-08-06 20:56:55 +00002763 if (IsDLLImport)
David Majnemer1fb1a042014-11-07 07:26:38 +00002764 return true;
David Majnemere2cb8d12014-07-07 06:20:47 +00002765 }
2766
2767 return false;
2768}
2769
2770/// IsIncompleteClassType - Returns whether the given record type is incomplete.
2771static bool IsIncompleteClassType(const RecordType *RecordTy) {
2772 return !RecordTy->getDecl()->isCompleteDefinition();
2773}
2774
2775/// ContainsIncompleteClassType - Returns whether the given type contains an
2776/// incomplete class type. This is true if
2777///
2778/// * The given type is an incomplete class type.
2779/// * The given type is a pointer type whose pointee type contains an
2780/// incomplete class type.
2781/// * The given type is a member pointer type whose class is an incomplete
2782/// class type.
2783/// * The given type is a member pointer type whoise pointee type contains an
2784/// incomplete class type.
2785/// is an indirect or direct pointer to an incomplete class type.
2786static bool ContainsIncompleteClassType(QualType Ty) {
2787 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2788 if (IsIncompleteClassType(RecordTy))
2789 return true;
2790 }
2791
2792 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2793 return ContainsIncompleteClassType(PointerTy->getPointeeType());
2794
2795 if (const MemberPointerType *MemberPointerTy =
2796 dyn_cast<MemberPointerType>(Ty)) {
2797 // Check if the class type is incomplete.
2798 const RecordType *ClassType = cast<RecordType>(MemberPointerTy->getClass());
2799 if (IsIncompleteClassType(ClassType))
2800 return true;
2801
2802 return ContainsIncompleteClassType(MemberPointerTy->getPointeeType());
2803 }
2804
2805 return false;
2806}
2807
2808// CanUseSingleInheritance - Return whether the given record decl has a "single,
2809// public, non-virtual base at offset zero (i.e. the derived class is dynamic
2810// iff the base is)", according to Itanium C++ ABI, 2.95p6b.
2811static bool CanUseSingleInheritance(const CXXRecordDecl *RD) {
2812 // Check the number of bases.
2813 if (RD->getNumBases() != 1)
2814 return false;
2815
2816 // Get the base.
2817 CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin();
2818
2819 // Check that the base is not virtual.
2820 if (Base->isVirtual())
2821 return false;
2822
2823 // Check that the base is public.
2824 if (Base->getAccessSpecifier() != AS_public)
2825 return false;
2826
2827 // Check that the class is dynamic iff the base is.
2828 const CXXRecordDecl *BaseDecl =
2829 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2830 if (!BaseDecl->isEmpty() &&
2831 BaseDecl->isDynamicClass() != RD->isDynamicClass())
2832 return false;
2833
2834 return true;
2835}
2836
2837void ItaniumRTTIBuilder::BuildVTablePointer(const Type *Ty) {
2838 // abi::__class_type_info.
2839 static const char * const ClassTypeInfo =
2840 "_ZTVN10__cxxabiv117__class_type_infoE";
2841 // abi::__si_class_type_info.
2842 static const char * const SIClassTypeInfo =
2843 "_ZTVN10__cxxabiv120__si_class_type_infoE";
2844 // abi::__vmi_class_type_info.
2845 static const char * const VMIClassTypeInfo =
2846 "_ZTVN10__cxxabiv121__vmi_class_type_infoE";
2847
2848 const char *VTableName = nullptr;
2849
2850 switch (Ty->getTypeClass()) {
2851#define TYPE(Class, Base)
2852#define ABSTRACT_TYPE(Class, Base)
2853#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2854#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2855#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2856#include "clang/AST/TypeNodes.def"
2857 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
2858
2859 case Type::LValueReference:
2860 case Type::RValueReference:
2861 llvm_unreachable("References shouldn't get here");
2862
2863 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00002864 case Type::DeducedTemplateSpecialization:
2865 llvm_unreachable("Undeduced type shouldn't get here");
David Majnemere2cb8d12014-07-07 06:20:47 +00002866
Xiuli Pan9c14e282016-01-09 12:53:17 +00002867 case Type::Pipe:
2868 llvm_unreachable("Pipe types shouldn't get here");
2869
David Majnemere2cb8d12014-07-07 06:20:47 +00002870 case Type::Builtin:
2871 // GCC treats vector and complex types as fundamental types.
2872 case Type::Vector:
2873 case Type::ExtVector:
2874 case Type::Complex:
2875 case Type::Atomic:
2876 // FIXME: GCC treats block pointers as fundamental types?!
2877 case Type::BlockPointer:
2878 // abi::__fundamental_type_info.
2879 VTableName = "_ZTVN10__cxxabiv123__fundamental_type_infoE";
2880 break;
2881
2882 case Type::ConstantArray:
2883 case Type::IncompleteArray:
2884 case Type::VariableArray:
2885 // abi::__array_type_info.
2886 VTableName = "_ZTVN10__cxxabiv117__array_type_infoE";
2887 break;
2888
2889 case Type::FunctionNoProto:
2890 case Type::FunctionProto:
Richard Smithb17d6fa2016-12-01 03:04:07 +00002891 // abi::__function_type_info.
2892 VTableName = "_ZTVN10__cxxabiv120__function_type_infoE";
David Majnemere2cb8d12014-07-07 06:20:47 +00002893 break;
2894
2895 case Type::Enum:
2896 // abi::__enum_type_info.
2897 VTableName = "_ZTVN10__cxxabiv116__enum_type_infoE";
2898 break;
2899
2900 case Type::Record: {
2901 const CXXRecordDecl *RD =
2902 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
2903
2904 if (!RD->hasDefinition() || !RD->getNumBases()) {
2905 VTableName = ClassTypeInfo;
2906 } else if (CanUseSingleInheritance(RD)) {
2907 VTableName = SIClassTypeInfo;
2908 } else {
2909 VTableName = VMIClassTypeInfo;
2910 }
2911
2912 break;
2913 }
2914
2915 case Type::ObjCObject:
2916 // Ignore protocol qualifiers.
2917 Ty = cast<ObjCObjectType>(Ty)->getBaseType().getTypePtr();
2918
2919 // Handle id and Class.
2920 if (isa<BuiltinType>(Ty)) {
2921 VTableName = ClassTypeInfo;
2922 break;
2923 }
2924
2925 assert(isa<ObjCInterfaceType>(Ty));
2926 // Fall through.
2927
2928 case Type::ObjCInterface:
2929 if (cast<ObjCInterfaceType>(Ty)->getDecl()->getSuperClass()) {
2930 VTableName = SIClassTypeInfo;
2931 } else {
2932 VTableName = ClassTypeInfo;
2933 }
2934 break;
2935
2936 case Type::ObjCObjectPointer:
2937 case Type::Pointer:
2938 // abi::__pointer_type_info.
2939 VTableName = "_ZTVN10__cxxabiv119__pointer_type_infoE";
2940 break;
2941
2942 case Type::MemberPointer:
2943 // abi::__pointer_to_member_type_info.
2944 VTableName = "_ZTVN10__cxxabiv129__pointer_to_member_type_infoE";
2945 break;
2946 }
2947
2948 llvm::Constant *VTable =
2949 CGM.getModule().getOrInsertGlobal(VTableName, CGM.Int8PtrTy);
2950
2951 llvm::Type *PtrDiffTy =
2952 CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
2953
2954 // The vtable address point is 2.
2955 llvm::Constant *Two = llvm::ConstantInt::get(PtrDiffTy, 2);
David Blaikiee3b172a2015-04-02 18:55:21 +00002956 VTable =
2957 llvm::ConstantExpr::getInBoundsGetElementPtr(CGM.Int8PtrTy, VTable, Two);
David Majnemere2cb8d12014-07-07 06:20:47 +00002958 VTable = llvm::ConstantExpr::getBitCast(VTable, CGM.Int8PtrTy);
2959
2960 Fields.push_back(VTable);
2961}
2962
2963/// \brief Return the linkage that the type info and type info name constants
2964/// should have for the given type.
2965static llvm::GlobalVariable::LinkageTypes getTypeInfoLinkage(CodeGenModule &CGM,
2966 QualType Ty) {
2967 // Itanium C++ ABI 2.9.5p7:
2968 // In addition, it and all of the intermediate abi::__pointer_type_info
2969 // structs in the chain down to the abi::__class_type_info for the
2970 // incomplete class type must be prevented from resolving to the
2971 // corresponding type_info structs for the complete class type, possibly
2972 // by making them local static objects. Finally, a dummy class RTTI is
2973 // generated for the incomplete type that will not resolve to the final
2974 // complete class RTTI (because the latter need not exist), possibly by
2975 // making it a local static object.
2976 if (ContainsIncompleteClassType(Ty))
2977 return llvm::GlobalValue::InternalLinkage;
2978
2979 switch (Ty->getLinkage()) {
2980 case NoLinkage:
2981 case InternalLinkage:
2982 case UniqueExternalLinkage:
2983 return llvm::GlobalValue::InternalLinkage;
2984
2985 case VisibleNoLinkage:
Richard Smith1283e982017-07-07 20:04:28 +00002986 case ModuleInternalLinkage:
2987 case ModuleLinkage:
David Majnemere2cb8d12014-07-07 06:20:47 +00002988 case ExternalLinkage:
Saleem Abdulrasool18820022016-12-02 22:46:18 +00002989 // RTTI is not enabled, which means that this type info struct is going
2990 // to be used for exception handling. Give it linkonce_odr linkage.
2991 if (!CGM.getLangOpts().RTTI)
David Majnemere2cb8d12014-07-07 06:20:47 +00002992 return llvm::GlobalValue::LinkOnceODRLinkage;
David Majnemere2cb8d12014-07-07 06:20:47 +00002993
2994 if (const RecordType *Record = dyn_cast<RecordType>(Ty)) {
2995 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2996 if (RD->hasAttr<WeakAttr>())
2997 return llvm::GlobalValue::WeakODRLinkage;
Saleem Abdulrasool18820022016-12-02 22:46:18 +00002998 if (CGM.getTriple().isWindowsItaniumEnvironment())
Shoaib Meenai61118e72017-07-04 01:02:19 +00002999 if (RD->hasAttr<DLLImportAttr>() &&
3000 ShouldUseExternalRTTIDescriptor(CGM, Ty))
Saleem Abdulrasool18820022016-12-02 22:46:18 +00003001 return llvm::GlobalValue::ExternalLinkage;
Martin Storsjoc6c5af72017-09-01 06:41:55 +00003002 // MinGW always uses LinkOnceODRLinkage for type info.
3003 if (RD->isDynamicClass() &&
3004 !CGM.getContext()
3005 .getTargetInfo()
3006 .getTriple()
3007 .isWindowsGNUEnvironment())
3008 return CGM.getVTableLinkage(RD);
David Majnemere2cb8d12014-07-07 06:20:47 +00003009 }
3010
3011 return llvm::GlobalValue::LinkOnceODRLinkage;
3012 }
3013
3014 llvm_unreachable("Invalid linkage!");
3015}
3016
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00003017llvm::Constant *ItaniumRTTIBuilder::BuildTypeInfo(QualType Ty, bool Force,
3018 bool DLLExport) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003019 // We want to operate on the canonical type.
Yaron Kerenebd14262016-03-16 12:14:43 +00003020 Ty = Ty.getCanonicalType();
David Majnemere2cb8d12014-07-07 06:20:47 +00003021
3022 // Check if we've already emitted an RTTI descriptor for this type.
Yaron Kerene46f7ed2015-07-29 14:21:47 +00003023 SmallString<256> Name;
3024 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00003025 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00003026
3027 llvm::GlobalVariable *OldGV = CGM.getModule().getNamedGlobal(Name);
3028 if (OldGV && !OldGV->isDeclaration()) {
3029 assert(!OldGV->hasAvailableExternallyLinkage() &&
3030 "available_externally typeinfos not yet implemented");
3031
3032 return llvm::ConstantExpr::getBitCast(OldGV, CGM.Int8PtrTy);
3033 }
3034
3035 // Check if there is already an external RTTI descriptor for this type.
3036 bool IsStdLib = IsStandardLibraryRTTIDescriptor(Ty);
3037 if (!Force && (IsStdLib || ShouldUseExternalRTTIDescriptor(CGM, Ty)))
3038 return GetAddrOfExternalRTTIDescriptor(Ty);
3039
3040 // Emit the standard library with external linkage.
3041 llvm::GlobalVariable::LinkageTypes Linkage;
3042 if (IsStdLib)
3043 Linkage = llvm::GlobalValue::ExternalLinkage;
3044 else
3045 Linkage = getTypeInfoLinkage(CGM, Ty);
3046
3047 // Add the vtable pointer.
3048 BuildVTablePointer(cast<Type>(Ty));
3049
3050 // And the name.
3051 llvm::GlobalVariable *TypeName = GetAddrOfTypeName(Ty, Linkage);
3052 llvm::Constant *TypeNameField;
3053
3054 // If we're supposed to demote the visibility, be sure to set a flag
3055 // to use a string comparison for type_info comparisons.
3056 ItaniumCXXABI::RTTIUniquenessKind RTTIUniqueness =
3057 CXXABI.classifyRTTIUniqueness(Ty, Linkage);
3058 if (RTTIUniqueness != ItaniumCXXABI::RUK_Unique) {
3059 // The flag is the sign bit, which on ARM64 is defined to be clear
3060 // for global pointers. This is very ARM64-specific.
3061 TypeNameField = llvm::ConstantExpr::getPtrToInt(TypeName, CGM.Int64Ty);
3062 llvm::Constant *flag =
3063 llvm::ConstantInt::get(CGM.Int64Ty, ((uint64_t)1) << 63);
3064 TypeNameField = llvm::ConstantExpr::getAdd(TypeNameField, flag);
3065 TypeNameField =
3066 llvm::ConstantExpr::getIntToPtr(TypeNameField, CGM.Int8PtrTy);
3067 } else {
3068 TypeNameField = llvm::ConstantExpr::getBitCast(TypeName, CGM.Int8PtrTy);
3069 }
3070 Fields.push_back(TypeNameField);
3071
3072 switch (Ty->getTypeClass()) {
3073#define TYPE(Class, Base)
3074#define ABSTRACT_TYPE(Class, Base)
3075#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
3076#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3077#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3078#include "clang/AST/TypeNodes.def"
3079 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
3080
3081 // GCC treats vector types as fundamental types.
3082 case Type::Builtin:
3083 case Type::Vector:
3084 case Type::ExtVector:
3085 case Type::Complex:
3086 case Type::BlockPointer:
3087 // Itanium C++ ABI 2.9.5p4:
3088 // abi::__fundamental_type_info adds no data members to std::type_info.
3089 break;
3090
3091 case Type::LValueReference:
3092 case Type::RValueReference:
3093 llvm_unreachable("References shouldn't get here");
3094
3095 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00003096 case Type::DeducedTemplateSpecialization:
3097 llvm_unreachable("Undeduced type shouldn't get here");
David Majnemere2cb8d12014-07-07 06:20:47 +00003098
Xiuli Pan9c14e282016-01-09 12:53:17 +00003099 case Type::Pipe:
3100 llvm_unreachable("Pipe type shouldn't get here");
3101
David Majnemere2cb8d12014-07-07 06:20:47 +00003102 case Type::ConstantArray:
3103 case Type::IncompleteArray:
3104 case Type::VariableArray:
3105 // Itanium C++ ABI 2.9.5p5:
3106 // abi::__array_type_info adds no data members to std::type_info.
3107 break;
3108
3109 case Type::FunctionNoProto:
Richard Smithb17d6fa2016-12-01 03:04:07 +00003110 case Type::FunctionProto:
David Majnemere2cb8d12014-07-07 06:20:47 +00003111 // Itanium C++ ABI 2.9.5p5:
3112 // abi::__function_type_info adds no data members to std::type_info.
3113 break;
3114
3115 case Type::Enum:
3116 // Itanium C++ ABI 2.9.5p5:
3117 // abi::__enum_type_info adds no data members to std::type_info.
3118 break;
3119
3120 case Type::Record: {
3121 const CXXRecordDecl *RD =
3122 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
3123 if (!RD->hasDefinition() || !RD->getNumBases()) {
3124 // We don't need to emit any fields.
3125 break;
3126 }
3127
3128 if (CanUseSingleInheritance(RD))
3129 BuildSIClassTypeInfo(RD);
3130 else
3131 BuildVMIClassTypeInfo(RD);
3132
3133 break;
3134 }
3135
3136 case Type::ObjCObject:
3137 case Type::ObjCInterface:
3138 BuildObjCObjectTypeInfo(cast<ObjCObjectType>(Ty));
3139 break;
3140
3141 case Type::ObjCObjectPointer:
3142 BuildPointerTypeInfo(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
3143 break;
3144
3145 case Type::Pointer:
3146 BuildPointerTypeInfo(cast<PointerType>(Ty)->getPointeeType());
3147 break;
3148
3149 case Type::MemberPointer:
3150 BuildPointerToMemberTypeInfo(cast<MemberPointerType>(Ty));
3151 break;
3152
3153 case Type::Atomic:
3154 // No fields, at least for the moment.
3155 break;
3156 }
3157
3158 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Fields);
3159
Rafael Espindolacb92c192015-01-15 23:18:01 +00003160 llvm::Module &M = CGM.getModule();
David Majnemere2cb8d12014-07-07 06:20:47 +00003161 llvm::GlobalVariable *GV =
Rafael Espindolacb92c192015-01-15 23:18:01 +00003162 new llvm::GlobalVariable(M, Init->getType(),
3163 /*Constant=*/true, Linkage, Init, Name);
3164
David Majnemere2cb8d12014-07-07 06:20:47 +00003165 // If there's already an old global variable, replace it with the new one.
3166 if (OldGV) {
3167 GV->takeName(OldGV);
3168 llvm::Constant *NewPtr =
3169 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
3170 OldGV->replaceAllUsesWith(NewPtr);
3171 OldGV->eraseFromParent();
3172 }
3173
Yaron Keren04da2382015-07-29 15:42:28 +00003174 if (CGM.supportsCOMDAT() && GV->isWeakForLinker())
3175 GV->setComdat(M.getOrInsertComdat(GV->getName()));
3176
David Majnemere2cb8d12014-07-07 06:20:47 +00003177 // The Itanium ABI specifies that type_info objects must be globally
3178 // unique, with one exception: if the type is an incomplete class
3179 // type or a (possibly indirect) pointer to one. That exception
3180 // affects the general case of comparing type_info objects produced
3181 // by the typeid operator, which is why the comparison operators on
3182 // std::type_info generally use the type_info name pointers instead
3183 // of the object addresses. However, the language's built-in uses
3184 // of RTTI generally require class types to be complete, even when
3185 // manipulating pointers to those class types. This allows the
3186 // implementation of dynamic_cast to rely on address equality tests,
3187 // which is much faster.
3188
3189 // All of this is to say that it's important that both the type_info
3190 // object and the type_info name be uniqued when weakly emitted.
3191
3192 // Give the type_info object and name the formal visibility of the
3193 // type itself.
3194 llvm::GlobalValue::VisibilityTypes llvmVisibility;
3195 if (llvm::GlobalValue::isLocalLinkage(Linkage))
3196 // If the linkage is local, only default visibility makes sense.
3197 llvmVisibility = llvm::GlobalValue::DefaultVisibility;
3198 else if (RTTIUniqueness == ItaniumCXXABI::RUK_NonUniqueHidden)
3199 llvmVisibility = llvm::GlobalValue::HiddenVisibility;
3200 else
3201 llvmVisibility = CodeGenModule::GetLLVMVisibility(Ty->getVisibility());
Saleem Abdulrasool18820022016-12-02 22:46:18 +00003202
David Majnemere2cb8d12014-07-07 06:20:47 +00003203 TypeName->setVisibility(llvmVisibility);
3204 GV->setVisibility(llvmVisibility);
Saleem Abdulrasool18820022016-12-02 22:46:18 +00003205
3206 if (CGM.getTriple().isWindowsItaniumEnvironment()) {
3207 auto RD = Ty->getAsCXXRecordDecl();
3208 if (DLLExport || (RD && RD->hasAttr<DLLExportAttr>())) {
3209 TypeName->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
3210 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
Shoaib Meenai61118e72017-07-04 01:02:19 +00003211 } else if (RD && RD->hasAttr<DLLImportAttr>() &&
3212 ShouldUseExternalRTTIDescriptor(CGM, Ty)) {
Saleem Abdulrasool18820022016-12-02 22:46:18 +00003213 TypeName->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
3214 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
3215
3216 // Because the typename and the typeinfo are DLL import, convert them to
3217 // declarations rather than definitions. The initializers still need to
3218 // be constructed to calculate the type for the declarations.
3219 TypeName->setInitializer(nullptr);
3220 GV->setInitializer(nullptr);
3221 }
3222 }
David Majnemere2cb8d12014-07-07 06:20:47 +00003223
3224 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
3225}
3226
David Majnemere2cb8d12014-07-07 06:20:47 +00003227/// BuildObjCObjectTypeInfo - Build the appropriate kind of type_info
3228/// for the given Objective-C object type.
3229void ItaniumRTTIBuilder::BuildObjCObjectTypeInfo(const ObjCObjectType *OT) {
3230 // Drop qualifiers.
3231 const Type *T = OT->getBaseType().getTypePtr();
3232 assert(isa<BuiltinType>(T) || isa<ObjCInterfaceType>(T));
3233
3234 // The builtin types are abi::__class_type_infos and don't require
3235 // extra fields.
3236 if (isa<BuiltinType>(T)) return;
3237
3238 ObjCInterfaceDecl *Class = cast<ObjCInterfaceType>(T)->getDecl();
3239 ObjCInterfaceDecl *Super = Class->getSuperClass();
3240
3241 // Root classes are also __class_type_info.
3242 if (!Super) return;
3243
3244 QualType SuperTy = CGM.getContext().getObjCInterfaceType(Super);
3245
3246 // Everything else is single inheritance.
3247 llvm::Constant *BaseTypeInfo =
3248 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(SuperTy);
3249 Fields.push_back(BaseTypeInfo);
3250}
3251
3252/// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
3253/// inheritance, according to the Itanium C++ ABI, 2.95p6b.
3254void ItaniumRTTIBuilder::BuildSIClassTypeInfo(const CXXRecordDecl *RD) {
3255 // Itanium C++ ABI 2.9.5p6b:
3256 // It adds to abi::__class_type_info a single member pointing to the
3257 // type_info structure for the base type,
3258 llvm::Constant *BaseTypeInfo =
3259 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(RD->bases_begin()->getType());
3260 Fields.push_back(BaseTypeInfo);
3261}
3262
3263namespace {
3264 /// SeenBases - Contains virtual and non-virtual bases seen when traversing
3265 /// a class hierarchy.
3266 struct SeenBases {
3267 llvm::SmallPtrSet<const CXXRecordDecl *, 16> NonVirtualBases;
3268 llvm::SmallPtrSet<const CXXRecordDecl *, 16> VirtualBases;
3269 };
3270}
3271
3272/// ComputeVMIClassTypeInfoFlags - Compute the value of the flags member in
3273/// abi::__vmi_class_type_info.
3274///
3275static unsigned ComputeVMIClassTypeInfoFlags(const CXXBaseSpecifier *Base,
3276 SeenBases &Bases) {
3277
3278 unsigned Flags = 0;
3279
3280 const CXXRecordDecl *BaseDecl =
3281 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
3282
3283 if (Base->isVirtual()) {
3284 // Mark the virtual base as seen.
David Blaikie82e95a32014-11-19 07:49:47 +00003285 if (!Bases.VirtualBases.insert(BaseDecl).second) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003286 // If this virtual base has been seen before, then the class is diamond
3287 // shaped.
3288 Flags |= ItaniumRTTIBuilder::VMI_DiamondShaped;
3289 } else {
3290 if (Bases.NonVirtualBases.count(BaseDecl))
3291 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3292 }
3293 } else {
3294 // Mark the non-virtual base as seen.
David Blaikie82e95a32014-11-19 07:49:47 +00003295 if (!Bases.NonVirtualBases.insert(BaseDecl).second) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003296 // If this non-virtual base has been seen before, then the class has non-
3297 // diamond shaped repeated inheritance.
3298 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3299 } else {
3300 if (Bases.VirtualBases.count(BaseDecl))
3301 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3302 }
3303 }
3304
3305 // Walk all bases.
3306 for (const auto &I : BaseDecl->bases())
3307 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
3308
3309 return Flags;
3310}
3311
3312static unsigned ComputeVMIClassTypeInfoFlags(const CXXRecordDecl *RD) {
3313 unsigned Flags = 0;
3314 SeenBases Bases;
3315
3316 // Walk all bases.
3317 for (const auto &I : RD->bases())
3318 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
3319
3320 return Flags;
3321}
3322
3323/// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
3324/// classes with bases that do not satisfy the abi::__si_class_type_info
3325/// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
3326void ItaniumRTTIBuilder::BuildVMIClassTypeInfo(const CXXRecordDecl *RD) {
3327 llvm::Type *UnsignedIntLTy =
3328 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3329
3330 // Itanium C++ ABI 2.9.5p6c:
3331 // __flags is a word with flags describing details about the class
3332 // structure, which may be referenced by using the __flags_masks
3333 // enumeration. These flags refer to both direct and indirect bases.
3334 unsigned Flags = ComputeVMIClassTypeInfoFlags(RD);
3335 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3336
3337 // Itanium C++ ABI 2.9.5p6c:
3338 // __base_count is a word with the number of direct proper base class
3339 // descriptions that follow.
3340 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, RD->getNumBases()));
3341
3342 if (!RD->getNumBases())
3343 return;
3344
David Majnemere2cb8d12014-07-07 06:20:47 +00003345 // Now add the base class descriptions.
3346
3347 // Itanium C++ ABI 2.9.5p6c:
3348 // __base_info[] is an array of base class descriptions -- one for every
3349 // direct proper base. Each description is of the type:
3350 //
3351 // struct abi::__base_class_type_info {
3352 // public:
3353 // const __class_type_info *__base_type;
3354 // long __offset_flags;
3355 //
3356 // enum __offset_flags_masks {
3357 // __virtual_mask = 0x1,
3358 // __public_mask = 0x2,
3359 // __offset_shift = 8
3360 // };
3361 // };
Reid Klecknerd8b04662016-08-25 22:16:30 +00003362
3363 // If we're in mingw and 'long' isn't wide enough for a pointer, use 'long
3364 // long' instead of 'long' for __offset_flags. libstdc++abi uses long long on
3365 // LLP64 platforms.
3366 // FIXME: Consider updating libc++abi to match, and extend this logic to all
3367 // LLP64 platforms.
3368 QualType OffsetFlagsTy = CGM.getContext().LongTy;
3369 const TargetInfo &TI = CGM.getContext().getTargetInfo();
3370 if (TI.getTriple().isOSCygMing() && TI.getPointerWidth(0) > TI.getLongWidth())
3371 OffsetFlagsTy = CGM.getContext().LongLongTy;
3372 llvm::Type *OffsetFlagsLTy =
3373 CGM.getTypes().ConvertType(OffsetFlagsTy);
3374
David Majnemere2cb8d12014-07-07 06:20:47 +00003375 for (const auto &Base : RD->bases()) {
3376 // The __base_type member points to the RTTI for the base type.
3377 Fields.push_back(ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(Base.getType()));
3378
3379 const CXXRecordDecl *BaseDecl =
3380 cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
3381
3382 int64_t OffsetFlags = 0;
3383
3384 // All but the lower 8 bits of __offset_flags are a signed offset.
3385 // For a non-virtual base, this is the offset in the object of the base
3386 // subobject. For a virtual base, this is the offset in the virtual table of
3387 // the virtual base offset for the virtual base referenced (negative).
3388 CharUnits Offset;
3389 if (Base.isVirtual())
3390 Offset =
3391 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(RD, BaseDecl);
3392 else {
3393 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
3394 Offset = Layout.getBaseClassOffset(BaseDecl);
3395 };
3396
3397 OffsetFlags = uint64_t(Offset.getQuantity()) << 8;
3398
3399 // The low-order byte of __offset_flags contains flags, as given by the
3400 // masks from the enumeration __offset_flags_masks.
3401 if (Base.isVirtual())
3402 OffsetFlags |= BCTI_Virtual;
3403 if (Base.getAccessSpecifier() == AS_public)
3404 OffsetFlags |= BCTI_Public;
3405
Reid Klecknerd8b04662016-08-25 22:16:30 +00003406 Fields.push_back(llvm::ConstantInt::get(OffsetFlagsLTy, OffsetFlags));
David Majnemere2cb8d12014-07-07 06:20:47 +00003407 }
3408}
3409
Richard Smitha7d93782016-12-01 03:32:42 +00003410/// Compute the flags for a __pbase_type_info, and remove the corresponding
3411/// pieces from \p Type.
3412static unsigned extractPBaseFlags(ASTContext &Ctx, QualType &Type) {
3413 unsigned Flags = 0;
David Majnemere2cb8d12014-07-07 06:20:47 +00003414
Richard Smitha7d93782016-12-01 03:32:42 +00003415 if (Type.isConstQualified())
3416 Flags |= ItaniumRTTIBuilder::PTI_Const;
3417 if (Type.isVolatileQualified())
3418 Flags |= ItaniumRTTIBuilder::PTI_Volatile;
3419 if (Type.isRestrictQualified())
3420 Flags |= ItaniumRTTIBuilder::PTI_Restrict;
3421 Type = Type.getUnqualifiedType();
David Majnemere2cb8d12014-07-07 06:20:47 +00003422
3423 // Itanium C++ ABI 2.9.5p7:
3424 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
3425 // incomplete class type, the incomplete target type flag is set.
Richard Smitha7d93782016-12-01 03:32:42 +00003426 if (ContainsIncompleteClassType(Type))
3427 Flags |= ItaniumRTTIBuilder::PTI_Incomplete;
3428
3429 if (auto *Proto = Type->getAs<FunctionProtoType>()) {
3430 if (Proto->isNothrow(Ctx)) {
3431 Flags |= ItaniumRTTIBuilder::PTI_Noexcept;
3432 Type = Ctx.getFunctionType(
3433 Proto->getReturnType(), Proto->getParamTypes(),
3434 Proto->getExtProtoInfo().withExceptionSpec(EST_None));
3435 }
3436 }
3437
3438 return Flags;
3439}
3440
3441/// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct,
3442/// used for pointer types.
3443void ItaniumRTTIBuilder::BuildPointerTypeInfo(QualType PointeeTy) {
3444 // Itanium C++ ABI 2.9.5p7:
3445 // __flags is a flag word describing the cv-qualification and other
3446 // attributes of the type pointed to
3447 unsigned Flags = extractPBaseFlags(CGM.getContext(), PointeeTy);
David Majnemere2cb8d12014-07-07 06:20:47 +00003448
3449 llvm::Type *UnsignedIntLTy =
3450 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3451 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3452
3453 // Itanium C++ ABI 2.9.5p7:
3454 // __pointee is a pointer to the std::type_info derivation for the
3455 // unqualified type being pointed to.
3456 llvm::Constant *PointeeTypeInfo =
Richard Smitha7d93782016-12-01 03:32:42 +00003457 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(PointeeTy);
David Majnemere2cb8d12014-07-07 06:20:47 +00003458 Fields.push_back(PointeeTypeInfo);
3459}
3460
3461/// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
3462/// struct, used for member pointer types.
3463void
3464ItaniumRTTIBuilder::BuildPointerToMemberTypeInfo(const MemberPointerType *Ty) {
3465 QualType PointeeTy = Ty->getPointeeType();
3466
David Majnemere2cb8d12014-07-07 06:20:47 +00003467 // Itanium C++ ABI 2.9.5p7:
3468 // __flags is a flag word describing the cv-qualification and other
3469 // attributes of the type pointed to.
Richard Smitha7d93782016-12-01 03:32:42 +00003470 unsigned Flags = extractPBaseFlags(CGM.getContext(), PointeeTy);
David Majnemere2cb8d12014-07-07 06:20:47 +00003471
3472 const RecordType *ClassType = cast<RecordType>(Ty->getClass());
David Majnemere2cb8d12014-07-07 06:20:47 +00003473 if (IsIncompleteClassType(ClassType))
3474 Flags |= PTI_ContainingClassIncomplete;
3475
3476 llvm::Type *UnsignedIntLTy =
3477 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3478 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3479
3480 // Itanium C++ ABI 2.9.5p7:
3481 // __pointee is a pointer to the std::type_info derivation for the
3482 // unqualified type being pointed to.
3483 llvm::Constant *PointeeTypeInfo =
Richard Smitha7d93782016-12-01 03:32:42 +00003484 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(PointeeTy);
David Majnemere2cb8d12014-07-07 06:20:47 +00003485 Fields.push_back(PointeeTypeInfo);
3486
3487 // Itanium C++ ABI 2.9.5p9:
3488 // __context is a pointer to an abi::__class_type_info corresponding to the
3489 // class type containing the member pointed to
3490 // (e.g., the "A" in "int A::*").
3491 Fields.push_back(
3492 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(QualType(ClassType, 0)));
3493}
3494
David Majnemer443250f2015-03-17 20:35:00 +00003495llvm::Constant *ItaniumCXXABI::getAddrOfRTTIDescriptor(QualType Ty) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003496 return ItaniumRTTIBuilder(*this).BuildTypeInfo(Ty);
3497}
3498
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00003499void ItaniumCXXABI::EmitFundamentalRTTIDescriptor(QualType Type,
3500 bool DLLExport) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003501 QualType PointerType = getContext().getPointerType(Type);
3502 QualType PointerTypeConst = getContext().getPointerType(Type.withConst());
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00003503 ItaniumRTTIBuilder(*this).BuildTypeInfo(Type, /*Force=*/true, DLLExport);
3504 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerType, /*Force=*/true,
3505 DLLExport);
3506 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerTypeConst, /*Force=*/true,
3507 DLLExport);
David Majnemere2cb8d12014-07-07 06:20:47 +00003508}
3509
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00003510void ItaniumCXXABI::EmitFundamentalRTTIDescriptors(bool DLLExport) {
Richard Smith4a382012016-02-03 01:32:42 +00003511 // Types added here must also be added to TypeInfoIsInStandardLibrary.
David Majnemere2cb8d12014-07-07 06:20:47 +00003512 QualType FundamentalTypes[] = {
3513 getContext().VoidTy, getContext().NullPtrTy,
3514 getContext().BoolTy, getContext().WCharTy,
3515 getContext().CharTy, getContext().UnsignedCharTy,
3516 getContext().SignedCharTy, getContext().ShortTy,
3517 getContext().UnsignedShortTy, getContext().IntTy,
3518 getContext().UnsignedIntTy, getContext().LongTy,
3519 getContext().UnsignedLongTy, getContext().LongLongTy,
Richard Smith4a382012016-02-03 01:32:42 +00003520 getContext().UnsignedLongLongTy, getContext().Int128Ty,
3521 getContext().UnsignedInt128Ty, getContext().HalfTy,
David Majnemere2cb8d12014-07-07 06:20:47 +00003522 getContext().FloatTy, getContext().DoubleTy,
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00003523 getContext().LongDoubleTy, getContext().Float128Ty,
3524 getContext().Char16Ty, getContext().Char32Ty
David Majnemere2cb8d12014-07-07 06:20:47 +00003525 };
3526 for (const QualType &FundamentalType : FundamentalTypes)
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00003527 EmitFundamentalRTTIDescriptor(FundamentalType, DLLExport);
David Majnemere2cb8d12014-07-07 06:20:47 +00003528}
3529
3530/// What sort of uniqueness rules should we use for the RTTI for the
3531/// given type?
3532ItaniumCXXABI::RTTIUniquenessKind ItaniumCXXABI::classifyRTTIUniqueness(
3533 QualType CanTy, llvm::GlobalValue::LinkageTypes Linkage) const {
3534 if (shouldRTTIBeUnique())
3535 return RUK_Unique;
3536
3537 // It's only necessary for linkonce_odr or weak_odr linkage.
3538 if (Linkage != llvm::GlobalValue::LinkOnceODRLinkage &&
3539 Linkage != llvm::GlobalValue::WeakODRLinkage)
3540 return RUK_Unique;
3541
3542 // It's only necessary with default visibility.
3543 if (CanTy->getVisibility() != DefaultVisibility)
3544 return RUK_Unique;
3545
3546 // If we're not required to publish this symbol, hide it.
3547 if (Linkage == llvm::GlobalValue::LinkOnceODRLinkage)
3548 return RUK_NonUniqueHidden;
3549
3550 // If we're required to publish this symbol, as we might be under an
3551 // explicit instantiation, leave it with default visibility but
3552 // enable string-comparisons.
3553 assert(Linkage == llvm::GlobalValue::WeakODRLinkage);
3554 return RUK_NonUniqueVisible;
3555}
Rafael Espindola91f68b42014-09-15 19:20:10 +00003556
Rafael Espindola1e4df922014-09-16 15:18:21 +00003557// Find out how to codegen the complete destructor and constructor
3558namespace {
3559enum class StructorCodegen { Emit, RAUW, Alias, COMDAT };
3560}
3561static StructorCodegen getCodegenToUse(CodeGenModule &CGM,
3562 const CXXMethodDecl *MD) {
3563 if (!CGM.getCodeGenOpts().CXXCtorDtorAliases)
3564 return StructorCodegen::Emit;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003565
Rafael Espindola1e4df922014-09-16 15:18:21 +00003566 // The complete and base structors are not equivalent if there are any virtual
3567 // bases, so emit separate functions.
3568 if (MD->getParent()->getNumVBases())
3569 return StructorCodegen::Emit;
3570
3571 GlobalDecl AliasDecl;
3572 if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) {
3573 AliasDecl = GlobalDecl(DD, Dtor_Complete);
3574 } else {
3575 const auto *CD = cast<CXXConstructorDecl>(MD);
3576 AliasDecl = GlobalDecl(CD, Ctor_Complete);
3577 }
3578 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3579
3580 if (llvm::GlobalValue::isDiscardableIfUnused(Linkage))
3581 return StructorCodegen::RAUW;
3582
3583 // FIXME: Should we allow available_externally aliases?
3584 if (!llvm::GlobalAlias::isValidLinkage(Linkage))
3585 return StructorCodegen::RAUW;
3586
Rafael Espindola0806f982014-09-16 20:19:43 +00003587 if (llvm::GlobalValue::isWeakForLinker(Linkage)) {
Dan Gohman839f2152017-01-17 21:46:38 +00003588 // Only ELF and wasm support COMDATs with arbitrary names (C5/D5).
3589 if (CGM.getTarget().getTriple().isOSBinFormatELF() ||
3590 CGM.getTarget().getTriple().isOSBinFormatWasm())
Rafael Espindola0806f982014-09-16 20:19:43 +00003591 return StructorCodegen::COMDAT;
3592 return StructorCodegen::Emit;
3593 }
Rafael Espindola1e4df922014-09-16 15:18:21 +00003594
3595 return StructorCodegen::Alias;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003596}
3597
Rafael Espindola1e4df922014-09-16 15:18:21 +00003598static void emitConstructorDestructorAlias(CodeGenModule &CGM,
3599 GlobalDecl AliasDecl,
3600 GlobalDecl TargetDecl) {
3601 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3602
3603 StringRef MangledName = CGM.getMangledName(AliasDecl);
3604 llvm::GlobalValue *Entry = CGM.GetGlobalValue(MangledName);
3605 if (Entry && !Entry->isDeclaration())
3606 return;
3607
3608 auto *Aliasee = cast<llvm::GlobalValue>(CGM.GetAddrOfGlobal(TargetDecl));
Rafael Espindola1e4df922014-09-16 15:18:21 +00003609
3610 // Create the alias with no name.
David Blaikie2a791d72015-09-14 18:38:22 +00003611 auto *Alias = llvm::GlobalAlias::create(Linkage, "", Aliasee);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003612
3613 // Switch any previous uses to the alias.
3614 if (Entry) {
NAKAMURA Takumie9621042015-09-15 01:39:27 +00003615 assert(Entry->getType() == Aliasee->getType() &&
Rafael Espindola1e4df922014-09-16 15:18:21 +00003616 "declaration exists with different type");
3617 Alias->takeName(Entry);
3618 Entry->replaceAllUsesWith(Alias);
3619 Entry->eraseFromParent();
3620 } else {
3621 Alias->setName(MangledName);
3622 }
3623
3624 // Finally, set up the alias with its proper name and attributes.
Dario Domiziolic4fb8ca72014-09-19 22:06:24 +00003625 CGM.setAliasAttributes(cast<NamedDecl>(AliasDecl.getDecl()), Alias);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003626}
3627
3628void ItaniumCXXABI::emitCXXStructor(const CXXMethodDecl *MD,
3629 StructorType Type) {
3630 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
3631 const CXXDestructorDecl *DD = CD ? nullptr : cast<CXXDestructorDecl>(MD);
3632
3633 StructorCodegen CGType = getCodegenToUse(CGM, MD);
3634
3635 if (Type == StructorType::Complete) {
3636 GlobalDecl CompleteDecl;
3637 GlobalDecl BaseDecl;
3638 if (CD) {
3639 CompleteDecl = GlobalDecl(CD, Ctor_Complete);
3640 BaseDecl = GlobalDecl(CD, Ctor_Base);
3641 } else {
3642 CompleteDecl = GlobalDecl(DD, Dtor_Complete);
3643 BaseDecl = GlobalDecl(DD, Dtor_Base);
3644 }
3645
3646 if (CGType == StructorCodegen::Alias || CGType == StructorCodegen::COMDAT) {
3647 emitConstructorDestructorAlias(CGM, CompleteDecl, BaseDecl);
3648 return;
3649 }
3650
3651 if (CGType == StructorCodegen::RAUW) {
3652 StringRef MangledName = CGM.getMangledName(CompleteDecl);
Andrey Bokhankocab58582015-08-31 13:20:44 +00003653 auto *Aliasee = CGM.GetAddrOfGlobal(BaseDecl);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003654 CGM.addReplacement(MangledName, Aliasee);
3655 return;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003656 }
3657 }
3658
3659 // The base destructor is equivalent to the base destructor of its
3660 // base class if there is exactly one non-virtual base class with a
3661 // non-trivial destructor, there are no fields with a non-trivial
3662 // destructor, and the body of the destructor is trivial.
Rafael Espindola1e4df922014-09-16 15:18:21 +00003663 if (DD && Type == StructorType::Base && CGType != StructorCodegen::COMDAT &&
3664 !CGM.TryEmitBaseDestructorAsAlias(DD))
Rafael Espindola91f68b42014-09-15 19:20:10 +00003665 return;
3666
Richard Smith5b349582017-10-13 01:55:36 +00003667 // FIXME: The deleting destructor is equivalent to the selected operator
3668 // delete if:
3669 // * either the delete is a destroying operator delete or the destructor
3670 // would be trivial if it weren't virtual,
3671 // * the conversion from the 'this' parameter to the first parameter of the
3672 // destructor is equivalent to a bitcast,
3673 // * the destructor does not have an implicit "this" return, and
3674 // * the operator delete has the same calling convention and IR function type
3675 // as the destructor.
3676 // In such cases we should try to emit the deleting dtor as an alias to the
3677 // selected 'operator delete'.
3678
Rafael Espindola1e4df922014-09-16 15:18:21 +00003679 llvm::Function *Fn = CGM.codegenCXXStructor(MD, Type);
Rafael Espindola91f68b42014-09-15 19:20:10 +00003680
Rafael Espindola1e4df922014-09-16 15:18:21 +00003681 if (CGType == StructorCodegen::COMDAT) {
3682 SmallString<256> Buffer;
3683 llvm::raw_svector_ostream Out(Buffer);
3684 if (DD)
3685 getMangleContext().mangleCXXDtorComdat(DD, Out);
3686 else
3687 getMangleContext().mangleCXXCtorComdat(CD, Out);
3688 llvm::Comdat *C = CGM.getModule().getOrInsertComdat(Out.str());
3689 Fn->setComdat(C);
Rafael Espindoladbee8a72015-01-15 21:36:08 +00003690 } else {
3691 CGM.maybeSetTrivialComdat(*MD, *Fn);
Rafael Espindola91f68b42014-09-15 19:20:10 +00003692 }
Rafael Espindola91f68b42014-09-15 19:20:10 +00003693}
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003694
3695static llvm::Constant *getBeginCatchFn(CodeGenModule &CGM) {
3696 // void *__cxa_begin_catch(void*);
3697 llvm::FunctionType *FTy = llvm::FunctionType::get(
3698 CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3699
3700 return CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
3701}
3702
3703static llvm::Constant *getEndCatchFn(CodeGenModule &CGM) {
3704 // void __cxa_end_catch();
3705 llvm::FunctionType *FTy =
3706 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
3707
3708 return CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
3709}
3710
3711static llvm::Constant *getGetExceptionPtrFn(CodeGenModule &CGM) {
3712 // void *__cxa_get_exception_ptr(void*);
3713 llvm::FunctionType *FTy = llvm::FunctionType::get(
3714 CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3715
3716 return CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
3717}
3718
3719namespace {
3720 /// A cleanup to call __cxa_end_catch. In many cases, the caught
3721 /// exception type lets us state definitively that the thrown exception
3722 /// type does not have a destructor. In particular:
3723 /// - Catch-alls tell us nothing, so we have to conservatively
3724 /// assume that the thrown exception might have a destructor.
3725 /// - Catches by reference behave according to their base types.
3726 /// - Catches of non-record types will only trigger for exceptions
3727 /// of non-record types, which never have destructors.
3728 /// - Catches of record types can trigger for arbitrary subclasses
3729 /// of the caught type, so we have to assume the actual thrown
3730 /// exception type might have a throwing destructor, even if the
3731 /// caught type's destructor is trivial or nothrow.
David Blaikie7e70d682015-08-18 22:40:54 +00003732 struct CallEndCatch final : EHScopeStack::Cleanup {
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003733 CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
3734 bool MightThrow;
3735
3736 void Emit(CodeGenFunction &CGF, Flags flags) override {
3737 if (!MightThrow) {
3738 CGF.EmitNounwindRuntimeCall(getEndCatchFn(CGF.CGM));
3739 return;
3740 }
3741
3742 CGF.EmitRuntimeCallOrInvoke(getEndCatchFn(CGF.CGM));
3743 }
3744 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003745}
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003746
3747/// Emits a call to __cxa_begin_catch and enters a cleanup to call
3748/// __cxa_end_catch.
3749///
3750/// \param EndMightThrow - true if __cxa_end_catch might throw
3751static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
3752 llvm::Value *Exn,
3753 bool EndMightThrow) {
3754 llvm::CallInst *call =
3755 CGF.EmitNounwindRuntimeCall(getBeginCatchFn(CGF.CGM), Exn);
3756
3757 CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
3758
3759 return call;
3760}
3761
3762/// A "special initializer" callback for initializing a catch
3763/// parameter during catch initialization.
3764static void InitCatchParam(CodeGenFunction &CGF,
3765 const VarDecl &CatchParam,
John McCall7f416cc2015-09-08 08:05:57 +00003766 Address ParamAddr,
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003767 SourceLocation Loc) {
3768 // Load the exception from where the landing pad saved it.
3769 llvm::Value *Exn = CGF.getExceptionFromSlot();
3770
3771 CanQualType CatchType =
3772 CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
3773 llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
3774
3775 // If we're catching by reference, we can just cast the object
3776 // pointer to the appropriate pointer.
3777 if (isa<ReferenceType>(CatchType)) {
3778 QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
3779 bool EndCatchMightThrow = CaughtType->isRecordType();
3780
3781 // __cxa_begin_catch returns the adjusted object pointer.
3782 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
3783
3784 // We have no way to tell the personality function that we're
3785 // catching by reference, so if we're catching a pointer,
3786 // __cxa_begin_catch will actually return that pointer by value.
3787 if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
3788 QualType PointeeType = PT->getPointeeType();
3789
3790 // When catching by reference, generally we should just ignore
3791 // this by-value pointer and use the exception object instead.
3792 if (!PointeeType->isRecordType()) {
3793
3794 // Exn points to the struct _Unwind_Exception header, which
3795 // we have to skip past in order to reach the exception data.
3796 unsigned HeaderSize =
3797 CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
3798 AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
3799
3800 // However, if we're catching a pointer-to-record type that won't
3801 // work, because the personality function might have adjusted
3802 // the pointer. There's actually no way for us to fully satisfy
3803 // the language/ABI contract here: we can't use Exn because it
3804 // might have the wrong adjustment, but we can't use the by-value
3805 // pointer because it's off by a level of abstraction.
3806 //
3807 // The current solution is to dump the adjusted pointer into an
3808 // alloca, which breaks language semantics (because changing the
3809 // pointer doesn't change the exception) but at least works.
3810 // The better solution would be to filter out non-exact matches
3811 // and rethrow them, but this is tricky because the rethrow
3812 // really needs to be catchable by other sites at this landing
3813 // pad. The best solution is to fix the personality function.
3814 } else {
3815 // Pull the pointer for the reference type off.
3816 llvm::Type *PtrTy =
3817 cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
3818
3819 // Create the temporary and write the adjusted pointer into it.
John McCall7f416cc2015-09-08 08:05:57 +00003820 Address ExnPtrTmp =
3821 CGF.CreateTempAlloca(PtrTy, CGF.getPointerAlign(), "exn.byref.tmp");
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003822 llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
3823 CGF.Builder.CreateStore(Casted, ExnPtrTmp);
3824
3825 // Bind the reference to the temporary.
John McCall7f416cc2015-09-08 08:05:57 +00003826 AdjustedExn = ExnPtrTmp.getPointer();
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003827 }
3828 }
3829
3830 llvm::Value *ExnCast =
3831 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
3832 CGF.Builder.CreateStore(ExnCast, ParamAddr);
3833 return;
3834 }
3835
3836 // Scalars and complexes.
3837 TypeEvaluationKind TEK = CGF.getEvaluationKind(CatchType);
3838 if (TEK != TEK_Aggregate) {
3839 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
3840
3841 // If the catch type is a pointer type, __cxa_begin_catch returns
3842 // the pointer by value.
3843 if (CatchType->hasPointerRepresentation()) {
3844 llvm::Value *CastExn =
3845 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
3846
3847 switch (CatchType.getQualifiers().getObjCLifetime()) {
3848 case Qualifiers::OCL_Strong:
3849 CastExn = CGF.EmitARCRetainNonBlock(CastExn);
3850 // fallthrough
3851
3852 case Qualifiers::OCL_None:
3853 case Qualifiers::OCL_ExplicitNone:
3854 case Qualifiers::OCL_Autoreleasing:
3855 CGF.Builder.CreateStore(CastExn, ParamAddr);
3856 return;
3857
3858 case Qualifiers::OCL_Weak:
3859 CGF.EmitARCInitWeak(ParamAddr, CastExn);
3860 return;
3861 }
3862 llvm_unreachable("bad ownership qualifier!");
3863 }
3864
3865 // Otherwise, it returns a pointer into the exception object.
3866
3867 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
3868 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
3869
3870 LValue srcLV = CGF.MakeNaturalAlignAddrLValue(Cast, CatchType);
John McCall7f416cc2015-09-08 08:05:57 +00003871 LValue destLV = CGF.MakeAddrLValue(ParamAddr, CatchType);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003872 switch (TEK) {
3873 case TEK_Complex:
3874 CGF.EmitStoreOfComplex(CGF.EmitLoadOfComplex(srcLV, Loc), destLV,
3875 /*init*/ true);
3876 return;
3877 case TEK_Scalar: {
3878 llvm::Value *ExnLoad = CGF.EmitLoadOfScalar(srcLV, Loc);
3879 CGF.EmitStoreOfScalar(ExnLoad, destLV, /*init*/ true);
3880 return;
3881 }
3882 case TEK_Aggregate:
3883 llvm_unreachable("evaluation kind filtered out!");
3884 }
3885 llvm_unreachable("bad evaluation kind");
3886 }
3887
3888 assert(isa<RecordType>(CatchType) && "unexpected catch type!");
John McCall7f416cc2015-09-08 08:05:57 +00003889 auto catchRD = CatchType->getAsCXXRecordDecl();
3890 CharUnits caughtExnAlignment = CGF.CGM.getClassPointerAlignment(catchRD);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003891
3892 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
3893
3894 // Check for a copy expression. If we don't have a copy expression,
3895 // that means a trivial copy is okay.
3896 const Expr *copyExpr = CatchParam.getInit();
3897 if (!copyExpr) {
3898 llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true);
John McCall7f416cc2015-09-08 08:05:57 +00003899 Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy),
3900 caughtExnAlignment);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003901 CGF.EmitAggregateCopy(ParamAddr, adjustedExn, CatchType);
3902 return;
3903 }
3904
3905 // We have to call __cxa_get_exception_ptr to get the adjusted
3906 // pointer before copying.
3907 llvm::CallInst *rawAdjustedExn =
3908 CGF.EmitNounwindRuntimeCall(getGetExceptionPtrFn(CGF.CGM), Exn);
3909
3910 // Cast that to the appropriate type.
John McCall7f416cc2015-09-08 08:05:57 +00003911 Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy),
3912 caughtExnAlignment);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003913
3914 // The copy expression is defined in terms of an OpaqueValueExpr.
3915 // Find it and map it to the adjusted expression.
3916 CodeGenFunction::OpaqueValueMapping
3917 opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr),
3918 CGF.MakeAddrLValue(adjustedExn, CatchParam.getType()));
3919
3920 // Call the copy ctor in a terminate scope.
3921 CGF.EHStack.pushTerminate();
3922
3923 // Perform the copy construction.
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003924 CGF.EmitAggExpr(copyExpr,
John McCall7f416cc2015-09-08 08:05:57 +00003925 AggValueSlot::forAddr(ParamAddr, Qualifiers(),
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003926 AggValueSlot::IsNotDestructed,
3927 AggValueSlot::DoesNotNeedGCBarriers,
3928 AggValueSlot::IsNotAliased));
3929
3930 // Leave the terminate scope.
3931 CGF.EHStack.popTerminate();
3932
3933 // Undo the opaque value mapping.
3934 opaque.pop();
3935
3936 // Finally we can call __cxa_begin_catch.
3937 CallBeginCatch(CGF, Exn, true);
3938}
3939
3940/// Begins a catch statement by initializing the catch variable and
3941/// calling __cxa_begin_catch.
3942void ItaniumCXXABI::emitBeginCatch(CodeGenFunction &CGF,
3943 const CXXCatchStmt *S) {
3944 // We have to be very careful with the ordering of cleanups here:
3945 // C++ [except.throw]p4:
3946 // The destruction [of the exception temporary] occurs
3947 // immediately after the destruction of the object declared in
3948 // the exception-declaration in the handler.
3949 //
3950 // So the precise ordering is:
3951 // 1. Construct catch variable.
3952 // 2. __cxa_begin_catch
3953 // 3. Enter __cxa_end_catch cleanup
3954 // 4. Enter dtor cleanup
3955 //
3956 // We do this by using a slightly abnormal initialization process.
3957 // Delegation sequence:
3958 // - ExitCXXTryStmt opens a RunCleanupsScope
3959 // - EmitAutoVarAlloca creates the variable and debug info
3960 // - InitCatchParam initializes the variable from the exception
3961 // - CallBeginCatch calls __cxa_begin_catch
3962 // - CallBeginCatch enters the __cxa_end_catch cleanup
3963 // - EmitAutoVarCleanups enters the variable destructor cleanup
3964 // - EmitCXXTryStmt emits the code for the catch body
3965 // - EmitCXXTryStmt close the RunCleanupsScope
3966
3967 VarDecl *CatchParam = S->getExceptionDecl();
3968 if (!CatchParam) {
3969 llvm::Value *Exn = CGF.getExceptionFromSlot();
3970 CallBeginCatch(CGF, Exn, true);
3971 return;
3972 }
3973
3974 // Emit the local.
3975 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
3976 InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF), S->getLocStart());
3977 CGF.EmitAutoVarCleanups(var);
3978}
3979
3980/// Get or define the following function:
3981/// void @__clang_call_terminate(i8* %exn) nounwind noreturn
3982/// This code is used only in C++.
3983static llvm::Constant *getClangCallTerminateFn(CodeGenModule &CGM) {
3984 llvm::FunctionType *fnTy =
3985 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
Reid Klecknerde864822017-03-21 16:57:30 +00003986 llvm::Constant *fnRef = CGM.CreateRuntimeFunction(
3987 fnTy, "__clang_call_terminate", llvm::AttributeList(), /*Local=*/true);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003988
3989 llvm::Function *fn = dyn_cast<llvm::Function>(fnRef);
3990 if (fn && fn->empty()) {
3991 fn->setDoesNotThrow();
3992 fn->setDoesNotReturn();
3993
3994 // What we really want is to massively penalize inlining without
3995 // forbidding it completely. The difference between that and
3996 // 'noinline' is negligible.
3997 fn->addFnAttr(llvm::Attribute::NoInline);
3998
3999 // Allow this function to be shared across translation units, but
4000 // we don't want it to turn into an exported symbol.
4001 fn->setLinkage(llvm::Function::LinkOnceODRLinkage);
4002 fn->setVisibility(llvm::Function::HiddenVisibility);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00004003 if (CGM.supportsCOMDAT())
4004 fn->setComdat(CGM.getModule().getOrInsertComdat(fn->getName()));
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004005
4006 // Set up the function.
4007 llvm::BasicBlock *entry =
4008 llvm::BasicBlock::Create(CGM.getLLVMContext(), "", fn);
John McCall7f416cc2015-09-08 08:05:57 +00004009 CGBuilderTy builder(CGM, entry);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004010
4011 // Pull the exception pointer out of the parameter list.
4012 llvm::Value *exn = &*fn->arg_begin();
4013
4014 // Call __cxa_begin_catch(exn).
4015 llvm::CallInst *catchCall = builder.CreateCall(getBeginCatchFn(CGM), exn);
4016 catchCall->setDoesNotThrow();
4017 catchCall->setCallingConv(CGM.getRuntimeCC());
4018
4019 // Call std::terminate().
David Blaikie4ba525b2015-07-14 17:27:39 +00004020 llvm::CallInst *termCall = builder.CreateCall(CGM.getTerminateFn());
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004021 termCall->setDoesNotThrow();
4022 termCall->setDoesNotReturn();
4023 termCall->setCallingConv(CGM.getRuntimeCC());
4024
4025 // std::terminate cannot return.
4026 builder.CreateUnreachable();
4027 }
4028
4029 return fnRef;
4030}
4031
4032llvm::CallInst *
4033ItaniumCXXABI::emitTerminateForUnexpectedException(CodeGenFunction &CGF,
4034 llvm::Value *Exn) {
4035 // In C++, we want to call __cxa_begin_catch() before terminating.
4036 if (Exn) {
4037 assert(CGF.CGM.getLangOpts().CPlusPlus);
4038 return CGF.EmitNounwindRuntimeCall(getClangCallTerminateFn(CGF.CGM), Exn);
4039 }
4040 return CGF.EmitNounwindRuntimeCall(CGF.CGM.getTerminateFn());
4041}