blob: 5c33f8c1afac1e971baf891ff10bff1ae8769375 [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
Craig Topper4f12f102014-03-12 06:41:41 +000065 RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const override {
Richard Smith96cd6712017-08-16 01:49:53 +000066 // If C++ prohibits us from making a copy, pass by address.
67 if (!canCopyArgument(RD))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000068 return RAA_Indirect;
69 return RAA_Default;
70 }
71
John McCall7f416cc2015-09-08 08:05:57 +000072 bool isThisCompleteObject(GlobalDecl GD) const override {
73 // The Itanium ABI has separate complete-object vs. base-object
74 // variants of both constructors and destructors.
75 if (isa<CXXDestructorDecl>(GD.getDecl())) {
76 switch (GD.getDtorType()) {
77 case Dtor_Complete:
78 case Dtor_Deleting:
79 return true;
80
81 case Dtor_Base:
82 return false;
83
84 case Dtor_Comdat:
85 llvm_unreachable("emitting dtor comdat as function?");
86 }
87 llvm_unreachable("bad dtor kind");
88 }
89 if (isa<CXXConstructorDecl>(GD.getDecl())) {
90 switch (GD.getCtorType()) {
91 case Ctor_Complete:
92 return true;
93
94 case Ctor_Base:
95 return false;
96
97 case Ctor_CopyingClosure:
98 case Ctor_DefaultClosure:
99 llvm_unreachable("closure ctors in Itanium ABI?");
100
101 case Ctor_Comdat:
102 llvm_unreachable("emitting ctor comdat as function?");
103 }
104 llvm_unreachable("bad dtor kind");
105 }
106
107 // No other kinds.
108 return false;
109 }
110
Craig Topper4f12f102014-03-12 06:41:41 +0000111 bool isZeroInitializable(const MemberPointerType *MPT) override;
John McCall84fa5102010-08-22 04:16:24 +0000112
Craig Topper4f12f102014-03-12 06:41:41 +0000113 llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT) override;
John McCall7a9aac22010-08-23 01:21:21 +0000114
John McCallb92ab1a2016-10-26 23:46:34 +0000115 CGCallee
Craig Topper4f12f102014-03-12 06:41:41 +0000116 EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
117 const Expr *E,
John McCall7f416cc2015-09-08 08:05:57 +0000118 Address This,
119 llvm::Value *&ThisPtrForCall,
Craig Topper4f12f102014-03-12 06:41:41 +0000120 llvm::Value *MemFnPtr,
121 const MemberPointerType *MPT) override;
John McCalla8bbb822010-08-22 03:04:22 +0000122
Craig Topper4f12f102014-03-12 06:41:41 +0000123 llvm::Value *
124 EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E,
John McCall7f416cc2015-09-08 08:05:57 +0000125 Address Base,
Craig Topper4f12f102014-03-12 06:41:41 +0000126 llvm::Value *MemPtr,
127 const MemberPointerType *MPT) override;
John McCallc134eb52010-08-31 21:07:20 +0000128
John McCall7a9aac22010-08-23 01:21:21 +0000129 llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
130 const CastExpr *E,
Craig Topper4f12f102014-03-12 06:41:41 +0000131 llvm::Value *Src) override;
John McCallc62bb392012-02-15 01:22:51 +0000132 llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
Craig Topper4f12f102014-03-12 06:41:41 +0000133 llvm::Constant *Src) override;
John McCall84fa5102010-08-22 04:16:24 +0000134
Craig Topper4f12f102014-03-12 06:41:41 +0000135 llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT) override;
John McCall84fa5102010-08-22 04:16:24 +0000136
David Majnemere2be95b2015-06-23 07:31:01 +0000137 llvm::Constant *EmitMemberFunctionPointer(const CXXMethodDecl *MD) override;
John McCallf3a88602011-02-03 08:15:49 +0000138 llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
Craig Topper4f12f102014-03-12 06:41:41 +0000139 CharUnits offset) override;
140 llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT) override;
Richard Smithdafff942012-01-14 04:30:29 +0000141 llvm::Constant *BuildMemberPointer(const CXXMethodDecl *MD,
142 CharUnits ThisAdjustment);
John McCall1c456c82010-08-22 06:43:33 +0000143
John McCall7a9aac22010-08-23 01:21:21 +0000144 llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000145 llvm::Value *L, llvm::Value *R,
John McCall7a9aac22010-08-23 01:21:21 +0000146 const MemberPointerType *MPT,
Craig Topper4f12f102014-03-12 06:41:41 +0000147 bool Inequality) override;
John McCall131d97d2010-08-22 08:30:07 +0000148
John McCall7a9aac22010-08-23 01:21:21 +0000149 llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000150 llvm::Value *Addr,
151 const MemberPointerType *MPT) override;
John McCall5d865c322010-08-31 07:33:07 +0000152
David Majnemer08681372014-11-01 07:37:17 +0000153 void emitVirtualObjectDelete(CodeGenFunction &CGF, const CXXDeleteExpr *DE,
John McCall7f416cc2015-09-08 08:05:57 +0000154 Address Ptr, QualType ElementType,
David Majnemer0c0b6d92014-10-31 20:09:12 +0000155 const CXXDestructorDecl *Dtor) override;
John McCall82fb8922012-09-25 10:10:39 +0000156
Akira Hatanakac47fcf02017-07-27 18:52:44 +0000157 /// Itanium says that an _Unwind_Exception has to be "double-word"
158 /// aligned (and thus the end of it is also so-aligned), meaning 16
159 /// bytes. Of course, that was written for the actual Itanium,
160 /// which is a 64-bit platform. Classically, the ABI doesn't really
161 /// specify the alignment on other platforms, but in practice
162 /// libUnwind declares the struct with __attribute__((aligned)), so
163 /// we assume that alignment here. (It's generally 16 bytes, but
164 /// some targets overwrite it.)
John McCall7f416cc2015-09-08 08:05:57 +0000165 CharUnits getAlignmentOfExnObject() {
Akira Hatanakac47fcf02017-07-27 18:52:44 +0000166 auto align = CGM.getContext().getTargetDefaultAlignForAttributeAligned();
167 return CGM.getContext().toCharUnitsFromBits(align);
John McCall7f416cc2015-09-08 08:05:57 +0000168 }
169
David Majnemer442d0a22014-11-25 07:20:20 +0000170 void emitRethrow(CodeGenFunction &CGF, bool isNoReturn) override;
David Majnemer7c237072015-03-05 00:46:22 +0000171 void emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) override;
David Majnemer442d0a22014-11-25 07:20:20 +0000172
Reid Klecknerfff8e7f2015-03-03 19:21:04 +0000173 void emitBeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *C) override;
174
175 llvm::CallInst *
176 emitTerminateForUnexpectedException(CodeGenFunction &CGF,
177 llvm::Value *Exn) override;
178
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +0000179 void EmitFundamentalRTTIDescriptor(QualType Type, bool DLLExport);
180 void EmitFundamentalRTTIDescriptors(bool DLLExport);
David Majnemer443250f2015-03-17 20:35:00 +0000181 llvm::Constant *getAddrOfRTTIDescriptor(QualType Ty) override;
Reid Kleckner10aa7702015-09-16 20:15:55 +0000182 CatchTypeInfo
David Majnemer37b417f2015-03-29 21:55:10 +0000183 getAddrOfCXXCatchHandlerType(QualType Ty,
184 QualType CatchHandlerType) override {
Reid Kleckner10aa7702015-09-16 20:15:55 +0000185 return CatchTypeInfo{getAddrOfRTTIDescriptor(Ty), 0};
David Majnemer443250f2015-03-17 20:35:00 +0000186 }
David Majnemere2cb8d12014-07-07 06:20:47 +0000187
David Majnemer1162d252014-06-22 19:05:33 +0000188 bool shouldTypeidBeNullChecked(bool IsDeref, QualType SrcRecordTy) override;
189 void EmitBadTypeidCall(CodeGenFunction &CGF) override;
190 llvm::Value *EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy,
John McCall7f416cc2015-09-08 08:05:57 +0000191 Address ThisPtr,
David Majnemer1162d252014-06-22 19:05:33 +0000192 llvm::Type *StdTypeInfoPtrTy) override;
193
194 bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
195 QualType SrcRecordTy) override;
196
John McCall7f416cc2015-09-08 08:05:57 +0000197 llvm::Value *EmitDynamicCastCall(CodeGenFunction &CGF, Address Value,
David Majnemer1162d252014-06-22 19:05:33 +0000198 QualType SrcRecordTy, QualType DestTy,
199 QualType DestRecordTy,
200 llvm::BasicBlock *CastEnd) override;
201
John McCall7f416cc2015-09-08 08:05:57 +0000202 llvm::Value *EmitDynamicCastToVoid(CodeGenFunction &CGF, Address Value,
David Majnemer1162d252014-06-22 19:05:33 +0000203 QualType SrcRecordTy,
204 QualType DestTy) override;
205
206 bool EmitBadCastCall(CodeGenFunction &CGF) override;
207
Craig Topper4f12f102014-03-12 06:41:41 +0000208 llvm::Value *
John McCall7f416cc2015-09-08 08:05:57 +0000209 GetVirtualBaseClassOffset(CodeGenFunction &CGF, Address This,
Craig Topper4f12f102014-03-12 06:41:41 +0000210 const CXXRecordDecl *ClassDecl,
211 const CXXRecordDecl *BaseClassDecl) override;
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000212
Craig Topper4f12f102014-03-12 06:41:41 +0000213 void EmitCXXConstructors(const CXXConstructorDecl *D) override;
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +0000214
George Burgess IVf203dbf2017-02-22 20:28:02 +0000215 AddedStructorArgs
216 buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
217 SmallVectorImpl<CanQualType> &ArgTys) override;
John McCall5d865c322010-08-31 07:33:07 +0000218
Reid Klecknere7de47e2013-07-22 13:51:44 +0000219 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
Craig Topper4f12f102014-03-12 06:41:41 +0000220 CXXDtorType DT) const override {
Reid Klecknere7de47e2013-07-22 13:51:44 +0000221 // Itanium does not emit any destructor variant as an inline thunk.
222 // Delegating may occur as an optimization, but all variants are either
223 // emitted with external linkage or as linkonce if they are inline and used.
224 return false;
225 }
226
Craig Topper4f12f102014-03-12 06:41:41 +0000227 void EmitCXXDestructors(const CXXDestructorDecl *D) override;
Reid Klecknere7de47e2013-07-22 13:51:44 +0000228
Reid Kleckner89077a12013-12-17 19:46:40 +0000229 void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
Craig Topper4f12f102014-03-12 06:41:41 +0000230 FunctionArgList &Params) override;
John McCall5d865c322010-08-31 07:33:07 +0000231
Craig Topper4f12f102014-03-12 06:41:41 +0000232 void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override;
John McCall8ed55a52010-09-02 09:58:18 +0000233
George Burgess IVf203dbf2017-02-22 20:28:02 +0000234 AddedStructorArgs
235 addImplicitConstructorArgs(CodeGenFunction &CGF, const CXXConstructorDecl *D,
236 CXXCtorType Type, bool ForVirtualBase,
237 bool Delegating, CallArgList &Args) override;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000238
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000239 void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD,
240 CXXDtorType Type, bool ForVirtualBase,
John McCall7f416cc2015-09-08 08:05:57 +0000241 bool Delegating, Address This) override;
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000242
Craig Topper4f12f102014-03-12 06:41:41 +0000243 void emitVTableDefinitions(CodeGenVTables &CGVT,
244 const CXXRecordDecl *RD) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000245
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000246 bool isVirtualOffsetNeededForVTableField(CodeGenFunction &CGF,
247 CodeGenFunction::VPtr Vptr) override;
248
249 bool doStructorsInitializeVPtrs(const CXXRecordDecl *VTableClass) override {
250 return true;
251 }
252
253 llvm::Constant *
254 getVTableAddressPoint(BaseSubobject Base,
255 const CXXRecordDecl *VTableClass) override;
256
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000257 llvm::Value *getVTableAddressPointInStructor(
258 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000259 BaseSubobject Base, const CXXRecordDecl *NearestVBase) override;
260
261 llvm::Value *getVTableAddressPointInStructorWithVTT(
262 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
263 BaseSubobject Base, const CXXRecordDecl *NearestVBase);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000264
265 llvm::Constant *
266 getVTableAddressPointForConstExpr(BaseSubobject Base,
Craig Topper4f12f102014-03-12 06:41:41 +0000267 const CXXRecordDecl *VTableClass) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000268
269 llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
Craig Topper4f12f102014-03-12 06:41:41 +0000270 CharUnits VPtrOffset) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000271
John McCallb92ab1a2016-10-26 23:46:34 +0000272 CGCallee getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
273 Address This, llvm::Type *Ty,
274 SourceLocation Loc) override;
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000275
David Majnemer0c0b6d92014-10-31 20:09:12 +0000276 llvm::Value *EmitVirtualDestructorCall(CodeGenFunction &CGF,
277 const CXXDestructorDecl *Dtor,
278 CXXDtorType DtorType,
John McCall7f416cc2015-09-08 08:05:57 +0000279 Address This,
David Majnemer0c0b6d92014-10-31 20:09:12 +0000280 const CXXMemberCallExpr *CE) override;
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000281
Craig Topper4f12f102014-03-12 06:41:41 +0000282 void emitVirtualInheritanceTables(const CXXRecordDecl *RD) override;
Reid Kleckner7810af02013-06-19 15:20:38 +0000283
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000284 bool canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const override;
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000285
Hans Wennborgc94391d2014-06-06 20:04:01 +0000286 void setThunkLinkage(llvm::Function *Thunk, bool ForVTable, GlobalDecl GD,
287 bool ReturnAdjustment) override {
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000288 // Allow inlining of thunks by emitting them with available_externally
289 // linkage together with vtables when needed.
Peter Collingbourne8fabc1b2015-07-01 02:10:26 +0000290 if (ForVTable && !Thunk->hasLocalLinkage())
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000291 Thunk->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
Shoaib Meenaicef66e52017-07-24 17:16:27 +0000292
293 // Propagate dllexport storage, to enable the linker to generate import
294 // thunks as necessary (e.g. when a parent class has a key function and a
295 // child class doesn't, and the construction vtable for the parent in the
296 // child needs to reference the parent's thunks).
297 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
298 if (MD->hasAttr<DLLExportAttr>())
299 Thunk->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000300 }
301
John McCall7f416cc2015-09-08 08:05:57 +0000302 llvm::Value *performThisAdjustment(CodeGenFunction &CGF, Address This,
Craig Topper4f12f102014-03-12 06:41:41 +0000303 const ThisAdjustment &TA) override;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000304
John McCall7f416cc2015-09-08 08:05:57 +0000305 llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
Craig Topper4f12f102014-03-12 06:41:41 +0000306 const ReturnAdjustment &RA) override;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000307
David Majnemer196ac332014-09-11 23:05:02 +0000308 size_t getSrcArgforCopyCtor(const CXXConstructorDecl *,
309 FunctionArgList &Args) const override {
310 assert(!Args.empty() && "expected the arglist to not be empty!");
311 return Args.size() - 1;
312 }
313
Craig Topper4f12f102014-03-12 06:41:41 +0000314 StringRef GetPureVirtualCallName() override { return "__cxa_pure_virtual"; }
315 StringRef GetDeletedVirtualCallName() override
316 { return "__cxa_deleted_virtual"; }
Joao Matos2ce88ef2012-07-17 17:10:11 +0000317
Craig Topper4f12f102014-03-12 06:41:41 +0000318 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
John McCall7f416cc2015-09-08 08:05:57 +0000319 Address InitializeArrayCookie(CodeGenFunction &CGF,
320 Address NewPtr,
321 llvm::Value *NumElements,
322 const CXXNewExpr *expr,
323 QualType ElementType) override;
John McCallb91cd662012-05-01 05:23:51 +0000324 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000325 Address allocPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000326 CharUnits cookieSize) override;
John McCall68ff0372010-09-08 01:44:27 +0000327
John McCallcdf7ef52010-11-06 09:44:32 +0000328 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
Craig Topper4f12f102014-03-12 06:41:41 +0000329 llvm::GlobalVariable *DeclPtr,
330 bool PerformInit) override;
Richard Smithdbf74ba2013-04-14 23:01:42 +0000331 void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
Craig Topper4f12f102014-03-12 06:41:41 +0000332 llvm::Constant *dtor, llvm::Constant *addr) override;
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000333
334 llvm::Function *getOrCreateThreadLocalWrapper(const VarDecl *VD,
Alexander Musmanf94c3182014-09-26 06:28:25 +0000335 llvm::Value *Val);
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000336 void EmitThreadLocalInitFuncs(
David Majnemerb3341ea2014-10-05 05:05:40 +0000337 CodeGenModule &CGM,
Richard Smith5a99c492015-12-01 01:10:48 +0000338 ArrayRef<const VarDecl *> CXXThreadLocals,
David Majnemerb3341ea2014-10-05 05:05:40 +0000339 ArrayRef<llvm::Function *> CXXThreadLocalInits,
Richard Smith5a99c492015-12-01 01:10:48 +0000340 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) override;
David Majnemerb3341ea2014-10-05 05:05:40 +0000341
342 bool usesThreadWrapperFunction() const override { return true; }
Richard Smith0f383742014-03-26 22:48:22 +0000343 LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD,
344 QualType LValType) override;
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000345
Craig Topper4f12f102014-03-12 06:41:41 +0000346 bool NeedsVTTParameter(GlobalDecl GD) override;
David Majnemere2cb8d12014-07-07 06:20:47 +0000347
348 /**************************** RTTI Uniqueness ******************************/
349
350protected:
351 /// Returns true if the ABI requires RTTI type_info objects to be unique
352 /// across a program.
353 virtual bool shouldRTTIBeUnique() const { return true; }
354
355public:
356 /// What sort of unique-RTTI behavior should we use?
357 enum RTTIUniquenessKind {
358 /// We are guaranteeing, or need to guarantee, that the RTTI string
359 /// is unique.
360 RUK_Unique,
361
362 /// We are not guaranteeing uniqueness for the RTTI string, so we
363 /// can demote to hidden visibility but must use string comparisons.
364 RUK_NonUniqueHidden,
365
366 /// We are not guaranteeing uniqueness for the RTTI string, so we
367 /// have to use string comparisons, but we also have to emit it with
368 /// non-hidden visibility.
369 RUK_NonUniqueVisible
370 };
371
372 /// Return the required visibility status for the given type and linkage in
373 /// the current ABI.
374 RTTIUniquenessKind
375 classifyRTTIUniqueness(QualType CanTy,
376 llvm::GlobalValue::LinkageTypes Linkage) const;
377 friend class ItaniumRTTIBuilder;
Rafael Espindola91f68b42014-09-15 19:20:10 +0000378
379 void emitCXXStructor(const CXXMethodDecl *MD, StructorType Type) override;
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000380
381 private:
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +0000382 bool hasAnyUnusedVirtualInlineFunction(const CXXRecordDecl *RD) const {
383 const auto &VtableLayout =
384 CGM.getItaniumVTableContext().getVTableLayout(RD);
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000385
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +0000386 for (const auto &VtableComponent : VtableLayout.vtable_components()) {
387 // Skip empty slot.
388 if (!VtableComponent.isUsedFunctionPointerKind())
389 continue;
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000390
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +0000391 const CXXMethodDecl *Method = VtableComponent.getFunctionDecl();
392 if (!Method->getCanonicalDecl()->isInlined())
393 continue;
394
395 StringRef Name = CGM.getMangledName(VtableComponent.getGlobalDecl());
396 auto *Entry = CGM.GetGlobalValue(Name);
397 // This checks if virtual inline function has already been emitted.
398 // Note that it is possible that this inline function would be emitted
399 // after trying to emit vtable speculatively. Because of this we do
400 // an extra pass after emitting all deferred vtables to find and emit
401 // these vtables opportunistically.
402 if (!Entry || Entry->isDeclaration())
403 return true;
404 }
405 return false;
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000406 }
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000407
408 bool isVTableHidden(const CXXRecordDecl *RD) const {
409 const auto &VtableLayout =
410 CGM.getItaniumVTableContext().getVTableLayout(RD);
411
412 for (const auto &VtableComponent : VtableLayout.vtable_components()) {
413 if (VtableComponent.isRTTIKind()) {
414 const CXXRecordDecl *RTTIDecl = VtableComponent.getRTTIDecl();
415 if (RTTIDecl->getVisibility() == Visibility::HiddenVisibility)
416 return true;
417 } else if (VtableComponent.isUsedFunctionPointerKind()) {
418 const CXXMethodDecl *Method = VtableComponent.getFunctionDecl();
419 if (Method->getVisibility() == Visibility::HiddenVisibility &&
420 !Method->isDefined())
421 return true;
422 }
423 }
424 return false;
425 }
Charles Davis4e786dd2010-05-25 19:52:27 +0000426};
John McCall86353412010-08-21 22:46:04 +0000427
428class ARMCXXABI : public ItaniumCXXABI {
429public:
Mark Seabornedf0d382013-07-24 16:25:13 +0000430 ARMCXXABI(CodeGen::CodeGenModule &CGM) :
431 ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
432 /* UseARMGuardVarABI = */ true) {}
John McCall5d865c322010-08-31 07:33:07 +0000433
Craig Topper4f12f102014-03-12 06:41:41 +0000434 bool HasThisReturn(GlobalDecl GD) const override {
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000435 return (isa<CXXConstructorDecl>(GD.getDecl()) || (
436 isa<CXXDestructorDecl>(GD.getDecl()) &&
437 GD.getDtorType() != Dtor_Deleting));
438 }
John McCall5d865c322010-08-31 07:33:07 +0000439
Craig Topper4f12f102014-03-12 06:41:41 +0000440 void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV,
441 QualType ResTy) override;
John McCall5d865c322010-08-31 07:33:07 +0000442
Craig Topper4f12f102014-03-12 06:41:41 +0000443 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
John McCall7f416cc2015-09-08 08:05:57 +0000444 Address InitializeArrayCookie(CodeGenFunction &CGF,
445 Address NewPtr,
446 llvm::Value *NumElements,
447 const CXXNewExpr *expr,
448 QualType ElementType) override;
449 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, Address allocPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000450 CharUnits cookieSize) override;
John McCall86353412010-08-21 22:46:04 +0000451};
Tim Northovera2ee4332014-03-29 15:09:45 +0000452
453class iOS64CXXABI : public ARMCXXABI {
454public:
John McCalld23b27e2016-09-16 02:40:45 +0000455 iOS64CXXABI(CodeGen::CodeGenModule &CGM) : ARMCXXABI(CGM) {
456 Use32BitVTableOffsetABI = true;
457 }
Tim Northover65f582f2014-03-30 17:32:48 +0000458
459 // ARM64 libraries are prepared for non-unique RTTI.
David Majnemere2cb8d12014-07-07 06:20:47 +0000460 bool shouldRTTIBeUnique() const override { return false; }
Tim Northovera2ee4332014-03-29 15:09:45 +0000461};
Dan Gohmanc2853072015-09-03 22:51:53 +0000462
463class WebAssemblyCXXABI final : public ItaniumCXXABI {
464public:
465 explicit WebAssemblyCXXABI(CodeGen::CodeGenModule &CGM)
466 : ItaniumCXXABI(CGM, /*UseARMMethodPtrABI=*/true,
467 /*UseARMGuardVarABI=*/true) {}
468
469private:
470 bool HasThisReturn(GlobalDecl GD) const override {
471 return isa<CXXConstructorDecl>(GD.getDecl()) ||
472 (isa<CXXDestructorDecl>(GD.getDecl()) &&
473 GD.getDtorType() != Dtor_Deleting);
474 }
Derek Schuff8179be42016-05-10 17:44:55 +0000475 bool canCallMismatchedFunctionType() const override { return false; }
Dan Gohmanc2853072015-09-03 22:51:53 +0000476};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000477}
Charles Davis4e786dd2010-05-25 19:52:27 +0000478
Charles Davis53c59df2010-08-16 03:33:14 +0000479CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
John McCallc8e01702013-04-16 22:48:15 +0000480 switch (CGM.getTarget().getCXXABI().getKind()) {
John McCall57625922013-01-25 23:36:14 +0000481 // For IR-generation purposes, there's no significant difference
482 // between the ARM and iOS ABIs.
483 case TargetCXXABI::GenericARM:
484 case TargetCXXABI::iOS:
Tim Northover756447a2015-10-30 16:30:36 +0000485 case TargetCXXABI::WatchOS:
John McCall57625922013-01-25 23:36:14 +0000486 return new ARMCXXABI(CGM);
Charles Davis4e786dd2010-05-25 19:52:27 +0000487
Tim Northovera2ee4332014-03-29 15:09:45 +0000488 case TargetCXXABI::iOS64:
489 return new iOS64CXXABI(CGM);
490
Tim Northover9bb857a2013-01-31 12:13:10 +0000491 // Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't
492 // include the other 32-bit ARM oddities: constructor/destructor return values
493 // and array cookies.
494 case TargetCXXABI::GenericAArch64:
Mark Seabornedf0d382013-07-24 16:25:13 +0000495 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
496 /* UseARMGuardVarABI = */ true);
Tim Northover9bb857a2013-01-31 12:13:10 +0000497
Zoran Jovanovic26a12162015-02-18 15:21:35 +0000498 case TargetCXXABI::GenericMIPS:
499 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true);
500
Dan Gohmanc2853072015-09-03 22:51:53 +0000501 case TargetCXXABI::WebAssembly:
502 return new WebAssemblyCXXABI(CGM);
503
John McCall57625922013-01-25 23:36:14 +0000504 case TargetCXXABI::GenericItanium:
Mark Seabornedf0d382013-07-24 16:25:13 +0000505 if (CGM.getContext().getTargetInfo().getTriple().getArch()
506 == llvm::Triple::le32) {
507 // For PNaCl, use ARM-style method pointers so that PNaCl code
508 // does not assume anything about the alignment of function
509 // pointers.
510 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
511 /* UseARMGuardVarABI = */ false);
512 }
John McCall57625922013-01-25 23:36:14 +0000513 return new ItaniumCXXABI(CGM);
514
515 case TargetCXXABI::Microsoft:
516 llvm_unreachable("Microsoft ABI is not Itanium-based");
517 }
518 llvm_unreachable("bad ABI kind");
John McCall86353412010-08-21 22:46:04 +0000519}
520
Chris Lattnera5f58b02011-07-09 17:41:47 +0000521llvm::Type *
John McCall7a9aac22010-08-23 01:21:21 +0000522ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
523 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000524 return CGM.PtrDiffTy;
Serge Guelton1d993272017-05-09 19:31:30 +0000525 return llvm::StructType::get(CGM.PtrDiffTy, CGM.PtrDiffTy);
John McCall1c456c82010-08-22 06:43:33 +0000526}
527
John McCalld9c6c0b2010-08-22 00:59:17 +0000528/// In the Itanium and ARM ABIs, method pointers have the form:
529/// struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
530///
531/// In the Itanium ABI:
532/// - method pointers are virtual if (memptr.ptr & 1) is nonzero
533/// - the this-adjustment is (memptr.adj)
534/// - the virtual offset is (memptr.ptr - 1)
535///
536/// In the ARM ABI:
537/// - method pointers are virtual if (memptr.adj & 1) is nonzero
538/// - the this-adjustment is (memptr.adj >> 1)
539/// - the virtual offset is (memptr.ptr)
540/// ARM uses 'adj' for the virtual flag because Thumb functions
541/// may be only single-byte aligned.
542///
543/// If the member is virtual, the adjusted 'this' pointer points
544/// to a vtable pointer from which the virtual offset is applied.
545///
546/// If the member is non-virtual, memptr.ptr is the address of
547/// the function to call.
John McCallb92ab1a2016-10-26 23:46:34 +0000548CGCallee ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(
John McCall7f416cc2015-09-08 08:05:57 +0000549 CodeGenFunction &CGF, const Expr *E, Address ThisAddr,
550 llvm::Value *&ThisPtrForCall,
David Majnemer2b0d66d2014-02-20 23:22:07 +0000551 llvm::Value *MemFnPtr, const MemberPointerType *MPT) {
John McCall475999d2010-08-22 00:05:51 +0000552 CGBuilderTy &Builder = CGF.Builder;
553
554 const FunctionProtoType *FPT =
555 MPT->getPointeeType()->getAs<FunctionProtoType>();
556 const CXXRecordDecl *RD =
557 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
558
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000559 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(
560 CGM.getTypes().arrangeCXXMethodType(RD, FPT, /*FD=*/nullptr));
John McCall475999d2010-08-22 00:05:51 +0000561
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000562 llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(CGM.PtrDiffTy, 1);
John McCall475999d2010-08-22 00:05:51 +0000563
John McCalld9c6c0b2010-08-22 00:59:17 +0000564 llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
565 llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
566 llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
567
John McCalla1dee5302010-08-22 10:59:02 +0000568 // Extract memptr.adj, which is in the second field.
569 llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
John McCalld9c6c0b2010-08-22 00:59:17 +0000570
571 // Compute the true adjustment.
572 llvm::Value *Adj = RawAdj;
Mark Seabornedf0d382013-07-24 16:25:13 +0000573 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000574 Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
John McCall475999d2010-08-22 00:05:51 +0000575
576 // Apply the adjustment and cast back to the original struct type
577 // for consistency.
John McCall7f416cc2015-09-08 08:05:57 +0000578 llvm::Value *This = ThisAddr.getPointer();
John McCalld9c6c0b2010-08-22 00:59:17 +0000579 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
580 Ptr = Builder.CreateInBoundsGEP(Ptr, Adj);
581 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
John McCall7f416cc2015-09-08 08:05:57 +0000582 ThisPtrForCall = This;
John McCall475999d2010-08-22 00:05:51 +0000583
584 // Load the function pointer.
John McCalla1dee5302010-08-22 10:59:02 +0000585 llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
John McCall475999d2010-08-22 00:05:51 +0000586
587 // If the LSB in the function pointer is 1, the function pointer points to
588 // a virtual function.
John McCalld9c6c0b2010-08-22 00:59:17 +0000589 llvm::Value *IsVirtual;
Mark Seabornedf0d382013-07-24 16:25:13 +0000590 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000591 IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
592 else
593 IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
594 IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
John McCall475999d2010-08-22 00:05:51 +0000595 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
596
597 // In the virtual path, the adjustment left 'This' pointing to the
598 // vtable of the correct base subobject. The "function pointer" is an
John McCalld9c6c0b2010-08-22 00:59:17 +0000599 // offset within the vtable (+1 for the virtual flag on non-ARM).
John McCall475999d2010-08-22 00:05:51 +0000600 CGF.EmitBlock(FnVirtual);
601
602 // Cast the adjusted this to a pointer to vtable pointer and load.
Chris Lattner2192fe52011-07-18 04:24:23 +0000603 llvm::Type *VTableTy = Builder.getInt8PtrTy();
John McCall7f416cc2015-09-08 08:05:57 +0000604 CharUnits VTablePtrAlign =
605 CGF.CGM.getDynamicOffsetAlignment(ThisAddr.getAlignment(), RD,
606 CGF.getPointerAlign());
607 llvm::Value *VTable =
Piotr Padlewski4b1ac722015-09-15 21:46:55 +0000608 CGF.GetVTablePtr(Address(This, VTablePtrAlign), VTableTy, RD);
John McCall475999d2010-08-22 00:05:51 +0000609
610 // Apply the offset.
John McCalld23b27e2016-09-16 02:40:45 +0000611 // On ARM64, to reserve extra space in virtual member function pointers,
612 // we only pay attention to the low 32 bits of the offset.
John McCalld9c6c0b2010-08-22 00:59:17 +0000613 llvm::Value *VTableOffset = FnAsInt;
Mark Seabornedf0d382013-07-24 16:25:13 +0000614 if (!UseARMMethodPtrABI)
615 VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
John McCalld23b27e2016-09-16 02:40:45 +0000616 if (Use32BitVTableOffsetABI) {
617 VTableOffset = Builder.CreateTrunc(VTableOffset, CGF.Int32Ty);
618 VTableOffset = Builder.CreateZExt(VTableOffset, CGM.PtrDiffTy);
619 }
John McCalld9c6c0b2010-08-22 00:59:17 +0000620 VTable = Builder.CreateGEP(VTable, VTableOffset);
John McCall475999d2010-08-22 00:05:51 +0000621
622 // Load the virtual function to call.
623 VTable = Builder.CreateBitCast(VTable, FTy->getPointerTo()->getPointerTo());
John McCall7f416cc2015-09-08 08:05:57 +0000624 llvm::Value *VirtualFn =
625 Builder.CreateAlignedLoad(VTable, CGF.getPointerAlign(),
626 "memptr.virtualfn");
John McCall475999d2010-08-22 00:05:51 +0000627 CGF.EmitBranch(FnEnd);
628
629 // In the non-virtual path, the function pointer is actually a
630 // function pointer.
631 CGF.EmitBlock(FnNonVirtual);
632 llvm::Value *NonVirtualFn =
John McCalld9c6c0b2010-08-22 00:59:17 +0000633 Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn");
John McCall475999d2010-08-22 00:05:51 +0000634
635 // We're done.
636 CGF.EmitBlock(FnEnd);
John McCallb92ab1a2016-10-26 23:46:34 +0000637 llvm::PHINode *CalleePtr = Builder.CreatePHI(FTy->getPointerTo(), 2);
638 CalleePtr->addIncoming(VirtualFn, FnVirtual);
639 CalleePtr->addIncoming(NonVirtualFn, FnNonVirtual);
640
641 CGCallee Callee(FPT, CalleePtr);
John McCall475999d2010-08-22 00:05:51 +0000642 return Callee;
643}
John McCalla8bbb822010-08-22 03:04:22 +0000644
John McCallc134eb52010-08-31 21:07:20 +0000645/// Compute an l-value by applying the given pointer-to-member to a
646/// base object.
David Majnemer2b0d66d2014-02-20 23:22:07 +0000647llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(
John McCall7f416cc2015-09-08 08:05:57 +0000648 CodeGenFunction &CGF, const Expr *E, Address Base, llvm::Value *MemPtr,
David Majnemer2b0d66d2014-02-20 23:22:07 +0000649 const MemberPointerType *MPT) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000650 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCallc134eb52010-08-31 21:07:20 +0000651
652 CGBuilderTy &Builder = CGF.Builder;
653
John McCallc134eb52010-08-31 21:07:20 +0000654 // Cast to char*.
John McCall7f416cc2015-09-08 08:05:57 +0000655 Base = Builder.CreateElementBitCast(Base, CGF.Int8Ty);
John McCallc134eb52010-08-31 21:07:20 +0000656
657 // Apply the offset, which we assume is non-null.
John McCall7f416cc2015-09-08 08:05:57 +0000658 llvm::Value *Addr =
659 Builder.CreateInBoundsGEP(Base.getPointer(), MemPtr, "memptr.offset");
John McCallc134eb52010-08-31 21:07:20 +0000660
661 // Cast the address to the appropriate pointer type, adopting the
662 // address space of the base pointer.
John McCall7f416cc2015-09-08 08:05:57 +0000663 llvm::Type *PType = CGF.ConvertTypeForMem(MPT->getPointeeType())
664 ->getPointerTo(Base.getAddressSpace());
John McCallc134eb52010-08-31 21:07:20 +0000665 return Builder.CreateBitCast(Addr, PType);
666}
667
John McCallc62bb392012-02-15 01:22:51 +0000668/// Perform a bitcast, derived-to-base, or base-to-derived member pointer
669/// conversion.
670///
671/// Bitcast conversions are always a no-op under Itanium.
John McCall7a9aac22010-08-23 01:21:21 +0000672///
673/// Obligatory offset/adjustment diagram:
674/// <-- offset --> <-- adjustment -->
675/// |--------------------------|----------------------|--------------------|
676/// ^Derived address point ^Base address point ^Member address point
677///
678/// So when converting a base member pointer to a derived member pointer,
679/// we add the offset to the adjustment because the address point has
680/// decreased; and conversely, when converting a derived MP to a base MP
681/// we subtract the offset from the adjustment because the address point
682/// has increased.
683///
684/// The standard forbids (at compile time) conversion to and from
685/// virtual bases, which is why we don't have to consider them here.
686///
687/// The standard forbids (at run time) casting a derived MP to a base
688/// MP when the derived MP does not point to a member of the base.
689/// This is why -1 is a reasonable choice for null data member
690/// pointers.
John McCalla1dee5302010-08-22 10:59:02 +0000691llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000692ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
693 const CastExpr *E,
John McCallc62bb392012-02-15 01:22:51 +0000694 llvm::Value *src) {
John McCalle3027922010-08-25 11:45:40 +0000695 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
John McCallc62bb392012-02-15 01:22:51 +0000696 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
697 E->getCastKind() == CK_ReinterpretMemberPointer);
698
699 // Under Itanium, reinterprets don't require any additional processing.
700 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
701
702 // Use constant emission if we can.
703 if (isa<llvm::Constant>(src))
704 return EmitMemberPointerConversion(E, cast<llvm::Constant>(src));
705
706 llvm::Constant *adj = getMemberPointerAdjustment(E);
707 if (!adj) return src;
John McCalla8bbb822010-08-22 03:04:22 +0000708
709 CGBuilderTy &Builder = CGF.Builder;
John McCallc62bb392012-02-15 01:22:51 +0000710 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
John McCalla8bbb822010-08-22 03:04:22 +0000711
John McCallc62bb392012-02-15 01:22:51 +0000712 const MemberPointerType *destTy =
713 E->getType()->castAs<MemberPointerType>();
John McCall1c456c82010-08-22 06:43:33 +0000714
John McCall7a9aac22010-08-23 01:21:21 +0000715 // For member data pointers, this is just a matter of adding the
716 // offset if the source is non-null.
John McCallc62bb392012-02-15 01:22:51 +0000717 if (destTy->isMemberDataPointer()) {
718 llvm::Value *dst;
719 if (isDerivedToBase)
720 dst = Builder.CreateNSWSub(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000721 else
John McCallc62bb392012-02-15 01:22:51 +0000722 dst = Builder.CreateNSWAdd(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000723
724 // Null check.
John McCallc62bb392012-02-15 01:22:51 +0000725 llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType());
726 llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull");
727 return Builder.CreateSelect(isNull, src, dst);
John McCall7a9aac22010-08-23 01:21:21 +0000728 }
729
John McCalla1dee5302010-08-22 10:59:02 +0000730 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000731 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000732 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
733 offset <<= 1;
734 adj = llvm::ConstantInt::get(adj->getType(), offset);
John McCalla1dee5302010-08-22 10:59:02 +0000735 }
736
John McCallc62bb392012-02-15 01:22:51 +0000737 llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj");
738 llvm::Value *dstAdj;
739 if (isDerivedToBase)
740 dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000741 else
John McCallc62bb392012-02-15 01:22:51 +0000742 dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000743
John McCallc62bb392012-02-15 01:22:51 +0000744 return Builder.CreateInsertValue(src, dstAdj, 1);
745}
746
747llvm::Constant *
748ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E,
749 llvm::Constant *src) {
750 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
751 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
752 E->getCastKind() == CK_ReinterpretMemberPointer);
753
754 // Under Itanium, reinterprets don't require any additional processing.
755 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
756
757 // If the adjustment is trivial, we don't need to do anything.
758 llvm::Constant *adj = getMemberPointerAdjustment(E);
759 if (!adj) return src;
760
761 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
762
763 const MemberPointerType *destTy =
764 E->getType()->castAs<MemberPointerType>();
765
766 // For member data pointers, this is just a matter of adding the
767 // offset if the source is non-null.
768 if (destTy->isMemberDataPointer()) {
769 // null maps to null.
770 if (src->isAllOnesValue()) return src;
771
772 if (isDerivedToBase)
773 return llvm::ConstantExpr::getNSWSub(src, adj);
774 else
775 return llvm::ConstantExpr::getNSWAdd(src, adj);
776 }
777
778 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000779 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000780 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
781 offset <<= 1;
782 adj = llvm::ConstantInt::get(adj->getType(), offset);
783 }
784
785 llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1);
786 llvm::Constant *dstAdj;
787 if (isDerivedToBase)
788 dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj);
789 else
790 dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj);
791
792 return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1);
John McCalla8bbb822010-08-22 03:04:22 +0000793}
John McCall84fa5102010-08-22 04:16:24 +0000794
795llvm::Constant *
John McCall7a9aac22010-08-23 01:21:21 +0000796ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
John McCall7a9aac22010-08-23 01:21:21 +0000797 // Itanium C++ ABI 2.3:
798 // A NULL pointer is represented as -1.
799 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000800 return llvm::ConstantInt::get(CGM.PtrDiffTy, -1ULL, /*isSigned=*/true);
John McCalla1dee5302010-08-22 10:59:02 +0000801
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000802 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.PtrDiffTy, 0);
John McCalla1dee5302010-08-22 10:59:02 +0000803 llvm::Constant *Values[2] = { Zero, Zero };
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000804 return llvm::ConstantStruct::getAnon(Values);
John McCall84fa5102010-08-22 04:16:24 +0000805}
806
John McCallf3a88602011-02-03 08:15:49 +0000807llvm::Constant *
808ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
809 CharUnits offset) {
John McCall7a9aac22010-08-23 01:21:21 +0000810 // Itanium C++ ABI 2.3:
811 // A pointer to data member is an offset from the base address of
812 // the class object containing it, represented as a ptrdiff_t
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000813 return llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity());
John McCall7a9aac22010-08-23 01:21:21 +0000814}
815
David Majnemere2be95b2015-06-23 07:31:01 +0000816llvm::Constant *
817ItaniumCXXABI::EmitMemberFunctionPointer(const CXXMethodDecl *MD) {
Richard Smithdafff942012-01-14 04:30:29 +0000818 return BuildMemberPointer(MD, CharUnits::Zero());
819}
820
821llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD,
822 CharUnits ThisAdjustment) {
John McCalla1dee5302010-08-22 10:59:02 +0000823 assert(MD->isInstance() && "Member function must not be static!");
824 MD = MD->getCanonicalDecl();
825
826 CodeGenTypes &Types = CGM.getTypes();
John McCalla1dee5302010-08-22 10:59:02 +0000827
828 // Get the function pointer (or index if this is a virtual function).
829 llvm::Constant *MemPtr[2];
830 if (MD->isVirtual()) {
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000831 uint64_t Index = CGM.getItaniumVTableContext().getMethodVTableIndex(MD);
John McCalla1dee5302010-08-22 10:59:02 +0000832
Ken Dyckdf016282011-04-09 01:30:02 +0000833 const ASTContext &Context = getContext();
834 CharUnits PointerWidth =
Douglas Gregore8bbc122011-09-02 00:18:52 +0000835 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Ken Dyckdf016282011-04-09 01:30:02 +0000836 uint64_t VTableOffset = (Index * PointerWidth.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000837
Mark Seabornedf0d382013-07-24 16:25:13 +0000838 if (UseARMMethodPtrABI) {
John McCalla1dee5302010-08-22 10:59:02 +0000839 // ARM C++ ABI 3.2.1:
840 // This ABI specifies that adj contains twice the this
841 // adjustment, plus 1 if the member function is virtual. The
842 // least significant bit of adj then makes exactly the same
843 // discrimination as the least significant bit of ptr does for
844 // Itanium.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000845 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset);
846 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000847 2 * ThisAdjustment.getQuantity() + 1);
John McCalla1dee5302010-08-22 10:59:02 +0000848 } else {
849 // Itanium C++ ABI 2.3:
850 // For a virtual function, [the pointer field] is 1 plus the
851 // virtual table offset (in bytes) of the function,
852 // represented as a ptrdiff_t.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000853 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset + 1);
854 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000855 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000856 }
857 } else {
John McCall2979fe02011-04-12 00:42:48 +0000858 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
Chris Lattner2192fe52011-07-18 04:24:23 +0000859 llvm::Type *Ty;
John McCall2979fe02011-04-12 00:42:48 +0000860 // Check whether the function has a computable LLVM signature.
Chris Lattner8806e322011-07-10 00:18:59 +0000861 if (Types.isFuncTypeConvertible(FPT)) {
John McCall2979fe02011-04-12 00:42:48 +0000862 // The function has a computable LLVM signature; use the correct type.
John McCalla729c622012-02-17 03:33:10 +0000863 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
John McCalla1dee5302010-08-22 10:59:02 +0000864 } else {
John McCall2979fe02011-04-12 00:42:48 +0000865 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
866 // function type is incomplete.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000867 Ty = CGM.PtrDiffTy;
John McCalla1dee5302010-08-22 10:59:02 +0000868 }
John McCall2979fe02011-04-12 00:42:48 +0000869 llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty);
John McCalla1dee5302010-08-22 10:59:02 +0000870
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000871 MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, CGM.PtrDiffTy);
Mark Seabornedf0d382013-07-24 16:25:13 +0000872 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
873 (UseARMMethodPtrABI ? 2 : 1) *
Richard Smithdafff942012-01-14 04:30:29 +0000874 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000875 }
John McCall1c456c82010-08-22 06:43:33 +0000876
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000877 return llvm::ConstantStruct::getAnon(MemPtr);
John McCall1c456c82010-08-22 06:43:33 +0000878}
879
Richard Smithdafff942012-01-14 04:30:29 +0000880llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP,
881 QualType MPType) {
882 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
883 const ValueDecl *MPD = MP.getMemberPointerDecl();
884 if (!MPD)
885 return EmitNullMemberPointer(MPT);
886
Reid Kleckner452abac2013-05-09 21:01:17 +0000887 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
Richard Smithdafff942012-01-14 04:30:29 +0000888
889 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
890 return BuildMemberPointer(MD, ThisAdjustment);
891
892 CharUnits FieldOffset =
893 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
894 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
895}
896
John McCall131d97d2010-08-22 08:30:07 +0000897/// The comparison algorithm is pretty easy: the member pointers are
898/// the same if they're either bitwise identical *or* both null.
899///
900/// ARM is different here only because null-ness is more complicated.
901llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000902ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
903 llvm::Value *L,
904 llvm::Value *R,
905 const MemberPointerType *MPT,
906 bool Inequality) {
John McCall131d97d2010-08-22 08:30:07 +0000907 CGBuilderTy &Builder = CGF.Builder;
908
John McCall131d97d2010-08-22 08:30:07 +0000909 llvm::ICmpInst::Predicate Eq;
910 llvm::Instruction::BinaryOps And, Or;
911 if (Inequality) {
912 Eq = llvm::ICmpInst::ICMP_NE;
913 And = llvm::Instruction::Or;
914 Or = llvm::Instruction::And;
915 } else {
916 Eq = llvm::ICmpInst::ICMP_EQ;
917 And = llvm::Instruction::And;
918 Or = llvm::Instruction::Or;
919 }
920
John McCall7a9aac22010-08-23 01:21:21 +0000921 // Member data pointers are easy because there's a unique null
922 // value, so it just comes down to bitwise equality.
923 if (MPT->isMemberDataPointer())
924 return Builder.CreateICmp(Eq, L, R);
925
926 // For member function pointers, the tautologies are more complex.
927 // The Itanium tautology is:
John McCall61a14882010-08-23 06:56:36 +0000928 // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
John McCall7a9aac22010-08-23 01:21:21 +0000929 // The ARM tautology is:
John McCall61a14882010-08-23 06:56:36 +0000930 // (L == R) <==> (L.ptr == R.ptr &&
931 // (L.adj == R.adj ||
932 // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
John McCall7a9aac22010-08-23 01:21:21 +0000933 // The inequality tautologies have exactly the same structure, except
934 // applying De Morgan's laws.
935
936 llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
937 llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
938
John McCall131d97d2010-08-22 08:30:07 +0000939 // This condition tests whether L.ptr == R.ptr. This must always be
940 // true for equality to hold.
941 llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
942
943 // This condition, together with the assumption that L.ptr == R.ptr,
944 // tests whether the pointers are both null. ARM imposes an extra
945 // condition.
946 llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
947 llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
948
949 // This condition tests whether L.adj == R.adj. If this isn't
950 // true, the pointers are unequal unless they're both null.
John McCalla1dee5302010-08-22 10:59:02 +0000951 llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
952 llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000953 llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
954
955 // Null member function pointers on ARM clear the low bit of Adj,
956 // so the zero condition has to check that neither low bit is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000957 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000958 llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
959
960 // Compute (l.adj | r.adj) & 1 and test it against zero.
961 llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
962 llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
963 llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
964 "cmp.or.adj");
965 EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
966 }
967
968 // Tie together all our conditions.
969 llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
970 Result = Builder.CreateBinOp(And, PtrEq, Result,
971 Inequality ? "memptr.ne" : "memptr.eq");
972 return Result;
973}
974
975llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000976ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
977 llvm::Value *MemPtr,
978 const MemberPointerType *MPT) {
John McCall131d97d2010-08-22 08:30:07 +0000979 CGBuilderTy &Builder = CGF.Builder;
John McCall7a9aac22010-08-23 01:21:21 +0000980
981 /// For member data pointers, this is just a check against -1.
982 if (MPT->isMemberDataPointer()) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000983 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCall7a9aac22010-08-23 01:21:21 +0000984 llvm::Value *NegativeOne =
985 llvm::Constant::getAllOnesValue(MemPtr->getType());
986 return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
987 }
John McCall131d97d2010-08-22 08:30:07 +0000988
Daniel Dunbar914bc412011-04-19 23:10:47 +0000989 // In Itanium, a member function pointer is not null if 'ptr' is not null.
John McCalla1dee5302010-08-22 10:59:02 +0000990 llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
John McCall131d97d2010-08-22 08:30:07 +0000991
992 llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
993 llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
994
Daniel Dunbar914bc412011-04-19 23:10:47 +0000995 // On ARM, a member function pointer is also non-null if the low bit of 'adj'
996 // (the virtual bit) is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000997 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000998 llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
John McCalla1dee5302010-08-22 10:59:02 +0000999 llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +00001000 llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
Daniel Dunbar914bc412011-04-19 23:10:47 +00001001 llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero,
1002 "memptr.isvirtual");
1003 Result = Builder.CreateOr(Result, IsVirtual);
John McCall131d97d2010-08-22 08:30:07 +00001004 }
1005
1006 return Result;
1007}
John McCall1c456c82010-08-22 06:43:33 +00001008
Reid Kleckner40ca9132014-05-13 22:05:45 +00001009bool ItaniumCXXABI::classifyReturnType(CGFunctionInfo &FI) const {
1010 const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl();
1011 if (!RD)
1012 return false;
1013
Richard Smith96cd6712017-08-16 01:49:53 +00001014 // If C++ prohibits us from making a copy, return by address.
1015 if (!canCopyArgument(RD)) {
John McCall7f416cc2015-09-08 08:05:57 +00001016 auto Align = CGM.getContext().getTypeAlignInChars(FI.getReturnType());
1017 FI.getReturnInfo() = ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
Reid Kleckner40ca9132014-05-13 22:05:45 +00001018 return true;
1019 }
Reid Kleckner40ca9132014-05-13 22:05:45 +00001020 return false;
1021}
1022
John McCall614dbdc2010-08-22 21:01:12 +00001023/// The Itanium ABI requires non-zero initialization only for data
1024/// member pointers, for which '0' is a valid offset.
1025bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
David Majnemer5fd33e02015-04-24 01:25:08 +00001026 return MPT->isMemberFunctionPointer();
John McCall84fa5102010-08-22 04:16:24 +00001027}
John McCall5d865c322010-08-31 07:33:07 +00001028
John McCall82fb8922012-09-25 10:10:39 +00001029/// The Itanium ABI always places an offset to the complete object
1030/// at entry -2 in the vtable.
David Majnemer08681372014-11-01 07:37:17 +00001031void ItaniumCXXABI::emitVirtualObjectDelete(CodeGenFunction &CGF,
1032 const CXXDeleteExpr *DE,
John McCall7f416cc2015-09-08 08:05:57 +00001033 Address Ptr,
David Majnemer08681372014-11-01 07:37:17 +00001034 QualType ElementType,
1035 const CXXDestructorDecl *Dtor) {
1036 bool UseGlobalDelete = DE->isGlobalDelete();
David Majnemer0c0b6d92014-10-31 20:09:12 +00001037 if (UseGlobalDelete) {
1038 // Derive the complete-object pointer, which is what we need
1039 // to pass to the deallocation function.
John McCall82fb8922012-09-25 10:10:39 +00001040
David Majnemer0c0b6d92014-10-31 20:09:12 +00001041 // Grab the vtable pointer as an intptr_t*.
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001042 auto *ClassDecl =
1043 cast<CXXRecordDecl>(ElementType->getAs<RecordType>()->getDecl());
1044 llvm::Value *VTable =
1045 CGF.GetVTablePtr(Ptr, CGF.IntPtrTy->getPointerTo(), ClassDecl);
John McCall82fb8922012-09-25 10:10:39 +00001046
David Majnemer0c0b6d92014-10-31 20:09:12 +00001047 // Track back to entry -2 and pull out the offset there.
1048 llvm::Value *OffsetPtr = CGF.Builder.CreateConstInBoundsGEP1_64(
1049 VTable, -2, "complete-offset.ptr");
John McCall7f416cc2015-09-08 08:05:57 +00001050 llvm::Value *Offset =
1051 CGF.Builder.CreateAlignedLoad(OffsetPtr, CGF.getPointerAlign());
David Majnemer0c0b6d92014-10-31 20:09:12 +00001052
1053 // Apply the offset.
John McCall7f416cc2015-09-08 08:05:57 +00001054 llvm::Value *CompletePtr =
1055 CGF.Builder.CreateBitCast(Ptr.getPointer(), CGF.Int8PtrTy);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001056 CompletePtr = CGF.Builder.CreateInBoundsGEP(CompletePtr, Offset);
1057
1058 // If we're supposed to call the global delete, make sure we do so
1059 // even if the destructor throws.
David Majnemer08681372014-11-01 07:37:17 +00001060 CGF.pushCallObjectDeleteCleanup(DE->getOperatorDelete(), CompletePtr,
1061 ElementType);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001062 }
1063
1064 // FIXME: Provide a source location here even though there's no
1065 // CXXMemberCallExpr for dtor call.
1066 CXXDtorType DtorType = UseGlobalDelete ? Dtor_Complete : Dtor_Deleting;
1067 EmitVirtualDestructorCall(CGF, Dtor, DtorType, Ptr, /*CE=*/nullptr);
1068
1069 if (UseGlobalDelete)
1070 CGF.PopCleanupBlock();
John McCall82fb8922012-09-25 10:10:39 +00001071}
1072
David Majnemer442d0a22014-11-25 07:20:20 +00001073void ItaniumCXXABI::emitRethrow(CodeGenFunction &CGF, bool isNoReturn) {
1074 // void __cxa_rethrow();
1075
1076 llvm::FunctionType *FTy =
1077 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
1078
1079 llvm::Constant *Fn = CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow");
1080
1081 if (isNoReturn)
1082 CGF.EmitNoreturnRuntimeCallOrInvoke(Fn, None);
1083 else
1084 CGF.EmitRuntimeCallOrInvoke(Fn);
1085}
1086
David Majnemer7c237072015-03-05 00:46:22 +00001087static llvm::Constant *getAllocateExceptionFn(CodeGenModule &CGM) {
1088 // void *__cxa_allocate_exception(size_t thrown_size);
1089
1090 llvm::FunctionType *FTy =
1091 llvm::FunctionType::get(CGM.Int8PtrTy, CGM.SizeTy, /*IsVarArgs=*/false);
1092
1093 return CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
1094}
1095
1096static llvm::Constant *getThrowFn(CodeGenModule &CGM) {
1097 // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
1098 // void (*dest) (void *));
1099
1100 llvm::Type *Args[3] = { CGM.Int8PtrTy, CGM.Int8PtrTy, CGM.Int8PtrTy };
1101 llvm::FunctionType *FTy =
1102 llvm::FunctionType::get(CGM.VoidTy, Args, /*IsVarArgs=*/false);
1103
1104 return CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
1105}
1106
1107void ItaniumCXXABI::emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) {
1108 QualType ThrowType = E->getSubExpr()->getType();
1109 // Now allocate the exception object.
1110 llvm::Type *SizeTy = CGF.ConvertType(getContext().getSizeType());
1111 uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
1112
1113 llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(CGM);
1114 llvm::CallInst *ExceptionPtr = CGF.EmitNounwindRuntimeCall(
1115 AllocExceptionFn, llvm::ConstantInt::get(SizeTy, TypeSize), "exception");
1116
John McCall7f416cc2015-09-08 08:05:57 +00001117 CharUnits ExnAlign = getAlignmentOfExnObject();
1118 CGF.EmitAnyExprToExn(E->getSubExpr(), Address(ExceptionPtr, ExnAlign));
David Majnemer7c237072015-03-05 00:46:22 +00001119
1120 // Now throw the exception.
1121 llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType,
1122 /*ForEH=*/true);
1123
1124 // The address of the destructor. If the exception type has a
1125 // trivial destructor (or isn't a record), we just pass null.
1126 llvm::Constant *Dtor = nullptr;
1127 if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
1128 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
1129 if (!Record->hasTrivialDestructor()) {
1130 CXXDestructorDecl *DtorD = Record->getDestructor();
1131 Dtor = CGM.getAddrOfCXXStructor(DtorD, StructorType::Complete);
1132 Dtor = llvm::ConstantExpr::getBitCast(Dtor, CGM.Int8PtrTy);
1133 }
1134 }
1135 if (!Dtor) Dtor = llvm::Constant::getNullValue(CGM.Int8PtrTy);
1136
1137 llvm::Value *args[] = { ExceptionPtr, TypeInfo, Dtor };
1138 CGF.EmitNoreturnRuntimeCallOrInvoke(getThrowFn(CGM), args);
1139}
1140
David Majnemer1162d252014-06-22 19:05:33 +00001141static llvm::Constant *getItaniumDynamicCastFn(CodeGenFunction &CGF) {
1142 // void *__dynamic_cast(const void *sub,
1143 // const abi::__class_type_info *src,
1144 // const abi::__class_type_info *dst,
1145 // std::ptrdiff_t src2dst_offset);
1146
1147 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
1148 llvm::Type *PtrDiffTy =
1149 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1150
1151 llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
1152
1153 llvm::FunctionType *FTy = llvm::FunctionType::get(Int8PtrTy, Args, false);
1154
1155 // Mark the function as nounwind readonly.
1156 llvm::Attribute::AttrKind FuncAttrs[] = { llvm::Attribute::NoUnwind,
1157 llvm::Attribute::ReadOnly };
Reid Klecknerde864822017-03-21 16:57:30 +00001158 llvm::AttributeList Attrs = llvm::AttributeList::get(
1159 CGF.getLLVMContext(), llvm::AttributeList::FunctionIndex, FuncAttrs);
David Majnemer1162d252014-06-22 19:05:33 +00001160
1161 return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast", Attrs);
1162}
1163
1164static llvm::Constant *getBadCastFn(CodeGenFunction &CGF) {
1165 // void __cxa_bad_cast();
1166 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1167 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
1168}
1169
1170/// \brief Compute the src2dst_offset hint as described in the
1171/// Itanium C++ ABI [2.9.7]
1172static CharUnits computeOffsetHint(ASTContext &Context,
1173 const CXXRecordDecl *Src,
1174 const CXXRecordDecl *Dst) {
1175 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1176 /*DetectVirtual=*/false);
1177
1178 // If Dst is not derived from Src we can skip the whole computation below and
1179 // return that Src is not a public base of Dst. Record all inheritance paths.
1180 if (!Dst->isDerivedFrom(Src, Paths))
1181 return CharUnits::fromQuantity(-2ULL);
1182
1183 unsigned NumPublicPaths = 0;
1184 CharUnits Offset;
1185
1186 // Now walk all possible inheritance paths.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001187 for (const CXXBasePath &Path : Paths) {
1188 if (Path.Access != AS_public) // Ignore non-public inheritance.
David Majnemer1162d252014-06-22 19:05:33 +00001189 continue;
1190
1191 ++NumPublicPaths;
1192
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001193 for (const CXXBasePathElement &PathElement : Path) {
David Majnemer1162d252014-06-22 19:05:33 +00001194 // If the path contains a virtual base class we can't give any hint.
1195 // -1: no hint.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001196 if (PathElement.Base->isVirtual())
David Majnemer1162d252014-06-22 19:05:33 +00001197 return CharUnits::fromQuantity(-1ULL);
1198
1199 if (NumPublicPaths > 1) // Won't use offsets, skip computation.
1200 continue;
1201
1202 // Accumulate the base class offsets.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001203 const ASTRecordLayout &L = Context.getASTRecordLayout(PathElement.Class);
1204 Offset += L.getBaseClassOffset(
1205 PathElement.Base->getType()->getAsCXXRecordDecl());
David Majnemer1162d252014-06-22 19:05:33 +00001206 }
1207 }
1208
1209 // -2: Src is not a public base of Dst.
1210 if (NumPublicPaths == 0)
1211 return CharUnits::fromQuantity(-2ULL);
1212
1213 // -3: Src is a multiple public base type but never a virtual base type.
1214 if (NumPublicPaths > 1)
1215 return CharUnits::fromQuantity(-3ULL);
1216
1217 // Otherwise, the Src type is a unique public nonvirtual base type of Dst.
1218 // Return the offset of Src from the origin of Dst.
1219 return Offset;
1220}
1221
1222static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) {
1223 // void __cxa_bad_typeid();
1224 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1225
1226 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
1227}
1228
1229bool ItaniumCXXABI::shouldTypeidBeNullChecked(bool IsDeref,
1230 QualType SrcRecordTy) {
1231 return IsDeref;
1232}
1233
1234void ItaniumCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) {
1235 llvm::Value *Fn = getBadTypeidFn(CGF);
1236 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
1237 CGF.Builder.CreateUnreachable();
1238}
1239
1240llvm::Value *ItaniumCXXABI::EmitTypeid(CodeGenFunction &CGF,
1241 QualType SrcRecordTy,
John McCall7f416cc2015-09-08 08:05:57 +00001242 Address ThisPtr,
David Majnemer1162d252014-06-22 19:05:33 +00001243 llvm::Type *StdTypeInfoPtrTy) {
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001244 auto *ClassDecl =
1245 cast<CXXRecordDecl>(SrcRecordTy->getAs<RecordType>()->getDecl());
David Majnemer1162d252014-06-22 19:05:33 +00001246 llvm::Value *Value =
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001247 CGF.GetVTablePtr(ThisPtr, StdTypeInfoPtrTy->getPointerTo(), ClassDecl);
David Majnemer1162d252014-06-22 19:05:33 +00001248
1249 // Load the type info.
1250 Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL);
John McCall7f416cc2015-09-08 08:05:57 +00001251 return CGF.Builder.CreateAlignedLoad(Value, CGF.getPointerAlign());
David Majnemer1162d252014-06-22 19:05:33 +00001252}
1253
1254bool ItaniumCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
1255 QualType SrcRecordTy) {
1256 return SrcIsPtr;
1257}
1258
1259llvm::Value *ItaniumCXXABI::EmitDynamicCastCall(
John McCall7f416cc2015-09-08 08:05:57 +00001260 CodeGenFunction &CGF, Address ThisAddr, QualType SrcRecordTy,
David Majnemer1162d252014-06-22 19:05:33 +00001261 QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) {
1262 llvm::Type *PtrDiffLTy =
1263 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1264 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1265
1266 llvm::Value *SrcRTTI =
1267 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
1268 llvm::Value *DestRTTI =
1269 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
1270
1271 // Compute the offset hint.
1272 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
1273 const CXXRecordDecl *DestDecl = DestRecordTy->getAsCXXRecordDecl();
1274 llvm::Value *OffsetHint = llvm::ConstantInt::get(
1275 PtrDiffLTy,
1276 computeOffsetHint(CGF.getContext(), SrcDecl, DestDecl).getQuantity());
1277
1278 // Emit the call to __dynamic_cast.
John McCall7f416cc2015-09-08 08:05:57 +00001279 llvm::Value *Value = ThisAddr.getPointer();
David Majnemer1162d252014-06-22 19:05:33 +00001280 Value = CGF.EmitCastToVoidPtr(Value);
1281
1282 llvm::Value *args[] = {Value, SrcRTTI, DestRTTI, OffsetHint};
1283 Value = CGF.EmitNounwindRuntimeCall(getItaniumDynamicCastFn(CGF), args);
1284 Value = CGF.Builder.CreateBitCast(Value, DestLTy);
1285
1286 /// C++ [expr.dynamic.cast]p9:
1287 /// A failed cast to reference type throws std::bad_cast
1288 if (DestTy->isReferenceType()) {
1289 llvm::BasicBlock *BadCastBlock =
1290 CGF.createBasicBlock("dynamic_cast.bad_cast");
1291
1292 llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
1293 CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
1294
1295 CGF.EmitBlock(BadCastBlock);
1296 EmitBadCastCall(CGF);
1297 }
1298
1299 return Value;
1300}
1301
1302llvm::Value *ItaniumCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001303 Address ThisAddr,
David Majnemer1162d252014-06-22 19:05:33 +00001304 QualType SrcRecordTy,
1305 QualType DestTy) {
1306 llvm::Type *PtrDiffLTy =
1307 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1308 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1309
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001310 auto *ClassDecl =
1311 cast<CXXRecordDecl>(SrcRecordTy->getAs<RecordType>()->getDecl());
David Majnemer1162d252014-06-22 19:05:33 +00001312 // Get the vtable pointer.
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001313 llvm::Value *VTable = CGF.GetVTablePtr(ThisAddr, PtrDiffLTy->getPointerTo(),
1314 ClassDecl);
David Majnemer1162d252014-06-22 19:05:33 +00001315
1316 // Get the offset-to-top from the vtable.
1317 llvm::Value *OffsetToTop =
1318 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL);
John McCall7f416cc2015-09-08 08:05:57 +00001319 OffsetToTop =
1320 CGF.Builder.CreateAlignedLoad(OffsetToTop, CGF.getPointerAlign(),
1321 "offset.to.top");
David Majnemer1162d252014-06-22 19:05:33 +00001322
1323 // Finally, add the offset to the pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001324 llvm::Value *Value = ThisAddr.getPointer();
David Majnemer1162d252014-06-22 19:05:33 +00001325 Value = CGF.EmitCastToVoidPtr(Value);
1326 Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop);
1327
1328 return CGF.Builder.CreateBitCast(Value, DestLTy);
1329}
1330
1331bool ItaniumCXXABI::EmitBadCastCall(CodeGenFunction &CGF) {
1332 llvm::Value *Fn = getBadCastFn(CGF);
1333 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
1334 CGF.Builder.CreateUnreachable();
1335 return true;
1336}
1337
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001338llvm::Value *
1339ItaniumCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001340 Address This,
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001341 const CXXRecordDecl *ClassDecl,
1342 const CXXRecordDecl *BaseClassDecl) {
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001343 llvm::Value *VTablePtr = CGF.GetVTablePtr(This, CGM.Int8PtrTy, ClassDecl);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001344 CharUnits VBaseOffsetOffset =
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001345 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(ClassDecl,
1346 BaseClassDecl);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001347
1348 llvm::Value *VBaseOffsetPtr =
1349 CGF.Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
1350 "vbase.offset.ptr");
1351 VBaseOffsetPtr = CGF.Builder.CreateBitCast(VBaseOffsetPtr,
1352 CGM.PtrDiffTy->getPointerTo());
1353
1354 llvm::Value *VBaseOffset =
John McCall7f416cc2015-09-08 08:05:57 +00001355 CGF.Builder.CreateAlignedLoad(VBaseOffsetPtr, CGF.getPointerAlign(),
1356 "vbase.offset");
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001357
1358 return VBaseOffset;
1359}
1360
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001361void ItaniumCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
1362 // Just make sure we're in sync with TargetCXXABI.
1363 assert(CGM.getTarget().getCXXABI().hasConstructorVariants());
1364
Rafael Espindolac3cde362013-12-09 14:51:17 +00001365 // The constructor used for constructing this as a base class;
1366 // ignores virtual bases.
1367 CGM.EmitGlobal(GlobalDecl(D, Ctor_Base));
1368
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001369 // The constructor used for constructing this as a complete class;
Nico Weber4c2ffb22015-01-07 05:25:05 +00001370 // constructs the virtual bases, then calls the base constructor.
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001371 if (!D->getParent()->isAbstract()) {
1372 // We don't need to emit the complete ctor if the class is abstract.
1373 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
1374 }
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001375}
1376
George Burgess IVf203dbf2017-02-22 20:28:02 +00001377CGCXXABI::AddedStructorArgs
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001378ItaniumCXXABI::buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
1379 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9bca9232010-09-02 10:25:57 +00001380 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001381
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001382 // All parameters are already in place except VTT, which goes after 'this'.
1383 // These are Clang types, so we don't need to worry about sret yet.
John McCall5d865c322010-08-31 07:33:07 +00001384
1385 // Check if we need to add a VTT parameter (which has type void **).
George Burgess IVf203dbf2017-02-22 20:28:02 +00001386 if (T == StructorType::Base && MD->getParent()->getNumVBases() != 0) {
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001387 ArgTys.insert(ArgTys.begin() + 1,
1388 Context.getPointerType(Context.VoidPtrTy));
George Burgess IVf203dbf2017-02-22 20:28:02 +00001389 return AddedStructorArgs::prefix(1);
1390 }
1391 return AddedStructorArgs{};
John McCall5d865c322010-08-31 07:33:07 +00001392}
1393
Reid Klecknere7de47e2013-07-22 13:51:44 +00001394void ItaniumCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
Rafael Espindolac3cde362013-12-09 14:51:17 +00001395 // The destructor used for destructing this as a base class; ignores
1396 // virtual bases.
1397 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001398
1399 // The destructor used for destructing this as a most-derived class;
1400 // call the base destructor and then destructs any virtual bases.
1401 CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));
1402
Rafael Espindolac3cde362013-12-09 14:51:17 +00001403 // The destructor in a virtual table is always a 'deleting'
1404 // destructor, which calls the complete destructor and then uses the
1405 // appropriate operator delete.
1406 if (D->isVirtual())
1407 CGM.EmitGlobal(GlobalDecl(D, Dtor_Deleting));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001408}
1409
Reid Kleckner89077a12013-12-17 19:46:40 +00001410void ItaniumCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
1411 QualType &ResTy,
1412 FunctionArgList &Params) {
John McCall5d865c322010-08-31 07:33:07 +00001413 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
Reid Kleckner89077a12013-12-17 19:46:40 +00001414 assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
John McCall5d865c322010-08-31 07:33:07 +00001415
1416 // Check if we need a VTT parameter as well.
Peter Collingbourne66f82e62013-06-28 20:45:28 +00001417 if (NeedsVTTParameter(CGF.CurGD)) {
John McCall9bca9232010-09-02 10:25:57 +00001418 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001419
1420 // FIXME: avoid the fake decl
1421 QualType T = Context.getPointerType(Context.VoidPtrTy);
Alexey Bataev56223232017-06-09 13:40:18 +00001422 auto *VTTDecl = ImplicitParamDecl::Create(
1423 Context, /*DC=*/nullptr, MD->getLocation(), &Context.Idents.get("vtt"),
1424 T, ImplicitParamDecl::CXXVTT);
Reid Kleckner89077a12013-12-17 19:46:40 +00001425 Params.insert(Params.begin() + 1, VTTDecl);
Reid Kleckner2af6d732013-12-13 00:09:59 +00001426 getStructorImplicitParamDecl(CGF) = VTTDecl;
John McCall5d865c322010-08-31 07:33:07 +00001427 }
1428}
1429
John McCall5d865c322010-08-31 07:33:07 +00001430void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
Justin Lebared4f1722016-07-27 22:04:24 +00001431 // Naked functions have no prolog.
1432 if (CGF.CurFuncDecl && CGF.CurFuncDecl->hasAttr<NakedAttr>())
1433 return;
1434
John McCall5d865c322010-08-31 07:33:07 +00001435 /// Initialize the 'this' slot.
1436 EmitThisParam(CGF);
1437
1438 /// Initialize the 'vtt' slot if needed.
Reid Kleckner2af6d732013-12-13 00:09:59 +00001439 if (getStructorImplicitParamDecl(CGF)) {
1440 getStructorImplicitParamValue(CGF) = CGF.Builder.CreateLoad(
1441 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), "vtt");
John McCall5d865c322010-08-31 07:33:07 +00001442 }
John McCall5d865c322010-08-31 07:33:07 +00001443
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001444 /// If this is a function that the ABI specifies returns 'this', initialize
1445 /// the return slot to 'this' at the start of the function.
1446 ///
1447 /// Unlike the setting of return types, this is done within the ABI
1448 /// implementation instead of by clients of CGCXXABI because:
1449 /// 1) getThisValue is currently protected
1450 /// 2) in theory, an ABI could implement 'this' returns some other way;
1451 /// HasThisReturn only specifies a contract, not the implementation
John McCall5d865c322010-08-31 07:33:07 +00001452 if (HasThisReturn(CGF.CurGD))
Eli Friedman9fbeba02012-02-11 02:57:39 +00001453 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
John McCall5d865c322010-08-31 07:33:07 +00001454}
1455
George Burgess IVf203dbf2017-02-22 20:28:02 +00001456CGCXXABI::AddedStructorArgs ItaniumCXXABI::addImplicitConstructorArgs(
Reid Kleckner89077a12013-12-17 19:46:40 +00001457 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
1458 bool ForVirtualBase, bool Delegating, CallArgList &Args) {
1459 if (!NeedsVTTParameter(GlobalDecl(D, Type)))
George Burgess IVf203dbf2017-02-22 20:28:02 +00001460 return AddedStructorArgs{};
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001461
Reid Kleckner89077a12013-12-17 19:46:40 +00001462 // Insert the implicit 'vtt' argument as the second argument.
1463 llvm::Value *VTT =
1464 CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase, Delegating);
1465 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1466 Args.insert(Args.begin() + 1,
1467 CallArg(RValue::get(VTT), VTTTy, /*needscopy=*/false));
George Burgess IVf203dbf2017-02-22 20:28:02 +00001468 return AddedStructorArgs::prefix(1); // Added one arg.
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001469}
1470
1471void ItaniumCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
1472 const CXXDestructorDecl *DD,
1473 CXXDtorType Type, bool ForVirtualBase,
John McCall7f416cc2015-09-08 08:05:57 +00001474 bool Delegating, Address This) {
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001475 GlobalDecl GD(DD, Type);
1476 llvm::Value *VTT = CGF.GetVTTParameter(GD, ForVirtualBase, Delegating);
1477 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1478
John McCallb92ab1a2016-10-26 23:46:34 +00001479 CGCallee Callee;
1480 if (getContext().getLangOpts().AppleKext &&
1481 Type != Dtor_Base && DD->isVirtual())
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001482 Callee = CGF.BuildAppleKextVirtualDestructorCall(DD, Type, DD->getParent());
John McCallb92ab1a2016-10-26 23:46:34 +00001483 else
1484 Callee =
1485 CGCallee::forDirect(CGM.getAddrOfCXXStructor(DD, getFromDtorType(Type)),
1486 DD);
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001487
John McCall7f416cc2015-09-08 08:05:57 +00001488 CGF.EmitCXXMemberOrOperatorCall(DD, Callee, ReturnValueSlot(),
Richard Smith762672a2016-09-28 19:09:10 +00001489 This.getPointer(), VTT, VTTTy,
1490 nullptr, nullptr);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001491}
1492
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001493void ItaniumCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
1494 const CXXRecordDecl *RD) {
1495 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, CharUnits());
1496 if (VTable->hasInitializer())
1497 return;
1498
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001499 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001500 const VTableLayout &VTLayout = VTContext.getVTableLayout(RD);
1501 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
David Majnemerd905da42014-07-01 20:30:31 +00001502 llvm::Constant *RTTI =
1503 CGM.GetAddrOfRTTIDescriptor(CGM.getContext().getTagDeclType(RD));
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001504
1505 // Create and set the initializer.
John McCall9c6cb762016-11-28 22:18:33 +00001506 ConstantInitBuilder Builder(CGM);
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001507 auto Components = Builder.beginStruct();
John McCall9c6cb762016-11-28 22:18:33 +00001508 CGVT.createVTableInitializer(Components, VTLayout, RTTI);
1509 Components.finishAndSetAsInitializer(VTable);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001510
1511 // Set the correct linkage.
1512 VTable->setLinkage(Linkage);
1513
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00001514 if (CGM.supportsCOMDAT() && VTable->isWeakForLinker())
1515 VTable->setComdat(CGM.getModule().getOrInsertComdat(VTable->getName()));
Rafael Espindolacb92c192015-01-15 23:18:01 +00001516
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001517 // Set the right visibility.
John McCall8f80a612014-02-08 00:41:16 +00001518 CGM.setGlobalVisibility(VTable, RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001519
Benjamin Kramer5d34a2b2014-09-10 12:50:59 +00001520 // Use pointer alignment for the vtable. Otherwise we would align them based
1521 // on the size of the initializer which doesn't make sense as only single
1522 // values are read.
1523 unsigned PAlign = CGM.getTarget().getPointerAlign(0);
1524 VTable->setAlignment(getContext().toCharUnitsFromBits(PAlign).getQuantity());
1525
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001526 // If this is the magic class __cxxabiv1::__fundamental_type_info,
1527 // we will emit the typeinfo for the fundamental types. This is the
1528 // same behaviour as GCC.
1529 const DeclContext *DC = RD->getDeclContext();
1530 if (RD->getIdentifier() &&
1531 RD->getIdentifier()->isStr("__fundamental_type_info") &&
1532 isa<NamespaceDecl>(DC) && cast<NamespaceDecl>(DC)->getIdentifier() &&
1533 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
1534 DC->getParent()->isTranslationUnit())
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00001535 EmitFundamentalRTTIDescriptors(RD->hasAttr<DLLExportAttr>());
Peter Collingbournea4ccff32015-02-20 20:30:56 +00001536
Evgeniy Stepanov93987df2016-01-23 01:20:18 +00001537 if (!VTable->isDeclarationForLinker())
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00001538 CGM.EmitVTableTypeMetadata(VTable, VTLayout);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001539}
1540
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001541bool ItaniumCXXABI::isVirtualOffsetNeededForVTableField(
1542 CodeGenFunction &CGF, CodeGenFunction::VPtr Vptr) {
1543 if (Vptr.NearestVBase == nullptr)
1544 return false;
1545 return NeedsVTTParameter(CGF.CurGD);
Piotr Padlewski255652e2015-09-09 22:20:28 +00001546}
1547
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001548llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructor(
1549 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1550 const CXXRecordDecl *NearestVBase) {
1551
1552 if ((Base.getBase()->getNumVBases() || NearestVBase != nullptr) &&
1553 NeedsVTTParameter(CGF.CurGD)) {
1554 return getVTableAddressPointInStructorWithVTT(CGF, VTableClass, Base,
1555 NearestVBase);
1556 }
1557 return getVTableAddressPoint(Base, VTableClass);
1558}
1559
1560llvm::Constant *
1561ItaniumCXXABI::getVTableAddressPoint(BaseSubobject Base,
1562 const CXXRecordDecl *VTableClass) {
1563 llvm::GlobalValue *VTable = getAddrOfVTable(VTableClass, CharUnits());
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001564
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001565 // Find the appropriate vtable within the vtable group, and the address point
1566 // within that vtable.
1567 VTableLayout::AddressPointLocation AddressPoint =
1568 CGM.getItaniumVTableContext()
1569 .getVTableLayout(VTableClass)
1570 .getAddressPoint(Base);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001571 llvm::Value *Indices[] = {
Peter Collingbourne4e6a5402016-03-14 19:07:10 +00001572 llvm::ConstantInt::get(CGM.Int32Ty, 0),
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001573 llvm::ConstantInt::get(CGM.Int32Ty, AddressPoint.VTableIndex),
1574 llvm::ConstantInt::get(CGM.Int32Ty, AddressPoint.AddressPointIndex),
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001575 };
1576
Peter Collingbourne25a2b702016-12-13 20:50:44 +00001577 return llvm::ConstantExpr::getGetElementPtr(VTable->getValueType(), VTable,
1578 Indices, /*InBounds=*/true,
1579 /*InRangeIndex=*/1);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001580}
1581
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001582llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructorWithVTT(
1583 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1584 const CXXRecordDecl *NearestVBase) {
1585 assert((Base.getBase()->getNumVBases() || NearestVBase != nullptr) &&
1586 NeedsVTTParameter(CGF.CurGD) && "This class doesn't have VTT");
1587
1588 // Get the secondary vpointer index.
1589 uint64_t VirtualPointerIndex =
1590 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1591
1592 /// Load the VTT.
1593 llvm::Value *VTT = CGF.LoadCXXVTT();
1594 if (VirtualPointerIndex)
1595 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1596
1597 // And load the address point from the VTT.
1598 return CGF.Builder.CreateAlignedLoad(VTT, CGF.getPointerAlign());
1599}
1600
1601llvm::Constant *ItaniumCXXABI::getVTableAddressPointForConstExpr(
1602 BaseSubobject Base, const CXXRecordDecl *VTableClass) {
1603 return getVTableAddressPoint(Base, VTableClass);
1604}
1605
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001606llvm::GlobalVariable *ItaniumCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
1607 CharUnits VPtrOffset) {
1608 assert(VPtrOffset.isZero() && "Itanium ABI only supports zero vptr offsets");
1609
1610 llvm::GlobalVariable *&VTable = VTables[RD];
1611 if (VTable)
1612 return VTable;
1613
Eric Christopherd160c502016-01-29 01:35:53 +00001614 // Queue up this vtable for possible deferred emission.
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001615 CGM.addDeferredVTable(RD);
1616
Yaron Kerene46f7ed2015-07-29 14:21:47 +00001617 SmallString<256> Name;
1618 llvm::raw_svector_ostream Out(Name);
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00001619 getMangleContext().mangleCXXVTable(RD, Out);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001620
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001621 const VTableLayout &VTLayout =
1622 CGM.getItaniumVTableContext().getVTableLayout(RD);
1623 llvm::Type *VTableType = CGM.getVTables().getVTableType(VTLayout);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001624
1625 VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001626 Name, VTableType, llvm::GlobalValue::ExternalLinkage);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00001627 VTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Hans Wennborgda24e9c2014-06-02 23:13:03 +00001628
1629 if (RD->hasAttr<DLLImportAttr>())
1630 VTable->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1631 else if (RD->hasAttr<DLLExportAttr>())
1632 VTable->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1633
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001634 return VTable;
1635}
1636
John McCallb92ab1a2016-10-26 23:46:34 +00001637CGCallee ItaniumCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
1638 GlobalDecl GD,
1639 Address This,
1640 llvm::Type *Ty,
1641 SourceLocation Loc) {
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001642 GD = GD.getCanonicalDecl();
1643 Ty = Ty->getPointerTo()->getPointerTo();
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001644 auto *MethodDecl = cast<CXXMethodDecl>(GD.getDecl());
1645 llvm::Value *VTable = CGF.GetVTablePtr(This, Ty, MethodDecl->getParent());
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001646
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001647 uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
John McCallb92ab1a2016-10-26 23:46:34 +00001648 llvm::Value *VFunc;
Peter Collingbourne0ca03632016-06-25 00:24:06 +00001649 if (CGF.ShouldEmitVTableTypeCheckedLoad(MethodDecl->getParent())) {
John McCallb92ab1a2016-10-26 23:46:34 +00001650 VFunc = CGF.EmitVTableTypeCheckedLoad(
Peter Collingbourne0ca03632016-06-25 00:24:06 +00001651 MethodDecl->getParent(), VTable,
1652 VTableIndex * CGM.getContext().getTargetInfo().getPointerWidth(0) / 8);
1653 } else {
1654 CGF.EmitTypeMetadataCodeForVCall(MethodDecl->getParent(), VTable, Loc);
1655
1656 llvm::Value *VFuncPtr =
1657 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfn");
Piotr Padlewski77cc9622016-10-29 15:28:30 +00001658 auto *VFuncLoad =
1659 CGF.Builder.CreateAlignedLoad(VFuncPtr, CGF.getPointerAlign());
1660
1661 // Add !invariant.load md to virtual function load to indicate that
1662 // function didn't change inside vtable.
1663 // It's safe to add it without -fstrict-vtable-pointers, but it would not
1664 // help in devirtualization because it will only matter if we will have 2
1665 // the same virtual function loads from the same vtable load, which won't
1666 // happen without enabled devirtualization with -fstrict-vtable-pointers.
1667 if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1668 CGM.getCodeGenOpts().StrictVTablePointers)
1669 VFuncLoad->setMetadata(
1670 llvm::LLVMContext::MD_invariant_load,
1671 llvm::MDNode::get(CGM.getLLVMContext(),
1672 llvm::ArrayRef<llvm::Metadata *>()));
1673 VFunc = VFuncLoad;
Peter Collingbourne0ca03632016-06-25 00:24:06 +00001674 }
John McCallb92ab1a2016-10-26 23:46:34 +00001675
1676 CGCallee Callee(MethodDecl, VFunc);
1677 return Callee;
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001678}
1679
David Majnemer0c0b6d92014-10-31 20:09:12 +00001680llvm::Value *ItaniumCXXABI::EmitVirtualDestructorCall(
1681 CodeGenFunction &CGF, const CXXDestructorDecl *Dtor, CXXDtorType DtorType,
John McCall7f416cc2015-09-08 08:05:57 +00001682 Address This, const CXXMemberCallExpr *CE) {
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001683 assert(CE == nullptr || CE->arg_begin() == CE->arg_end());
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001684 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
1685
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001686 const CGFunctionInfo *FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
1687 Dtor, getFromDtorType(DtorType));
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001688 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
John McCallb92ab1a2016-10-26 23:46:34 +00001689 CGCallee Callee =
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00001690 getVirtualFunctionPointer(CGF, GlobalDecl(Dtor, DtorType), This, Ty,
1691 CE ? CE->getLocStart() : SourceLocation());
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001692
John McCall7f416cc2015-09-08 08:05:57 +00001693 CGF.EmitCXXMemberOrOperatorCall(Dtor, Callee, ReturnValueSlot(),
1694 This.getPointer(), /*ImplicitParam=*/nullptr,
Richard Smith762672a2016-09-28 19:09:10 +00001695 QualType(), CE, nullptr);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001696 return nullptr;
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001697}
1698
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001699void ItaniumCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
Reid Kleckner7810af02013-06-19 15:20:38 +00001700 CodeGenVTables &VTables = CGM.getVTables();
1701 llvm::GlobalVariable *VTT = VTables.GetAddrOfVTT(RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001702 VTables.EmitVTTDefinition(VTT, CGM.getVTableLinkage(RD), RD);
Reid Kleckner7810af02013-06-19 15:20:38 +00001703}
1704
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001705bool ItaniumCXXABI::canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const {
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001706 // We don't emit available_externally vtables if we are in -fapple-kext mode
1707 // because kext mode does not permit devirtualization.
1708 if (CGM.getLangOpts().AppleKext)
1709 return false;
1710
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +00001711 // If we don't have any not emitted inline virtual function, and if vtable is
1712 // not hidden, then we are safe to emit available_externally copy of vtable.
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001713 // FIXME we can still emit a copy of the vtable if we
1714 // can emit definition of the inline functions.
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +00001715 return !hasAnyUnusedVirtualInlineFunction(RD) && !isVTableHidden(RD);
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001716}
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001717static llvm::Value *performTypeAdjustment(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001718 Address InitialPtr,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001719 int64_t NonVirtualAdjustment,
1720 int64_t VirtualAdjustment,
1721 bool IsReturnAdjustment) {
1722 if (!NonVirtualAdjustment && !VirtualAdjustment)
John McCall7f416cc2015-09-08 08:05:57 +00001723 return InitialPtr.getPointer();
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001724
John McCall7f416cc2015-09-08 08:05:57 +00001725 Address V = CGF.Builder.CreateElementBitCast(InitialPtr, CGF.Int8Ty);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001726
John McCall7f416cc2015-09-08 08:05:57 +00001727 // In a base-to-derived cast, the non-virtual adjustment is applied first.
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001728 if (NonVirtualAdjustment && !IsReturnAdjustment) {
John McCall7f416cc2015-09-08 08:05:57 +00001729 V = CGF.Builder.CreateConstInBoundsByteGEP(V,
1730 CharUnits::fromQuantity(NonVirtualAdjustment));
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001731 }
1732
John McCall7f416cc2015-09-08 08:05:57 +00001733 // Perform the virtual adjustment if we have one.
1734 llvm::Value *ResultPtr;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001735 if (VirtualAdjustment) {
1736 llvm::Type *PtrDiffTy =
1737 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1738
John McCall7f416cc2015-09-08 08:05:57 +00001739 Address VTablePtrPtr = CGF.Builder.CreateElementBitCast(V, CGF.Int8PtrTy);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001740 llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr);
1741
1742 llvm::Value *OffsetPtr =
1743 CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
1744
1745 OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo());
1746
1747 // Load the adjustment offset from the vtable.
John McCall7f416cc2015-09-08 08:05:57 +00001748 llvm::Value *Offset =
1749 CGF.Builder.CreateAlignedLoad(OffsetPtr, CGF.getPointerAlign());
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001750
1751 // Adjust our pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001752 ResultPtr = CGF.Builder.CreateInBoundsGEP(V.getPointer(), Offset);
1753 } else {
1754 ResultPtr = V.getPointer();
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001755 }
1756
John McCall7f416cc2015-09-08 08:05:57 +00001757 // In a derived-to-base conversion, the non-virtual adjustment is
1758 // applied second.
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001759 if (NonVirtualAdjustment && IsReturnAdjustment) {
John McCall7f416cc2015-09-08 08:05:57 +00001760 ResultPtr = CGF.Builder.CreateConstInBoundsGEP1_64(ResultPtr,
1761 NonVirtualAdjustment);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001762 }
1763
1764 // Cast back to the original type.
John McCall7f416cc2015-09-08 08:05:57 +00001765 return CGF.Builder.CreateBitCast(ResultPtr, InitialPtr.getType());
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001766}
1767
1768llvm::Value *ItaniumCXXABI::performThisAdjustment(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001769 Address This,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001770 const ThisAdjustment &TA) {
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00001771 return performTypeAdjustment(CGF, This, TA.NonVirtual,
1772 TA.Virtual.Itanium.VCallOffsetOffset,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001773 /*IsReturnAdjustment=*/false);
1774}
1775
1776llvm::Value *
John McCall7f416cc2015-09-08 08:05:57 +00001777ItaniumCXXABI::performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001778 const ReturnAdjustment &RA) {
1779 return performTypeAdjustment(CGF, Ret, RA.NonVirtual,
1780 RA.Virtual.Itanium.VBaseOffsetOffset,
1781 /*IsReturnAdjustment=*/true);
1782}
1783
John McCall5d865c322010-08-31 07:33:07 +00001784void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
1785 RValue RV, QualType ResultType) {
1786 if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
1787 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
1788
1789 // Destructor thunks in the ARM ABI have indeterminate results.
John McCall7f416cc2015-09-08 08:05:57 +00001790 llvm::Type *T = CGF.ReturnValue.getElementType();
John McCall5d865c322010-08-31 07:33:07 +00001791 RValue Undef = RValue::get(llvm::UndefValue::get(T));
1792 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
1793}
John McCall8ed55a52010-09-02 09:58:18 +00001794
1795/************************** Array allocation cookies **************************/
1796
John McCallb91cd662012-05-01 05:23:51 +00001797CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
1798 // The array cookie is a size_t; pad that up to the element alignment.
1799 // The cookie is actually right-justified in that space.
1800 return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
1801 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001802}
1803
John McCall7f416cc2015-09-08 08:05:57 +00001804Address ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1805 Address NewPtr,
1806 llvm::Value *NumElements,
1807 const CXXNewExpr *expr,
1808 QualType ElementType) {
John McCallb91cd662012-05-01 05:23:51 +00001809 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001810
John McCall7f416cc2015-09-08 08:05:57 +00001811 unsigned AS = NewPtr.getAddressSpace();
John McCall8ed55a52010-09-02 09:58:18 +00001812
John McCall9bca9232010-09-02 10:25:57 +00001813 ASTContext &Ctx = getContext();
John McCall7f416cc2015-09-08 08:05:57 +00001814 CharUnits SizeSize = CGF.getSizeSize();
John McCall8ed55a52010-09-02 09:58:18 +00001815
1816 // The size of the cookie.
1817 CharUnits CookieSize =
1818 std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
John McCallb91cd662012-05-01 05:23:51 +00001819 assert(CookieSize == getArrayCookieSizeImpl(ElementType));
John McCall8ed55a52010-09-02 09:58:18 +00001820
1821 // Compute an offset to the cookie.
John McCall7f416cc2015-09-08 08:05:57 +00001822 Address CookiePtr = NewPtr;
John McCall8ed55a52010-09-02 09:58:18 +00001823 CharUnits CookieOffset = CookieSize - SizeSize;
1824 if (!CookieOffset.isZero())
John McCall7f416cc2015-09-08 08:05:57 +00001825 CookiePtr = CGF.Builder.CreateConstInBoundsByteGEP(CookiePtr, CookieOffset);
John McCall8ed55a52010-09-02 09:58:18 +00001826
1827 // Write the number of elements into the appropriate slot.
John McCall7f416cc2015-09-08 08:05:57 +00001828 Address NumElementsPtr =
1829 CGF.Builder.CreateElementBitCast(CookiePtr, CGF.SizeTy);
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001830 llvm::Instruction *SI = CGF.Builder.CreateStore(NumElements, NumElementsPtr);
John McCall7f416cc2015-09-08 08:05:57 +00001831
1832 // Handle the array cookie specially in ASan.
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001833 if (CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) && AS == 0 &&
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001834 expr->getOperatorNew()->isReplaceableGlobalAllocationFunction()) {
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001835 // The store to the CookiePtr does not need to be instrumented.
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001836 CGM.getSanitizerMetadata()->disableSanitizerForInstruction(SI);
1837 llvm::FunctionType *FTy =
John McCall7f416cc2015-09-08 08:05:57 +00001838 llvm::FunctionType::get(CGM.VoidTy, NumElementsPtr.getType(), false);
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001839 llvm::Constant *F =
1840 CGM.CreateRuntimeFunction(FTy, "__asan_poison_cxx_array_cookie");
John McCall7f416cc2015-09-08 08:05:57 +00001841 CGF.Builder.CreateCall(F, NumElementsPtr.getPointer());
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001842 }
John McCall8ed55a52010-09-02 09:58:18 +00001843
1844 // Finally, compute a pointer to the actual data buffer by skipping
1845 // over the cookie completely.
John McCall7f416cc2015-09-08 08:05:57 +00001846 return CGF.Builder.CreateConstInBoundsByteGEP(NewPtr, CookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001847}
1848
John McCallb91cd662012-05-01 05:23:51 +00001849llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001850 Address allocPtr,
John McCallb91cd662012-05-01 05:23:51 +00001851 CharUnits cookieSize) {
1852 // The element size is right-justified in the cookie.
John McCall7f416cc2015-09-08 08:05:57 +00001853 Address numElementsPtr = allocPtr;
1854 CharUnits numElementsOffset = cookieSize - CGF.getSizeSize();
John McCallb91cd662012-05-01 05:23:51 +00001855 if (!numElementsOffset.isZero())
1856 numElementsPtr =
John McCall7f416cc2015-09-08 08:05:57 +00001857 CGF.Builder.CreateConstInBoundsByteGEP(numElementsPtr, numElementsOffset);
John McCall8ed55a52010-09-02 09:58:18 +00001858
John McCall7f416cc2015-09-08 08:05:57 +00001859 unsigned AS = allocPtr.getAddressSpace();
1860 numElementsPtr = CGF.Builder.CreateElementBitCast(numElementsPtr, CGF.SizeTy);
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001861 if (!CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) || AS != 0)
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001862 return CGF.Builder.CreateLoad(numElementsPtr);
1863 // In asan mode emit a function call instead of a regular load and let the
1864 // run-time deal with it: if the shadow is properly poisoned return the
1865 // cookie, otherwise return 0 to avoid an infinite loop calling DTORs.
1866 // We can't simply ignore this load using nosanitize metadata because
1867 // the metadata may be lost.
1868 llvm::FunctionType *FTy =
1869 llvm::FunctionType::get(CGF.SizeTy, CGF.SizeTy->getPointerTo(0), false);
1870 llvm::Constant *F =
1871 CGM.CreateRuntimeFunction(FTy, "__asan_load_cxx_array_cookie");
John McCall7f416cc2015-09-08 08:05:57 +00001872 return CGF.Builder.CreateCall(F, numElementsPtr.getPointer());
John McCall8ed55a52010-09-02 09:58:18 +00001873}
1874
John McCallb91cd662012-05-01 05:23:51 +00001875CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
John McCallc19c7062013-01-25 23:36:19 +00001876 // ARM says that the cookie is always:
John McCall8ed55a52010-09-02 09:58:18 +00001877 // struct array_cookie {
1878 // std::size_t element_size; // element_size != 0
1879 // std::size_t element_count;
1880 // };
John McCallc19c7062013-01-25 23:36:19 +00001881 // But the base ABI doesn't give anything an alignment greater than
1882 // 8, so we can dismiss this as typical ABI-author blindness to
1883 // actual language complexity and round up to the element alignment.
1884 return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes),
1885 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001886}
1887
John McCall7f416cc2015-09-08 08:05:57 +00001888Address ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1889 Address newPtr,
1890 llvm::Value *numElements,
1891 const CXXNewExpr *expr,
1892 QualType elementType) {
John McCallb91cd662012-05-01 05:23:51 +00001893 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001894
John McCall8ed55a52010-09-02 09:58:18 +00001895 // The cookie is always at the start of the buffer.
John McCall7f416cc2015-09-08 08:05:57 +00001896 Address cookie = newPtr;
John McCall8ed55a52010-09-02 09:58:18 +00001897
1898 // The first element is the element size.
John McCall7f416cc2015-09-08 08:05:57 +00001899 cookie = CGF.Builder.CreateElementBitCast(cookie, CGF.SizeTy);
John McCallc19c7062013-01-25 23:36:19 +00001900 llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy,
1901 getContext().getTypeSizeInChars(elementType).getQuantity());
1902 CGF.Builder.CreateStore(elementSize, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001903
1904 // The second element is the element count.
John McCall7f416cc2015-09-08 08:05:57 +00001905 cookie = CGF.Builder.CreateConstInBoundsGEP(cookie, 1, CGF.getSizeSize());
John McCallc19c7062013-01-25 23:36:19 +00001906 CGF.Builder.CreateStore(numElements, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001907
1908 // Finally, compute a pointer to the actual data buffer by skipping
1909 // over the cookie completely.
John McCallc19c7062013-01-25 23:36:19 +00001910 CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType);
John McCall7f416cc2015-09-08 08:05:57 +00001911 return CGF.Builder.CreateConstInBoundsByteGEP(newPtr, cookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001912}
1913
John McCallb91cd662012-05-01 05:23:51 +00001914llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001915 Address allocPtr,
John McCallb91cd662012-05-01 05:23:51 +00001916 CharUnits cookieSize) {
1917 // The number of elements is at offset sizeof(size_t) relative to
1918 // the allocated pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001919 Address numElementsPtr
1920 = CGF.Builder.CreateConstInBoundsByteGEP(allocPtr, CGF.getSizeSize());
John McCall8ed55a52010-09-02 09:58:18 +00001921
John McCall7f416cc2015-09-08 08:05:57 +00001922 numElementsPtr = CGF.Builder.CreateElementBitCast(numElementsPtr, CGF.SizeTy);
John McCallb91cd662012-05-01 05:23:51 +00001923 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall8ed55a52010-09-02 09:58:18 +00001924}
1925
John McCall68ff0372010-09-08 01:44:27 +00001926/*********************** Static local initialization **************************/
1927
1928static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001929 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001930 // int __cxa_guard_acquire(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001931 llvm::FunctionType *FTy =
John McCall68ff0372010-09-08 01:44:27 +00001932 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
Jay Foad5709f7c2011-07-29 13:56:53 +00001933 GuardPtrTy, /*isVarArg=*/false);
Reid Klecknerde864822017-03-21 16:57:30 +00001934 return CGM.CreateRuntimeFunction(
1935 FTy, "__cxa_guard_acquire",
1936 llvm::AttributeList::get(CGM.getLLVMContext(),
1937 llvm::AttributeList::FunctionIndex,
1938 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001939}
1940
1941static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001942 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001943 // void __cxa_guard_release(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001944 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001945 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Reid Klecknerde864822017-03-21 16:57:30 +00001946 return CGM.CreateRuntimeFunction(
1947 FTy, "__cxa_guard_release",
1948 llvm::AttributeList::get(CGM.getLLVMContext(),
1949 llvm::AttributeList::FunctionIndex,
1950 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001951}
1952
1953static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001954 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001955 // void __cxa_guard_abort(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001956 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001957 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Reid Klecknerde864822017-03-21 16:57:30 +00001958 return CGM.CreateRuntimeFunction(
1959 FTy, "__cxa_guard_abort",
1960 llvm::AttributeList::get(CGM.getLLVMContext(),
1961 llvm::AttributeList::FunctionIndex,
1962 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001963}
1964
1965namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001966 struct CallGuardAbort final : EHScopeStack::Cleanup {
John McCall68ff0372010-09-08 01:44:27 +00001967 llvm::GlobalVariable *Guard;
Chandler Carruth84537952012-03-30 19:44:53 +00001968 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
John McCall68ff0372010-09-08 01:44:27 +00001969
Craig Topper4f12f102014-03-12 06:41:41 +00001970 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall882987f2013-02-28 19:01:20 +00001971 CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()),
1972 Guard);
John McCall68ff0372010-09-08 01:44:27 +00001973 }
1974 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001975}
John McCall68ff0372010-09-08 01:44:27 +00001976
1977/// The ARM code here follows the Itanium code closely enough that we
1978/// just special-case it at particular places.
John McCallcdf7ef52010-11-06 09:44:32 +00001979void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
1980 const VarDecl &D,
John McCallb88a5662012-03-30 21:00:39 +00001981 llvm::GlobalVariable *var,
1982 bool shouldPerformInit) {
John McCall68ff0372010-09-08 01:44:27 +00001983 CGBuilderTy &Builder = CGF.Builder;
John McCallcdf7ef52010-11-06 09:44:32 +00001984
Richard Smith62f19e72016-06-25 00:15:56 +00001985 // Inline variables that weren't instantiated from variable templates have
1986 // partially-ordered initialization within their translation unit.
1987 bool NonTemplateInline =
1988 D.isInline() &&
1989 !isTemplateInstantiation(D.getTemplateSpecializationKind());
1990
1991 // We only need to use thread-safe statics for local non-TLS variables and
1992 // inline variables; other global initialization is always single-threaded
1993 // or (through lazy dynamic loading in multiple threads) unsequenced.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001994 bool threadsafe = getContext().getLangOpts().ThreadsafeStatics &&
Richard Smith62f19e72016-06-25 00:15:56 +00001995 (D.isLocalVarDecl() || NonTemplateInline) &&
1996 !D.getTLSKind();
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001997
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001998 // If we have a global variable with internal linkage and thread-safe statics
1999 // are disabled, we can just let the guard variable be of type i8.
John McCallb88a5662012-03-30 21:00:39 +00002000 bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
2001
2002 llvm::IntegerType *guardTy;
John McCall7f416cc2015-09-08 08:05:57 +00002003 CharUnits guardAlignment;
John McCall5aa52592011-06-17 07:33:57 +00002004 if (useInt8GuardVariable) {
John McCallb88a5662012-03-30 21:00:39 +00002005 guardTy = CGF.Int8Ty;
John McCall7f416cc2015-09-08 08:05:57 +00002006 guardAlignment = CharUnits::One();
John McCall5aa52592011-06-17 07:33:57 +00002007 } else {
Tim Northover9bb857a2013-01-31 12:13:10 +00002008 // Guard variables are 64 bits in the generic ABI and size width on ARM
2009 // (i.e. 32-bit on AArch32, 64-bit on AArch64).
John McCall7f416cc2015-09-08 08:05:57 +00002010 if (UseARMGuardVarABI) {
2011 guardTy = CGF.SizeTy;
2012 guardAlignment = CGF.getSizeAlign();
2013 } else {
2014 guardTy = CGF.Int64Ty;
2015 guardAlignment = CharUnits::fromQuantity(
2016 CGM.getDataLayout().getABITypeAlignment(guardTy));
2017 }
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00002018 }
John McCallb88a5662012-03-30 21:00:39 +00002019 llvm::PointerType *guardPtrTy = guardTy->getPointerTo();
John McCall68ff0372010-09-08 01:44:27 +00002020
John McCallb88a5662012-03-30 21:00:39 +00002021 // Create the guard variable if we don't already have it (as we
2022 // might if we're double-emitting this function body).
2023 llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
2024 if (!guard) {
2025 // Mangle the name for the guard.
2026 SmallString<256> guardName;
2027 {
2028 llvm::raw_svector_ostream out(guardName);
Reid Klecknerd8110b62013-09-10 20:14:30 +00002029 getMangleContext().mangleStaticGuardVariable(&D, out);
John McCallb88a5662012-03-30 21:00:39 +00002030 }
John McCall8e7cb6d2010-11-02 21:04:24 +00002031
John McCallb88a5662012-03-30 21:00:39 +00002032 // Create the guard variable with a zero-initializer.
2033 // Just absorb linkage and visibility from the guarded variable.
2034 guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
2035 false, var->getLinkage(),
2036 llvm::ConstantInt::get(guardTy, 0),
2037 guardName.str());
2038 guard->setVisibility(var->getVisibility());
Richard Smithdbf74ba2013-04-14 23:01:42 +00002039 // If the variable is thread-local, so is its guard variable.
2040 guard->setThreadLocalMode(var->getThreadLocalMode());
John McCall7f416cc2015-09-08 08:05:57 +00002041 guard->setAlignment(guardAlignment.getQuantity());
John McCallb88a5662012-03-30 21:00:39 +00002042
Yaron Keren5bfa1082015-09-03 20:33:29 +00002043 // The ABI says: "It is suggested that it be emitted in the same COMDAT
2044 // group as the associated data object." In practice, this doesn't work for
Dan Gohman839f2152017-01-17 21:46:38 +00002045 // non-ELF and non-Wasm object formats, so only do it for ELF and Wasm.
Rafael Espindola0d4fb982015-01-12 22:13:53 +00002046 llvm::Comdat *C = var->getComdat();
Yaron Keren5bfa1082015-09-03 20:33:29 +00002047 if (!D.isLocalVarDecl() && C &&
Dan Gohman839f2152017-01-17 21:46:38 +00002048 (CGM.getTarget().getTriple().isOSBinFormatELF() ||
2049 CGM.getTarget().getTriple().isOSBinFormatWasm())) {
Rafael Espindola2ae4b632014-09-19 19:43:18 +00002050 guard->setComdat(C);
Richard Smith62f19e72016-06-25 00:15:56 +00002051 // An inline variable's guard function is run from the per-TU
2052 // initialization function, not via a dedicated global ctor function, so
2053 // we can't put it in a comdat.
2054 if (!NonTemplateInline)
2055 CGF.CurFn->setComdat(C);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00002056 } else if (CGM.supportsCOMDAT() && guard->isWeakForLinker()) {
2057 guard->setComdat(CGM.getModule().getOrInsertComdat(guard->getName()));
Rafael Espindola2ae4b632014-09-19 19:43:18 +00002058 }
2059
John McCallb88a5662012-03-30 21:00:39 +00002060 CGM.setStaticLocalDeclGuardAddress(&D, guard);
2061 }
John McCall87590e62012-03-30 07:09:50 +00002062
John McCall7f416cc2015-09-08 08:05:57 +00002063 Address guardAddr = Address(guard, guardAlignment);
2064
John McCall68ff0372010-09-08 01:44:27 +00002065 // Test whether the variable has completed initialization.
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002066 //
John McCall68ff0372010-09-08 01:44:27 +00002067 // Itanium C++ ABI 3.3.2:
2068 // The following is pseudo-code showing how these functions can be used:
2069 // if (obj_guard.first_byte == 0) {
2070 // if ( __cxa_guard_acquire (&obj_guard) ) {
2071 // try {
2072 // ... initialize the object ...;
2073 // } catch (...) {
2074 // __cxa_guard_abort (&obj_guard);
2075 // throw;
2076 // }
2077 // ... queue object destructor with __cxa_atexit() ...;
2078 // __cxa_guard_release (&obj_guard);
2079 // }
2080 // }
Tim Northovera2ee4332014-03-29 15:09:45 +00002081
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002082 // Load the first byte of the guard variable.
2083 llvm::LoadInst *LI =
John McCall7f416cc2015-09-08 08:05:57 +00002084 Builder.CreateLoad(Builder.CreateElementBitCast(guardAddr, CGM.Int8Ty));
John McCall68ff0372010-09-08 01:44:27 +00002085
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002086 // Itanium ABI:
2087 // An implementation supporting thread-safety on multiprocessor
2088 // systems must also guarantee that references to the initialized
2089 // object do not occur before the load of the initialization flag.
2090 //
2091 // In LLVM, we do this by marking the load Acquire.
2092 if (threadsafe)
JF Bastien92f4ef12016-04-06 17:26:42 +00002093 LI->setAtomic(llvm::AtomicOrdering::Acquire);
Eli Friedman84d28122011-09-13 22:21:56 +00002094
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002095 // For ARM, we should only check the first bit, rather than the entire byte:
2096 //
2097 // ARM C++ ABI 3.2.3.1:
2098 // To support the potential use of initialization guard variables
2099 // as semaphores that are the target of ARM SWP and LDREX/STREX
2100 // synchronizing instructions we define a static initialization
2101 // guard variable to be a 4-byte aligned, 4-byte word with the
2102 // following inline access protocol.
2103 // #define INITIALIZED 1
2104 // if ((obj_guard & INITIALIZED) != INITIALIZED) {
2105 // if (__cxa_guard_acquire(&obj_guard))
2106 // ...
2107 // }
2108 //
2109 // and similarly for ARM64:
2110 //
2111 // ARM64 C++ ABI 3.2.2:
2112 // This ABI instead only specifies the value bit 0 of the static guard
2113 // variable; all other bits are platform defined. Bit 0 shall be 0 when the
2114 // variable is not initialized and 1 when it is.
2115 llvm::Value *V =
2116 (UseARMGuardVarABI && !useInt8GuardVariable)
2117 ? Builder.CreateAnd(LI, llvm::ConstantInt::get(CGM.Int8Ty, 1))
2118 : LI;
Richard Smithae8d62c2017-07-26 22:01:09 +00002119 llvm::Value *NeedsInit = Builder.CreateIsNull(V, "guard.uninitialized");
John McCall68ff0372010-09-08 01:44:27 +00002120
2121 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
2122 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
2123
2124 // Check if the first byte of the guard variable is zero.
Richard Smithae8d62c2017-07-26 22:01:09 +00002125 CGF.EmitCXXGuardedInitBranch(NeedsInit, InitCheckBlock, EndBlock,
2126 CodeGenFunction::GuardKind::VariableGuard, &D);
John McCall68ff0372010-09-08 01:44:27 +00002127
2128 CGF.EmitBlock(InitCheckBlock);
2129
2130 // Variables used when coping with thread-safe statics and exceptions.
John McCall5aa52592011-06-17 07:33:57 +00002131 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00002132 // Call __cxa_guard_acquire.
2133 llvm::Value *V
John McCall882987f2013-02-28 19:01:20 +00002134 = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
John McCall68ff0372010-09-08 01:44:27 +00002135
2136 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
2137
2138 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
2139 InitBlock, EndBlock);
2140
2141 // Call __cxa_guard_abort along the exceptional edge.
John McCallb88a5662012-03-30 21:00:39 +00002142 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
John McCall68ff0372010-09-08 01:44:27 +00002143
2144 CGF.EmitBlock(InitBlock);
2145 }
2146
2147 // Emit the initializer and add a global destructor if appropriate.
John McCallb88a5662012-03-30 21:00:39 +00002148 CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
John McCall68ff0372010-09-08 01:44:27 +00002149
John McCall5aa52592011-06-17 07:33:57 +00002150 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00002151 // Pop the guard-abort cleanup if we pushed one.
2152 CGF.PopCleanupBlock();
2153
2154 // Call __cxa_guard_release. This cannot throw.
John McCall7f416cc2015-09-08 08:05:57 +00002155 CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy),
2156 guardAddr.getPointer());
John McCall68ff0372010-09-08 01:44:27 +00002157 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002158 Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guardAddr);
John McCall68ff0372010-09-08 01:44:27 +00002159 }
2160
2161 CGF.EmitBlock(EndBlock);
2162}
John McCallc84ed6a2012-05-01 06:13:13 +00002163
2164/// Register a global destructor using __cxa_atexit.
2165static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
2166 llvm::Constant *dtor,
Richard Smithdbf74ba2013-04-14 23:01:42 +00002167 llvm::Constant *addr,
2168 bool TLS) {
Bill Wendling95cae882013-05-02 19:18:03 +00002169 const char *Name = "__cxa_atexit";
2170 if (TLS) {
2171 const llvm::Triple &T = CGF.getTarget().getTriple();
Manman Renf93fff22015-11-11 23:08:18 +00002172 Name = T.isOSDarwin() ? "_tlv_atexit" : "__cxa_thread_atexit";
Bill Wendling95cae882013-05-02 19:18:03 +00002173 }
Richard Smithdbf74ba2013-04-14 23:01:42 +00002174
John McCallc84ed6a2012-05-01 06:13:13 +00002175 // We're assuming that the destructor function is something we can
2176 // reasonably call with the default CC. Go ahead and cast it to the
2177 // right prototype.
2178 llvm::Type *dtorTy =
2179 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo();
2180
2181 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
2182 llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
2183 llvm::FunctionType *atexitTy =
2184 llvm::FunctionType::get(CGF.IntTy, paramTys, false);
2185
2186 // Fetch the actual function.
Richard Smithdbf74ba2013-04-14 23:01:42 +00002187 llvm::Constant *atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name);
John McCallc84ed6a2012-05-01 06:13:13 +00002188 if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit))
2189 fn->setDoesNotThrow();
2190
2191 // Create a variable that binds the atexit to this shared object.
2192 llvm::Constant *handle =
Reid Kleckner9de92142017-02-13 18:49:21 +00002193 CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
2194 auto *GV = cast<llvm::GlobalValue>(handle->stripPointerCasts());
2195 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
John McCallc84ed6a2012-05-01 06:13:13 +00002196
2197 llvm::Value *args[] = {
2198 llvm::ConstantExpr::getBitCast(dtor, dtorTy),
2199 llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy),
2200 handle
2201 };
John McCall882987f2013-02-28 19:01:20 +00002202 CGF.EmitNounwindRuntimeCall(atexit, args);
John McCallc84ed6a2012-05-01 06:13:13 +00002203}
2204
2205/// Register a global destructor as best as we know how.
2206void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF,
Richard Smithdbf74ba2013-04-14 23:01:42 +00002207 const VarDecl &D,
John McCallc84ed6a2012-05-01 06:13:13 +00002208 llvm::Constant *dtor,
2209 llvm::Constant *addr) {
2210 // Use __cxa_atexit if available.
Richard Smithdbf74ba2013-04-14 23:01:42 +00002211 if (CGM.getCodeGenOpts().CXAAtExit)
2212 return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind());
2213
2214 if (D.getTLSKind())
2215 CGM.ErrorUnsupported(&D, "non-trivial TLS destruction");
John McCallc84ed6a2012-05-01 06:13:13 +00002216
2217 // In Apple kexts, we want to add a global destructor entry.
2218 // FIXME: shouldn't this be guarded by some variable?
Richard Smith9c6890a2012-11-01 22:30:59 +00002219 if (CGM.getLangOpts().AppleKext) {
John McCallc84ed6a2012-05-01 06:13:13 +00002220 // Generate a global destructor entry.
2221 return CGM.AddCXXDtorEntry(dtor, addr);
2222 }
2223
David Blaikieebe87e12013-08-27 23:57:18 +00002224 CGF.registerGlobalDtorWithAtExit(D, dtor, addr);
John McCallc84ed6a2012-05-01 06:13:13 +00002225}
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002226
David Majnemer9b21c332014-07-11 20:28:10 +00002227static bool isThreadWrapperReplaceable(const VarDecl *VD,
2228 CodeGen::CodeGenModule &CGM) {
2229 assert(!VD->isStaticLocal() && "static local VarDecls don't need wrappers!");
Manman Renf93fff22015-11-11 23:08:18 +00002230 // Darwin prefers to have references to thread local variables to go through
David Majnemer9b21c332014-07-11 20:28:10 +00002231 // the thread wrapper instead of directly referencing the backing variable.
2232 return VD->getTLSKind() == VarDecl::TLS_Dynamic &&
Manman Renf93fff22015-11-11 23:08:18 +00002233 CGM.getTarget().getTriple().isOSDarwin();
David Majnemer9b21c332014-07-11 20:28:10 +00002234}
2235
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002236/// Get the appropriate linkage for the wrapper function. This is essentially
David Majnemer4632e1e2014-06-27 16:56:27 +00002237/// the weak form of the variable's linkage; every translation unit which needs
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002238/// the wrapper emits a copy, and we want the linker to merge them.
David Majnemer35ab3282014-06-11 04:08:55 +00002239static llvm::GlobalValue::LinkageTypes
2240getThreadLocalWrapperLinkage(const VarDecl *VD, CodeGen::CodeGenModule &CGM) {
2241 llvm::GlobalValue::LinkageTypes VarLinkage =
2242 CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false);
2243
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002244 // For internal linkage variables, we don't need an external or weak wrapper.
2245 if (llvm::GlobalValue::isLocalLinkage(VarLinkage))
2246 return VarLinkage;
David Majnemer35ab3282014-06-11 04:08:55 +00002247
David Majnemer9b21c332014-07-11 20:28:10 +00002248 // If the thread wrapper is replaceable, give it appropriate linkage.
Manman Ren68150262015-11-11 22:42:31 +00002249 if (isThreadWrapperReplaceable(VD, CGM))
2250 if (!llvm::GlobalVariable::isLinkOnceLinkage(VarLinkage) &&
2251 !llvm::GlobalVariable::isWeakODRLinkage(VarLinkage))
2252 return VarLinkage;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002253 return llvm::GlobalValue::WeakODRLinkage;
2254}
2255
2256llvm::Function *
2257ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD,
Alexander Musmanf94c3182014-09-26 06:28:25 +00002258 llvm::Value *Val) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002259 // Mangle the name for the thread_local wrapper function.
2260 SmallString<256> WrapperName;
2261 {
2262 llvm::raw_svector_ostream Out(WrapperName);
2263 getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002264 }
2265
Akira Hatanaka26907f92016-01-15 03:34:06 +00002266 // FIXME: If VD is a definition, we should regenerate the function attributes
2267 // before returning.
Alexander Musmanf94c3182014-09-26 06:28:25 +00002268 if (llvm::Value *V = CGM.getModule().getNamedValue(WrapperName))
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002269 return cast<llvm::Function>(V);
2270
Akira Hatanaka26907f92016-01-15 03:34:06 +00002271 QualType RetQT = VD->getType();
2272 if (RetQT->isReferenceType())
2273 RetQT = RetQT.getNonReferenceType();
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002274
John McCallc56a8b32016-03-11 04:30:31 +00002275 const CGFunctionInfo &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
2276 getContext().getPointerType(RetQT), FunctionArgList());
Akira Hatanaka26907f92016-01-15 03:34:06 +00002277
2278 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FI);
David Majnemer35ab3282014-06-11 04:08:55 +00002279 llvm::Function *Wrapper =
2280 llvm::Function::Create(FnTy, getThreadLocalWrapperLinkage(VD, CGM),
2281 WrapperName.str(), &CGM.getModule());
Akira Hatanaka26907f92016-01-15 03:34:06 +00002282
2283 CGM.SetLLVMFunctionAttributes(nullptr, FI, Wrapper);
2284
2285 if (VD->hasDefinition())
2286 CGM.SetLLVMFunctionAttributesForDefinition(nullptr, Wrapper);
2287
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002288 // Always resolve references to the wrapper at link time.
Manman Ren68150262015-11-11 22:42:31 +00002289 if (!Wrapper->hasLocalLinkage() && !(isThreadWrapperReplaceable(VD, CGM) &&
2290 !llvm::GlobalVariable::isLinkOnceLinkage(Wrapper->getLinkage()) &&
2291 !llvm::GlobalVariable::isWeakODRLinkage(Wrapper->getLinkage())))
Duncan P. N. Exon Smith4434d362014-05-07 22:36:11 +00002292 Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
Manman Renb0b3af72015-12-17 00:42:36 +00002293
2294 if (isThreadWrapperReplaceable(VD, CGM)) {
2295 Wrapper->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2296 Wrapper->addFnAttr(llvm::Attribute::NoUnwind);
2297 }
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002298 return Wrapper;
2299}
2300
2301void ItaniumCXXABI::EmitThreadLocalInitFuncs(
Richard Smith5a99c492015-12-01 01:10:48 +00002302 CodeGenModule &CGM, ArrayRef<const VarDecl *> CXXThreadLocals,
2303 ArrayRef<llvm::Function *> CXXThreadLocalInits,
2304 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) {
David Majnemerb3341ea2014-10-05 05:05:40 +00002305 llvm::Function *InitFunc = nullptr;
Richard Smithfbe23692017-01-13 00:43:31 +00002306
2307 // Separate initializers into those with ordered (or partially-ordered)
2308 // initialization and those with unordered initialization.
2309 llvm::SmallVector<llvm::Function *, 8> OrderedInits;
2310 llvm::SmallDenseMap<const VarDecl *, llvm::Function *> UnorderedInits;
2311 for (unsigned I = 0; I != CXXThreadLocalInits.size(); ++I) {
2312 if (isTemplateInstantiation(
2313 CXXThreadLocalInitVars[I]->getTemplateSpecializationKind()))
2314 UnorderedInits[CXXThreadLocalInitVars[I]->getCanonicalDecl()] =
2315 CXXThreadLocalInits[I];
2316 else
2317 OrderedInits.push_back(CXXThreadLocalInits[I]);
2318 }
2319
2320 if (!OrderedInits.empty()) {
David Majnemerb3341ea2014-10-05 05:05:40 +00002321 // Generate a guarded initialization function.
2322 llvm::FunctionType *FTy =
2323 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002324 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
2325 InitFunc = CGM.CreateGlobalInitOrDestructFunction(FTy, "__tls_init", FI,
Alexey Samsonov1444bb92014-10-17 00:20:19 +00002326 SourceLocation(),
David Majnemerb3341ea2014-10-05 05:05:40 +00002327 /*TLS=*/true);
2328 llvm::GlobalVariable *Guard = new llvm::GlobalVariable(
2329 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false,
2330 llvm::GlobalVariable::InternalLinkage,
2331 llvm::ConstantInt::get(CGM.Int8Ty, 0), "__tls_guard");
2332 Guard->setThreadLocal(true);
John McCall7f416cc2015-09-08 08:05:57 +00002333
2334 CharUnits GuardAlign = CharUnits::One();
2335 Guard->setAlignment(GuardAlign.getQuantity());
2336
Richard Smithfbe23692017-01-13 00:43:31 +00002337 CodeGenFunction(CGM).GenerateCXXGlobalInitFunc(InitFunc, OrderedInits,
2338 Address(Guard, GuardAlign));
Manman Ren5e5d0462016-03-18 23:35:21 +00002339 // On Darwin platforms, use CXX_FAST_TLS calling convention.
2340 if (CGM.getTarget().getTriple().isOSDarwin()) {
2341 InitFunc->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2342 InitFunc->addFnAttr(llvm::Attribute::NoUnwind);
2343 }
David Majnemerb3341ea2014-10-05 05:05:40 +00002344 }
Richard Smithfbe23692017-01-13 00:43:31 +00002345
2346 // Emit thread wrappers.
Richard Smith5a99c492015-12-01 01:10:48 +00002347 for (const VarDecl *VD : CXXThreadLocals) {
2348 llvm::GlobalVariable *Var =
2349 cast<llvm::GlobalVariable>(CGM.GetGlobalValue(CGM.getMangledName(VD)));
Richard Smithfbe23692017-01-13 00:43:31 +00002350 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Var);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002351
David Majnemer9b21c332014-07-11 20:28:10 +00002352 // Some targets require that all access to thread local variables go through
2353 // the thread wrapper. This means that we cannot attempt to create a thread
2354 // wrapper or a thread helper.
Richard Smithfbe23692017-01-13 00:43:31 +00002355 if (isThreadWrapperReplaceable(VD, CGM) && !VD->hasDefinition()) {
2356 Wrapper->setLinkage(llvm::Function::ExternalLinkage);
David Majnemer9b21c332014-07-11 20:28:10 +00002357 continue;
Richard Smithfbe23692017-01-13 00:43:31 +00002358 }
David Majnemer9b21c332014-07-11 20:28:10 +00002359
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002360 // Mangle the name for the thread_local initialization function.
2361 SmallString<256> InitFnName;
2362 {
2363 llvm::raw_svector_ostream Out(InitFnName);
2364 getMangleContext().mangleItaniumThreadLocalInit(VD, Out);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002365 }
2366
2367 // If we have a definition for the variable, emit the initialization
2368 // function as an alias to the global Init function (if any). Otherwise,
2369 // produce a declaration of the initialization function.
Craig Topper8a13c412014-05-21 05:09:00 +00002370 llvm::GlobalValue *Init = nullptr;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002371 bool InitIsInitFunc = false;
2372 if (VD->hasDefinition()) {
2373 InitIsInitFunc = true;
Richard Smithfbe23692017-01-13 00:43:31 +00002374 llvm::Function *InitFuncToUse = InitFunc;
2375 if (isTemplateInstantiation(VD->getTemplateSpecializationKind()))
2376 InitFuncToUse = UnorderedInits.lookup(VD->getCanonicalDecl());
2377 if (InitFuncToUse)
Rafael Espindola234405b2014-05-17 21:30:14 +00002378 Init = llvm::GlobalAlias::create(Var->getLinkage(), InitFnName.str(),
Richard Smithfbe23692017-01-13 00:43:31 +00002379 InitFuncToUse);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002380 } else {
2381 // Emit a weak global function referring to the initialization function.
2382 // This function will not exist if the TU defining the thread_local
2383 // variable in question does not need any dynamic initialization for
2384 // its thread_local variables.
2385 llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, false);
Richard Smithfbe23692017-01-13 00:43:31 +00002386 Init = llvm::Function::Create(FnTy,
2387 llvm::GlobalVariable::ExternalWeakLinkage,
2388 InitFnName.str(), &CGM.getModule());
John McCallc56a8b32016-03-11 04:30:31 +00002389 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
Akira Hatanaka26907f92016-01-15 03:34:06 +00002390 CGM.SetLLVMFunctionAttributes(nullptr, FI, cast<llvm::Function>(Init));
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002391 }
2392
2393 if (Init)
2394 Init->setVisibility(Var->getVisibility());
2395
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002396 llvm::LLVMContext &Context = CGM.getModule().getContext();
2397 llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper);
John McCall7f416cc2015-09-08 08:05:57 +00002398 CGBuilderTy Builder(CGM, Entry);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002399 if (InitIsInitFunc) {
Manman Ren5e5d0462016-03-18 23:35:21 +00002400 if (Init) {
2401 llvm::CallInst *CallVal = Builder.CreateCall(Init);
2402 if (isThreadWrapperReplaceable(VD, CGM))
2403 CallVal->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2404 }
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002405 } else {
2406 // Don't know whether we have an init function. Call it if it exists.
2407 llvm::Value *Have = Builder.CreateIsNotNull(Init);
2408 llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2409 llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2410 Builder.CreateCondBr(Have, InitBB, ExitBB);
2411
2412 Builder.SetInsertPoint(InitBB);
David Blaikie4ba525b2015-07-14 17:27:39 +00002413 Builder.CreateCall(Init);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002414 Builder.CreateBr(ExitBB);
2415
2416 Builder.SetInsertPoint(ExitBB);
2417 }
2418
2419 // For a reference, the result of the wrapper function is a pointer to
2420 // the referenced object.
2421 llvm::Value *Val = Var;
2422 if (VD->getType()->isReferenceType()) {
John McCall7f416cc2015-09-08 08:05:57 +00002423 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2424 Val = Builder.CreateAlignedLoad(Val, Align);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002425 }
Alexander Musmanf94c3182014-09-26 06:28:25 +00002426 if (Val->getType() != Wrapper->getReturnType())
2427 Val = Builder.CreatePointerBitCastOrAddrSpaceCast(
2428 Val, Wrapper->getReturnType(), "");
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002429 Builder.CreateRet(Val);
2430 }
2431}
2432
Richard Smith0f383742014-03-26 22:48:22 +00002433LValue ItaniumCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
2434 const VarDecl *VD,
2435 QualType LValType) {
Richard Smith5a99c492015-12-01 01:10:48 +00002436 llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD);
Alexander Musmanf94c3182014-09-26 06:28:25 +00002437 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Val);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002438
Manman Renb0b3af72015-12-17 00:42:36 +00002439 llvm::CallInst *CallVal = CGF.Builder.CreateCall(Wrapper);
Saleem Abdulrasool4a7130a2016-08-01 21:31:24 +00002440 CallVal->setCallingConv(Wrapper->getCallingConv());
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002441
2442 LValue LV;
2443 if (VD->getType()->isReferenceType())
Manman Renb0b3af72015-12-17 00:42:36 +00002444 LV = CGF.MakeNaturalAlignAddrLValue(CallVal, LValType);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002445 else
Manman Renb0b3af72015-12-17 00:42:36 +00002446 LV = CGF.MakeAddrLValue(CallVal, LValType,
2447 CGF.getContext().getDeclAlign(VD));
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002448 // FIXME: need setObjCGCLValueClass?
2449 return LV;
2450}
Peter Collingbourne66f82e62013-06-28 20:45:28 +00002451
2452/// Return whether the given global decl needs a VTT parameter, which it does
2453/// if it's a base constructor or destructor with virtual bases.
2454bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) {
2455 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
2456
2457 // We don't have any virtual bases, just return early.
2458 if (!MD->getParent()->getNumVBases())
2459 return false;
2460
2461 // Check if we have a base constructor.
2462 if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base)
2463 return true;
2464
2465 // Check if we have a base destructor.
2466 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
2467 return true;
2468
2469 return false;
2470}
David Majnemere2cb8d12014-07-07 06:20:47 +00002471
2472namespace {
2473class ItaniumRTTIBuilder {
2474 CodeGenModule &CGM; // Per-module state.
2475 llvm::LLVMContext &VMContext;
2476 const ItaniumCXXABI &CXXABI; // Per-module state.
2477
2478 /// Fields - The fields of the RTTI descriptor currently being built.
2479 SmallVector<llvm::Constant *, 16> Fields;
2480
2481 /// GetAddrOfTypeName - Returns the mangled type name of the given type.
2482 llvm::GlobalVariable *
2483 GetAddrOfTypeName(QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage);
2484
2485 /// GetAddrOfExternalRTTIDescriptor - Returns the constant for the RTTI
2486 /// descriptor of the given type.
2487 llvm::Constant *GetAddrOfExternalRTTIDescriptor(QualType Ty);
2488
2489 /// BuildVTablePointer - Build the vtable pointer for the given type.
2490 void BuildVTablePointer(const Type *Ty);
2491
2492 /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
2493 /// inheritance, according to the Itanium C++ ABI, 2.9.5p6b.
2494 void BuildSIClassTypeInfo(const CXXRecordDecl *RD);
2495
2496 /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
2497 /// classes with bases that do not satisfy the abi::__si_class_type_info
2498 /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
2499 void BuildVMIClassTypeInfo(const CXXRecordDecl *RD);
2500
2501 /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct, used
2502 /// for pointer types.
2503 void BuildPointerTypeInfo(QualType PointeeTy);
2504
2505 /// BuildObjCObjectTypeInfo - Build the appropriate kind of
2506 /// type_info for an object type.
2507 void BuildObjCObjectTypeInfo(const ObjCObjectType *Ty);
2508
2509 /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
2510 /// struct, used for member pointer types.
2511 void BuildPointerToMemberTypeInfo(const MemberPointerType *Ty);
2512
2513public:
2514 ItaniumRTTIBuilder(const ItaniumCXXABI &ABI)
2515 : CGM(ABI.CGM), VMContext(CGM.getModule().getContext()), CXXABI(ABI) {}
2516
2517 // Pointer type info flags.
2518 enum {
2519 /// PTI_Const - Type has const qualifier.
2520 PTI_Const = 0x1,
2521
2522 /// PTI_Volatile - Type has volatile qualifier.
2523 PTI_Volatile = 0x2,
2524
2525 /// PTI_Restrict - Type has restrict qualifier.
2526 PTI_Restrict = 0x4,
2527
2528 /// PTI_Incomplete - Type is incomplete.
2529 PTI_Incomplete = 0x8,
2530
2531 /// PTI_ContainingClassIncomplete - Containing class is incomplete.
2532 /// (in pointer to member).
Richard Smitha7d93782016-12-01 03:32:42 +00002533 PTI_ContainingClassIncomplete = 0x10,
2534
2535 /// PTI_TransactionSafe - Pointee is transaction_safe function (C++ TM TS).
2536 //PTI_TransactionSafe = 0x20,
2537
2538 /// PTI_Noexcept - Pointee is noexcept function (C++1z).
2539 PTI_Noexcept = 0x40,
David Majnemere2cb8d12014-07-07 06:20:47 +00002540 };
2541
2542 // VMI type info flags.
2543 enum {
2544 /// VMI_NonDiamondRepeat - Class has non-diamond repeated inheritance.
2545 VMI_NonDiamondRepeat = 0x1,
2546
2547 /// VMI_DiamondShaped - Class is diamond shaped.
2548 VMI_DiamondShaped = 0x2
2549 };
2550
2551 // Base class type info flags.
2552 enum {
2553 /// BCTI_Virtual - Base class is virtual.
2554 BCTI_Virtual = 0x1,
2555
2556 /// BCTI_Public - Base class is public.
2557 BCTI_Public = 0x2
2558 };
2559
2560 /// BuildTypeInfo - Build the RTTI type info struct for the given type.
2561 ///
2562 /// \param Force - true to force the creation of this RTTI value
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00002563 /// \param DLLExport - true to mark the RTTI value as DLLExport
2564 llvm::Constant *BuildTypeInfo(QualType Ty, bool Force = false,
2565 bool DLLExport = false);
David Majnemere2cb8d12014-07-07 06:20:47 +00002566};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002567}
David Majnemere2cb8d12014-07-07 06:20:47 +00002568
2569llvm::GlobalVariable *ItaniumRTTIBuilder::GetAddrOfTypeName(
2570 QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage) {
Yaron Kerene46f7ed2015-07-29 14:21:47 +00002571 SmallString<256> Name;
2572 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00002573 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00002574
2575 // We know that the mangled name of the type starts at index 4 of the
2576 // mangled name of the typename, so we can just index into it in order to
2577 // get the mangled name of the type.
2578 llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,
2579 Name.substr(4));
2580
2581 llvm::GlobalVariable *GV =
2582 CGM.CreateOrReplaceCXXRuntimeVariable(Name, Init->getType(), Linkage);
2583
2584 GV->setInitializer(Init);
2585
2586 return GV;
2587}
2588
2589llvm::Constant *
2590ItaniumRTTIBuilder::GetAddrOfExternalRTTIDescriptor(QualType Ty) {
2591 // Mangle the RTTI name.
Yaron Kerene46f7ed2015-07-29 14:21:47 +00002592 SmallString<256> Name;
2593 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00002594 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00002595
2596 // Look for an existing global.
2597 llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name);
2598
2599 if (!GV) {
2600 // Create a new global variable.
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +00002601 // Note for the future: If we would ever like to do deferred emission of
2602 // RTTI, check if emitting vtables opportunistically need any adjustment.
2603
David Majnemere2cb8d12014-07-07 06:20:47 +00002604 GV = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
2605 /*Constant=*/true,
2606 llvm::GlobalValue::ExternalLinkage, nullptr,
2607 Name);
David Majnemer1fb1a042014-11-07 07:26:38 +00002608 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2609 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
2610 if (RD->hasAttr<DLLImportAttr>())
2611 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
2612 }
David Majnemere2cb8d12014-07-07 06:20:47 +00002613 }
2614
2615 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
2616}
2617
2618/// TypeInfoIsInStandardLibrary - Given a builtin type, returns whether the type
2619/// info for that type is defined in the standard library.
2620static bool TypeInfoIsInStandardLibrary(const BuiltinType *Ty) {
2621 // Itanium C++ ABI 2.9.2:
2622 // Basic type information (e.g. for "int", "bool", etc.) will be kept in
2623 // the run-time support library. Specifically, the run-time support
2624 // library should contain type_info objects for the types X, X* and
2625 // X const*, for every X in: void, std::nullptr_t, bool, wchar_t, char,
2626 // unsigned char, signed char, short, unsigned short, int, unsigned int,
2627 // long, unsigned long, long long, unsigned long long, float, double,
2628 // long double, char16_t, char32_t, and the IEEE 754r decimal and
2629 // half-precision floating point types.
Richard Smith4a382012016-02-03 01:32:42 +00002630 //
2631 // GCC also emits RTTI for __int128.
2632 // FIXME: We do not emit RTTI information for decimal types here.
2633
2634 // Types added here must also be added to EmitFundamentalRTTIDescriptors.
David Majnemere2cb8d12014-07-07 06:20:47 +00002635 switch (Ty->getKind()) {
2636 case BuiltinType::Void:
2637 case BuiltinType::NullPtr:
2638 case BuiltinType::Bool:
2639 case BuiltinType::WChar_S:
2640 case BuiltinType::WChar_U:
2641 case BuiltinType::Char_U:
2642 case BuiltinType::Char_S:
2643 case BuiltinType::UChar:
2644 case BuiltinType::SChar:
2645 case BuiltinType::Short:
2646 case BuiltinType::UShort:
2647 case BuiltinType::Int:
2648 case BuiltinType::UInt:
2649 case BuiltinType::Long:
2650 case BuiltinType::ULong:
2651 case BuiltinType::LongLong:
2652 case BuiltinType::ULongLong:
2653 case BuiltinType::Half:
2654 case BuiltinType::Float:
2655 case BuiltinType::Double:
2656 case BuiltinType::LongDouble:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002657 case BuiltinType::Float128:
David Majnemere2cb8d12014-07-07 06:20:47 +00002658 case BuiltinType::Char16:
2659 case BuiltinType::Char32:
2660 case BuiltinType::Int128:
2661 case BuiltinType::UInt128:
Richard Smith4a382012016-02-03 01:32:42 +00002662 return true;
2663
Alexey Bader954ba212016-04-08 13:40:33 +00002664#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2665 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00002666#include "clang/Basic/OpenCLImageTypes.def"
David Majnemere2cb8d12014-07-07 06:20:47 +00002667 case BuiltinType::OCLSampler:
2668 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00002669 case BuiltinType::OCLClkEvent:
2670 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00002671 case BuiltinType::OCLReserveID:
Richard Smith4a382012016-02-03 01:32:42 +00002672 return false;
David Majnemere2cb8d12014-07-07 06:20:47 +00002673
2674 case BuiltinType::Dependent:
2675#define BUILTIN_TYPE(Id, SingletonId)
2676#define PLACEHOLDER_TYPE(Id, SingletonId) \
2677 case BuiltinType::Id:
2678#include "clang/AST/BuiltinTypes.def"
2679 llvm_unreachable("asking for RRTI for a placeholder type!");
2680
2681 case BuiltinType::ObjCId:
2682 case BuiltinType::ObjCClass:
2683 case BuiltinType::ObjCSel:
2684 llvm_unreachable("FIXME: Objective-C types are unsupported!");
2685 }
2686
2687 llvm_unreachable("Invalid BuiltinType Kind!");
2688}
2689
2690static bool TypeInfoIsInStandardLibrary(const PointerType *PointerTy) {
2691 QualType PointeeTy = PointerTy->getPointeeType();
2692 const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(PointeeTy);
2693 if (!BuiltinTy)
2694 return false;
2695
2696 // Check the qualifiers.
2697 Qualifiers Quals = PointeeTy.getQualifiers();
2698 Quals.removeConst();
2699
2700 if (!Quals.empty())
2701 return false;
2702
2703 return TypeInfoIsInStandardLibrary(BuiltinTy);
2704}
2705
2706/// IsStandardLibraryRTTIDescriptor - Returns whether the type
2707/// information for the given type exists in the standard library.
2708static bool IsStandardLibraryRTTIDescriptor(QualType Ty) {
2709 // Type info for builtin types is defined in the standard library.
2710 if (const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(Ty))
2711 return TypeInfoIsInStandardLibrary(BuiltinTy);
2712
2713 // Type info for some pointer types to builtin types is defined in the
2714 // standard library.
2715 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2716 return TypeInfoIsInStandardLibrary(PointerTy);
2717
2718 return false;
2719}
2720
2721/// ShouldUseExternalRTTIDescriptor - Returns whether the type information for
2722/// the given type exists somewhere else, and that we should not emit the type
2723/// information in this translation unit. Assumes that it is not a
2724/// standard-library type.
2725static bool ShouldUseExternalRTTIDescriptor(CodeGenModule &CGM,
2726 QualType Ty) {
2727 ASTContext &Context = CGM.getContext();
2728
2729 // If RTTI is disabled, assume it might be disabled in the
2730 // translation unit that defines any potential key function, too.
2731 if (!Context.getLangOpts().RTTI) return false;
2732
2733 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2734 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
2735 if (!RD->hasDefinition())
2736 return false;
2737
2738 if (!RD->isDynamicClass())
2739 return false;
2740
2741 // FIXME: this may need to be reconsidered if the key function
2742 // changes.
David Majnemerbe9022c2015-08-06 20:56:55 +00002743 // N.B. We must always emit the RTTI data ourselves if there exists a key
2744 // function.
2745 bool IsDLLImport = RD->hasAttr<DLLImportAttr>();
David Majnemer1fb1a042014-11-07 07:26:38 +00002746 if (CGM.getVTables().isVTableExternal(RD))
Shoaib Meenai61118e72017-07-04 01:02:19 +00002747 return IsDLLImport && !CGM.getTriple().isWindowsItaniumEnvironment()
2748 ? false
2749 : true;
David Majnemer1fb1a042014-11-07 07:26:38 +00002750
David Majnemerbe9022c2015-08-06 20:56:55 +00002751 if (IsDLLImport)
David Majnemer1fb1a042014-11-07 07:26:38 +00002752 return true;
David Majnemere2cb8d12014-07-07 06:20:47 +00002753 }
2754
2755 return false;
2756}
2757
2758/// IsIncompleteClassType - Returns whether the given record type is incomplete.
2759static bool IsIncompleteClassType(const RecordType *RecordTy) {
2760 return !RecordTy->getDecl()->isCompleteDefinition();
2761}
2762
2763/// ContainsIncompleteClassType - Returns whether the given type contains an
2764/// incomplete class type. This is true if
2765///
2766/// * The given type is an incomplete class type.
2767/// * The given type is a pointer type whose pointee type contains an
2768/// incomplete class type.
2769/// * The given type is a member pointer type whose class is an incomplete
2770/// class type.
2771/// * The given type is a member pointer type whoise pointee type contains an
2772/// incomplete class type.
2773/// is an indirect or direct pointer to an incomplete class type.
2774static bool ContainsIncompleteClassType(QualType Ty) {
2775 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2776 if (IsIncompleteClassType(RecordTy))
2777 return true;
2778 }
2779
2780 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2781 return ContainsIncompleteClassType(PointerTy->getPointeeType());
2782
2783 if (const MemberPointerType *MemberPointerTy =
2784 dyn_cast<MemberPointerType>(Ty)) {
2785 // Check if the class type is incomplete.
2786 const RecordType *ClassType = cast<RecordType>(MemberPointerTy->getClass());
2787 if (IsIncompleteClassType(ClassType))
2788 return true;
2789
2790 return ContainsIncompleteClassType(MemberPointerTy->getPointeeType());
2791 }
2792
2793 return false;
2794}
2795
2796// CanUseSingleInheritance - Return whether the given record decl has a "single,
2797// public, non-virtual base at offset zero (i.e. the derived class is dynamic
2798// iff the base is)", according to Itanium C++ ABI, 2.95p6b.
2799static bool CanUseSingleInheritance(const CXXRecordDecl *RD) {
2800 // Check the number of bases.
2801 if (RD->getNumBases() != 1)
2802 return false;
2803
2804 // Get the base.
2805 CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin();
2806
2807 // Check that the base is not virtual.
2808 if (Base->isVirtual())
2809 return false;
2810
2811 // Check that the base is public.
2812 if (Base->getAccessSpecifier() != AS_public)
2813 return false;
2814
2815 // Check that the class is dynamic iff the base is.
2816 const CXXRecordDecl *BaseDecl =
2817 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2818 if (!BaseDecl->isEmpty() &&
2819 BaseDecl->isDynamicClass() != RD->isDynamicClass())
2820 return false;
2821
2822 return true;
2823}
2824
2825void ItaniumRTTIBuilder::BuildVTablePointer(const Type *Ty) {
2826 // abi::__class_type_info.
2827 static const char * const ClassTypeInfo =
2828 "_ZTVN10__cxxabiv117__class_type_infoE";
2829 // abi::__si_class_type_info.
2830 static const char * const SIClassTypeInfo =
2831 "_ZTVN10__cxxabiv120__si_class_type_infoE";
2832 // abi::__vmi_class_type_info.
2833 static const char * const VMIClassTypeInfo =
2834 "_ZTVN10__cxxabiv121__vmi_class_type_infoE";
2835
2836 const char *VTableName = nullptr;
2837
2838 switch (Ty->getTypeClass()) {
2839#define TYPE(Class, Base)
2840#define ABSTRACT_TYPE(Class, Base)
2841#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2842#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2843#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2844#include "clang/AST/TypeNodes.def"
2845 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
2846
2847 case Type::LValueReference:
2848 case Type::RValueReference:
2849 llvm_unreachable("References shouldn't get here");
2850
2851 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00002852 case Type::DeducedTemplateSpecialization:
2853 llvm_unreachable("Undeduced type shouldn't get here");
David Majnemere2cb8d12014-07-07 06:20:47 +00002854
Xiuli Pan9c14e282016-01-09 12:53:17 +00002855 case Type::Pipe:
2856 llvm_unreachable("Pipe types shouldn't get here");
2857
David Majnemere2cb8d12014-07-07 06:20:47 +00002858 case Type::Builtin:
2859 // GCC treats vector and complex types as fundamental types.
2860 case Type::Vector:
2861 case Type::ExtVector:
2862 case Type::Complex:
2863 case Type::Atomic:
2864 // FIXME: GCC treats block pointers as fundamental types?!
2865 case Type::BlockPointer:
2866 // abi::__fundamental_type_info.
2867 VTableName = "_ZTVN10__cxxabiv123__fundamental_type_infoE";
2868 break;
2869
2870 case Type::ConstantArray:
2871 case Type::IncompleteArray:
2872 case Type::VariableArray:
2873 // abi::__array_type_info.
2874 VTableName = "_ZTVN10__cxxabiv117__array_type_infoE";
2875 break;
2876
2877 case Type::FunctionNoProto:
2878 case Type::FunctionProto:
Richard Smithb17d6fa2016-12-01 03:04:07 +00002879 // abi::__function_type_info.
2880 VTableName = "_ZTVN10__cxxabiv120__function_type_infoE";
David Majnemere2cb8d12014-07-07 06:20:47 +00002881 break;
2882
2883 case Type::Enum:
2884 // abi::__enum_type_info.
2885 VTableName = "_ZTVN10__cxxabiv116__enum_type_infoE";
2886 break;
2887
2888 case Type::Record: {
2889 const CXXRecordDecl *RD =
2890 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
2891
2892 if (!RD->hasDefinition() || !RD->getNumBases()) {
2893 VTableName = ClassTypeInfo;
2894 } else if (CanUseSingleInheritance(RD)) {
2895 VTableName = SIClassTypeInfo;
2896 } else {
2897 VTableName = VMIClassTypeInfo;
2898 }
2899
2900 break;
2901 }
2902
2903 case Type::ObjCObject:
2904 // Ignore protocol qualifiers.
2905 Ty = cast<ObjCObjectType>(Ty)->getBaseType().getTypePtr();
2906
2907 // Handle id and Class.
2908 if (isa<BuiltinType>(Ty)) {
2909 VTableName = ClassTypeInfo;
2910 break;
2911 }
2912
2913 assert(isa<ObjCInterfaceType>(Ty));
2914 // Fall through.
2915
2916 case Type::ObjCInterface:
2917 if (cast<ObjCInterfaceType>(Ty)->getDecl()->getSuperClass()) {
2918 VTableName = SIClassTypeInfo;
2919 } else {
2920 VTableName = ClassTypeInfo;
2921 }
2922 break;
2923
2924 case Type::ObjCObjectPointer:
2925 case Type::Pointer:
2926 // abi::__pointer_type_info.
2927 VTableName = "_ZTVN10__cxxabiv119__pointer_type_infoE";
2928 break;
2929
2930 case Type::MemberPointer:
2931 // abi::__pointer_to_member_type_info.
2932 VTableName = "_ZTVN10__cxxabiv129__pointer_to_member_type_infoE";
2933 break;
2934 }
2935
2936 llvm::Constant *VTable =
2937 CGM.getModule().getOrInsertGlobal(VTableName, CGM.Int8PtrTy);
2938
2939 llvm::Type *PtrDiffTy =
2940 CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
2941
2942 // The vtable address point is 2.
2943 llvm::Constant *Two = llvm::ConstantInt::get(PtrDiffTy, 2);
David Blaikiee3b172a2015-04-02 18:55:21 +00002944 VTable =
2945 llvm::ConstantExpr::getInBoundsGetElementPtr(CGM.Int8PtrTy, VTable, Two);
David Majnemere2cb8d12014-07-07 06:20:47 +00002946 VTable = llvm::ConstantExpr::getBitCast(VTable, CGM.Int8PtrTy);
2947
2948 Fields.push_back(VTable);
2949}
2950
2951/// \brief Return the linkage that the type info and type info name constants
2952/// should have for the given type.
2953static llvm::GlobalVariable::LinkageTypes getTypeInfoLinkage(CodeGenModule &CGM,
2954 QualType Ty) {
2955 // Itanium C++ ABI 2.9.5p7:
2956 // In addition, it and all of the intermediate abi::__pointer_type_info
2957 // structs in the chain down to the abi::__class_type_info for the
2958 // incomplete class type must be prevented from resolving to the
2959 // corresponding type_info structs for the complete class type, possibly
2960 // by making them local static objects. Finally, a dummy class RTTI is
2961 // generated for the incomplete type that will not resolve to the final
2962 // complete class RTTI (because the latter need not exist), possibly by
2963 // making it a local static object.
2964 if (ContainsIncompleteClassType(Ty))
2965 return llvm::GlobalValue::InternalLinkage;
2966
2967 switch (Ty->getLinkage()) {
2968 case NoLinkage:
2969 case InternalLinkage:
2970 case UniqueExternalLinkage:
2971 return llvm::GlobalValue::InternalLinkage;
2972
2973 case VisibleNoLinkage:
Richard Smith1283e982017-07-07 20:04:28 +00002974 case ModuleInternalLinkage:
2975 case ModuleLinkage:
David Majnemere2cb8d12014-07-07 06:20:47 +00002976 case ExternalLinkage:
Saleem Abdulrasool18820022016-12-02 22:46:18 +00002977 // RTTI is not enabled, which means that this type info struct is going
2978 // to be used for exception handling. Give it linkonce_odr linkage.
2979 if (!CGM.getLangOpts().RTTI)
David Majnemere2cb8d12014-07-07 06:20:47 +00002980 return llvm::GlobalValue::LinkOnceODRLinkage;
David Majnemere2cb8d12014-07-07 06:20:47 +00002981
2982 if (const RecordType *Record = dyn_cast<RecordType>(Ty)) {
2983 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2984 if (RD->hasAttr<WeakAttr>())
2985 return llvm::GlobalValue::WeakODRLinkage;
Saleem Abdulrasool18820022016-12-02 22:46:18 +00002986 if (CGM.getTriple().isWindowsItaniumEnvironment())
Shoaib Meenai61118e72017-07-04 01:02:19 +00002987 if (RD->hasAttr<DLLImportAttr>() &&
2988 ShouldUseExternalRTTIDescriptor(CGM, Ty))
Saleem Abdulrasool18820022016-12-02 22:46:18 +00002989 return llvm::GlobalValue::ExternalLinkage;
David Majnemerbe9022c2015-08-06 20:56:55 +00002990 if (RD->isDynamicClass()) {
2991 llvm::GlobalValue::LinkageTypes LT = CGM.getVTableLinkage(RD);
2992 // MinGW won't export the RTTI information when there is a key function.
2993 // Make sure we emit our own copy instead of attempting to dllimport it.
2994 if (RD->hasAttr<DLLImportAttr>() &&
2995 llvm::GlobalValue::isAvailableExternallyLinkage(LT))
2996 LT = llvm::GlobalValue::LinkOnceODRLinkage;
2997 return LT;
2998 }
David Majnemere2cb8d12014-07-07 06:20:47 +00002999 }
3000
3001 return llvm::GlobalValue::LinkOnceODRLinkage;
3002 }
3003
3004 llvm_unreachable("Invalid linkage!");
3005}
3006
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00003007llvm::Constant *ItaniumRTTIBuilder::BuildTypeInfo(QualType Ty, bool Force,
3008 bool DLLExport) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003009 // We want to operate on the canonical type.
Yaron Kerenebd14262016-03-16 12:14:43 +00003010 Ty = Ty.getCanonicalType();
David Majnemere2cb8d12014-07-07 06:20:47 +00003011
3012 // Check if we've already emitted an RTTI descriptor for this type.
Yaron Kerene46f7ed2015-07-29 14:21:47 +00003013 SmallString<256> Name;
3014 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00003015 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00003016
3017 llvm::GlobalVariable *OldGV = CGM.getModule().getNamedGlobal(Name);
3018 if (OldGV && !OldGV->isDeclaration()) {
3019 assert(!OldGV->hasAvailableExternallyLinkage() &&
3020 "available_externally typeinfos not yet implemented");
3021
3022 return llvm::ConstantExpr::getBitCast(OldGV, CGM.Int8PtrTy);
3023 }
3024
3025 // Check if there is already an external RTTI descriptor for this type.
3026 bool IsStdLib = IsStandardLibraryRTTIDescriptor(Ty);
3027 if (!Force && (IsStdLib || ShouldUseExternalRTTIDescriptor(CGM, Ty)))
3028 return GetAddrOfExternalRTTIDescriptor(Ty);
3029
3030 // Emit the standard library with external linkage.
3031 llvm::GlobalVariable::LinkageTypes Linkage;
3032 if (IsStdLib)
3033 Linkage = llvm::GlobalValue::ExternalLinkage;
3034 else
3035 Linkage = getTypeInfoLinkage(CGM, Ty);
3036
3037 // Add the vtable pointer.
3038 BuildVTablePointer(cast<Type>(Ty));
3039
3040 // And the name.
3041 llvm::GlobalVariable *TypeName = GetAddrOfTypeName(Ty, Linkage);
3042 llvm::Constant *TypeNameField;
3043
3044 // If we're supposed to demote the visibility, be sure to set a flag
3045 // to use a string comparison for type_info comparisons.
3046 ItaniumCXXABI::RTTIUniquenessKind RTTIUniqueness =
3047 CXXABI.classifyRTTIUniqueness(Ty, Linkage);
3048 if (RTTIUniqueness != ItaniumCXXABI::RUK_Unique) {
3049 // The flag is the sign bit, which on ARM64 is defined to be clear
3050 // for global pointers. This is very ARM64-specific.
3051 TypeNameField = llvm::ConstantExpr::getPtrToInt(TypeName, CGM.Int64Ty);
3052 llvm::Constant *flag =
3053 llvm::ConstantInt::get(CGM.Int64Ty, ((uint64_t)1) << 63);
3054 TypeNameField = llvm::ConstantExpr::getAdd(TypeNameField, flag);
3055 TypeNameField =
3056 llvm::ConstantExpr::getIntToPtr(TypeNameField, CGM.Int8PtrTy);
3057 } else {
3058 TypeNameField = llvm::ConstantExpr::getBitCast(TypeName, CGM.Int8PtrTy);
3059 }
3060 Fields.push_back(TypeNameField);
3061
3062 switch (Ty->getTypeClass()) {
3063#define TYPE(Class, Base)
3064#define ABSTRACT_TYPE(Class, Base)
3065#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
3066#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3067#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3068#include "clang/AST/TypeNodes.def"
3069 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
3070
3071 // GCC treats vector types as fundamental types.
3072 case Type::Builtin:
3073 case Type::Vector:
3074 case Type::ExtVector:
3075 case Type::Complex:
3076 case Type::BlockPointer:
3077 // Itanium C++ ABI 2.9.5p4:
3078 // abi::__fundamental_type_info adds no data members to std::type_info.
3079 break;
3080
3081 case Type::LValueReference:
3082 case Type::RValueReference:
3083 llvm_unreachable("References shouldn't get here");
3084
3085 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00003086 case Type::DeducedTemplateSpecialization:
3087 llvm_unreachable("Undeduced type shouldn't get here");
David Majnemere2cb8d12014-07-07 06:20:47 +00003088
Xiuli Pan9c14e282016-01-09 12:53:17 +00003089 case Type::Pipe:
3090 llvm_unreachable("Pipe type shouldn't get here");
3091
David Majnemere2cb8d12014-07-07 06:20:47 +00003092 case Type::ConstantArray:
3093 case Type::IncompleteArray:
3094 case Type::VariableArray:
3095 // Itanium C++ ABI 2.9.5p5:
3096 // abi::__array_type_info adds no data members to std::type_info.
3097 break;
3098
3099 case Type::FunctionNoProto:
Richard Smithb17d6fa2016-12-01 03:04:07 +00003100 case Type::FunctionProto:
David Majnemere2cb8d12014-07-07 06:20:47 +00003101 // Itanium C++ ABI 2.9.5p5:
3102 // abi::__function_type_info adds no data members to std::type_info.
3103 break;
3104
3105 case Type::Enum:
3106 // Itanium C++ ABI 2.9.5p5:
3107 // abi::__enum_type_info adds no data members to std::type_info.
3108 break;
3109
3110 case Type::Record: {
3111 const CXXRecordDecl *RD =
3112 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
3113 if (!RD->hasDefinition() || !RD->getNumBases()) {
3114 // We don't need to emit any fields.
3115 break;
3116 }
3117
3118 if (CanUseSingleInheritance(RD))
3119 BuildSIClassTypeInfo(RD);
3120 else
3121 BuildVMIClassTypeInfo(RD);
3122
3123 break;
3124 }
3125
3126 case Type::ObjCObject:
3127 case Type::ObjCInterface:
3128 BuildObjCObjectTypeInfo(cast<ObjCObjectType>(Ty));
3129 break;
3130
3131 case Type::ObjCObjectPointer:
3132 BuildPointerTypeInfo(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
3133 break;
3134
3135 case Type::Pointer:
3136 BuildPointerTypeInfo(cast<PointerType>(Ty)->getPointeeType());
3137 break;
3138
3139 case Type::MemberPointer:
3140 BuildPointerToMemberTypeInfo(cast<MemberPointerType>(Ty));
3141 break;
3142
3143 case Type::Atomic:
3144 // No fields, at least for the moment.
3145 break;
3146 }
3147
3148 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Fields);
3149
Rafael Espindolacb92c192015-01-15 23:18:01 +00003150 llvm::Module &M = CGM.getModule();
David Majnemere2cb8d12014-07-07 06:20:47 +00003151 llvm::GlobalVariable *GV =
Rafael Espindolacb92c192015-01-15 23:18:01 +00003152 new llvm::GlobalVariable(M, Init->getType(),
3153 /*Constant=*/true, Linkage, Init, Name);
3154
David Majnemere2cb8d12014-07-07 06:20:47 +00003155 // If there's already an old global variable, replace it with the new one.
3156 if (OldGV) {
3157 GV->takeName(OldGV);
3158 llvm::Constant *NewPtr =
3159 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
3160 OldGV->replaceAllUsesWith(NewPtr);
3161 OldGV->eraseFromParent();
3162 }
3163
Yaron Keren04da2382015-07-29 15:42:28 +00003164 if (CGM.supportsCOMDAT() && GV->isWeakForLinker())
3165 GV->setComdat(M.getOrInsertComdat(GV->getName()));
3166
David Majnemere2cb8d12014-07-07 06:20:47 +00003167 // The Itanium ABI specifies that type_info objects must be globally
3168 // unique, with one exception: if the type is an incomplete class
3169 // type or a (possibly indirect) pointer to one. That exception
3170 // affects the general case of comparing type_info objects produced
3171 // by the typeid operator, which is why the comparison operators on
3172 // std::type_info generally use the type_info name pointers instead
3173 // of the object addresses. However, the language's built-in uses
3174 // of RTTI generally require class types to be complete, even when
3175 // manipulating pointers to those class types. This allows the
3176 // implementation of dynamic_cast to rely on address equality tests,
3177 // which is much faster.
3178
3179 // All of this is to say that it's important that both the type_info
3180 // object and the type_info name be uniqued when weakly emitted.
3181
3182 // Give the type_info object and name the formal visibility of the
3183 // type itself.
3184 llvm::GlobalValue::VisibilityTypes llvmVisibility;
3185 if (llvm::GlobalValue::isLocalLinkage(Linkage))
3186 // If the linkage is local, only default visibility makes sense.
3187 llvmVisibility = llvm::GlobalValue::DefaultVisibility;
3188 else if (RTTIUniqueness == ItaniumCXXABI::RUK_NonUniqueHidden)
3189 llvmVisibility = llvm::GlobalValue::HiddenVisibility;
3190 else
3191 llvmVisibility = CodeGenModule::GetLLVMVisibility(Ty->getVisibility());
Saleem Abdulrasool18820022016-12-02 22:46:18 +00003192
David Majnemere2cb8d12014-07-07 06:20:47 +00003193 TypeName->setVisibility(llvmVisibility);
3194 GV->setVisibility(llvmVisibility);
Saleem Abdulrasool18820022016-12-02 22:46:18 +00003195
3196 if (CGM.getTriple().isWindowsItaniumEnvironment()) {
3197 auto RD = Ty->getAsCXXRecordDecl();
3198 if (DLLExport || (RD && RD->hasAttr<DLLExportAttr>())) {
3199 TypeName->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
3200 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
Shoaib Meenai61118e72017-07-04 01:02:19 +00003201 } else if (RD && RD->hasAttr<DLLImportAttr>() &&
3202 ShouldUseExternalRTTIDescriptor(CGM, Ty)) {
Saleem Abdulrasool18820022016-12-02 22:46:18 +00003203 TypeName->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
3204 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
3205
3206 // Because the typename and the typeinfo are DLL import, convert them to
3207 // declarations rather than definitions. The initializers still need to
3208 // be constructed to calculate the type for the declarations.
3209 TypeName->setInitializer(nullptr);
3210 GV->setInitializer(nullptr);
3211 }
3212 }
David Majnemere2cb8d12014-07-07 06:20:47 +00003213
3214 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
3215}
3216
David Majnemere2cb8d12014-07-07 06:20:47 +00003217/// BuildObjCObjectTypeInfo - Build the appropriate kind of type_info
3218/// for the given Objective-C object type.
3219void ItaniumRTTIBuilder::BuildObjCObjectTypeInfo(const ObjCObjectType *OT) {
3220 // Drop qualifiers.
3221 const Type *T = OT->getBaseType().getTypePtr();
3222 assert(isa<BuiltinType>(T) || isa<ObjCInterfaceType>(T));
3223
3224 // The builtin types are abi::__class_type_infos and don't require
3225 // extra fields.
3226 if (isa<BuiltinType>(T)) return;
3227
3228 ObjCInterfaceDecl *Class = cast<ObjCInterfaceType>(T)->getDecl();
3229 ObjCInterfaceDecl *Super = Class->getSuperClass();
3230
3231 // Root classes are also __class_type_info.
3232 if (!Super) return;
3233
3234 QualType SuperTy = CGM.getContext().getObjCInterfaceType(Super);
3235
3236 // Everything else is single inheritance.
3237 llvm::Constant *BaseTypeInfo =
3238 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(SuperTy);
3239 Fields.push_back(BaseTypeInfo);
3240}
3241
3242/// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
3243/// inheritance, according to the Itanium C++ ABI, 2.95p6b.
3244void ItaniumRTTIBuilder::BuildSIClassTypeInfo(const CXXRecordDecl *RD) {
3245 // Itanium C++ ABI 2.9.5p6b:
3246 // It adds to abi::__class_type_info a single member pointing to the
3247 // type_info structure for the base type,
3248 llvm::Constant *BaseTypeInfo =
3249 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(RD->bases_begin()->getType());
3250 Fields.push_back(BaseTypeInfo);
3251}
3252
3253namespace {
3254 /// SeenBases - Contains virtual and non-virtual bases seen when traversing
3255 /// a class hierarchy.
3256 struct SeenBases {
3257 llvm::SmallPtrSet<const CXXRecordDecl *, 16> NonVirtualBases;
3258 llvm::SmallPtrSet<const CXXRecordDecl *, 16> VirtualBases;
3259 };
3260}
3261
3262/// ComputeVMIClassTypeInfoFlags - Compute the value of the flags member in
3263/// abi::__vmi_class_type_info.
3264///
3265static unsigned ComputeVMIClassTypeInfoFlags(const CXXBaseSpecifier *Base,
3266 SeenBases &Bases) {
3267
3268 unsigned Flags = 0;
3269
3270 const CXXRecordDecl *BaseDecl =
3271 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
3272
3273 if (Base->isVirtual()) {
3274 // Mark the virtual base as seen.
David Blaikie82e95a32014-11-19 07:49:47 +00003275 if (!Bases.VirtualBases.insert(BaseDecl).second) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003276 // If this virtual base has been seen before, then the class is diamond
3277 // shaped.
3278 Flags |= ItaniumRTTIBuilder::VMI_DiamondShaped;
3279 } else {
3280 if (Bases.NonVirtualBases.count(BaseDecl))
3281 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3282 }
3283 } else {
3284 // Mark the non-virtual base as seen.
David Blaikie82e95a32014-11-19 07:49:47 +00003285 if (!Bases.NonVirtualBases.insert(BaseDecl).second) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003286 // If this non-virtual base has been seen before, then the class has non-
3287 // diamond shaped repeated inheritance.
3288 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3289 } else {
3290 if (Bases.VirtualBases.count(BaseDecl))
3291 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3292 }
3293 }
3294
3295 // Walk all bases.
3296 for (const auto &I : BaseDecl->bases())
3297 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
3298
3299 return Flags;
3300}
3301
3302static unsigned ComputeVMIClassTypeInfoFlags(const CXXRecordDecl *RD) {
3303 unsigned Flags = 0;
3304 SeenBases Bases;
3305
3306 // Walk all bases.
3307 for (const auto &I : RD->bases())
3308 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
3309
3310 return Flags;
3311}
3312
3313/// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
3314/// classes with bases that do not satisfy the abi::__si_class_type_info
3315/// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
3316void ItaniumRTTIBuilder::BuildVMIClassTypeInfo(const CXXRecordDecl *RD) {
3317 llvm::Type *UnsignedIntLTy =
3318 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3319
3320 // Itanium C++ ABI 2.9.5p6c:
3321 // __flags is a word with flags describing details about the class
3322 // structure, which may be referenced by using the __flags_masks
3323 // enumeration. These flags refer to both direct and indirect bases.
3324 unsigned Flags = ComputeVMIClassTypeInfoFlags(RD);
3325 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3326
3327 // Itanium C++ ABI 2.9.5p6c:
3328 // __base_count is a word with the number of direct proper base class
3329 // descriptions that follow.
3330 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, RD->getNumBases()));
3331
3332 if (!RD->getNumBases())
3333 return;
3334
David Majnemere2cb8d12014-07-07 06:20:47 +00003335 // Now add the base class descriptions.
3336
3337 // Itanium C++ ABI 2.9.5p6c:
3338 // __base_info[] is an array of base class descriptions -- one for every
3339 // direct proper base. Each description is of the type:
3340 //
3341 // struct abi::__base_class_type_info {
3342 // public:
3343 // const __class_type_info *__base_type;
3344 // long __offset_flags;
3345 //
3346 // enum __offset_flags_masks {
3347 // __virtual_mask = 0x1,
3348 // __public_mask = 0x2,
3349 // __offset_shift = 8
3350 // };
3351 // };
Reid Klecknerd8b04662016-08-25 22:16:30 +00003352
3353 // If we're in mingw and 'long' isn't wide enough for a pointer, use 'long
3354 // long' instead of 'long' for __offset_flags. libstdc++abi uses long long on
3355 // LLP64 platforms.
3356 // FIXME: Consider updating libc++abi to match, and extend this logic to all
3357 // LLP64 platforms.
3358 QualType OffsetFlagsTy = CGM.getContext().LongTy;
3359 const TargetInfo &TI = CGM.getContext().getTargetInfo();
3360 if (TI.getTriple().isOSCygMing() && TI.getPointerWidth(0) > TI.getLongWidth())
3361 OffsetFlagsTy = CGM.getContext().LongLongTy;
3362 llvm::Type *OffsetFlagsLTy =
3363 CGM.getTypes().ConvertType(OffsetFlagsTy);
3364
David Majnemere2cb8d12014-07-07 06:20:47 +00003365 for (const auto &Base : RD->bases()) {
3366 // The __base_type member points to the RTTI for the base type.
3367 Fields.push_back(ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(Base.getType()));
3368
3369 const CXXRecordDecl *BaseDecl =
3370 cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
3371
3372 int64_t OffsetFlags = 0;
3373
3374 // All but the lower 8 bits of __offset_flags are a signed offset.
3375 // For a non-virtual base, this is the offset in the object of the base
3376 // subobject. For a virtual base, this is the offset in the virtual table of
3377 // the virtual base offset for the virtual base referenced (negative).
3378 CharUnits Offset;
3379 if (Base.isVirtual())
3380 Offset =
3381 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(RD, BaseDecl);
3382 else {
3383 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
3384 Offset = Layout.getBaseClassOffset(BaseDecl);
3385 };
3386
3387 OffsetFlags = uint64_t(Offset.getQuantity()) << 8;
3388
3389 // The low-order byte of __offset_flags contains flags, as given by the
3390 // masks from the enumeration __offset_flags_masks.
3391 if (Base.isVirtual())
3392 OffsetFlags |= BCTI_Virtual;
3393 if (Base.getAccessSpecifier() == AS_public)
3394 OffsetFlags |= BCTI_Public;
3395
Reid Klecknerd8b04662016-08-25 22:16:30 +00003396 Fields.push_back(llvm::ConstantInt::get(OffsetFlagsLTy, OffsetFlags));
David Majnemere2cb8d12014-07-07 06:20:47 +00003397 }
3398}
3399
Richard Smitha7d93782016-12-01 03:32:42 +00003400/// Compute the flags for a __pbase_type_info, and remove the corresponding
3401/// pieces from \p Type.
3402static unsigned extractPBaseFlags(ASTContext &Ctx, QualType &Type) {
3403 unsigned Flags = 0;
David Majnemere2cb8d12014-07-07 06:20:47 +00003404
Richard Smitha7d93782016-12-01 03:32:42 +00003405 if (Type.isConstQualified())
3406 Flags |= ItaniumRTTIBuilder::PTI_Const;
3407 if (Type.isVolatileQualified())
3408 Flags |= ItaniumRTTIBuilder::PTI_Volatile;
3409 if (Type.isRestrictQualified())
3410 Flags |= ItaniumRTTIBuilder::PTI_Restrict;
3411 Type = Type.getUnqualifiedType();
David Majnemere2cb8d12014-07-07 06:20:47 +00003412
3413 // Itanium C++ ABI 2.9.5p7:
3414 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
3415 // incomplete class type, the incomplete target type flag is set.
Richard Smitha7d93782016-12-01 03:32:42 +00003416 if (ContainsIncompleteClassType(Type))
3417 Flags |= ItaniumRTTIBuilder::PTI_Incomplete;
3418
3419 if (auto *Proto = Type->getAs<FunctionProtoType>()) {
3420 if (Proto->isNothrow(Ctx)) {
3421 Flags |= ItaniumRTTIBuilder::PTI_Noexcept;
3422 Type = Ctx.getFunctionType(
3423 Proto->getReturnType(), Proto->getParamTypes(),
3424 Proto->getExtProtoInfo().withExceptionSpec(EST_None));
3425 }
3426 }
3427
3428 return Flags;
3429}
3430
3431/// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct,
3432/// used for pointer types.
3433void ItaniumRTTIBuilder::BuildPointerTypeInfo(QualType PointeeTy) {
3434 // Itanium C++ ABI 2.9.5p7:
3435 // __flags is a flag word describing the cv-qualification and other
3436 // attributes of the type pointed to
3437 unsigned Flags = extractPBaseFlags(CGM.getContext(), PointeeTy);
David Majnemere2cb8d12014-07-07 06:20:47 +00003438
3439 llvm::Type *UnsignedIntLTy =
3440 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3441 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3442
3443 // Itanium C++ ABI 2.9.5p7:
3444 // __pointee is a pointer to the std::type_info derivation for the
3445 // unqualified type being pointed to.
3446 llvm::Constant *PointeeTypeInfo =
Richard Smitha7d93782016-12-01 03:32:42 +00003447 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(PointeeTy);
David Majnemere2cb8d12014-07-07 06:20:47 +00003448 Fields.push_back(PointeeTypeInfo);
3449}
3450
3451/// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
3452/// struct, used for member pointer types.
3453void
3454ItaniumRTTIBuilder::BuildPointerToMemberTypeInfo(const MemberPointerType *Ty) {
3455 QualType PointeeTy = Ty->getPointeeType();
3456
David Majnemere2cb8d12014-07-07 06:20:47 +00003457 // Itanium C++ ABI 2.9.5p7:
3458 // __flags is a flag word describing the cv-qualification and other
3459 // attributes of the type pointed to.
Richard Smitha7d93782016-12-01 03:32:42 +00003460 unsigned Flags = extractPBaseFlags(CGM.getContext(), PointeeTy);
David Majnemere2cb8d12014-07-07 06:20:47 +00003461
3462 const RecordType *ClassType = cast<RecordType>(Ty->getClass());
David Majnemere2cb8d12014-07-07 06:20:47 +00003463 if (IsIncompleteClassType(ClassType))
3464 Flags |= PTI_ContainingClassIncomplete;
3465
3466 llvm::Type *UnsignedIntLTy =
3467 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3468 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3469
3470 // Itanium C++ ABI 2.9.5p7:
3471 // __pointee is a pointer to the std::type_info derivation for the
3472 // unqualified type being pointed to.
3473 llvm::Constant *PointeeTypeInfo =
Richard Smitha7d93782016-12-01 03:32:42 +00003474 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(PointeeTy);
David Majnemere2cb8d12014-07-07 06:20:47 +00003475 Fields.push_back(PointeeTypeInfo);
3476
3477 // Itanium C++ ABI 2.9.5p9:
3478 // __context is a pointer to an abi::__class_type_info corresponding to the
3479 // class type containing the member pointed to
3480 // (e.g., the "A" in "int A::*").
3481 Fields.push_back(
3482 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(QualType(ClassType, 0)));
3483}
3484
David Majnemer443250f2015-03-17 20:35:00 +00003485llvm::Constant *ItaniumCXXABI::getAddrOfRTTIDescriptor(QualType Ty) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003486 return ItaniumRTTIBuilder(*this).BuildTypeInfo(Ty);
3487}
3488
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00003489void ItaniumCXXABI::EmitFundamentalRTTIDescriptor(QualType Type,
3490 bool DLLExport) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003491 QualType PointerType = getContext().getPointerType(Type);
3492 QualType PointerTypeConst = getContext().getPointerType(Type.withConst());
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00003493 ItaniumRTTIBuilder(*this).BuildTypeInfo(Type, /*Force=*/true, DLLExport);
3494 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerType, /*Force=*/true,
3495 DLLExport);
3496 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerTypeConst, /*Force=*/true,
3497 DLLExport);
David Majnemere2cb8d12014-07-07 06:20:47 +00003498}
3499
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00003500void ItaniumCXXABI::EmitFundamentalRTTIDescriptors(bool DLLExport) {
Richard Smith4a382012016-02-03 01:32:42 +00003501 // Types added here must also be added to TypeInfoIsInStandardLibrary.
David Majnemere2cb8d12014-07-07 06:20:47 +00003502 QualType FundamentalTypes[] = {
3503 getContext().VoidTy, getContext().NullPtrTy,
3504 getContext().BoolTy, getContext().WCharTy,
3505 getContext().CharTy, getContext().UnsignedCharTy,
3506 getContext().SignedCharTy, getContext().ShortTy,
3507 getContext().UnsignedShortTy, getContext().IntTy,
3508 getContext().UnsignedIntTy, getContext().LongTy,
3509 getContext().UnsignedLongTy, getContext().LongLongTy,
Richard Smith4a382012016-02-03 01:32:42 +00003510 getContext().UnsignedLongLongTy, getContext().Int128Ty,
3511 getContext().UnsignedInt128Ty, getContext().HalfTy,
David Majnemere2cb8d12014-07-07 06:20:47 +00003512 getContext().FloatTy, getContext().DoubleTy,
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00003513 getContext().LongDoubleTy, getContext().Float128Ty,
3514 getContext().Char16Ty, getContext().Char32Ty
David Majnemere2cb8d12014-07-07 06:20:47 +00003515 };
3516 for (const QualType &FundamentalType : FundamentalTypes)
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00003517 EmitFundamentalRTTIDescriptor(FundamentalType, DLLExport);
David Majnemere2cb8d12014-07-07 06:20:47 +00003518}
3519
3520/// What sort of uniqueness rules should we use for the RTTI for the
3521/// given type?
3522ItaniumCXXABI::RTTIUniquenessKind ItaniumCXXABI::classifyRTTIUniqueness(
3523 QualType CanTy, llvm::GlobalValue::LinkageTypes Linkage) const {
3524 if (shouldRTTIBeUnique())
3525 return RUK_Unique;
3526
3527 // It's only necessary for linkonce_odr or weak_odr linkage.
3528 if (Linkage != llvm::GlobalValue::LinkOnceODRLinkage &&
3529 Linkage != llvm::GlobalValue::WeakODRLinkage)
3530 return RUK_Unique;
3531
3532 // It's only necessary with default visibility.
3533 if (CanTy->getVisibility() != DefaultVisibility)
3534 return RUK_Unique;
3535
3536 // If we're not required to publish this symbol, hide it.
3537 if (Linkage == llvm::GlobalValue::LinkOnceODRLinkage)
3538 return RUK_NonUniqueHidden;
3539
3540 // If we're required to publish this symbol, as we might be under an
3541 // explicit instantiation, leave it with default visibility but
3542 // enable string-comparisons.
3543 assert(Linkage == llvm::GlobalValue::WeakODRLinkage);
3544 return RUK_NonUniqueVisible;
3545}
Rafael Espindola91f68b42014-09-15 19:20:10 +00003546
Rafael Espindola1e4df922014-09-16 15:18:21 +00003547// Find out how to codegen the complete destructor and constructor
3548namespace {
3549enum class StructorCodegen { Emit, RAUW, Alias, COMDAT };
3550}
3551static StructorCodegen getCodegenToUse(CodeGenModule &CGM,
3552 const CXXMethodDecl *MD) {
3553 if (!CGM.getCodeGenOpts().CXXCtorDtorAliases)
3554 return StructorCodegen::Emit;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003555
Rafael Espindola1e4df922014-09-16 15:18:21 +00003556 // The complete and base structors are not equivalent if there are any virtual
3557 // bases, so emit separate functions.
3558 if (MD->getParent()->getNumVBases())
3559 return StructorCodegen::Emit;
3560
3561 GlobalDecl AliasDecl;
3562 if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) {
3563 AliasDecl = GlobalDecl(DD, Dtor_Complete);
3564 } else {
3565 const auto *CD = cast<CXXConstructorDecl>(MD);
3566 AliasDecl = GlobalDecl(CD, Ctor_Complete);
3567 }
3568 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3569
3570 if (llvm::GlobalValue::isDiscardableIfUnused(Linkage))
3571 return StructorCodegen::RAUW;
3572
3573 // FIXME: Should we allow available_externally aliases?
3574 if (!llvm::GlobalAlias::isValidLinkage(Linkage))
3575 return StructorCodegen::RAUW;
3576
Rafael Espindola0806f982014-09-16 20:19:43 +00003577 if (llvm::GlobalValue::isWeakForLinker(Linkage)) {
Dan Gohman839f2152017-01-17 21:46:38 +00003578 // Only ELF and wasm support COMDATs with arbitrary names (C5/D5).
3579 if (CGM.getTarget().getTriple().isOSBinFormatELF() ||
3580 CGM.getTarget().getTriple().isOSBinFormatWasm())
Rafael Espindola0806f982014-09-16 20:19:43 +00003581 return StructorCodegen::COMDAT;
3582 return StructorCodegen::Emit;
3583 }
Rafael Espindola1e4df922014-09-16 15:18:21 +00003584
3585 return StructorCodegen::Alias;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003586}
3587
Rafael Espindola1e4df922014-09-16 15:18:21 +00003588static void emitConstructorDestructorAlias(CodeGenModule &CGM,
3589 GlobalDecl AliasDecl,
3590 GlobalDecl TargetDecl) {
3591 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3592
3593 StringRef MangledName = CGM.getMangledName(AliasDecl);
3594 llvm::GlobalValue *Entry = CGM.GetGlobalValue(MangledName);
3595 if (Entry && !Entry->isDeclaration())
3596 return;
3597
3598 auto *Aliasee = cast<llvm::GlobalValue>(CGM.GetAddrOfGlobal(TargetDecl));
Rafael Espindola1e4df922014-09-16 15:18:21 +00003599
3600 // Create the alias with no name.
David Blaikie2a791d72015-09-14 18:38:22 +00003601 auto *Alias = llvm::GlobalAlias::create(Linkage, "", Aliasee);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003602
3603 // Switch any previous uses to the alias.
3604 if (Entry) {
NAKAMURA Takumie9621042015-09-15 01:39:27 +00003605 assert(Entry->getType() == Aliasee->getType() &&
Rafael Espindola1e4df922014-09-16 15:18:21 +00003606 "declaration exists with different type");
3607 Alias->takeName(Entry);
3608 Entry->replaceAllUsesWith(Alias);
3609 Entry->eraseFromParent();
3610 } else {
3611 Alias->setName(MangledName);
3612 }
3613
3614 // Finally, set up the alias with its proper name and attributes.
Dario Domiziolic4fb8ca72014-09-19 22:06:24 +00003615 CGM.setAliasAttributes(cast<NamedDecl>(AliasDecl.getDecl()), Alias);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003616}
3617
3618void ItaniumCXXABI::emitCXXStructor(const CXXMethodDecl *MD,
3619 StructorType Type) {
3620 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
3621 const CXXDestructorDecl *DD = CD ? nullptr : cast<CXXDestructorDecl>(MD);
3622
3623 StructorCodegen CGType = getCodegenToUse(CGM, MD);
3624
3625 if (Type == StructorType::Complete) {
3626 GlobalDecl CompleteDecl;
3627 GlobalDecl BaseDecl;
3628 if (CD) {
3629 CompleteDecl = GlobalDecl(CD, Ctor_Complete);
3630 BaseDecl = GlobalDecl(CD, Ctor_Base);
3631 } else {
3632 CompleteDecl = GlobalDecl(DD, Dtor_Complete);
3633 BaseDecl = GlobalDecl(DD, Dtor_Base);
3634 }
3635
3636 if (CGType == StructorCodegen::Alias || CGType == StructorCodegen::COMDAT) {
3637 emitConstructorDestructorAlias(CGM, CompleteDecl, BaseDecl);
3638 return;
3639 }
3640
3641 if (CGType == StructorCodegen::RAUW) {
3642 StringRef MangledName = CGM.getMangledName(CompleteDecl);
Andrey Bokhankocab58582015-08-31 13:20:44 +00003643 auto *Aliasee = CGM.GetAddrOfGlobal(BaseDecl);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003644 CGM.addReplacement(MangledName, Aliasee);
3645 return;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003646 }
3647 }
3648
3649 // The base destructor is equivalent to the base destructor of its
3650 // base class if there is exactly one non-virtual base class with a
3651 // non-trivial destructor, there are no fields with a non-trivial
3652 // destructor, and the body of the destructor is trivial.
Rafael Espindola1e4df922014-09-16 15:18:21 +00003653 if (DD && Type == StructorType::Base && CGType != StructorCodegen::COMDAT &&
3654 !CGM.TryEmitBaseDestructorAsAlias(DD))
Rafael Espindola91f68b42014-09-15 19:20:10 +00003655 return;
3656
Rafael Espindola1e4df922014-09-16 15:18:21 +00003657 llvm::Function *Fn = CGM.codegenCXXStructor(MD, Type);
Rafael Espindola91f68b42014-09-15 19:20:10 +00003658
Rafael Espindola1e4df922014-09-16 15:18:21 +00003659 if (CGType == StructorCodegen::COMDAT) {
3660 SmallString<256> Buffer;
3661 llvm::raw_svector_ostream Out(Buffer);
3662 if (DD)
3663 getMangleContext().mangleCXXDtorComdat(DD, Out);
3664 else
3665 getMangleContext().mangleCXXCtorComdat(CD, Out);
3666 llvm::Comdat *C = CGM.getModule().getOrInsertComdat(Out.str());
3667 Fn->setComdat(C);
Rafael Espindoladbee8a72015-01-15 21:36:08 +00003668 } else {
3669 CGM.maybeSetTrivialComdat(*MD, *Fn);
Rafael Espindola91f68b42014-09-15 19:20:10 +00003670 }
Rafael Espindola91f68b42014-09-15 19:20:10 +00003671}
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003672
3673static llvm::Constant *getBeginCatchFn(CodeGenModule &CGM) {
3674 // void *__cxa_begin_catch(void*);
3675 llvm::FunctionType *FTy = llvm::FunctionType::get(
3676 CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3677
3678 return CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
3679}
3680
3681static llvm::Constant *getEndCatchFn(CodeGenModule &CGM) {
3682 // void __cxa_end_catch();
3683 llvm::FunctionType *FTy =
3684 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
3685
3686 return CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
3687}
3688
3689static llvm::Constant *getGetExceptionPtrFn(CodeGenModule &CGM) {
3690 // void *__cxa_get_exception_ptr(void*);
3691 llvm::FunctionType *FTy = llvm::FunctionType::get(
3692 CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3693
3694 return CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
3695}
3696
3697namespace {
3698 /// A cleanup to call __cxa_end_catch. In many cases, the caught
3699 /// exception type lets us state definitively that the thrown exception
3700 /// type does not have a destructor. In particular:
3701 /// - Catch-alls tell us nothing, so we have to conservatively
3702 /// assume that the thrown exception might have a destructor.
3703 /// - Catches by reference behave according to their base types.
3704 /// - Catches of non-record types will only trigger for exceptions
3705 /// of non-record types, which never have destructors.
3706 /// - Catches of record types can trigger for arbitrary subclasses
3707 /// of the caught type, so we have to assume the actual thrown
3708 /// exception type might have a throwing destructor, even if the
3709 /// caught type's destructor is trivial or nothrow.
David Blaikie7e70d682015-08-18 22:40:54 +00003710 struct CallEndCatch final : EHScopeStack::Cleanup {
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003711 CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
3712 bool MightThrow;
3713
3714 void Emit(CodeGenFunction &CGF, Flags flags) override {
3715 if (!MightThrow) {
3716 CGF.EmitNounwindRuntimeCall(getEndCatchFn(CGF.CGM));
3717 return;
3718 }
3719
3720 CGF.EmitRuntimeCallOrInvoke(getEndCatchFn(CGF.CGM));
3721 }
3722 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003723}
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003724
3725/// Emits a call to __cxa_begin_catch and enters a cleanup to call
3726/// __cxa_end_catch.
3727///
3728/// \param EndMightThrow - true if __cxa_end_catch might throw
3729static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
3730 llvm::Value *Exn,
3731 bool EndMightThrow) {
3732 llvm::CallInst *call =
3733 CGF.EmitNounwindRuntimeCall(getBeginCatchFn(CGF.CGM), Exn);
3734
3735 CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
3736
3737 return call;
3738}
3739
3740/// A "special initializer" callback for initializing a catch
3741/// parameter during catch initialization.
3742static void InitCatchParam(CodeGenFunction &CGF,
3743 const VarDecl &CatchParam,
John McCall7f416cc2015-09-08 08:05:57 +00003744 Address ParamAddr,
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003745 SourceLocation Loc) {
3746 // Load the exception from where the landing pad saved it.
3747 llvm::Value *Exn = CGF.getExceptionFromSlot();
3748
3749 CanQualType CatchType =
3750 CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
3751 llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
3752
3753 // If we're catching by reference, we can just cast the object
3754 // pointer to the appropriate pointer.
3755 if (isa<ReferenceType>(CatchType)) {
3756 QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
3757 bool EndCatchMightThrow = CaughtType->isRecordType();
3758
3759 // __cxa_begin_catch returns the adjusted object pointer.
3760 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
3761
3762 // We have no way to tell the personality function that we're
3763 // catching by reference, so if we're catching a pointer,
3764 // __cxa_begin_catch will actually return that pointer by value.
3765 if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
3766 QualType PointeeType = PT->getPointeeType();
3767
3768 // When catching by reference, generally we should just ignore
3769 // this by-value pointer and use the exception object instead.
3770 if (!PointeeType->isRecordType()) {
3771
3772 // Exn points to the struct _Unwind_Exception header, which
3773 // we have to skip past in order to reach the exception data.
3774 unsigned HeaderSize =
3775 CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
3776 AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
3777
3778 // However, if we're catching a pointer-to-record type that won't
3779 // work, because the personality function might have adjusted
3780 // the pointer. There's actually no way for us to fully satisfy
3781 // the language/ABI contract here: we can't use Exn because it
3782 // might have the wrong adjustment, but we can't use the by-value
3783 // pointer because it's off by a level of abstraction.
3784 //
3785 // The current solution is to dump the adjusted pointer into an
3786 // alloca, which breaks language semantics (because changing the
3787 // pointer doesn't change the exception) but at least works.
3788 // The better solution would be to filter out non-exact matches
3789 // and rethrow them, but this is tricky because the rethrow
3790 // really needs to be catchable by other sites at this landing
3791 // pad. The best solution is to fix the personality function.
3792 } else {
3793 // Pull the pointer for the reference type off.
3794 llvm::Type *PtrTy =
3795 cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
3796
3797 // Create the temporary and write the adjusted pointer into it.
John McCall7f416cc2015-09-08 08:05:57 +00003798 Address ExnPtrTmp =
3799 CGF.CreateTempAlloca(PtrTy, CGF.getPointerAlign(), "exn.byref.tmp");
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003800 llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
3801 CGF.Builder.CreateStore(Casted, ExnPtrTmp);
3802
3803 // Bind the reference to the temporary.
John McCall7f416cc2015-09-08 08:05:57 +00003804 AdjustedExn = ExnPtrTmp.getPointer();
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003805 }
3806 }
3807
3808 llvm::Value *ExnCast =
3809 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
3810 CGF.Builder.CreateStore(ExnCast, ParamAddr);
3811 return;
3812 }
3813
3814 // Scalars and complexes.
3815 TypeEvaluationKind TEK = CGF.getEvaluationKind(CatchType);
3816 if (TEK != TEK_Aggregate) {
3817 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
3818
3819 // If the catch type is a pointer type, __cxa_begin_catch returns
3820 // the pointer by value.
3821 if (CatchType->hasPointerRepresentation()) {
3822 llvm::Value *CastExn =
3823 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
3824
3825 switch (CatchType.getQualifiers().getObjCLifetime()) {
3826 case Qualifiers::OCL_Strong:
3827 CastExn = CGF.EmitARCRetainNonBlock(CastExn);
3828 // fallthrough
3829
3830 case Qualifiers::OCL_None:
3831 case Qualifiers::OCL_ExplicitNone:
3832 case Qualifiers::OCL_Autoreleasing:
3833 CGF.Builder.CreateStore(CastExn, ParamAddr);
3834 return;
3835
3836 case Qualifiers::OCL_Weak:
3837 CGF.EmitARCInitWeak(ParamAddr, CastExn);
3838 return;
3839 }
3840 llvm_unreachable("bad ownership qualifier!");
3841 }
3842
3843 // Otherwise, it returns a pointer into the exception object.
3844
3845 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
3846 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
3847
3848 LValue srcLV = CGF.MakeNaturalAlignAddrLValue(Cast, CatchType);
John McCall7f416cc2015-09-08 08:05:57 +00003849 LValue destLV = CGF.MakeAddrLValue(ParamAddr, CatchType);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003850 switch (TEK) {
3851 case TEK_Complex:
3852 CGF.EmitStoreOfComplex(CGF.EmitLoadOfComplex(srcLV, Loc), destLV,
3853 /*init*/ true);
3854 return;
3855 case TEK_Scalar: {
3856 llvm::Value *ExnLoad = CGF.EmitLoadOfScalar(srcLV, Loc);
3857 CGF.EmitStoreOfScalar(ExnLoad, destLV, /*init*/ true);
3858 return;
3859 }
3860 case TEK_Aggregate:
3861 llvm_unreachable("evaluation kind filtered out!");
3862 }
3863 llvm_unreachable("bad evaluation kind");
3864 }
3865
3866 assert(isa<RecordType>(CatchType) && "unexpected catch type!");
John McCall7f416cc2015-09-08 08:05:57 +00003867 auto catchRD = CatchType->getAsCXXRecordDecl();
3868 CharUnits caughtExnAlignment = CGF.CGM.getClassPointerAlignment(catchRD);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003869
3870 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
3871
3872 // Check for a copy expression. If we don't have a copy expression,
3873 // that means a trivial copy is okay.
3874 const Expr *copyExpr = CatchParam.getInit();
3875 if (!copyExpr) {
3876 llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true);
John McCall7f416cc2015-09-08 08:05:57 +00003877 Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy),
3878 caughtExnAlignment);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003879 CGF.EmitAggregateCopy(ParamAddr, adjustedExn, CatchType);
3880 return;
3881 }
3882
3883 // We have to call __cxa_get_exception_ptr to get the adjusted
3884 // pointer before copying.
3885 llvm::CallInst *rawAdjustedExn =
3886 CGF.EmitNounwindRuntimeCall(getGetExceptionPtrFn(CGF.CGM), Exn);
3887
3888 // Cast that to the appropriate type.
John McCall7f416cc2015-09-08 08:05:57 +00003889 Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy),
3890 caughtExnAlignment);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003891
3892 // The copy expression is defined in terms of an OpaqueValueExpr.
3893 // Find it and map it to the adjusted expression.
3894 CodeGenFunction::OpaqueValueMapping
3895 opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr),
3896 CGF.MakeAddrLValue(adjustedExn, CatchParam.getType()));
3897
3898 // Call the copy ctor in a terminate scope.
3899 CGF.EHStack.pushTerminate();
3900
3901 // Perform the copy construction.
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003902 CGF.EmitAggExpr(copyExpr,
John McCall7f416cc2015-09-08 08:05:57 +00003903 AggValueSlot::forAddr(ParamAddr, Qualifiers(),
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003904 AggValueSlot::IsNotDestructed,
3905 AggValueSlot::DoesNotNeedGCBarriers,
3906 AggValueSlot::IsNotAliased));
3907
3908 // Leave the terminate scope.
3909 CGF.EHStack.popTerminate();
3910
3911 // Undo the opaque value mapping.
3912 opaque.pop();
3913
3914 // Finally we can call __cxa_begin_catch.
3915 CallBeginCatch(CGF, Exn, true);
3916}
3917
3918/// Begins a catch statement by initializing the catch variable and
3919/// calling __cxa_begin_catch.
3920void ItaniumCXXABI::emitBeginCatch(CodeGenFunction &CGF,
3921 const CXXCatchStmt *S) {
3922 // We have to be very careful with the ordering of cleanups here:
3923 // C++ [except.throw]p4:
3924 // The destruction [of the exception temporary] occurs
3925 // immediately after the destruction of the object declared in
3926 // the exception-declaration in the handler.
3927 //
3928 // So the precise ordering is:
3929 // 1. Construct catch variable.
3930 // 2. __cxa_begin_catch
3931 // 3. Enter __cxa_end_catch cleanup
3932 // 4. Enter dtor cleanup
3933 //
3934 // We do this by using a slightly abnormal initialization process.
3935 // Delegation sequence:
3936 // - ExitCXXTryStmt opens a RunCleanupsScope
3937 // - EmitAutoVarAlloca creates the variable and debug info
3938 // - InitCatchParam initializes the variable from the exception
3939 // - CallBeginCatch calls __cxa_begin_catch
3940 // - CallBeginCatch enters the __cxa_end_catch cleanup
3941 // - EmitAutoVarCleanups enters the variable destructor cleanup
3942 // - EmitCXXTryStmt emits the code for the catch body
3943 // - EmitCXXTryStmt close the RunCleanupsScope
3944
3945 VarDecl *CatchParam = S->getExceptionDecl();
3946 if (!CatchParam) {
3947 llvm::Value *Exn = CGF.getExceptionFromSlot();
3948 CallBeginCatch(CGF, Exn, true);
3949 return;
3950 }
3951
3952 // Emit the local.
3953 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
3954 InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF), S->getLocStart());
3955 CGF.EmitAutoVarCleanups(var);
3956}
3957
3958/// Get or define the following function:
3959/// void @__clang_call_terminate(i8* %exn) nounwind noreturn
3960/// This code is used only in C++.
3961static llvm::Constant *getClangCallTerminateFn(CodeGenModule &CGM) {
3962 llvm::FunctionType *fnTy =
3963 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
Reid Klecknerde864822017-03-21 16:57:30 +00003964 llvm::Constant *fnRef = CGM.CreateRuntimeFunction(
3965 fnTy, "__clang_call_terminate", llvm::AttributeList(), /*Local=*/true);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003966
3967 llvm::Function *fn = dyn_cast<llvm::Function>(fnRef);
3968 if (fn && fn->empty()) {
3969 fn->setDoesNotThrow();
3970 fn->setDoesNotReturn();
3971
3972 // What we really want is to massively penalize inlining without
3973 // forbidding it completely. The difference between that and
3974 // 'noinline' is negligible.
3975 fn->addFnAttr(llvm::Attribute::NoInline);
3976
3977 // Allow this function to be shared across translation units, but
3978 // we don't want it to turn into an exported symbol.
3979 fn->setLinkage(llvm::Function::LinkOnceODRLinkage);
3980 fn->setVisibility(llvm::Function::HiddenVisibility);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00003981 if (CGM.supportsCOMDAT())
3982 fn->setComdat(CGM.getModule().getOrInsertComdat(fn->getName()));
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003983
3984 // Set up the function.
3985 llvm::BasicBlock *entry =
3986 llvm::BasicBlock::Create(CGM.getLLVMContext(), "", fn);
John McCall7f416cc2015-09-08 08:05:57 +00003987 CGBuilderTy builder(CGM, entry);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003988
3989 // Pull the exception pointer out of the parameter list.
3990 llvm::Value *exn = &*fn->arg_begin();
3991
3992 // Call __cxa_begin_catch(exn).
3993 llvm::CallInst *catchCall = builder.CreateCall(getBeginCatchFn(CGM), exn);
3994 catchCall->setDoesNotThrow();
3995 catchCall->setCallingConv(CGM.getRuntimeCC());
3996
3997 // Call std::terminate().
David Blaikie4ba525b2015-07-14 17:27:39 +00003998 llvm::CallInst *termCall = builder.CreateCall(CGM.getTerminateFn());
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003999 termCall->setDoesNotThrow();
4000 termCall->setDoesNotReturn();
4001 termCall->setCallingConv(CGM.getRuntimeCC());
4002
4003 // std::terminate cannot return.
4004 builder.CreateUnreachable();
4005 }
4006
4007 return fnRef;
4008}
4009
4010llvm::CallInst *
4011ItaniumCXXABI::emitTerminateForUnexpectedException(CodeGenFunction &CGF,
4012 llvm::Value *Exn) {
4013 // In C++, we want to call __cxa_begin_catch() before terminating.
4014 if (Exn) {
4015 assert(CGF.CGM.getLangOpts().CPlusPlus);
4016 return CGF.EmitNounwindRuntimeCall(getClangCallTerminateFn(CGF.CGM), Exn);
4017 }
4018 return CGF.EmitNounwindRuntimeCall(CGF.CGM.getTerminateFn());
4019}