blob: 29261fd4b31fbfd6c91b86a2a9d6745c512c9b19 [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"
Craig Topperc9ee1d02012-09-15 18:47:51 +000028#include "clang/AST/Mangle.h"
29#include "clang/AST/Type.h"
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000030#include "clang/AST/StmtCXX.h"
David Majnemer1162d252014-06-22 19:05:33 +000031#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000032#include "llvm/IR/DataLayout.h"
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000033#include "llvm/IR/Instructions.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000034#include "llvm/IR/Intrinsics.h"
35#include "llvm/IR/Value.h"
Charles Davis4e786dd2010-05-25 19:52:27 +000036
37using namespace clang;
John McCall475999d2010-08-22 00:05:51 +000038using namespace CodeGen;
Charles Davis4e786dd2010-05-25 19:52:27 +000039
40namespace {
Charles Davis53c59df2010-08-16 03:33:14 +000041class ItaniumCXXABI : public CodeGen::CGCXXABI {
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +000042 /// VTables - All the vtables which have been defined.
43 llvm::DenseMap<const CXXRecordDecl *, llvm::GlobalVariable *> VTables;
44
John McCall475999d2010-08-22 00:05:51 +000045protected:
Mark Seabornedf0d382013-07-24 16:25:13 +000046 bool UseARMMethodPtrABI;
47 bool UseARMGuardVarABI;
John McCalld23b27e2016-09-16 02:40:45 +000048 bool Use32BitVTableOffsetABI;
John McCall7a9aac22010-08-23 01:21:21 +000049
Timur Iskhodzhanov67455222013-10-03 06:26:13 +000050 ItaniumMangleContext &getMangleContext() {
51 return cast<ItaniumMangleContext>(CodeGen::CGCXXABI::getMangleContext());
52 }
53
Charles Davis4e786dd2010-05-25 19:52:27 +000054public:
Mark Seabornedf0d382013-07-24 16:25:13 +000055 ItaniumCXXABI(CodeGen::CodeGenModule &CGM,
56 bool UseARMMethodPtrABI = false,
57 bool UseARMGuardVarABI = false) :
58 CGCXXABI(CGM), UseARMMethodPtrABI(UseARMMethodPtrABI),
John McCalld23b27e2016-09-16 02:40:45 +000059 UseARMGuardVarABI(UseARMGuardVarABI),
60 Use32BitVTableOffsetABI(false) { }
John McCall475999d2010-08-22 00:05:51 +000061
Reid Kleckner40ca9132014-05-13 22:05:45 +000062 bool classifyReturnType(CGFunctionInfo &FI) const override;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000063
Craig Topper4f12f102014-03-12 06:41:41 +000064 RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const override {
Reid Klecknerd355ca72014-05-15 01:26:32 +000065 // Structures with either a non-trivial destructor or a non-trivial
66 // copy constructor are always indirect.
67 // FIXME: Use canCopyArgument() when it is fixed to handle lazily declared
68 // special members.
69 if (RD->hasNonTrivialDestructor() || RD->hasNonTrivialCopyConstructor())
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000070 return RAA_Indirect;
71 return RAA_Default;
72 }
73
John McCall7f416cc2015-09-08 08:05:57 +000074 bool isThisCompleteObject(GlobalDecl GD) const override {
75 // The Itanium ABI has separate complete-object vs. base-object
76 // variants of both constructors and destructors.
77 if (isa<CXXDestructorDecl>(GD.getDecl())) {
78 switch (GD.getDtorType()) {
79 case Dtor_Complete:
80 case Dtor_Deleting:
81 return true;
82
83 case Dtor_Base:
84 return false;
85
86 case Dtor_Comdat:
87 llvm_unreachable("emitting dtor comdat as function?");
88 }
89 llvm_unreachable("bad dtor kind");
90 }
91 if (isa<CXXConstructorDecl>(GD.getDecl())) {
92 switch (GD.getCtorType()) {
93 case Ctor_Complete:
94 return true;
95
96 case Ctor_Base:
97 return false;
98
99 case Ctor_CopyingClosure:
100 case Ctor_DefaultClosure:
101 llvm_unreachable("closure ctors in Itanium ABI?");
102
103 case Ctor_Comdat:
104 llvm_unreachable("emitting ctor comdat as function?");
105 }
106 llvm_unreachable("bad dtor kind");
107 }
108
109 // No other kinds.
110 return false;
111 }
112
Craig Topper4f12f102014-03-12 06:41:41 +0000113 bool isZeroInitializable(const MemberPointerType *MPT) override;
John McCall84fa5102010-08-22 04:16:24 +0000114
Craig Topper4f12f102014-03-12 06:41:41 +0000115 llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT) override;
John McCall7a9aac22010-08-23 01:21:21 +0000116
John McCallb92ab1a2016-10-26 23:46:34 +0000117 CGCallee
Craig Topper4f12f102014-03-12 06:41:41 +0000118 EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
119 const Expr *E,
John McCall7f416cc2015-09-08 08:05:57 +0000120 Address This,
121 llvm::Value *&ThisPtrForCall,
Craig Topper4f12f102014-03-12 06:41:41 +0000122 llvm::Value *MemFnPtr,
123 const MemberPointerType *MPT) override;
John McCalla8bbb822010-08-22 03:04:22 +0000124
Craig Topper4f12f102014-03-12 06:41:41 +0000125 llvm::Value *
126 EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E,
John McCall7f416cc2015-09-08 08:05:57 +0000127 Address Base,
Craig Topper4f12f102014-03-12 06:41:41 +0000128 llvm::Value *MemPtr,
129 const MemberPointerType *MPT) override;
John McCallc134eb52010-08-31 21:07:20 +0000130
John McCall7a9aac22010-08-23 01:21:21 +0000131 llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
132 const CastExpr *E,
Craig Topper4f12f102014-03-12 06:41:41 +0000133 llvm::Value *Src) override;
John McCallc62bb392012-02-15 01:22:51 +0000134 llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
Craig Topper4f12f102014-03-12 06:41:41 +0000135 llvm::Constant *Src) override;
John McCall84fa5102010-08-22 04:16:24 +0000136
Craig Topper4f12f102014-03-12 06:41:41 +0000137 llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT) override;
John McCall84fa5102010-08-22 04:16:24 +0000138
David Majnemere2be95b2015-06-23 07:31:01 +0000139 llvm::Constant *EmitMemberFunctionPointer(const CXXMethodDecl *MD) override;
John McCallf3a88602011-02-03 08:15:49 +0000140 llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
Craig Topper4f12f102014-03-12 06:41:41 +0000141 CharUnits offset) override;
142 llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT) override;
Richard Smithdafff942012-01-14 04:30:29 +0000143 llvm::Constant *BuildMemberPointer(const CXXMethodDecl *MD,
144 CharUnits ThisAdjustment);
John McCall1c456c82010-08-22 06:43:33 +0000145
John McCall7a9aac22010-08-23 01:21:21 +0000146 llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000147 llvm::Value *L, llvm::Value *R,
John McCall7a9aac22010-08-23 01:21:21 +0000148 const MemberPointerType *MPT,
Craig Topper4f12f102014-03-12 06:41:41 +0000149 bool Inequality) override;
John McCall131d97d2010-08-22 08:30:07 +0000150
John McCall7a9aac22010-08-23 01:21:21 +0000151 llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000152 llvm::Value *Addr,
153 const MemberPointerType *MPT) override;
John McCall5d865c322010-08-31 07:33:07 +0000154
David Majnemer08681372014-11-01 07:37:17 +0000155 void emitVirtualObjectDelete(CodeGenFunction &CGF, const CXXDeleteExpr *DE,
John McCall7f416cc2015-09-08 08:05:57 +0000156 Address Ptr, QualType ElementType,
David Majnemer0c0b6d92014-10-31 20:09:12 +0000157 const CXXDestructorDecl *Dtor) override;
John McCall82fb8922012-09-25 10:10:39 +0000158
John McCall7f416cc2015-09-08 08:05:57 +0000159 CharUnits getAlignmentOfExnObject() {
Akira Hatanaka68ab7fe2016-03-31 06:36:07 +0000160 unsigned Align = CGM.getContext().getTargetInfo().getExnObjectAlignment();
161 return CGM.getContext().toCharUnitsFromBits(Align);
John McCall7f416cc2015-09-08 08:05:57 +0000162 }
163
David Majnemer442d0a22014-11-25 07:20:20 +0000164 void emitRethrow(CodeGenFunction &CGF, bool isNoReturn) override;
David Majnemer7c237072015-03-05 00:46:22 +0000165 void emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) override;
David Majnemer442d0a22014-11-25 07:20:20 +0000166
Reid Klecknerfff8e7f2015-03-03 19:21:04 +0000167 void emitBeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *C) override;
168
169 llvm::CallInst *
170 emitTerminateForUnexpectedException(CodeGenFunction &CGF,
171 llvm::Value *Exn) override;
172
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +0000173 void EmitFundamentalRTTIDescriptor(QualType Type, bool DLLExport);
174 void EmitFundamentalRTTIDescriptors(bool DLLExport);
David Majnemer443250f2015-03-17 20:35:00 +0000175 llvm::Constant *getAddrOfRTTIDescriptor(QualType Ty) override;
Reid Kleckner10aa7702015-09-16 20:15:55 +0000176 CatchTypeInfo
David Majnemer37b417f2015-03-29 21:55:10 +0000177 getAddrOfCXXCatchHandlerType(QualType Ty,
178 QualType CatchHandlerType) override {
Reid Kleckner10aa7702015-09-16 20:15:55 +0000179 return CatchTypeInfo{getAddrOfRTTIDescriptor(Ty), 0};
David Majnemer443250f2015-03-17 20:35:00 +0000180 }
David Majnemere2cb8d12014-07-07 06:20:47 +0000181
David Majnemer1162d252014-06-22 19:05:33 +0000182 bool shouldTypeidBeNullChecked(bool IsDeref, QualType SrcRecordTy) override;
183 void EmitBadTypeidCall(CodeGenFunction &CGF) override;
184 llvm::Value *EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy,
John McCall7f416cc2015-09-08 08:05:57 +0000185 Address ThisPtr,
David Majnemer1162d252014-06-22 19:05:33 +0000186 llvm::Type *StdTypeInfoPtrTy) override;
187
188 bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
189 QualType SrcRecordTy) override;
190
John McCall7f416cc2015-09-08 08:05:57 +0000191 llvm::Value *EmitDynamicCastCall(CodeGenFunction &CGF, Address Value,
David Majnemer1162d252014-06-22 19:05:33 +0000192 QualType SrcRecordTy, QualType DestTy,
193 QualType DestRecordTy,
194 llvm::BasicBlock *CastEnd) override;
195
John McCall7f416cc2015-09-08 08:05:57 +0000196 llvm::Value *EmitDynamicCastToVoid(CodeGenFunction &CGF, Address Value,
David Majnemer1162d252014-06-22 19:05:33 +0000197 QualType SrcRecordTy,
198 QualType DestTy) override;
199
200 bool EmitBadCastCall(CodeGenFunction &CGF) override;
201
Craig Topper4f12f102014-03-12 06:41:41 +0000202 llvm::Value *
John McCall7f416cc2015-09-08 08:05:57 +0000203 GetVirtualBaseClassOffset(CodeGenFunction &CGF, Address This,
Craig Topper4f12f102014-03-12 06:41:41 +0000204 const CXXRecordDecl *ClassDecl,
205 const CXXRecordDecl *BaseClassDecl) override;
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000206
Craig Topper4f12f102014-03-12 06:41:41 +0000207 void EmitCXXConstructors(const CXXConstructorDecl *D) override;
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +0000208
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000209 void buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
210 SmallVectorImpl<CanQualType> &ArgTys) override;
John McCall5d865c322010-08-31 07:33:07 +0000211
Reid Klecknere7de47e2013-07-22 13:51:44 +0000212 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
Craig Topper4f12f102014-03-12 06:41:41 +0000213 CXXDtorType DT) const override {
Reid Klecknere7de47e2013-07-22 13:51:44 +0000214 // Itanium does not emit any destructor variant as an inline thunk.
215 // Delegating may occur as an optimization, but all variants are either
216 // emitted with external linkage or as linkonce if they are inline and used.
217 return false;
218 }
219
Craig Topper4f12f102014-03-12 06:41:41 +0000220 void EmitCXXDestructors(const CXXDestructorDecl *D) override;
Reid Klecknere7de47e2013-07-22 13:51:44 +0000221
Reid Kleckner89077a12013-12-17 19:46:40 +0000222 void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
Craig Topper4f12f102014-03-12 06:41:41 +0000223 FunctionArgList &Params) override;
John McCall5d865c322010-08-31 07:33:07 +0000224
Craig Topper4f12f102014-03-12 06:41:41 +0000225 void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override;
John McCall8ed55a52010-09-02 09:58:18 +0000226
Reid Kleckner89077a12013-12-17 19:46:40 +0000227 unsigned addImplicitConstructorArgs(CodeGenFunction &CGF,
228 const CXXConstructorDecl *D,
229 CXXCtorType Type, bool ForVirtualBase,
Craig Topper4f12f102014-03-12 06:41:41 +0000230 bool Delegating,
231 CallArgList &Args) override;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000232
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000233 void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD,
234 CXXDtorType Type, bool ForVirtualBase,
John McCall7f416cc2015-09-08 08:05:57 +0000235 bool Delegating, Address This) override;
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000236
Craig Topper4f12f102014-03-12 06:41:41 +0000237 void emitVTableDefinitions(CodeGenVTables &CGVT,
238 const CXXRecordDecl *RD) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000239
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000240 bool isVirtualOffsetNeededForVTableField(CodeGenFunction &CGF,
241 CodeGenFunction::VPtr Vptr) override;
242
243 bool doStructorsInitializeVPtrs(const CXXRecordDecl *VTableClass) override {
244 return true;
245 }
246
247 llvm::Constant *
248 getVTableAddressPoint(BaseSubobject Base,
249 const CXXRecordDecl *VTableClass) override;
250
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000251 llvm::Value *getVTableAddressPointInStructor(
252 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000253 BaseSubobject Base, const CXXRecordDecl *NearestVBase) override;
254
255 llvm::Value *getVTableAddressPointInStructorWithVTT(
256 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
257 BaseSubobject Base, const CXXRecordDecl *NearestVBase);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000258
259 llvm::Constant *
260 getVTableAddressPointForConstExpr(BaseSubobject Base,
Craig Topper4f12f102014-03-12 06:41:41 +0000261 const CXXRecordDecl *VTableClass) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000262
263 llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
Craig Topper4f12f102014-03-12 06:41:41 +0000264 CharUnits VPtrOffset) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000265
John McCallb92ab1a2016-10-26 23:46:34 +0000266 CGCallee getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
267 Address This, llvm::Type *Ty,
268 SourceLocation Loc) override;
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000269
David Majnemer0c0b6d92014-10-31 20:09:12 +0000270 llvm::Value *EmitVirtualDestructorCall(CodeGenFunction &CGF,
271 const CXXDestructorDecl *Dtor,
272 CXXDtorType DtorType,
John McCall7f416cc2015-09-08 08:05:57 +0000273 Address This,
David Majnemer0c0b6d92014-10-31 20:09:12 +0000274 const CXXMemberCallExpr *CE) override;
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000275
Craig Topper4f12f102014-03-12 06:41:41 +0000276 void emitVirtualInheritanceTables(const CXXRecordDecl *RD) override;
Reid Kleckner7810af02013-06-19 15:20:38 +0000277
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000278 bool canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const override;
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000279
Hans Wennborgc94391d2014-06-06 20:04:01 +0000280 void setThunkLinkage(llvm::Function *Thunk, bool ForVTable, GlobalDecl GD,
281 bool ReturnAdjustment) override {
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000282 // Allow inlining of thunks by emitting them with available_externally
283 // linkage together with vtables when needed.
Peter Collingbourne8fabc1b2015-07-01 02:10:26 +0000284 if (ForVTable && !Thunk->hasLocalLinkage())
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000285 Thunk->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
286 }
287
John McCall7f416cc2015-09-08 08:05:57 +0000288 llvm::Value *performThisAdjustment(CodeGenFunction &CGF, Address This,
Craig Topper4f12f102014-03-12 06:41:41 +0000289 const ThisAdjustment &TA) override;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000290
John McCall7f416cc2015-09-08 08:05:57 +0000291 llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
Craig Topper4f12f102014-03-12 06:41:41 +0000292 const ReturnAdjustment &RA) override;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000293
David Majnemer196ac332014-09-11 23:05:02 +0000294 size_t getSrcArgforCopyCtor(const CXXConstructorDecl *,
295 FunctionArgList &Args) const override {
296 assert(!Args.empty() && "expected the arglist to not be empty!");
297 return Args.size() - 1;
298 }
299
Craig Topper4f12f102014-03-12 06:41:41 +0000300 StringRef GetPureVirtualCallName() override { return "__cxa_pure_virtual"; }
301 StringRef GetDeletedVirtualCallName() override
302 { return "__cxa_deleted_virtual"; }
Joao Matos2ce88ef2012-07-17 17:10:11 +0000303
Craig Topper4f12f102014-03-12 06:41:41 +0000304 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
John McCall7f416cc2015-09-08 08:05:57 +0000305 Address InitializeArrayCookie(CodeGenFunction &CGF,
306 Address NewPtr,
307 llvm::Value *NumElements,
308 const CXXNewExpr *expr,
309 QualType ElementType) override;
John McCallb91cd662012-05-01 05:23:51 +0000310 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000311 Address allocPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000312 CharUnits cookieSize) override;
John McCall68ff0372010-09-08 01:44:27 +0000313
John McCallcdf7ef52010-11-06 09:44:32 +0000314 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
Craig Topper4f12f102014-03-12 06:41:41 +0000315 llvm::GlobalVariable *DeclPtr,
316 bool PerformInit) override;
Richard Smithdbf74ba2013-04-14 23:01:42 +0000317 void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
Craig Topper4f12f102014-03-12 06:41:41 +0000318 llvm::Constant *dtor, llvm::Constant *addr) override;
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000319
320 llvm::Function *getOrCreateThreadLocalWrapper(const VarDecl *VD,
Alexander Musmanf94c3182014-09-26 06:28:25 +0000321 llvm::Value *Val);
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000322 void EmitThreadLocalInitFuncs(
David Majnemerb3341ea2014-10-05 05:05:40 +0000323 CodeGenModule &CGM,
Richard Smith5a99c492015-12-01 01:10:48 +0000324 ArrayRef<const VarDecl *> CXXThreadLocals,
David Majnemerb3341ea2014-10-05 05:05:40 +0000325 ArrayRef<llvm::Function *> CXXThreadLocalInits,
Richard Smith5a99c492015-12-01 01:10:48 +0000326 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) override;
David Majnemerb3341ea2014-10-05 05:05:40 +0000327
328 bool usesThreadWrapperFunction() const override { return true; }
Richard Smith0f383742014-03-26 22:48:22 +0000329 LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD,
330 QualType LValType) override;
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000331
Craig Topper4f12f102014-03-12 06:41:41 +0000332 bool NeedsVTTParameter(GlobalDecl GD) override;
David Majnemere2cb8d12014-07-07 06:20:47 +0000333
334 /**************************** RTTI Uniqueness ******************************/
335
336protected:
337 /// Returns true if the ABI requires RTTI type_info objects to be unique
338 /// across a program.
339 virtual bool shouldRTTIBeUnique() const { return true; }
340
341public:
342 /// What sort of unique-RTTI behavior should we use?
343 enum RTTIUniquenessKind {
344 /// We are guaranteeing, or need to guarantee, that the RTTI string
345 /// is unique.
346 RUK_Unique,
347
348 /// We are not guaranteeing uniqueness for the RTTI string, so we
349 /// can demote to hidden visibility but must use string comparisons.
350 RUK_NonUniqueHidden,
351
352 /// We are not guaranteeing uniqueness for the RTTI string, so we
353 /// have to use string comparisons, but we also have to emit it with
354 /// non-hidden visibility.
355 RUK_NonUniqueVisible
356 };
357
358 /// Return the required visibility status for the given type and linkage in
359 /// the current ABI.
360 RTTIUniquenessKind
361 classifyRTTIUniqueness(QualType CanTy,
362 llvm::GlobalValue::LinkageTypes Linkage) const;
363 friend class ItaniumRTTIBuilder;
Rafael Espindola91f68b42014-09-15 19:20:10 +0000364
365 void emitCXXStructor(const CXXMethodDecl *MD, StructorType Type) override;
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000366
367 private:
Piotr Padlewski1d02f682015-08-19 20:09:09 +0000368 bool hasAnyUsedVirtualInlineFunction(const CXXRecordDecl *RD) const {
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000369 const auto &VtableLayout =
370 CGM.getItaniumVTableContext().getVTableLayout(RD);
371
372 for (const auto &VtableComponent : VtableLayout.vtable_components()) {
Piotr Padlewski1d02f682015-08-19 20:09:09 +0000373 if (!VtableComponent.isUsedFunctionPointerKind())
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000374 continue;
375
Piotr Padlewski1d02f682015-08-19 20:09:09 +0000376 const CXXMethodDecl *Method = VtableComponent.getFunctionDecl();
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000377 if (Method->getCanonicalDecl()->isInlined())
378 return true;
379 }
380 return false;
381 }
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000382
383 bool isVTableHidden(const CXXRecordDecl *RD) const {
384 const auto &VtableLayout =
385 CGM.getItaniumVTableContext().getVTableLayout(RD);
386
387 for (const auto &VtableComponent : VtableLayout.vtable_components()) {
388 if (VtableComponent.isRTTIKind()) {
389 const CXXRecordDecl *RTTIDecl = VtableComponent.getRTTIDecl();
390 if (RTTIDecl->getVisibility() == Visibility::HiddenVisibility)
391 return true;
392 } else if (VtableComponent.isUsedFunctionPointerKind()) {
393 const CXXMethodDecl *Method = VtableComponent.getFunctionDecl();
394 if (Method->getVisibility() == Visibility::HiddenVisibility &&
395 !Method->isDefined())
396 return true;
397 }
398 }
399 return false;
400 }
Charles Davis4e786dd2010-05-25 19:52:27 +0000401};
John McCall86353412010-08-21 22:46:04 +0000402
403class ARMCXXABI : public ItaniumCXXABI {
404public:
Mark Seabornedf0d382013-07-24 16:25:13 +0000405 ARMCXXABI(CodeGen::CodeGenModule &CGM) :
406 ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
407 /* UseARMGuardVarABI = */ true) {}
John McCall5d865c322010-08-31 07:33:07 +0000408
Craig Topper4f12f102014-03-12 06:41:41 +0000409 bool HasThisReturn(GlobalDecl GD) const override {
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000410 return (isa<CXXConstructorDecl>(GD.getDecl()) || (
411 isa<CXXDestructorDecl>(GD.getDecl()) &&
412 GD.getDtorType() != Dtor_Deleting));
413 }
John McCall5d865c322010-08-31 07:33:07 +0000414
Craig Topper4f12f102014-03-12 06:41:41 +0000415 void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV,
416 QualType ResTy) override;
John McCall5d865c322010-08-31 07:33:07 +0000417
Craig Topper4f12f102014-03-12 06:41:41 +0000418 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
John McCall7f416cc2015-09-08 08:05:57 +0000419 Address InitializeArrayCookie(CodeGenFunction &CGF,
420 Address NewPtr,
421 llvm::Value *NumElements,
422 const CXXNewExpr *expr,
423 QualType ElementType) override;
424 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, Address allocPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000425 CharUnits cookieSize) override;
John McCall86353412010-08-21 22:46:04 +0000426};
Tim Northovera2ee4332014-03-29 15:09:45 +0000427
428class iOS64CXXABI : public ARMCXXABI {
429public:
John McCalld23b27e2016-09-16 02:40:45 +0000430 iOS64CXXABI(CodeGen::CodeGenModule &CGM) : ARMCXXABI(CGM) {
431 Use32BitVTableOffsetABI = true;
432 }
Tim Northover65f582f2014-03-30 17:32:48 +0000433
434 // ARM64 libraries are prepared for non-unique RTTI.
David Majnemere2cb8d12014-07-07 06:20:47 +0000435 bool shouldRTTIBeUnique() const override { return false; }
Tim Northovera2ee4332014-03-29 15:09:45 +0000436};
Dan Gohmanc2853072015-09-03 22:51:53 +0000437
438class WebAssemblyCXXABI final : public ItaniumCXXABI {
439public:
440 explicit WebAssemblyCXXABI(CodeGen::CodeGenModule &CGM)
441 : ItaniumCXXABI(CGM, /*UseARMMethodPtrABI=*/true,
442 /*UseARMGuardVarABI=*/true) {}
443
444private:
445 bool HasThisReturn(GlobalDecl GD) const override {
446 return isa<CXXConstructorDecl>(GD.getDecl()) ||
447 (isa<CXXDestructorDecl>(GD.getDecl()) &&
448 GD.getDtorType() != Dtor_Deleting);
449 }
Derek Schuff8179be42016-05-10 17:44:55 +0000450 bool canCallMismatchedFunctionType() const override { return false; }
Dan Gohmanc2853072015-09-03 22:51:53 +0000451};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000452}
Charles Davis4e786dd2010-05-25 19:52:27 +0000453
Charles Davis53c59df2010-08-16 03:33:14 +0000454CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
John McCallc8e01702013-04-16 22:48:15 +0000455 switch (CGM.getTarget().getCXXABI().getKind()) {
John McCall57625922013-01-25 23:36:14 +0000456 // For IR-generation purposes, there's no significant difference
457 // between the ARM and iOS ABIs.
458 case TargetCXXABI::GenericARM:
459 case TargetCXXABI::iOS:
Tim Northover756447a2015-10-30 16:30:36 +0000460 case TargetCXXABI::WatchOS:
John McCall57625922013-01-25 23:36:14 +0000461 return new ARMCXXABI(CGM);
Charles Davis4e786dd2010-05-25 19:52:27 +0000462
Tim Northovera2ee4332014-03-29 15:09:45 +0000463 case TargetCXXABI::iOS64:
464 return new iOS64CXXABI(CGM);
465
Tim Northover9bb857a2013-01-31 12:13:10 +0000466 // Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't
467 // include the other 32-bit ARM oddities: constructor/destructor return values
468 // and array cookies.
469 case TargetCXXABI::GenericAArch64:
Mark Seabornedf0d382013-07-24 16:25:13 +0000470 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
471 /* UseARMGuardVarABI = */ true);
Tim Northover9bb857a2013-01-31 12:13:10 +0000472
Zoran Jovanovic26a12162015-02-18 15:21:35 +0000473 case TargetCXXABI::GenericMIPS:
474 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true);
475
Dan Gohmanc2853072015-09-03 22:51:53 +0000476 case TargetCXXABI::WebAssembly:
477 return new WebAssemblyCXXABI(CGM);
478
John McCall57625922013-01-25 23:36:14 +0000479 case TargetCXXABI::GenericItanium:
Mark Seabornedf0d382013-07-24 16:25:13 +0000480 if (CGM.getContext().getTargetInfo().getTriple().getArch()
481 == llvm::Triple::le32) {
482 // For PNaCl, use ARM-style method pointers so that PNaCl code
483 // does not assume anything about the alignment of function
484 // pointers.
485 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
486 /* UseARMGuardVarABI = */ false);
487 }
John McCall57625922013-01-25 23:36:14 +0000488 return new ItaniumCXXABI(CGM);
489
490 case TargetCXXABI::Microsoft:
491 llvm_unreachable("Microsoft ABI is not Itanium-based");
492 }
493 llvm_unreachable("bad ABI kind");
John McCall86353412010-08-21 22:46:04 +0000494}
495
Chris Lattnera5f58b02011-07-09 17:41:47 +0000496llvm::Type *
John McCall7a9aac22010-08-23 01:21:21 +0000497ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
498 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000499 return CGM.PtrDiffTy;
Reid Kleckneree7cf842014-12-01 22:02:27 +0000500 return llvm::StructType::get(CGM.PtrDiffTy, CGM.PtrDiffTy, nullptr);
John McCall1c456c82010-08-22 06:43:33 +0000501}
502
John McCalld9c6c0b2010-08-22 00:59:17 +0000503/// In the Itanium and ARM ABIs, method pointers have the form:
504/// struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
505///
506/// In the Itanium ABI:
507/// - method pointers are virtual if (memptr.ptr & 1) is nonzero
508/// - the this-adjustment is (memptr.adj)
509/// - the virtual offset is (memptr.ptr - 1)
510///
511/// In the ARM ABI:
512/// - method pointers are virtual if (memptr.adj & 1) is nonzero
513/// - the this-adjustment is (memptr.adj >> 1)
514/// - the virtual offset is (memptr.ptr)
515/// ARM uses 'adj' for the virtual flag because Thumb functions
516/// may be only single-byte aligned.
517///
518/// If the member is virtual, the adjusted 'this' pointer points
519/// to a vtable pointer from which the virtual offset is applied.
520///
521/// If the member is non-virtual, memptr.ptr is the address of
522/// the function to call.
John McCallb92ab1a2016-10-26 23:46:34 +0000523CGCallee ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(
John McCall7f416cc2015-09-08 08:05:57 +0000524 CodeGenFunction &CGF, const Expr *E, Address ThisAddr,
525 llvm::Value *&ThisPtrForCall,
David Majnemer2b0d66d2014-02-20 23:22:07 +0000526 llvm::Value *MemFnPtr, const MemberPointerType *MPT) {
John McCall475999d2010-08-22 00:05:51 +0000527 CGBuilderTy &Builder = CGF.Builder;
528
529 const FunctionProtoType *FPT =
530 MPT->getPointeeType()->getAs<FunctionProtoType>();
531 const CXXRecordDecl *RD =
532 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
533
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000534 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(
535 CGM.getTypes().arrangeCXXMethodType(RD, FPT, /*FD=*/nullptr));
John McCall475999d2010-08-22 00:05:51 +0000536
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000537 llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(CGM.PtrDiffTy, 1);
John McCall475999d2010-08-22 00:05:51 +0000538
John McCalld9c6c0b2010-08-22 00:59:17 +0000539 llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
540 llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
541 llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
542
John McCalla1dee5302010-08-22 10:59:02 +0000543 // Extract memptr.adj, which is in the second field.
544 llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
John McCalld9c6c0b2010-08-22 00:59:17 +0000545
546 // Compute the true adjustment.
547 llvm::Value *Adj = RawAdj;
Mark Seabornedf0d382013-07-24 16:25:13 +0000548 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000549 Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
John McCall475999d2010-08-22 00:05:51 +0000550
551 // Apply the adjustment and cast back to the original struct type
552 // for consistency.
John McCall7f416cc2015-09-08 08:05:57 +0000553 llvm::Value *This = ThisAddr.getPointer();
John McCalld9c6c0b2010-08-22 00:59:17 +0000554 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
555 Ptr = Builder.CreateInBoundsGEP(Ptr, Adj);
556 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
John McCall7f416cc2015-09-08 08:05:57 +0000557 ThisPtrForCall = This;
John McCall475999d2010-08-22 00:05:51 +0000558
559 // Load the function pointer.
John McCalla1dee5302010-08-22 10:59:02 +0000560 llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
John McCall475999d2010-08-22 00:05:51 +0000561
562 // If the LSB in the function pointer is 1, the function pointer points to
563 // a virtual function.
John McCalld9c6c0b2010-08-22 00:59:17 +0000564 llvm::Value *IsVirtual;
Mark Seabornedf0d382013-07-24 16:25:13 +0000565 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000566 IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
567 else
568 IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
569 IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
John McCall475999d2010-08-22 00:05:51 +0000570 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
571
572 // In the virtual path, the adjustment left 'This' pointing to the
573 // vtable of the correct base subobject. The "function pointer" is an
John McCalld9c6c0b2010-08-22 00:59:17 +0000574 // offset within the vtable (+1 for the virtual flag on non-ARM).
John McCall475999d2010-08-22 00:05:51 +0000575 CGF.EmitBlock(FnVirtual);
576
577 // Cast the adjusted this to a pointer to vtable pointer and load.
Chris Lattner2192fe52011-07-18 04:24:23 +0000578 llvm::Type *VTableTy = Builder.getInt8PtrTy();
John McCall7f416cc2015-09-08 08:05:57 +0000579 CharUnits VTablePtrAlign =
580 CGF.CGM.getDynamicOffsetAlignment(ThisAddr.getAlignment(), RD,
581 CGF.getPointerAlign());
582 llvm::Value *VTable =
Piotr Padlewski4b1ac722015-09-15 21:46:55 +0000583 CGF.GetVTablePtr(Address(This, VTablePtrAlign), VTableTy, RD);
John McCall475999d2010-08-22 00:05:51 +0000584
585 // Apply the offset.
John McCalld23b27e2016-09-16 02:40:45 +0000586 // On ARM64, to reserve extra space in virtual member function pointers,
587 // we only pay attention to the low 32 bits of the offset.
John McCalld9c6c0b2010-08-22 00:59:17 +0000588 llvm::Value *VTableOffset = FnAsInt;
Mark Seabornedf0d382013-07-24 16:25:13 +0000589 if (!UseARMMethodPtrABI)
590 VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
John McCalld23b27e2016-09-16 02:40:45 +0000591 if (Use32BitVTableOffsetABI) {
592 VTableOffset = Builder.CreateTrunc(VTableOffset, CGF.Int32Ty);
593 VTableOffset = Builder.CreateZExt(VTableOffset, CGM.PtrDiffTy);
594 }
John McCalld9c6c0b2010-08-22 00:59:17 +0000595 VTable = Builder.CreateGEP(VTable, VTableOffset);
John McCall475999d2010-08-22 00:05:51 +0000596
597 // Load the virtual function to call.
598 VTable = Builder.CreateBitCast(VTable, FTy->getPointerTo()->getPointerTo());
John McCall7f416cc2015-09-08 08:05:57 +0000599 llvm::Value *VirtualFn =
600 Builder.CreateAlignedLoad(VTable, CGF.getPointerAlign(),
601 "memptr.virtualfn");
John McCall475999d2010-08-22 00:05:51 +0000602 CGF.EmitBranch(FnEnd);
603
604 // In the non-virtual path, the function pointer is actually a
605 // function pointer.
606 CGF.EmitBlock(FnNonVirtual);
607 llvm::Value *NonVirtualFn =
John McCalld9c6c0b2010-08-22 00:59:17 +0000608 Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn");
John McCall475999d2010-08-22 00:05:51 +0000609
610 // We're done.
611 CGF.EmitBlock(FnEnd);
John McCallb92ab1a2016-10-26 23:46:34 +0000612 llvm::PHINode *CalleePtr = Builder.CreatePHI(FTy->getPointerTo(), 2);
613 CalleePtr->addIncoming(VirtualFn, FnVirtual);
614 CalleePtr->addIncoming(NonVirtualFn, FnNonVirtual);
615
616 CGCallee Callee(FPT, CalleePtr);
John McCall475999d2010-08-22 00:05:51 +0000617 return Callee;
618}
John McCalla8bbb822010-08-22 03:04:22 +0000619
John McCallc134eb52010-08-31 21:07:20 +0000620/// Compute an l-value by applying the given pointer-to-member to a
621/// base object.
David Majnemer2b0d66d2014-02-20 23:22:07 +0000622llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(
John McCall7f416cc2015-09-08 08:05:57 +0000623 CodeGenFunction &CGF, const Expr *E, Address Base, llvm::Value *MemPtr,
David Majnemer2b0d66d2014-02-20 23:22:07 +0000624 const MemberPointerType *MPT) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000625 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCallc134eb52010-08-31 21:07:20 +0000626
627 CGBuilderTy &Builder = CGF.Builder;
628
John McCallc134eb52010-08-31 21:07:20 +0000629 // Cast to char*.
John McCall7f416cc2015-09-08 08:05:57 +0000630 Base = Builder.CreateElementBitCast(Base, CGF.Int8Ty);
John McCallc134eb52010-08-31 21:07:20 +0000631
632 // Apply the offset, which we assume is non-null.
John McCall7f416cc2015-09-08 08:05:57 +0000633 llvm::Value *Addr =
634 Builder.CreateInBoundsGEP(Base.getPointer(), MemPtr, "memptr.offset");
John McCallc134eb52010-08-31 21:07:20 +0000635
636 // Cast the address to the appropriate pointer type, adopting the
637 // address space of the base pointer.
John McCall7f416cc2015-09-08 08:05:57 +0000638 llvm::Type *PType = CGF.ConvertTypeForMem(MPT->getPointeeType())
639 ->getPointerTo(Base.getAddressSpace());
John McCallc134eb52010-08-31 21:07:20 +0000640 return Builder.CreateBitCast(Addr, PType);
641}
642
John McCallc62bb392012-02-15 01:22:51 +0000643/// Perform a bitcast, derived-to-base, or base-to-derived member pointer
644/// conversion.
645///
646/// Bitcast conversions are always a no-op under Itanium.
John McCall7a9aac22010-08-23 01:21:21 +0000647///
648/// Obligatory offset/adjustment diagram:
649/// <-- offset --> <-- adjustment -->
650/// |--------------------------|----------------------|--------------------|
651/// ^Derived address point ^Base address point ^Member address point
652///
653/// So when converting a base member pointer to a derived member pointer,
654/// we add the offset to the adjustment because the address point has
655/// decreased; and conversely, when converting a derived MP to a base MP
656/// we subtract the offset from the adjustment because the address point
657/// has increased.
658///
659/// The standard forbids (at compile time) conversion to and from
660/// virtual bases, which is why we don't have to consider them here.
661///
662/// The standard forbids (at run time) casting a derived MP to a base
663/// MP when the derived MP does not point to a member of the base.
664/// This is why -1 is a reasonable choice for null data member
665/// pointers.
John McCalla1dee5302010-08-22 10:59:02 +0000666llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000667ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
668 const CastExpr *E,
John McCallc62bb392012-02-15 01:22:51 +0000669 llvm::Value *src) {
John McCalle3027922010-08-25 11:45:40 +0000670 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
John McCallc62bb392012-02-15 01:22:51 +0000671 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
672 E->getCastKind() == CK_ReinterpretMemberPointer);
673
674 // Under Itanium, reinterprets don't require any additional processing.
675 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
676
677 // Use constant emission if we can.
678 if (isa<llvm::Constant>(src))
679 return EmitMemberPointerConversion(E, cast<llvm::Constant>(src));
680
681 llvm::Constant *adj = getMemberPointerAdjustment(E);
682 if (!adj) return src;
John McCalla8bbb822010-08-22 03:04:22 +0000683
684 CGBuilderTy &Builder = CGF.Builder;
John McCallc62bb392012-02-15 01:22:51 +0000685 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
John McCalla8bbb822010-08-22 03:04:22 +0000686
John McCallc62bb392012-02-15 01:22:51 +0000687 const MemberPointerType *destTy =
688 E->getType()->castAs<MemberPointerType>();
John McCall1c456c82010-08-22 06:43:33 +0000689
John McCall7a9aac22010-08-23 01:21:21 +0000690 // For member data pointers, this is just a matter of adding the
691 // offset if the source is non-null.
John McCallc62bb392012-02-15 01:22:51 +0000692 if (destTy->isMemberDataPointer()) {
693 llvm::Value *dst;
694 if (isDerivedToBase)
695 dst = Builder.CreateNSWSub(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000696 else
John McCallc62bb392012-02-15 01:22:51 +0000697 dst = Builder.CreateNSWAdd(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000698
699 // Null check.
John McCallc62bb392012-02-15 01:22:51 +0000700 llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType());
701 llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull");
702 return Builder.CreateSelect(isNull, src, dst);
John McCall7a9aac22010-08-23 01:21:21 +0000703 }
704
John McCalla1dee5302010-08-22 10:59:02 +0000705 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000706 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000707 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
708 offset <<= 1;
709 adj = llvm::ConstantInt::get(adj->getType(), offset);
John McCalla1dee5302010-08-22 10:59:02 +0000710 }
711
John McCallc62bb392012-02-15 01:22:51 +0000712 llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj");
713 llvm::Value *dstAdj;
714 if (isDerivedToBase)
715 dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000716 else
John McCallc62bb392012-02-15 01:22:51 +0000717 dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000718
John McCallc62bb392012-02-15 01:22:51 +0000719 return Builder.CreateInsertValue(src, dstAdj, 1);
720}
721
722llvm::Constant *
723ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E,
724 llvm::Constant *src) {
725 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
726 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
727 E->getCastKind() == CK_ReinterpretMemberPointer);
728
729 // Under Itanium, reinterprets don't require any additional processing.
730 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
731
732 // If the adjustment is trivial, we don't need to do anything.
733 llvm::Constant *adj = getMemberPointerAdjustment(E);
734 if (!adj) return src;
735
736 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
737
738 const MemberPointerType *destTy =
739 E->getType()->castAs<MemberPointerType>();
740
741 // For member data pointers, this is just a matter of adding the
742 // offset if the source is non-null.
743 if (destTy->isMemberDataPointer()) {
744 // null maps to null.
745 if (src->isAllOnesValue()) return src;
746
747 if (isDerivedToBase)
748 return llvm::ConstantExpr::getNSWSub(src, adj);
749 else
750 return llvm::ConstantExpr::getNSWAdd(src, adj);
751 }
752
753 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000754 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000755 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
756 offset <<= 1;
757 adj = llvm::ConstantInt::get(adj->getType(), offset);
758 }
759
760 llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1);
761 llvm::Constant *dstAdj;
762 if (isDerivedToBase)
763 dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj);
764 else
765 dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj);
766
767 return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1);
John McCalla8bbb822010-08-22 03:04:22 +0000768}
John McCall84fa5102010-08-22 04:16:24 +0000769
770llvm::Constant *
John McCall7a9aac22010-08-23 01:21:21 +0000771ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
John McCall7a9aac22010-08-23 01:21:21 +0000772 // Itanium C++ ABI 2.3:
773 // A NULL pointer is represented as -1.
774 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000775 return llvm::ConstantInt::get(CGM.PtrDiffTy, -1ULL, /*isSigned=*/true);
John McCalla1dee5302010-08-22 10:59:02 +0000776
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000777 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.PtrDiffTy, 0);
John McCalla1dee5302010-08-22 10:59:02 +0000778 llvm::Constant *Values[2] = { Zero, Zero };
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000779 return llvm::ConstantStruct::getAnon(Values);
John McCall84fa5102010-08-22 04:16:24 +0000780}
781
John McCallf3a88602011-02-03 08:15:49 +0000782llvm::Constant *
783ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
784 CharUnits offset) {
John McCall7a9aac22010-08-23 01:21:21 +0000785 // Itanium C++ ABI 2.3:
786 // A pointer to data member is an offset from the base address of
787 // the class object containing it, represented as a ptrdiff_t
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000788 return llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity());
John McCall7a9aac22010-08-23 01:21:21 +0000789}
790
David Majnemere2be95b2015-06-23 07:31:01 +0000791llvm::Constant *
792ItaniumCXXABI::EmitMemberFunctionPointer(const CXXMethodDecl *MD) {
Richard Smithdafff942012-01-14 04:30:29 +0000793 return BuildMemberPointer(MD, CharUnits::Zero());
794}
795
796llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD,
797 CharUnits ThisAdjustment) {
John McCalla1dee5302010-08-22 10:59:02 +0000798 assert(MD->isInstance() && "Member function must not be static!");
799 MD = MD->getCanonicalDecl();
800
801 CodeGenTypes &Types = CGM.getTypes();
John McCalla1dee5302010-08-22 10:59:02 +0000802
803 // Get the function pointer (or index if this is a virtual function).
804 llvm::Constant *MemPtr[2];
805 if (MD->isVirtual()) {
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000806 uint64_t Index = CGM.getItaniumVTableContext().getMethodVTableIndex(MD);
John McCalla1dee5302010-08-22 10:59:02 +0000807
Ken Dyckdf016282011-04-09 01:30:02 +0000808 const ASTContext &Context = getContext();
809 CharUnits PointerWidth =
Douglas Gregore8bbc122011-09-02 00:18:52 +0000810 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Ken Dyckdf016282011-04-09 01:30:02 +0000811 uint64_t VTableOffset = (Index * PointerWidth.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000812
Mark Seabornedf0d382013-07-24 16:25:13 +0000813 if (UseARMMethodPtrABI) {
John McCalla1dee5302010-08-22 10:59:02 +0000814 // ARM C++ ABI 3.2.1:
815 // This ABI specifies that adj contains twice the this
816 // adjustment, plus 1 if the member function is virtual. The
817 // least significant bit of adj then makes exactly the same
818 // discrimination as the least significant bit of ptr does for
819 // Itanium.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000820 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset);
821 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000822 2 * ThisAdjustment.getQuantity() + 1);
John McCalla1dee5302010-08-22 10:59:02 +0000823 } else {
824 // Itanium C++ ABI 2.3:
825 // For a virtual function, [the pointer field] is 1 plus the
826 // virtual table offset (in bytes) of the function,
827 // represented as a ptrdiff_t.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000828 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset + 1);
829 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000830 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000831 }
832 } else {
John McCall2979fe02011-04-12 00:42:48 +0000833 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
Chris Lattner2192fe52011-07-18 04:24:23 +0000834 llvm::Type *Ty;
John McCall2979fe02011-04-12 00:42:48 +0000835 // Check whether the function has a computable LLVM signature.
Chris Lattner8806e322011-07-10 00:18:59 +0000836 if (Types.isFuncTypeConvertible(FPT)) {
John McCall2979fe02011-04-12 00:42:48 +0000837 // The function has a computable LLVM signature; use the correct type.
John McCalla729c622012-02-17 03:33:10 +0000838 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
John McCalla1dee5302010-08-22 10:59:02 +0000839 } else {
John McCall2979fe02011-04-12 00:42:48 +0000840 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
841 // function type is incomplete.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000842 Ty = CGM.PtrDiffTy;
John McCalla1dee5302010-08-22 10:59:02 +0000843 }
John McCall2979fe02011-04-12 00:42:48 +0000844 llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty);
John McCalla1dee5302010-08-22 10:59:02 +0000845
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000846 MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, CGM.PtrDiffTy);
Mark Seabornedf0d382013-07-24 16:25:13 +0000847 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
848 (UseARMMethodPtrABI ? 2 : 1) *
Richard Smithdafff942012-01-14 04:30:29 +0000849 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000850 }
John McCall1c456c82010-08-22 06:43:33 +0000851
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000852 return llvm::ConstantStruct::getAnon(MemPtr);
John McCall1c456c82010-08-22 06:43:33 +0000853}
854
Richard Smithdafff942012-01-14 04:30:29 +0000855llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP,
856 QualType MPType) {
857 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
858 const ValueDecl *MPD = MP.getMemberPointerDecl();
859 if (!MPD)
860 return EmitNullMemberPointer(MPT);
861
Reid Kleckner452abac2013-05-09 21:01:17 +0000862 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
Richard Smithdafff942012-01-14 04:30:29 +0000863
864 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
865 return BuildMemberPointer(MD, ThisAdjustment);
866
867 CharUnits FieldOffset =
868 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
869 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
870}
871
John McCall131d97d2010-08-22 08:30:07 +0000872/// The comparison algorithm is pretty easy: the member pointers are
873/// the same if they're either bitwise identical *or* both null.
874///
875/// ARM is different here only because null-ness is more complicated.
876llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000877ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
878 llvm::Value *L,
879 llvm::Value *R,
880 const MemberPointerType *MPT,
881 bool Inequality) {
John McCall131d97d2010-08-22 08:30:07 +0000882 CGBuilderTy &Builder = CGF.Builder;
883
John McCall131d97d2010-08-22 08:30:07 +0000884 llvm::ICmpInst::Predicate Eq;
885 llvm::Instruction::BinaryOps And, Or;
886 if (Inequality) {
887 Eq = llvm::ICmpInst::ICMP_NE;
888 And = llvm::Instruction::Or;
889 Or = llvm::Instruction::And;
890 } else {
891 Eq = llvm::ICmpInst::ICMP_EQ;
892 And = llvm::Instruction::And;
893 Or = llvm::Instruction::Or;
894 }
895
John McCall7a9aac22010-08-23 01:21:21 +0000896 // Member data pointers are easy because there's a unique null
897 // value, so it just comes down to bitwise equality.
898 if (MPT->isMemberDataPointer())
899 return Builder.CreateICmp(Eq, L, R);
900
901 // For member function pointers, the tautologies are more complex.
902 // The Itanium tautology is:
John McCall61a14882010-08-23 06:56:36 +0000903 // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
John McCall7a9aac22010-08-23 01:21:21 +0000904 // The ARM tautology is:
John McCall61a14882010-08-23 06:56:36 +0000905 // (L == R) <==> (L.ptr == R.ptr &&
906 // (L.adj == R.adj ||
907 // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
John McCall7a9aac22010-08-23 01:21:21 +0000908 // The inequality tautologies have exactly the same structure, except
909 // applying De Morgan's laws.
910
911 llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
912 llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
913
John McCall131d97d2010-08-22 08:30:07 +0000914 // This condition tests whether L.ptr == R.ptr. This must always be
915 // true for equality to hold.
916 llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
917
918 // This condition, together with the assumption that L.ptr == R.ptr,
919 // tests whether the pointers are both null. ARM imposes an extra
920 // condition.
921 llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
922 llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
923
924 // This condition tests whether L.adj == R.adj. If this isn't
925 // true, the pointers are unequal unless they're both null.
John McCalla1dee5302010-08-22 10:59:02 +0000926 llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
927 llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000928 llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
929
930 // Null member function pointers on ARM clear the low bit of Adj,
931 // so the zero condition has to check that neither low bit is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000932 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000933 llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
934
935 // Compute (l.adj | r.adj) & 1 and test it against zero.
936 llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
937 llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
938 llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
939 "cmp.or.adj");
940 EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
941 }
942
943 // Tie together all our conditions.
944 llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
945 Result = Builder.CreateBinOp(And, PtrEq, Result,
946 Inequality ? "memptr.ne" : "memptr.eq");
947 return Result;
948}
949
950llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000951ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
952 llvm::Value *MemPtr,
953 const MemberPointerType *MPT) {
John McCall131d97d2010-08-22 08:30:07 +0000954 CGBuilderTy &Builder = CGF.Builder;
John McCall7a9aac22010-08-23 01:21:21 +0000955
956 /// For member data pointers, this is just a check against -1.
957 if (MPT->isMemberDataPointer()) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000958 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCall7a9aac22010-08-23 01:21:21 +0000959 llvm::Value *NegativeOne =
960 llvm::Constant::getAllOnesValue(MemPtr->getType());
961 return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
962 }
John McCall131d97d2010-08-22 08:30:07 +0000963
Daniel Dunbar914bc412011-04-19 23:10:47 +0000964 // In Itanium, a member function pointer is not null if 'ptr' is not null.
John McCalla1dee5302010-08-22 10:59:02 +0000965 llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
John McCall131d97d2010-08-22 08:30:07 +0000966
967 llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
968 llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
969
Daniel Dunbar914bc412011-04-19 23:10:47 +0000970 // On ARM, a member function pointer is also non-null if the low bit of 'adj'
971 // (the virtual bit) is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000972 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000973 llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
John McCalla1dee5302010-08-22 10:59:02 +0000974 llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000975 llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
Daniel Dunbar914bc412011-04-19 23:10:47 +0000976 llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero,
977 "memptr.isvirtual");
978 Result = Builder.CreateOr(Result, IsVirtual);
John McCall131d97d2010-08-22 08:30:07 +0000979 }
980
981 return Result;
982}
John McCall1c456c82010-08-22 06:43:33 +0000983
Reid Kleckner40ca9132014-05-13 22:05:45 +0000984bool ItaniumCXXABI::classifyReturnType(CGFunctionInfo &FI) const {
985 const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl();
986 if (!RD)
987 return false;
988
Reid Klecknerd355ca72014-05-15 01:26:32 +0000989 // Return indirectly if we have a non-trivial copy ctor or non-trivial dtor.
990 // FIXME: Use canCopyArgument() when it is fixed to handle lazily declared
991 // special members.
992 if (RD->hasNonTrivialDestructor() || RD->hasNonTrivialCopyConstructor()) {
John McCall7f416cc2015-09-08 08:05:57 +0000993 auto Align = CGM.getContext().getTypeAlignInChars(FI.getReturnType());
994 FI.getReturnInfo() = ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
Reid Kleckner40ca9132014-05-13 22:05:45 +0000995 return true;
996 }
Reid Kleckner40ca9132014-05-13 22:05:45 +0000997 return false;
998}
999
John McCall614dbdc2010-08-22 21:01:12 +00001000/// The Itanium ABI requires non-zero initialization only for data
1001/// member pointers, for which '0' is a valid offset.
1002bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
David Majnemer5fd33e02015-04-24 01:25:08 +00001003 return MPT->isMemberFunctionPointer();
John McCall84fa5102010-08-22 04:16:24 +00001004}
John McCall5d865c322010-08-31 07:33:07 +00001005
John McCall82fb8922012-09-25 10:10:39 +00001006/// The Itanium ABI always places an offset to the complete object
1007/// at entry -2 in the vtable.
David Majnemer08681372014-11-01 07:37:17 +00001008void ItaniumCXXABI::emitVirtualObjectDelete(CodeGenFunction &CGF,
1009 const CXXDeleteExpr *DE,
John McCall7f416cc2015-09-08 08:05:57 +00001010 Address Ptr,
David Majnemer08681372014-11-01 07:37:17 +00001011 QualType ElementType,
1012 const CXXDestructorDecl *Dtor) {
1013 bool UseGlobalDelete = DE->isGlobalDelete();
David Majnemer0c0b6d92014-10-31 20:09:12 +00001014 if (UseGlobalDelete) {
1015 // Derive the complete-object pointer, which is what we need
1016 // to pass to the deallocation function.
John McCall82fb8922012-09-25 10:10:39 +00001017
David Majnemer0c0b6d92014-10-31 20:09:12 +00001018 // Grab the vtable pointer as an intptr_t*.
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001019 auto *ClassDecl =
1020 cast<CXXRecordDecl>(ElementType->getAs<RecordType>()->getDecl());
1021 llvm::Value *VTable =
1022 CGF.GetVTablePtr(Ptr, CGF.IntPtrTy->getPointerTo(), ClassDecl);
John McCall82fb8922012-09-25 10:10:39 +00001023
David Majnemer0c0b6d92014-10-31 20:09:12 +00001024 // Track back to entry -2 and pull out the offset there.
1025 llvm::Value *OffsetPtr = CGF.Builder.CreateConstInBoundsGEP1_64(
1026 VTable, -2, "complete-offset.ptr");
John McCall7f416cc2015-09-08 08:05:57 +00001027 llvm::Value *Offset =
1028 CGF.Builder.CreateAlignedLoad(OffsetPtr, CGF.getPointerAlign());
David Majnemer0c0b6d92014-10-31 20:09:12 +00001029
1030 // Apply the offset.
John McCall7f416cc2015-09-08 08:05:57 +00001031 llvm::Value *CompletePtr =
1032 CGF.Builder.CreateBitCast(Ptr.getPointer(), CGF.Int8PtrTy);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001033 CompletePtr = CGF.Builder.CreateInBoundsGEP(CompletePtr, Offset);
1034
1035 // If we're supposed to call the global delete, make sure we do so
1036 // even if the destructor throws.
David Majnemer08681372014-11-01 07:37:17 +00001037 CGF.pushCallObjectDeleteCleanup(DE->getOperatorDelete(), CompletePtr,
1038 ElementType);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001039 }
1040
1041 // FIXME: Provide a source location here even though there's no
1042 // CXXMemberCallExpr for dtor call.
1043 CXXDtorType DtorType = UseGlobalDelete ? Dtor_Complete : Dtor_Deleting;
1044 EmitVirtualDestructorCall(CGF, Dtor, DtorType, Ptr, /*CE=*/nullptr);
1045
1046 if (UseGlobalDelete)
1047 CGF.PopCleanupBlock();
John McCall82fb8922012-09-25 10:10:39 +00001048}
1049
David Majnemer442d0a22014-11-25 07:20:20 +00001050void ItaniumCXXABI::emitRethrow(CodeGenFunction &CGF, bool isNoReturn) {
1051 // void __cxa_rethrow();
1052
1053 llvm::FunctionType *FTy =
1054 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
1055
1056 llvm::Constant *Fn = CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow");
1057
1058 if (isNoReturn)
1059 CGF.EmitNoreturnRuntimeCallOrInvoke(Fn, None);
1060 else
1061 CGF.EmitRuntimeCallOrInvoke(Fn);
1062}
1063
David Majnemer7c237072015-03-05 00:46:22 +00001064static llvm::Constant *getAllocateExceptionFn(CodeGenModule &CGM) {
1065 // void *__cxa_allocate_exception(size_t thrown_size);
1066
1067 llvm::FunctionType *FTy =
1068 llvm::FunctionType::get(CGM.Int8PtrTy, CGM.SizeTy, /*IsVarArgs=*/false);
1069
1070 return CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
1071}
1072
1073static llvm::Constant *getThrowFn(CodeGenModule &CGM) {
1074 // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
1075 // void (*dest) (void *));
1076
1077 llvm::Type *Args[3] = { CGM.Int8PtrTy, CGM.Int8PtrTy, CGM.Int8PtrTy };
1078 llvm::FunctionType *FTy =
1079 llvm::FunctionType::get(CGM.VoidTy, Args, /*IsVarArgs=*/false);
1080
1081 return CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
1082}
1083
1084void ItaniumCXXABI::emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) {
1085 QualType ThrowType = E->getSubExpr()->getType();
1086 // Now allocate the exception object.
1087 llvm::Type *SizeTy = CGF.ConvertType(getContext().getSizeType());
1088 uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
1089
1090 llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(CGM);
1091 llvm::CallInst *ExceptionPtr = CGF.EmitNounwindRuntimeCall(
1092 AllocExceptionFn, llvm::ConstantInt::get(SizeTy, TypeSize), "exception");
1093
John McCall7f416cc2015-09-08 08:05:57 +00001094 CharUnits ExnAlign = getAlignmentOfExnObject();
1095 CGF.EmitAnyExprToExn(E->getSubExpr(), Address(ExceptionPtr, ExnAlign));
David Majnemer7c237072015-03-05 00:46:22 +00001096
1097 // Now throw the exception.
1098 llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType,
1099 /*ForEH=*/true);
1100
1101 // The address of the destructor. If the exception type has a
1102 // trivial destructor (or isn't a record), we just pass null.
1103 llvm::Constant *Dtor = nullptr;
1104 if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
1105 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
1106 if (!Record->hasTrivialDestructor()) {
1107 CXXDestructorDecl *DtorD = Record->getDestructor();
1108 Dtor = CGM.getAddrOfCXXStructor(DtorD, StructorType::Complete);
1109 Dtor = llvm::ConstantExpr::getBitCast(Dtor, CGM.Int8PtrTy);
1110 }
1111 }
1112 if (!Dtor) Dtor = llvm::Constant::getNullValue(CGM.Int8PtrTy);
1113
1114 llvm::Value *args[] = { ExceptionPtr, TypeInfo, Dtor };
1115 CGF.EmitNoreturnRuntimeCallOrInvoke(getThrowFn(CGM), args);
1116}
1117
David Majnemer1162d252014-06-22 19:05:33 +00001118static llvm::Constant *getItaniumDynamicCastFn(CodeGenFunction &CGF) {
1119 // void *__dynamic_cast(const void *sub,
1120 // const abi::__class_type_info *src,
1121 // const abi::__class_type_info *dst,
1122 // std::ptrdiff_t src2dst_offset);
1123
1124 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
1125 llvm::Type *PtrDiffTy =
1126 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1127
1128 llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
1129
1130 llvm::FunctionType *FTy = llvm::FunctionType::get(Int8PtrTy, Args, false);
1131
1132 // Mark the function as nounwind readonly.
1133 llvm::Attribute::AttrKind FuncAttrs[] = { llvm::Attribute::NoUnwind,
1134 llvm::Attribute::ReadOnly };
1135 llvm::AttributeSet Attrs = llvm::AttributeSet::get(
1136 CGF.getLLVMContext(), llvm::AttributeSet::FunctionIndex, FuncAttrs);
1137
1138 return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast", Attrs);
1139}
1140
1141static llvm::Constant *getBadCastFn(CodeGenFunction &CGF) {
1142 // void __cxa_bad_cast();
1143 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1144 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
1145}
1146
1147/// \brief Compute the src2dst_offset hint as described in the
1148/// Itanium C++ ABI [2.9.7]
1149static CharUnits computeOffsetHint(ASTContext &Context,
1150 const CXXRecordDecl *Src,
1151 const CXXRecordDecl *Dst) {
1152 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1153 /*DetectVirtual=*/false);
1154
1155 // If Dst is not derived from Src we can skip the whole computation below and
1156 // return that Src is not a public base of Dst. Record all inheritance paths.
1157 if (!Dst->isDerivedFrom(Src, Paths))
1158 return CharUnits::fromQuantity(-2ULL);
1159
1160 unsigned NumPublicPaths = 0;
1161 CharUnits Offset;
1162
1163 // Now walk all possible inheritance paths.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001164 for (const CXXBasePath &Path : Paths) {
1165 if (Path.Access != AS_public) // Ignore non-public inheritance.
David Majnemer1162d252014-06-22 19:05:33 +00001166 continue;
1167
1168 ++NumPublicPaths;
1169
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001170 for (const CXXBasePathElement &PathElement : Path) {
David Majnemer1162d252014-06-22 19:05:33 +00001171 // If the path contains a virtual base class we can't give any hint.
1172 // -1: no hint.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001173 if (PathElement.Base->isVirtual())
David Majnemer1162d252014-06-22 19:05:33 +00001174 return CharUnits::fromQuantity(-1ULL);
1175
1176 if (NumPublicPaths > 1) // Won't use offsets, skip computation.
1177 continue;
1178
1179 // Accumulate the base class offsets.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001180 const ASTRecordLayout &L = Context.getASTRecordLayout(PathElement.Class);
1181 Offset += L.getBaseClassOffset(
1182 PathElement.Base->getType()->getAsCXXRecordDecl());
David Majnemer1162d252014-06-22 19:05:33 +00001183 }
1184 }
1185
1186 // -2: Src is not a public base of Dst.
1187 if (NumPublicPaths == 0)
1188 return CharUnits::fromQuantity(-2ULL);
1189
1190 // -3: Src is a multiple public base type but never a virtual base type.
1191 if (NumPublicPaths > 1)
1192 return CharUnits::fromQuantity(-3ULL);
1193
1194 // Otherwise, the Src type is a unique public nonvirtual base type of Dst.
1195 // Return the offset of Src from the origin of Dst.
1196 return Offset;
1197}
1198
1199static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) {
1200 // void __cxa_bad_typeid();
1201 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1202
1203 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
1204}
1205
1206bool ItaniumCXXABI::shouldTypeidBeNullChecked(bool IsDeref,
1207 QualType SrcRecordTy) {
1208 return IsDeref;
1209}
1210
1211void ItaniumCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) {
1212 llvm::Value *Fn = getBadTypeidFn(CGF);
1213 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
1214 CGF.Builder.CreateUnreachable();
1215}
1216
1217llvm::Value *ItaniumCXXABI::EmitTypeid(CodeGenFunction &CGF,
1218 QualType SrcRecordTy,
John McCall7f416cc2015-09-08 08:05:57 +00001219 Address ThisPtr,
David Majnemer1162d252014-06-22 19:05:33 +00001220 llvm::Type *StdTypeInfoPtrTy) {
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001221 auto *ClassDecl =
1222 cast<CXXRecordDecl>(SrcRecordTy->getAs<RecordType>()->getDecl());
David Majnemer1162d252014-06-22 19:05:33 +00001223 llvm::Value *Value =
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001224 CGF.GetVTablePtr(ThisPtr, StdTypeInfoPtrTy->getPointerTo(), ClassDecl);
David Majnemer1162d252014-06-22 19:05:33 +00001225
1226 // Load the type info.
1227 Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL);
John McCall7f416cc2015-09-08 08:05:57 +00001228 return CGF.Builder.CreateAlignedLoad(Value, CGF.getPointerAlign());
David Majnemer1162d252014-06-22 19:05:33 +00001229}
1230
1231bool ItaniumCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
1232 QualType SrcRecordTy) {
1233 return SrcIsPtr;
1234}
1235
1236llvm::Value *ItaniumCXXABI::EmitDynamicCastCall(
John McCall7f416cc2015-09-08 08:05:57 +00001237 CodeGenFunction &CGF, Address ThisAddr, QualType SrcRecordTy,
David Majnemer1162d252014-06-22 19:05:33 +00001238 QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) {
1239 llvm::Type *PtrDiffLTy =
1240 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1241 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1242
1243 llvm::Value *SrcRTTI =
1244 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
1245 llvm::Value *DestRTTI =
1246 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
1247
1248 // Compute the offset hint.
1249 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
1250 const CXXRecordDecl *DestDecl = DestRecordTy->getAsCXXRecordDecl();
1251 llvm::Value *OffsetHint = llvm::ConstantInt::get(
1252 PtrDiffLTy,
1253 computeOffsetHint(CGF.getContext(), SrcDecl, DestDecl).getQuantity());
1254
1255 // Emit the call to __dynamic_cast.
John McCall7f416cc2015-09-08 08:05:57 +00001256 llvm::Value *Value = ThisAddr.getPointer();
David Majnemer1162d252014-06-22 19:05:33 +00001257 Value = CGF.EmitCastToVoidPtr(Value);
1258
1259 llvm::Value *args[] = {Value, SrcRTTI, DestRTTI, OffsetHint};
1260 Value = CGF.EmitNounwindRuntimeCall(getItaniumDynamicCastFn(CGF), args);
1261 Value = CGF.Builder.CreateBitCast(Value, DestLTy);
1262
1263 /// C++ [expr.dynamic.cast]p9:
1264 /// A failed cast to reference type throws std::bad_cast
1265 if (DestTy->isReferenceType()) {
1266 llvm::BasicBlock *BadCastBlock =
1267 CGF.createBasicBlock("dynamic_cast.bad_cast");
1268
1269 llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
1270 CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
1271
1272 CGF.EmitBlock(BadCastBlock);
1273 EmitBadCastCall(CGF);
1274 }
1275
1276 return Value;
1277}
1278
1279llvm::Value *ItaniumCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001280 Address ThisAddr,
David Majnemer1162d252014-06-22 19:05:33 +00001281 QualType SrcRecordTy,
1282 QualType DestTy) {
1283 llvm::Type *PtrDiffLTy =
1284 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1285 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1286
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001287 auto *ClassDecl =
1288 cast<CXXRecordDecl>(SrcRecordTy->getAs<RecordType>()->getDecl());
David Majnemer1162d252014-06-22 19:05:33 +00001289 // Get the vtable pointer.
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001290 llvm::Value *VTable = CGF.GetVTablePtr(ThisAddr, PtrDiffLTy->getPointerTo(),
1291 ClassDecl);
David Majnemer1162d252014-06-22 19:05:33 +00001292
1293 // Get the offset-to-top from the vtable.
1294 llvm::Value *OffsetToTop =
1295 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL);
John McCall7f416cc2015-09-08 08:05:57 +00001296 OffsetToTop =
1297 CGF.Builder.CreateAlignedLoad(OffsetToTop, CGF.getPointerAlign(),
1298 "offset.to.top");
David Majnemer1162d252014-06-22 19:05:33 +00001299
1300 // Finally, add the offset to the pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001301 llvm::Value *Value = ThisAddr.getPointer();
David Majnemer1162d252014-06-22 19:05:33 +00001302 Value = CGF.EmitCastToVoidPtr(Value);
1303 Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop);
1304
1305 return CGF.Builder.CreateBitCast(Value, DestLTy);
1306}
1307
1308bool ItaniumCXXABI::EmitBadCastCall(CodeGenFunction &CGF) {
1309 llvm::Value *Fn = getBadCastFn(CGF);
1310 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
1311 CGF.Builder.CreateUnreachable();
1312 return true;
1313}
1314
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001315llvm::Value *
1316ItaniumCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001317 Address This,
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001318 const CXXRecordDecl *ClassDecl,
1319 const CXXRecordDecl *BaseClassDecl) {
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001320 llvm::Value *VTablePtr = CGF.GetVTablePtr(This, CGM.Int8PtrTy, ClassDecl);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001321 CharUnits VBaseOffsetOffset =
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001322 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(ClassDecl,
1323 BaseClassDecl);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001324
1325 llvm::Value *VBaseOffsetPtr =
1326 CGF.Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
1327 "vbase.offset.ptr");
1328 VBaseOffsetPtr = CGF.Builder.CreateBitCast(VBaseOffsetPtr,
1329 CGM.PtrDiffTy->getPointerTo());
1330
1331 llvm::Value *VBaseOffset =
John McCall7f416cc2015-09-08 08:05:57 +00001332 CGF.Builder.CreateAlignedLoad(VBaseOffsetPtr, CGF.getPointerAlign(),
1333 "vbase.offset");
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001334
1335 return VBaseOffset;
1336}
1337
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001338void ItaniumCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
1339 // Just make sure we're in sync with TargetCXXABI.
1340 assert(CGM.getTarget().getCXXABI().hasConstructorVariants());
1341
Rafael Espindolac3cde362013-12-09 14:51:17 +00001342 // The constructor used for constructing this as a base class;
1343 // ignores virtual bases.
1344 CGM.EmitGlobal(GlobalDecl(D, Ctor_Base));
1345
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001346 // The constructor used for constructing this as a complete class;
Nico Weber4c2ffb22015-01-07 05:25:05 +00001347 // constructs the virtual bases, then calls the base constructor.
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001348 if (!D->getParent()->isAbstract()) {
1349 // We don't need to emit the complete ctor if the class is abstract.
1350 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
1351 }
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001352}
1353
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001354void
1355ItaniumCXXABI::buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
1356 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9bca9232010-09-02 10:25:57 +00001357 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001358
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001359 // All parameters are already in place except VTT, which goes after 'this'.
1360 // These are Clang types, so we don't need to worry about sret yet.
John McCall5d865c322010-08-31 07:33:07 +00001361
1362 // Check if we need to add a VTT parameter (which has type void **).
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001363 if (T == StructorType::Base && MD->getParent()->getNumVBases() != 0)
1364 ArgTys.insert(ArgTys.begin() + 1,
1365 Context.getPointerType(Context.VoidPtrTy));
John McCall5d865c322010-08-31 07:33:07 +00001366}
1367
Reid Klecknere7de47e2013-07-22 13:51:44 +00001368void ItaniumCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
Rafael Espindolac3cde362013-12-09 14:51:17 +00001369 // The destructor used for destructing this as a base class; ignores
1370 // virtual bases.
1371 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001372
1373 // The destructor used for destructing this as a most-derived class;
1374 // call the base destructor and then destructs any virtual bases.
1375 CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));
1376
Rafael Espindolac3cde362013-12-09 14:51:17 +00001377 // The destructor in a virtual table is always a 'deleting'
1378 // destructor, which calls the complete destructor and then uses the
1379 // appropriate operator delete.
1380 if (D->isVirtual())
1381 CGM.EmitGlobal(GlobalDecl(D, Dtor_Deleting));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001382}
1383
Reid Kleckner89077a12013-12-17 19:46:40 +00001384void ItaniumCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
1385 QualType &ResTy,
1386 FunctionArgList &Params) {
John McCall5d865c322010-08-31 07:33:07 +00001387 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
Reid Kleckner89077a12013-12-17 19:46:40 +00001388 assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
John McCall5d865c322010-08-31 07:33:07 +00001389
1390 // Check if we need a VTT parameter as well.
Peter Collingbourne66f82e62013-06-28 20:45:28 +00001391 if (NeedsVTTParameter(CGF.CurGD)) {
John McCall9bca9232010-09-02 10:25:57 +00001392 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001393
1394 // FIXME: avoid the fake decl
1395 QualType T = Context.getPointerType(Context.VoidPtrTy);
1396 ImplicitParamDecl *VTTDecl
Craig Topper8a13c412014-05-21 05:09:00 +00001397 = ImplicitParamDecl::Create(Context, nullptr, MD->getLocation(),
John McCall5d865c322010-08-31 07:33:07 +00001398 &Context.Idents.get("vtt"), T);
Reid Kleckner89077a12013-12-17 19:46:40 +00001399 Params.insert(Params.begin() + 1, VTTDecl);
Reid Kleckner2af6d732013-12-13 00:09:59 +00001400 getStructorImplicitParamDecl(CGF) = VTTDecl;
John McCall5d865c322010-08-31 07:33:07 +00001401 }
1402}
1403
John McCall5d865c322010-08-31 07:33:07 +00001404void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
Justin Lebared4f1722016-07-27 22:04:24 +00001405 // Naked functions have no prolog.
1406 if (CGF.CurFuncDecl && CGF.CurFuncDecl->hasAttr<NakedAttr>())
1407 return;
1408
John McCall5d865c322010-08-31 07:33:07 +00001409 /// Initialize the 'this' slot.
1410 EmitThisParam(CGF);
1411
1412 /// Initialize the 'vtt' slot if needed.
Reid Kleckner2af6d732013-12-13 00:09:59 +00001413 if (getStructorImplicitParamDecl(CGF)) {
1414 getStructorImplicitParamValue(CGF) = CGF.Builder.CreateLoad(
1415 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), "vtt");
John McCall5d865c322010-08-31 07:33:07 +00001416 }
John McCall5d865c322010-08-31 07:33:07 +00001417
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001418 /// If this is a function that the ABI specifies returns 'this', initialize
1419 /// the return slot to 'this' at the start of the function.
1420 ///
1421 /// Unlike the setting of return types, this is done within the ABI
1422 /// implementation instead of by clients of CGCXXABI because:
1423 /// 1) getThisValue is currently protected
1424 /// 2) in theory, an ABI could implement 'this' returns some other way;
1425 /// HasThisReturn only specifies a contract, not the implementation
John McCall5d865c322010-08-31 07:33:07 +00001426 if (HasThisReturn(CGF.CurGD))
Eli Friedman9fbeba02012-02-11 02:57:39 +00001427 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
John McCall5d865c322010-08-31 07:33:07 +00001428}
1429
Reid Kleckner89077a12013-12-17 19:46:40 +00001430unsigned ItaniumCXXABI::addImplicitConstructorArgs(
1431 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
1432 bool ForVirtualBase, bool Delegating, CallArgList &Args) {
1433 if (!NeedsVTTParameter(GlobalDecl(D, Type)))
1434 return 0;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001435
Reid Kleckner89077a12013-12-17 19:46:40 +00001436 // Insert the implicit 'vtt' argument as the second argument.
1437 llvm::Value *VTT =
1438 CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase, Delegating);
1439 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1440 Args.insert(Args.begin() + 1,
1441 CallArg(RValue::get(VTT), VTTTy, /*needscopy=*/false));
1442 return 1; // Added one arg.
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001443}
1444
1445void ItaniumCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
1446 const CXXDestructorDecl *DD,
1447 CXXDtorType Type, bool ForVirtualBase,
John McCall7f416cc2015-09-08 08:05:57 +00001448 bool Delegating, Address This) {
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001449 GlobalDecl GD(DD, Type);
1450 llvm::Value *VTT = CGF.GetVTTParameter(GD, ForVirtualBase, Delegating);
1451 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1452
John McCallb92ab1a2016-10-26 23:46:34 +00001453 CGCallee Callee;
1454 if (getContext().getLangOpts().AppleKext &&
1455 Type != Dtor_Base && DD->isVirtual())
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001456 Callee = CGF.BuildAppleKextVirtualDestructorCall(DD, Type, DD->getParent());
John McCallb92ab1a2016-10-26 23:46:34 +00001457 else
1458 Callee =
1459 CGCallee::forDirect(CGM.getAddrOfCXXStructor(DD, getFromDtorType(Type)),
1460 DD);
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001461
John McCall7f416cc2015-09-08 08:05:57 +00001462 CGF.EmitCXXMemberOrOperatorCall(DD, Callee, ReturnValueSlot(),
Richard Smith762672a2016-09-28 19:09:10 +00001463 This.getPointer(), VTT, VTTTy,
1464 nullptr, nullptr);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001465}
1466
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001467void ItaniumCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
1468 const CXXRecordDecl *RD) {
1469 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, CharUnits());
1470 if (VTable->hasInitializer())
1471 return;
1472
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001473 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001474 const VTableLayout &VTLayout = VTContext.getVTableLayout(RD);
1475 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
David Majnemerd905da42014-07-01 20:30:31 +00001476 llvm::Constant *RTTI =
1477 CGM.GetAddrOfRTTIDescriptor(CGM.getContext().getTagDeclType(RD));
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001478
1479 // Create and set the initializer.
Peter Collingbournee53683f2016-09-08 01:14:39 +00001480 llvm::Constant *Init = CGVT.CreateVTableInitializer(VTLayout, RTTI);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001481 VTable->setInitializer(Init);
1482
1483 // Set the correct linkage.
1484 VTable->setLinkage(Linkage);
1485
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00001486 if (CGM.supportsCOMDAT() && VTable->isWeakForLinker())
1487 VTable->setComdat(CGM.getModule().getOrInsertComdat(VTable->getName()));
Rafael Espindolacb92c192015-01-15 23:18:01 +00001488
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001489 // Set the right visibility.
John McCall8f80a612014-02-08 00:41:16 +00001490 CGM.setGlobalVisibility(VTable, RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001491
Benjamin Kramer5d34a2b2014-09-10 12:50:59 +00001492 // Use pointer alignment for the vtable. Otherwise we would align them based
1493 // on the size of the initializer which doesn't make sense as only single
1494 // values are read.
1495 unsigned PAlign = CGM.getTarget().getPointerAlign(0);
1496 VTable->setAlignment(getContext().toCharUnitsFromBits(PAlign).getQuantity());
1497
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001498 // If this is the magic class __cxxabiv1::__fundamental_type_info,
1499 // we will emit the typeinfo for the fundamental types. This is the
1500 // same behaviour as GCC.
1501 const DeclContext *DC = RD->getDeclContext();
1502 if (RD->getIdentifier() &&
1503 RD->getIdentifier()->isStr("__fundamental_type_info") &&
1504 isa<NamespaceDecl>(DC) && cast<NamespaceDecl>(DC)->getIdentifier() &&
1505 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
1506 DC->getParent()->isTranslationUnit())
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00001507 EmitFundamentalRTTIDescriptors(RD->hasAttr<DLLExportAttr>());
Peter Collingbournea4ccff32015-02-20 20:30:56 +00001508
Evgeniy Stepanov93987df2016-01-23 01:20:18 +00001509 if (!VTable->isDeclarationForLinker())
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00001510 CGM.EmitVTableTypeMetadata(VTable, VTLayout);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001511}
1512
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001513bool ItaniumCXXABI::isVirtualOffsetNeededForVTableField(
1514 CodeGenFunction &CGF, CodeGenFunction::VPtr Vptr) {
1515 if (Vptr.NearestVBase == nullptr)
1516 return false;
1517 return NeedsVTTParameter(CGF.CurGD);
Piotr Padlewski255652e2015-09-09 22:20:28 +00001518}
1519
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001520llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructor(
1521 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1522 const CXXRecordDecl *NearestVBase) {
1523
1524 if ((Base.getBase()->getNumVBases() || NearestVBase != nullptr) &&
1525 NeedsVTTParameter(CGF.CurGD)) {
1526 return getVTableAddressPointInStructorWithVTT(CGF, VTableClass, Base,
1527 NearestVBase);
1528 }
1529 return getVTableAddressPoint(Base, VTableClass);
1530}
1531
1532llvm::Constant *
1533ItaniumCXXABI::getVTableAddressPoint(BaseSubobject Base,
1534 const CXXRecordDecl *VTableClass) {
1535 llvm::GlobalValue *VTable = getAddrOfVTable(VTableClass, CharUnits());
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001536
1537 // Find the appropriate vtable within the vtable group.
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001538 uint64_t AddressPoint = CGM.getItaniumVTableContext()
1539 .getVTableLayout(VTableClass)
1540 .getAddressPoint(Base);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001541 llvm::Value *Indices[] = {
Peter Collingbourne4e6a5402016-03-14 19:07:10 +00001542 llvm::ConstantInt::get(CGM.Int32Ty, 0),
1543 llvm::ConstantInt::get(CGM.Int32Ty, AddressPoint)
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001544 };
1545
David Blaikiee3b172a2015-04-02 18:55:21 +00001546 return llvm::ConstantExpr::getInBoundsGetElementPtr(VTable->getValueType(),
1547 VTable, Indices);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001548}
1549
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001550llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructorWithVTT(
1551 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1552 const CXXRecordDecl *NearestVBase) {
1553 assert((Base.getBase()->getNumVBases() || NearestVBase != nullptr) &&
1554 NeedsVTTParameter(CGF.CurGD) && "This class doesn't have VTT");
1555
1556 // Get the secondary vpointer index.
1557 uint64_t VirtualPointerIndex =
1558 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1559
1560 /// Load the VTT.
1561 llvm::Value *VTT = CGF.LoadCXXVTT();
1562 if (VirtualPointerIndex)
1563 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1564
1565 // And load the address point from the VTT.
1566 return CGF.Builder.CreateAlignedLoad(VTT, CGF.getPointerAlign());
1567}
1568
1569llvm::Constant *ItaniumCXXABI::getVTableAddressPointForConstExpr(
1570 BaseSubobject Base, const CXXRecordDecl *VTableClass) {
1571 return getVTableAddressPoint(Base, VTableClass);
1572}
1573
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001574llvm::GlobalVariable *ItaniumCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
1575 CharUnits VPtrOffset) {
1576 assert(VPtrOffset.isZero() && "Itanium ABI only supports zero vptr offsets");
1577
1578 llvm::GlobalVariable *&VTable = VTables[RD];
1579 if (VTable)
1580 return VTable;
1581
Eric Christopherd160c502016-01-29 01:35:53 +00001582 // Queue up this vtable for possible deferred emission.
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001583 CGM.addDeferredVTable(RD);
1584
Yaron Kerene46f7ed2015-07-29 14:21:47 +00001585 SmallString<256> Name;
1586 llvm::raw_svector_ostream Out(Name);
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00001587 getMangleContext().mangleCXXVTable(RD, Out);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001588
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001589 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001590 llvm::ArrayType *ArrayType = llvm::ArrayType::get(
Peter Collingbournee53683f2016-09-08 01:14:39 +00001591 CGM.Int8PtrTy, VTContext.getVTableLayout(RD).vtable_components().size());
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001592
1593 VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
1594 Name, ArrayType, llvm::GlobalValue::ExternalLinkage);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00001595 VTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Hans Wennborgda24e9c2014-06-02 23:13:03 +00001596
1597 if (RD->hasAttr<DLLImportAttr>())
1598 VTable->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1599 else if (RD->hasAttr<DLLExportAttr>())
1600 VTable->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1601
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001602 return VTable;
1603}
1604
John McCallb92ab1a2016-10-26 23:46:34 +00001605CGCallee ItaniumCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
1606 GlobalDecl GD,
1607 Address This,
1608 llvm::Type *Ty,
1609 SourceLocation Loc) {
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001610 GD = GD.getCanonicalDecl();
1611 Ty = Ty->getPointerTo()->getPointerTo();
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001612 auto *MethodDecl = cast<CXXMethodDecl>(GD.getDecl());
1613 llvm::Value *VTable = CGF.GetVTablePtr(This, Ty, MethodDecl->getParent());
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001614
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001615 uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
John McCallb92ab1a2016-10-26 23:46:34 +00001616 llvm::Value *VFunc;
Peter Collingbourne0ca03632016-06-25 00:24:06 +00001617 if (CGF.ShouldEmitVTableTypeCheckedLoad(MethodDecl->getParent())) {
John McCallb92ab1a2016-10-26 23:46:34 +00001618 VFunc = CGF.EmitVTableTypeCheckedLoad(
Peter Collingbourne0ca03632016-06-25 00:24:06 +00001619 MethodDecl->getParent(), VTable,
1620 VTableIndex * CGM.getContext().getTargetInfo().getPointerWidth(0) / 8);
1621 } else {
1622 CGF.EmitTypeMetadataCodeForVCall(MethodDecl->getParent(), VTable, Loc);
1623
1624 llvm::Value *VFuncPtr =
1625 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfn");
Piotr Padlewski77cc9622016-10-29 15:28:30 +00001626 auto *VFuncLoad =
1627 CGF.Builder.CreateAlignedLoad(VFuncPtr, CGF.getPointerAlign());
1628
1629 // Add !invariant.load md to virtual function load to indicate that
1630 // function didn't change inside vtable.
1631 // It's safe to add it without -fstrict-vtable-pointers, but it would not
1632 // help in devirtualization because it will only matter if we will have 2
1633 // the same virtual function loads from the same vtable load, which won't
1634 // happen without enabled devirtualization with -fstrict-vtable-pointers.
1635 if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1636 CGM.getCodeGenOpts().StrictVTablePointers)
1637 VFuncLoad->setMetadata(
1638 llvm::LLVMContext::MD_invariant_load,
1639 llvm::MDNode::get(CGM.getLLVMContext(),
1640 llvm::ArrayRef<llvm::Metadata *>()));
1641 VFunc = VFuncLoad;
Peter Collingbourne0ca03632016-06-25 00:24:06 +00001642 }
John McCallb92ab1a2016-10-26 23:46:34 +00001643
1644 CGCallee Callee(MethodDecl, VFunc);
1645 return Callee;
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001646}
1647
David Majnemer0c0b6d92014-10-31 20:09:12 +00001648llvm::Value *ItaniumCXXABI::EmitVirtualDestructorCall(
1649 CodeGenFunction &CGF, const CXXDestructorDecl *Dtor, CXXDtorType DtorType,
John McCall7f416cc2015-09-08 08:05:57 +00001650 Address This, const CXXMemberCallExpr *CE) {
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001651 assert(CE == nullptr || CE->arg_begin() == CE->arg_end());
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001652 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
1653
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001654 const CGFunctionInfo *FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
1655 Dtor, getFromDtorType(DtorType));
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001656 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
John McCallb92ab1a2016-10-26 23:46:34 +00001657 CGCallee Callee =
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00001658 getVirtualFunctionPointer(CGF, GlobalDecl(Dtor, DtorType), This, Ty,
1659 CE ? CE->getLocStart() : SourceLocation());
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001660
John McCall7f416cc2015-09-08 08:05:57 +00001661 CGF.EmitCXXMemberOrOperatorCall(Dtor, Callee, ReturnValueSlot(),
1662 This.getPointer(), /*ImplicitParam=*/nullptr,
Richard Smith762672a2016-09-28 19:09:10 +00001663 QualType(), CE, nullptr);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001664 return nullptr;
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001665}
1666
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001667void ItaniumCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
Reid Kleckner7810af02013-06-19 15:20:38 +00001668 CodeGenVTables &VTables = CGM.getVTables();
1669 llvm::GlobalVariable *VTT = VTables.GetAddrOfVTT(RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001670 VTables.EmitVTTDefinition(VTT, CGM.getVTableLinkage(RD), RD);
Reid Kleckner7810af02013-06-19 15:20:38 +00001671}
1672
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001673bool ItaniumCXXABI::canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const {
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001674 // We don't emit available_externally vtables if we are in -fapple-kext mode
1675 // because kext mode does not permit devirtualization.
1676 if (CGM.getLangOpts().AppleKext)
1677 return false;
1678
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001679 // If we don't have any inline virtual functions, and if vtable is not hidden,
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001680 // then we are safe to emit available_externally copy of vtable.
1681 // FIXME we can still emit a copy of the vtable if we
1682 // can emit definition of the inline functions.
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001683 return !hasAnyUsedVirtualInlineFunction(RD) && !isVTableHidden(RD);
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001684}
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001685static llvm::Value *performTypeAdjustment(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001686 Address InitialPtr,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001687 int64_t NonVirtualAdjustment,
1688 int64_t VirtualAdjustment,
1689 bool IsReturnAdjustment) {
1690 if (!NonVirtualAdjustment && !VirtualAdjustment)
John McCall7f416cc2015-09-08 08:05:57 +00001691 return InitialPtr.getPointer();
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001692
John McCall7f416cc2015-09-08 08:05:57 +00001693 Address V = CGF.Builder.CreateElementBitCast(InitialPtr, CGF.Int8Ty);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001694
John McCall7f416cc2015-09-08 08:05:57 +00001695 // In a base-to-derived cast, the non-virtual adjustment is applied first.
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001696 if (NonVirtualAdjustment && !IsReturnAdjustment) {
John McCall7f416cc2015-09-08 08:05:57 +00001697 V = CGF.Builder.CreateConstInBoundsByteGEP(V,
1698 CharUnits::fromQuantity(NonVirtualAdjustment));
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001699 }
1700
John McCall7f416cc2015-09-08 08:05:57 +00001701 // Perform the virtual adjustment if we have one.
1702 llvm::Value *ResultPtr;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001703 if (VirtualAdjustment) {
1704 llvm::Type *PtrDiffTy =
1705 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1706
John McCall7f416cc2015-09-08 08:05:57 +00001707 Address VTablePtrPtr = CGF.Builder.CreateElementBitCast(V, CGF.Int8PtrTy);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001708 llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr);
1709
1710 llvm::Value *OffsetPtr =
1711 CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
1712
1713 OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo());
1714
1715 // Load the adjustment offset from the vtable.
John McCall7f416cc2015-09-08 08:05:57 +00001716 llvm::Value *Offset =
1717 CGF.Builder.CreateAlignedLoad(OffsetPtr, CGF.getPointerAlign());
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001718
1719 // Adjust our pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001720 ResultPtr = CGF.Builder.CreateInBoundsGEP(V.getPointer(), Offset);
1721 } else {
1722 ResultPtr = V.getPointer();
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001723 }
1724
John McCall7f416cc2015-09-08 08:05:57 +00001725 // In a derived-to-base conversion, the non-virtual adjustment is
1726 // applied second.
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001727 if (NonVirtualAdjustment && IsReturnAdjustment) {
John McCall7f416cc2015-09-08 08:05:57 +00001728 ResultPtr = CGF.Builder.CreateConstInBoundsGEP1_64(ResultPtr,
1729 NonVirtualAdjustment);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001730 }
1731
1732 // Cast back to the original type.
John McCall7f416cc2015-09-08 08:05:57 +00001733 return CGF.Builder.CreateBitCast(ResultPtr, InitialPtr.getType());
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001734}
1735
1736llvm::Value *ItaniumCXXABI::performThisAdjustment(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001737 Address This,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001738 const ThisAdjustment &TA) {
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00001739 return performTypeAdjustment(CGF, This, TA.NonVirtual,
1740 TA.Virtual.Itanium.VCallOffsetOffset,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001741 /*IsReturnAdjustment=*/false);
1742}
1743
1744llvm::Value *
John McCall7f416cc2015-09-08 08:05:57 +00001745ItaniumCXXABI::performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001746 const ReturnAdjustment &RA) {
1747 return performTypeAdjustment(CGF, Ret, RA.NonVirtual,
1748 RA.Virtual.Itanium.VBaseOffsetOffset,
1749 /*IsReturnAdjustment=*/true);
1750}
1751
John McCall5d865c322010-08-31 07:33:07 +00001752void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
1753 RValue RV, QualType ResultType) {
1754 if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
1755 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
1756
1757 // Destructor thunks in the ARM ABI have indeterminate results.
John McCall7f416cc2015-09-08 08:05:57 +00001758 llvm::Type *T = CGF.ReturnValue.getElementType();
John McCall5d865c322010-08-31 07:33:07 +00001759 RValue Undef = RValue::get(llvm::UndefValue::get(T));
1760 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
1761}
John McCall8ed55a52010-09-02 09:58:18 +00001762
1763/************************** Array allocation cookies **************************/
1764
John McCallb91cd662012-05-01 05:23:51 +00001765CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
1766 // The array cookie is a size_t; pad that up to the element alignment.
1767 // The cookie is actually right-justified in that space.
1768 return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
1769 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001770}
1771
John McCall7f416cc2015-09-08 08:05:57 +00001772Address ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1773 Address NewPtr,
1774 llvm::Value *NumElements,
1775 const CXXNewExpr *expr,
1776 QualType ElementType) {
John McCallb91cd662012-05-01 05:23:51 +00001777 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001778
John McCall7f416cc2015-09-08 08:05:57 +00001779 unsigned AS = NewPtr.getAddressSpace();
John McCall8ed55a52010-09-02 09:58:18 +00001780
John McCall9bca9232010-09-02 10:25:57 +00001781 ASTContext &Ctx = getContext();
John McCall7f416cc2015-09-08 08:05:57 +00001782 CharUnits SizeSize = CGF.getSizeSize();
John McCall8ed55a52010-09-02 09:58:18 +00001783
1784 // The size of the cookie.
1785 CharUnits CookieSize =
1786 std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
John McCallb91cd662012-05-01 05:23:51 +00001787 assert(CookieSize == getArrayCookieSizeImpl(ElementType));
John McCall8ed55a52010-09-02 09:58:18 +00001788
1789 // Compute an offset to the cookie.
John McCall7f416cc2015-09-08 08:05:57 +00001790 Address CookiePtr = NewPtr;
John McCall8ed55a52010-09-02 09:58:18 +00001791 CharUnits CookieOffset = CookieSize - SizeSize;
1792 if (!CookieOffset.isZero())
John McCall7f416cc2015-09-08 08:05:57 +00001793 CookiePtr = CGF.Builder.CreateConstInBoundsByteGEP(CookiePtr, CookieOffset);
John McCall8ed55a52010-09-02 09:58:18 +00001794
1795 // Write the number of elements into the appropriate slot.
John McCall7f416cc2015-09-08 08:05:57 +00001796 Address NumElementsPtr =
1797 CGF.Builder.CreateElementBitCast(CookiePtr, CGF.SizeTy);
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001798 llvm::Instruction *SI = CGF.Builder.CreateStore(NumElements, NumElementsPtr);
John McCall7f416cc2015-09-08 08:05:57 +00001799
1800 // Handle the array cookie specially in ASan.
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001801 if (CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) && AS == 0 &&
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001802 expr->getOperatorNew()->isReplaceableGlobalAllocationFunction()) {
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001803 // The store to the CookiePtr does not need to be instrumented.
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001804 CGM.getSanitizerMetadata()->disableSanitizerForInstruction(SI);
1805 llvm::FunctionType *FTy =
John McCall7f416cc2015-09-08 08:05:57 +00001806 llvm::FunctionType::get(CGM.VoidTy, NumElementsPtr.getType(), false);
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001807 llvm::Constant *F =
1808 CGM.CreateRuntimeFunction(FTy, "__asan_poison_cxx_array_cookie");
John McCall7f416cc2015-09-08 08:05:57 +00001809 CGF.Builder.CreateCall(F, NumElementsPtr.getPointer());
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001810 }
John McCall8ed55a52010-09-02 09:58:18 +00001811
1812 // Finally, compute a pointer to the actual data buffer by skipping
1813 // over the cookie completely.
John McCall7f416cc2015-09-08 08:05:57 +00001814 return CGF.Builder.CreateConstInBoundsByteGEP(NewPtr, CookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001815}
1816
John McCallb91cd662012-05-01 05:23:51 +00001817llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001818 Address allocPtr,
John McCallb91cd662012-05-01 05:23:51 +00001819 CharUnits cookieSize) {
1820 // The element size is right-justified in the cookie.
John McCall7f416cc2015-09-08 08:05:57 +00001821 Address numElementsPtr = allocPtr;
1822 CharUnits numElementsOffset = cookieSize - CGF.getSizeSize();
John McCallb91cd662012-05-01 05:23:51 +00001823 if (!numElementsOffset.isZero())
1824 numElementsPtr =
John McCall7f416cc2015-09-08 08:05:57 +00001825 CGF.Builder.CreateConstInBoundsByteGEP(numElementsPtr, numElementsOffset);
John McCall8ed55a52010-09-02 09:58:18 +00001826
John McCall7f416cc2015-09-08 08:05:57 +00001827 unsigned AS = allocPtr.getAddressSpace();
1828 numElementsPtr = CGF.Builder.CreateElementBitCast(numElementsPtr, CGF.SizeTy);
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001829 if (!CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) || AS != 0)
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001830 return CGF.Builder.CreateLoad(numElementsPtr);
1831 // In asan mode emit a function call instead of a regular load and let the
1832 // run-time deal with it: if the shadow is properly poisoned return the
1833 // cookie, otherwise return 0 to avoid an infinite loop calling DTORs.
1834 // We can't simply ignore this load using nosanitize metadata because
1835 // the metadata may be lost.
1836 llvm::FunctionType *FTy =
1837 llvm::FunctionType::get(CGF.SizeTy, CGF.SizeTy->getPointerTo(0), false);
1838 llvm::Constant *F =
1839 CGM.CreateRuntimeFunction(FTy, "__asan_load_cxx_array_cookie");
John McCall7f416cc2015-09-08 08:05:57 +00001840 return CGF.Builder.CreateCall(F, numElementsPtr.getPointer());
John McCall8ed55a52010-09-02 09:58:18 +00001841}
1842
John McCallb91cd662012-05-01 05:23:51 +00001843CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
John McCallc19c7062013-01-25 23:36:19 +00001844 // ARM says that the cookie is always:
John McCall8ed55a52010-09-02 09:58:18 +00001845 // struct array_cookie {
1846 // std::size_t element_size; // element_size != 0
1847 // std::size_t element_count;
1848 // };
John McCallc19c7062013-01-25 23:36:19 +00001849 // But the base ABI doesn't give anything an alignment greater than
1850 // 8, so we can dismiss this as typical ABI-author blindness to
1851 // actual language complexity and round up to the element alignment.
1852 return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes),
1853 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001854}
1855
John McCall7f416cc2015-09-08 08:05:57 +00001856Address ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1857 Address newPtr,
1858 llvm::Value *numElements,
1859 const CXXNewExpr *expr,
1860 QualType elementType) {
John McCallb91cd662012-05-01 05:23:51 +00001861 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001862
John McCall8ed55a52010-09-02 09:58:18 +00001863 // The cookie is always at the start of the buffer.
John McCall7f416cc2015-09-08 08:05:57 +00001864 Address cookie = newPtr;
John McCall8ed55a52010-09-02 09:58:18 +00001865
1866 // The first element is the element size.
John McCall7f416cc2015-09-08 08:05:57 +00001867 cookie = CGF.Builder.CreateElementBitCast(cookie, CGF.SizeTy);
John McCallc19c7062013-01-25 23:36:19 +00001868 llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy,
1869 getContext().getTypeSizeInChars(elementType).getQuantity());
1870 CGF.Builder.CreateStore(elementSize, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001871
1872 // The second element is the element count.
John McCall7f416cc2015-09-08 08:05:57 +00001873 cookie = CGF.Builder.CreateConstInBoundsGEP(cookie, 1, CGF.getSizeSize());
John McCallc19c7062013-01-25 23:36:19 +00001874 CGF.Builder.CreateStore(numElements, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001875
1876 // Finally, compute a pointer to the actual data buffer by skipping
1877 // over the cookie completely.
John McCallc19c7062013-01-25 23:36:19 +00001878 CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType);
John McCall7f416cc2015-09-08 08:05:57 +00001879 return CGF.Builder.CreateConstInBoundsByteGEP(newPtr, cookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001880}
1881
John McCallb91cd662012-05-01 05:23:51 +00001882llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001883 Address allocPtr,
John McCallb91cd662012-05-01 05:23:51 +00001884 CharUnits cookieSize) {
1885 // The number of elements is at offset sizeof(size_t) relative to
1886 // the allocated pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001887 Address numElementsPtr
1888 = CGF.Builder.CreateConstInBoundsByteGEP(allocPtr, CGF.getSizeSize());
John McCall8ed55a52010-09-02 09:58:18 +00001889
John McCall7f416cc2015-09-08 08:05:57 +00001890 numElementsPtr = CGF.Builder.CreateElementBitCast(numElementsPtr, CGF.SizeTy);
John McCallb91cd662012-05-01 05:23:51 +00001891 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall8ed55a52010-09-02 09:58:18 +00001892}
1893
John McCall68ff0372010-09-08 01:44:27 +00001894/*********************** Static local initialization **************************/
1895
1896static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001897 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001898 // int __cxa_guard_acquire(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001899 llvm::FunctionType *FTy =
John McCall68ff0372010-09-08 01:44:27 +00001900 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
Jay Foad5709f7c2011-07-29 13:56:53 +00001901 GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001902 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_acquire",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001903 llvm::AttributeSet::get(CGM.getLLVMContext(),
1904 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001905 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001906}
1907
1908static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001909 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001910 // void __cxa_guard_release(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001911 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001912 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001913 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_release",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001914 llvm::AttributeSet::get(CGM.getLLVMContext(),
1915 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001916 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001917}
1918
1919static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001920 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001921 // void __cxa_guard_abort(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001922 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001923 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001924 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_abort",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001925 llvm::AttributeSet::get(CGM.getLLVMContext(),
1926 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001927 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001928}
1929
1930namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001931 struct CallGuardAbort final : EHScopeStack::Cleanup {
John McCall68ff0372010-09-08 01:44:27 +00001932 llvm::GlobalVariable *Guard;
Chandler Carruth84537952012-03-30 19:44:53 +00001933 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
John McCall68ff0372010-09-08 01:44:27 +00001934
Craig Topper4f12f102014-03-12 06:41:41 +00001935 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall882987f2013-02-28 19:01:20 +00001936 CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()),
1937 Guard);
John McCall68ff0372010-09-08 01:44:27 +00001938 }
1939 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001940}
John McCall68ff0372010-09-08 01:44:27 +00001941
1942/// The ARM code here follows the Itanium code closely enough that we
1943/// just special-case it at particular places.
John McCallcdf7ef52010-11-06 09:44:32 +00001944void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
1945 const VarDecl &D,
John McCallb88a5662012-03-30 21:00:39 +00001946 llvm::GlobalVariable *var,
1947 bool shouldPerformInit) {
John McCall68ff0372010-09-08 01:44:27 +00001948 CGBuilderTy &Builder = CGF.Builder;
John McCallcdf7ef52010-11-06 09:44:32 +00001949
Richard Smith62f19e72016-06-25 00:15:56 +00001950 // Inline variables that weren't instantiated from variable templates have
1951 // partially-ordered initialization within their translation unit.
1952 bool NonTemplateInline =
1953 D.isInline() &&
1954 !isTemplateInstantiation(D.getTemplateSpecializationKind());
1955
1956 // We only need to use thread-safe statics for local non-TLS variables and
1957 // inline variables; other global initialization is always single-threaded
1958 // or (through lazy dynamic loading in multiple threads) unsequenced.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001959 bool threadsafe = getContext().getLangOpts().ThreadsafeStatics &&
Richard Smith62f19e72016-06-25 00:15:56 +00001960 (D.isLocalVarDecl() || NonTemplateInline) &&
1961 !D.getTLSKind();
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001962
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001963 // If we have a global variable with internal linkage and thread-safe statics
1964 // are disabled, we can just let the guard variable be of type i8.
John McCallb88a5662012-03-30 21:00:39 +00001965 bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
1966
1967 llvm::IntegerType *guardTy;
John McCall7f416cc2015-09-08 08:05:57 +00001968 CharUnits guardAlignment;
John McCall5aa52592011-06-17 07:33:57 +00001969 if (useInt8GuardVariable) {
John McCallb88a5662012-03-30 21:00:39 +00001970 guardTy = CGF.Int8Ty;
John McCall7f416cc2015-09-08 08:05:57 +00001971 guardAlignment = CharUnits::One();
John McCall5aa52592011-06-17 07:33:57 +00001972 } else {
Tim Northover9bb857a2013-01-31 12:13:10 +00001973 // Guard variables are 64 bits in the generic ABI and size width on ARM
1974 // (i.e. 32-bit on AArch32, 64-bit on AArch64).
John McCall7f416cc2015-09-08 08:05:57 +00001975 if (UseARMGuardVarABI) {
1976 guardTy = CGF.SizeTy;
1977 guardAlignment = CGF.getSizeAlign();
1978 } else {
1979 guardTy = CGF.Int64Ty;
1980 guardAlignment = CharUnits::fromQuantity(
1981 CGM.getDataLayout().getABITypeAlignment(guardTy));
1982 }
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001983 }
John McCallb88a5662012-03-30 21:00:39 +00001984 llvm::PointerType *guardPtrTy = guardTy->getPointerTo();
John McCall68ff0372010-09-08 01:44:27 +00001985
John McCallb88a5662012-03-30 21:00:39 +00001986 // Create the guard variable if we don't already have it (as we
1987 // might if we're double-emitting this function body).
1988 llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
1989 if (!guard) {
1990 // Mangle the name for the guard.
1991 SmallString<256> guardName;
1992 {
1993 llvm::raw_svector_ostream out(guardName);
Reid Klecknerd8110b62013-09-10 20:14:30 +00001994 getMangleContext().mangleStaticGuardVariable(&D, out);
John McCallb88a5662012-03-30 21:00:39 +00001995 }
John McCall8e7cb6d2010-11-02 21:04:24 +00001996
John McCallb88a5662012-03-30 21:00:39 +00001997 // Create the guard variable with a zero-initializer.
1998 // Just absorb linkage and visibility from the guarded variable.
1999 guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
2000 false, var->getLinkage(),
2001 llvm::ConstantInt::get(guardTy, 0),
2002 guardName.str());
2003 guard->setVisibility(var->getVisibility());
Richard Smithdbf74ba2013-04-14 23:01:42 +00002004 // If the variable is thread-local, so is its guard variable.
2005 guard->setThreadLocalMode(var->getThreadLocalMode());
John McCall7f416cc2015-09-08 08:05:57 +00002006 guard->setAlignment(guardAlignment.getQuantity());
John McCallb88a5662012-03-30 21:00:39 +00002007
Yaron Keren5bfa1082015-09-03 20:33:29 +00002008 // The ABI says: "It is suggested that it be emitted in the same COMDAT
2009 // group as the associated data object." In practice, this doesn't work for
2010 // non-ELF object formats, so only do it for ELF.
Rafael Espindola0d4fb982015-01-12 22:13:53 +00002011 llvm::Comdat *C = var->getComdat();
Yaron Keren5bfa1082015-09-03 20:33:29 +00002012 if (!D.isLocalVarDecl() && C &&
2013 CGM.getTarget().getTriple().isOSBinFormatELF()) {
Rafael Espindola2ae4b632014-09-19 19:43:18 +00002014 guard->setComdat(C);
Richard Smith62f19e72016-06-25 00:15:56 +00002015 // An inline variable's guard function is run from the per-TU
2016 // initialization function, not via a dedicated global ctor function, so
2017 // we can't put it in a comdat.
2018 if (!NonTemplateInline)
2019 CGF.CurFn->setComdat(C);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00002020 } else if (CGM.supportsCOMDAT() && guard->isWeakForLinker()) {
2021 guard->setComdat(CGM.getModule().getOrInsertComdat(guard->getName()));
Rafael Espindola2ae4b632014-09-19 19:43:18 +00002022 }
2023
John McCallb88a5662012-03-30 21:00:39 +00002024 CGM.setStaticLocalDeclGuardAddress(&D, guard);
2025 }
John McCall87590e62012-03-30 07:09:50 +00002026
John McCall7f416cc2015-09-08 08:05:57 +00002027 Address guardAddr = Address(guard, guardAlignment);
2028
John McCall68ff0372010-09-08 01:44:27 +00002029 // Test whether the variable has completed initialization.
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002030 //
John McCall68ff0372010-09-08 01:44:27 +00002031 // Itanium C++ ABI 3.3.2:
2032 // The following is pseudo-code showing how these functions can be used:
2033 // if (obj_guard.first_byte == 0) {
2034 // if ( __cxa_guard_acquire (&obj_guard) ) {
2035 // try {
2036 // ... initialize the object ...;
2037 // } catch (...) {
2038 // __cxa_guard_abort (&obj_guard);
2039 // throw;
2040 // }
2041 // ... queue object destructor with __cxa_atexit() ...;
2042 // __cxa_guard_release (&obj_guard);
2043 // }
2044 // }
Tim Northovera2ee4332014-03-29 15:09:45 +00002045
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002046 // Load the first byte of the guard variable.
2047 llvm::LoadInst *LI =
John McCall7f416cc2015-09-08 08:05:57 +00002048 Builder.CreateLoad(Builder.CreateElementBitCast(guardAddr, CGM.Int8Ty));
John McCall68ff0372010-09-08 01:44:27 +00002049
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002050 // Itanium ABI:
2051 // An implementation supporting thread-safety on multiprocessor
2052 // systems must also guarantee that references to the initialized
2053 // object do not occur before the load of the initialization flag.
2054 //
2055 // In LLVM, we do this by marking the load Acquire.
2056 if (threadsafe)
JF Bastien92f4ef12016-04-06 17:26:42 +00002057 LI->setAtomic(llvm::AtomicOrdering::Acquire);
Eli Friedman84d28122011-09-13 22:21:56 +00002058
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002059 // For ARM, we should only check the first bit, rather than the entire byte:
2060 //
2061 // ARM C++ ABI 3.2.3.1:
2062 // To support the potential use of initialization guard variables
2063 // as semaphores that are the target of ARM SWP and LDREX/STREX
2064 // synchronizing instructions we define a static initialization
2065 // guard variable to be a 4-byte aligned, 4-byte word with the
2066 // following inline access protocol.
2067 // #define INITIALIZED 1
2068 // if ((obj_guard & INITIALIZED) != INITIALIZED) {
2069 // if (__cxa_guard_acquire(&obj_guard))
2070 // ...
2071 // }
2072 //
2073 // and similarly for ARM64:
2074 //
2075 // ARM64 C++ ABI 3.2.2:
2076 // This ABI instead only specifies the value bit 0 of the static guard
2077 // variable; all other bits are platform defined. Bit 0 shall be 0 when the
2078 // variable is not initialized and 1 when it is.
2079 llvm::Value *V =
2080 (UseARMGuardVarABI && !useInt8GuardVariable)
2081 ? Builder.CreateAnd(LI, llvm::ConstantInt::get(CGM.Int8Ty, 1))
2082 : LI;
2083 llvm::Value *isInitialized = Builder.CreateIsNull(V, "guard.uninitialized");
John McCall68ff0372010-09-08 01:44:27 +00002084
2085 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
2086 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
2087
2088 // Check if the first byte of the guard variable is zero.
John McCallb88a5662012-03-30 21:00:39 +00002089 Builder.CreateCondBr(isInitialized, InitCheckBlock, EndBlock);
John McCall68ff0372010-09-08 01:44:27 +00002090
2091 CGF.EmitBlock(InitCheckBlock);
2092
2093 // Variables used when coping with thread-safe statics and exceptions.
John McCall5aa52592011-06-17 07:33:57 +00002094 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00002095 // Call __cxa_guard_acquire.
2096 llvm::Value *V
John McCall882987f2013-02-28 19:01:20 +00002097 = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
John McCall68ff0372010-09-08 01:44:27 +00002098
2099 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
2100
2101 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
2102 InitBlock, EndBlock);
2103
2104 // Call __cxa_guard_abort along the exceptional edge.
John McCallb88a5662012-03-30 21:00:39 +00002105 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
John McCall68ff0372010-09-08 01:44:27 +00002106
2107 CGF.EmitBlock(InitBlock);
2108 }
2109
2110 // Emit the initializer and add a global destructor if appropriate.
John McCallb88a5662012-03-30 21:00:39 +00002111 CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
John McCall68ff0372010-09-08 01:44:27 +00002112
John McCall5aa52592011-06-17 07:33:57 +00002113 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00002114 // Pop the guard-abort cleanup if we pushed one.
2115 CGF.PopCleanupBlock();
2116
2117 // Call __cxa_guard_release. This cannot throw.
John McCall7f416cc2015-09-08 08:05:57 +00002118 CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy),
2119 guardAddr.getPointer());
John McCall68ff0372010-09-08 01:44:27 +00002120 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002121 Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guardAddr);
John McCall68ff0372010-09-08 01:44:27 +00002122 }
2123
2124 CGF.EmitBlock(EndBlock);
2125}
John McCallc84ed6a2012-05-01 06:13:13 +00002126
2127/// Register a global destructor using __cxa_atexit.
2128static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
2129 llvm::Constant *dtor,
Richard Smithdbf74ba2013-04-14 23:01:42 +00002130 llvm::Constant *addr,
2131 bool TLS) {
Bill Wendling95cae882013-05-02 19:18:03 +00002132 const char *Name = "__cxa_atexit";
2133 if (TLS) {
2134 const llvm::Triple &T = CGF.getTarget().getTriple();
Manman Renf93fff22015-11-11 23:08:18 +00002135 Name = T.isOSDarwin() ? "_tlv_atexit" : "__cxa_thread_atexit";
Bill Wendling95cae882013-05-02 19:18:03 +00002136 }
Richard Smithdbf74ba2013-04-14 23:01:42 +00002137
John McCallc84ed6a2012-05-01 06:13:13 +00002138 // We're assuming that the destructor function is something we can
2139 // reasonably call with the default CC. Go ahead and cast it to the
2140 // right prototype.
2141 llvm::Type *dtorTy =
2142 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo();
2143
2144 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
2145 llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
2146 llvm::FunctionType *atexitTy =
2147 llvm::FunctionType::get(CGF.IntTy, paramTys, false);
2148
2149 // Fetch the actual function.
Richard Smithdbf74ba2013-04-14 23:01:42 +00002150 llvm::Constant *atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name);
John McCallc84ed6a2012-05-01 06:13:13 +00002151 if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit))
2152 fn->setDoesNotThrow();
2153
2154 // Create a variable that binds the atexit to this shared object.
2155 llvm::Constant *handle =
2156 CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
2157
2158 llvm::Value *args[] = {
2159 llvm::ConstantExpr::getBitCast(dtor, dtorTy),
2160 llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy),
2161 handle
2162 };
John McCall882987f2013-02-28 19:01:20 +00002163 CGF.EmitNounwindRuntimeCall(atexit, args);
John McCallc84ed6a2012-05-01 06:13:13 +00002164}
2165
2166/// Register a global destructor as best as we know how.
2167void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF,
Richard Smithdbf74ba2013-04-14 23:01:42 +00002168 const VarDecl &D,
John McCallc84ed6a2012-05-01 06:13:13 +00002169 llvm::Constant *dtor,
2170 llvm::Constant *addr) {
2171 // Use __cxa_atexit if available.
Richard Smithdbf74ba2013-04-14 23:01:42 +00002172 if (CGM.getCodeGenOpts().CXAAtExit)
2173 return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind());
2174
2175 if (D.getTLSKind())
2176 CGM.ErrorUnsupported(&D, "non-trivial TLS destruction");
John McCallc84ed6a2012-05-01 06:13:13 +00002177
2178 // In Apple kexts, we want to add a global destructor entry.
2179 // FIXME: shouldn't this be guarded by some variable?
Richard Smith9c6890a2012-11-01 22:30:59 +00002180 if (CGM.getLangOpts().AppleKext) {
John McCallc84ed6a2012-05-01 06:13:13 +00002181 // Generate a global destructor entry.
2182 return CGM.AddCXXDtorEntry(dtor, addr);
2183 }
2184
David Blaikieebe87e12013-08-27 23:57:18 +00002185 CGF.registerGlobalDtorWithAtExit(D, dtor, addr);
John McCallc84ed6a2012-05-01 06:13:13 +00002186}
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002187
David Majnemer9b21c332014-07-11 20:28:10 +00002188static bool isThreadWrapperReplaceable(const VarDecl *VD,
2189 CodeGen::CodeGenModule &CGM) {
2190 assert(!VD->isStaticLocal() && "static local VarDecls don't need wrappers!");
Manman Renf93fff22015-11-11 23:08:18 +00002191 // Darwin prefers to have references to thread local variables to go through
David Majnemer9b21c332014-07-11 20:28:10 +00002192 // the thread wrapper instead of directly referencing the backing variable.
2193 return VD->getTLSKind() == VarDecl::TLS_Dynamic &&
Manman Renf93fff22015-11-11 23:08:18 +00002194 CGM.getTarget().getTriple().isOSDarwin();
David Majnemer9b21c332014-07-11 20:28:10 +00002195}
2196
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002197/// Get the appropriate linkage for the wrapper function. This is essentially
David Majnemer4632e1e2014-06-27 16:56:27 +00002198/// the weak form of the variable's linkage; every translation unit which needs
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002199/// the wrapper emits a copy, and we want the linker to merge them.
David Majnemer35ab3282014-06-11 04:08:55 +00002200static llvm::GlobalValue::LinkageTypes
2201getThreadLocalWrapperLinkage(const VarDecl *VD, CodeGen::CodeGenModule &CGM) {
2202 llvm::GlobalValue::LinkageTypes VarLinkage =
2203 CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false);
2204
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002205 // For internal linkage variables, we don't need an external or weak wrapper.
2206 if (llvm::GlobalValue::isLocalLinkage(VarLinkage))
2207 return VarLinkage;
David Majnemer35ab3282014-06-11 04:08:55 +00002208
David Majnemer9b21c332014-07-11 20:28:10 +00002209 // If the thread wrapper is replaceable, give it appropriate linkage.
Manman Ren68150262015-11-11 22:42:31 +00002210 if (isThreadWrapperReplaceable(VD, CGM))
2211 if (!llvm::GlobalVariable::isLinkOnceLinkage(VarLinkage) &&
2212 !llvm::GlobalVariable::isWeakODRLinkage(VarLinkage))
2213 return VarLinkage;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002214 return llvm::GlobalValue::WeakODRLinkage;
2215}
2216
2217llvm::Function *
2218ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD,
Alexander Musmanf94c3182014-09-26 06:28:25 +00002219 llvm::Value *Val) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002220 // Mangle the name for the thread_local wrapper function.
2221 SmallString<256> WrapperName;
2222 {
2223 llvm::raw_svector_ostream Out(WrapperName);
2224 getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002225 }
2226
Akira Hatanaka26907f92016-01-15 03:34:06 +00002227 // FIXME: If VD is a definition, we should regenerate the function attributes
2228 // before returning.
Alexander Musmanf94c3182014-09-26 06:28:25 +00002229 if (llvm::Value *V = CGM.getModule().getNamedValue(WrapperName))
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002230 return cast<llvm::Function>(V);
2231
Akira Hatanaka26907f92016-01-15 03:34:06 +00002232 QualType RetQT = VD->getType();
2233 if (RetQT->isReferenceType())
2234 RetQT = RetQT.getNonReferenceType();
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002235
John McCallc56a8b32016-03-11 04:30:31 +00002236 const CGFunctionInfo &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
2237 getContext().getPointerType(RetQT), FunctionArgList());
Akira Hatanaka26907f92016-01-15 03:34:06 +00002238
2239 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FI);
David Majnemer35ab3282014-06-11 04:08:55 +00002240 llvm::Function *Wrapper =
2241 llvm::Function::Create(FnTy, getThreadLocalWrapperLinkage(VD, CGM),
2242 WrapperName.str(), &CGM.getModule());
Akira Hatanaka26907f92016-01-15 03:34:06 +00002243
2244 CGM.SetLLVMFunctionAttributes(nullptr, FI, Wrapper);
2245
2246 if (VD->hasDefinition())
2247 CGM.SetLLVMFunctionAttributesForDefinition(nullptr, Wrapper);
2248
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002249 // Always resolve references to the wrapper at link time.
Manman Ren68150262015-11-11 22:42:31 +00002250 if (!Wrapper->hasLocalLinkage() && !(isThreadWrapperReplaceable(VD, CGM) &&
2251 !llvm::GlobalVariable::isLinkOnceLinkage(Wrapper->getLinkage()) &&
2252 !llvm::GlobalVariable::isWeakODRLinkage(Wrapper->getLinkage())))
Duncan P. N. Exon Smith4434d362014-05-07 22:36:11 +00002253 Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
Manman Renb0b3af72015-12-17 00:42:36 +00002254
2255 if (isThreadWrapperReplaceable(VD, CGM)) {
2256 Wrapper->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2257 Wrapper->addFnAttr(llvm::Attribute::NoUnwind);
2258 }
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002259 return Wrapper;
2260}
2261
2262void ItaniumCXXABI::EmitThreadLocalInitFuncs(
Richard Smith5a99c492015-12-01 01:10:48 +00002263 CodeGenModule &CGM, ArrayRef<const VarDecl *> CXXThreadLocals,
2264 ArrayRef<llvm::Function *> CXXThreadLocalInits,
2265 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) {
David Majnemerb3341ea2014-10-05 05:05:40 +00002266 llvm::Function *InitFunc = nullptr;
2267 if (!CXXThreadLocalInits.empty()) {
2268 // Generate a guarded initialization function.
2269 llvm::FunctionType *FTy =
2270 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002271 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
2272 InitFunc = CGM.CreateGlobalInitOrDestructFunction(FTy, "__tls_init", FI,
Alexey Samsonov1444bb92014-10-17 00:20:19 +00002273 SourceLocation(),
David Majnemerb3341ea2014-10-05 05:05:40 +00002274 /*TLS=*/true);
2275 llvm::GlobalVariable *Guard = new llvm::GlobalVariable(
2276 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false,
2277 llvm::GlobalVariable::InternalLinkage,
2278 llvm::ConstantInt::get(CGM.Int8Ty, 0), "__tls_guard");
2279 Guard->setThreadLocal(true);
John McCall7f416cc2015-09-08 08:05:57 +00002280
2281 CharUnits GuardAlign = CharUnits::One();
2282 Guard->setAlignment(GuardAlign.getQuantity());
2283
David Majnemerb3341ea2014-10-05 05:05:40 +00002284 CodeGenFunction(CGM)
John McCall7f416cc2015-09-08 08:05:57 +00002285 .GenerateCXXGlobalInitFunc(InitFunc, CXXThreadLocalInits,
2286 Address(Guard, GuardAlign));
Manman Ren5e5d0462016-03-18 23:35:21 +00002287 // On Darwin platforms, use CXX_FAST_TLS calling convention.
2288 if (CGM.getTarget().getTriple().isOSDarwin()) {
2289 InitFunc->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2290 InitFunc->addFnAttr(llvm::Attribute::NoUnwind);
2291 }
David Majnemerb3341ea2014-10-05 05:05:40 +00002292 }
Richard Smith5a99c492015-12-01 01:10:48 +00002293 for (const VarDecl *VD : CXXThreadLocals) {
2294 llvm::GlobalVariable *Var =
2295 cast<llvm::GlobalVariable>(CGM.GetGlobalValue(CGM.getMangledName(VD)));
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002296
David Majnemer9b21c332014-07-11 20:28:10 +00002297 // Some targets require that all access to thread local variables go through
2298 // the thread wrapper. This means that we cannot attempt to create a thread
2299 // wrapper or a thread helper.
2300 if (isThreadWrapperReplaceable(VD, CGM) && !VD->hasDefinition())
2301 continue;
2302
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002303 // Mangle the name for the thread_local initialization function.
2304 SmallString<256> InitFnName;
2305 {
2306 llvm::raw_svector_ostream Out(InitFnName);
2307 getMangleContext().mangleItaniumThreadLocalInit(VD, Out);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002308 }
2309
2310 // If we have a definition for the variable, emit the initialization
2311 // function as an alias to the global Init function (if any). Otherwise,
2312 // produce a declaration of the initialization function.
Craig Topper8a13c412014-05-21 05:09:00 +00002313 llvm::GlobalValue *Init = nullptr;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002314 bool InitIsInitFunc = false;
2315 if (VD->hasDefinition()) {
2316 InitIsInitFunc = true;
2317 if (InitFunc)
Rafael Espindola234405b2014-05-17 21:30:14 +00002318 Init = llvm::GlobalAlias::create(Var->getLinkage(), InitFnName.str(),
2319 InitFunc);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002320 } else {
2321 // Emit a weak global function referring to the initialization function.
2322 // This function will not exist if the TU defining the thread_local
2323 // variable in question does not need any dynamic initialization for
2324 // its thread_local variables.
2325 llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, false);
2326 Init = llvm::Function::Create(
2327 FnTy, llvm::GlobalVariable::ExternalWeakLinkage, InitFnName.str(),
2328 &CGM.getModule());
John McCallc56a8b32016-03-11 04:30:31 +00002329 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
Akira Hatanaka26907f92016-01-15 03:34:06 +00002330 CGM.SetLLVMFunctionAttributes(nullptr, FI, cast<llvm::Function>(Init));
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002331 }
2332
2333 if (Init)
2334 Init->setVisibility(Var->getVisibility());
2335
2336 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Var);
2337 llvm::LLVMContext &Context = CGM.getModule().getContext();
2338 llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper);
John McCall7f416cc2015-09-08 08:05:57 +00002339 CGBuilderTy Builder(CGM, Entry);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002340 if (InitIsInitFunc) {
Manman Ren5e5d0462016-03-18 23:35:21 +00002341 if (Init) {
2342 llvm::CallInst *CallVal = Builder.CreateCall(Init);
2343 if (isThreadWrapperReplaceable(VD, CGM))
2344 CallVal->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2345 }
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002346 } else {
2347 // Don't know whether we have an init function. Call it if it exists.
2348 llvm::Value *Have = Builder.CreateIsNotNull(Init);
2349 llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2350 llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2351 Builder.CreateCondBr(Have, InitBB, ExitBB);
2352
2353 Builder.SetInsertPoint(InitBB);
David Blaikie4ba525b2015-07-14 17:27:39 +00002354 Builder.CreateCall(Init);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002355 Builder.CreateBr(ExitBB);
2356
2357 Builder.SetInsertPoint(ExitBB);
2358 }
2359
2360 // For a reference, the result of the wrapper function is a pointer to
2361 // the referenced object.
2362 llvm::Value *Val = Var;
2363 if (VD->getType()->isReferenceType()) {
John McCall7f416cc2015-09-08 08:05:57 +00002364 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2365 Val = Builder.CreateAlignedLoad(Val, Align);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002366 }
Alexander Musmanf94c3182014-09-26 06:28:25 +00002367 if (Val->getType() != Wrapper->getReturnType())
2368 Val = Builder.CreatePointerBitCastOrAddrSpaceCast(
2369 Val, Wrapper->getReturnType(), "");
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002370 Builder.CreateRet(Val);
2371 }
2372}
2373
Richard Smith0f383742014-03-26 22:48:22 +00002374LValue ItaniumCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
2375 const VarDecl *VD,
2376 QualType LValType) {
Richard Smith5a99c492015-12-01 01:10:48 +00002377 llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD);
Alexander Musmanf94c3182014-09-26 06:28:25 +00002378 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Val);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002379
Manman Renb0b3af72015-12-17 00:42:36 +00002380 llvm::CallInst *CallVal = CGF.Builder.CreateCall(Wrapper);
Saleem Abdulrasool4a7130a2016-08-01 21:31:24 +00002381 CallVal->setCallingConv(Wrapper->getCallingConv());
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002382
2383 LValue LV;
2384 if (VD->getType()->isReferenceType())
Manman Renb0b3af72015-12-17 00:42:36 +00002385 LV = CGF.MakeNaturalAlignAddrLValue(CallVal, LValType);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002386 else
Manman Renb0b3af72015-12-17 00:42:36 +00002387 LV = CGF.MakeAddrLValue(CallVal, LValType,
2388 CGF.getContext().getDeclAlign(VD));
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002389 // FIXME: need setObjCGCLValueClass?
2390 return LV;
2391}
Peter Collingbourne66f82e62013-06-28 20:45:28 +00002392
2393/// Return whether the given global decl needs a VTT parameter, which it does
2394/// if it's a base constructor or destructor with virtual bases.
2395bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) {
2396 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
2397
2398 // We don't have any virtual bases, just return early.
2399 if (!MD->getParent()->getNumVBases())
2400 return false;
2401
2402 // Check if we have a base constructor.
2403 if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base)
2404 return true;
2405
2406 // Check if we have a base destructor.
2407 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
2408 return true;
2409
2410 return false;
2411}
David Majnemere2cb8d12014-07-07 06:20:47 +00002412
2413namespace {
2414class ItaniumRTTIBuilder {
2415 CodeGenModule &CGM; // Per-module state.
2416 llvm::LLVMContext &VMContext;
2417 const ItaniumCXXABI &CXXABI; // Per-module state.
2418
2419 /// Fields - The fields of the RTTI descriptor currently being built.
2420 SmallVector<llvm::Constant *, 16> Fields;
2421
2422 /// GetAddrOfTypeName - Returns the mangled type name of the given type.
2423 llvm::GlobalVariable *
2424 GetAddrOfTypeName(QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage);
2425
2426 /// GetAddrOfExternalRTTIDescriptor - Returns the constant for the RTTI
2427 /// descriptor of the given type.
2428 llvm::Constant *GetAddrOfExternalRTTIDescriptor(QualType Ty);
2429
2430 /// BuildVTablePointer - Build the vtable pointer for the given type.
2431 void BuildVTablePointer(const Type *Ty);
2432
2433 /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
2434 /// inheritance, according to the Itanium C++ ABI, 2.9.5p6b.
2435 void BuildSIClassTypeInfo(const CXXRecordDecl *RD);
2436
2437 /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
2438 /// classes with bases that do not satisfy the abi::__si_class_type_info
2439 /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
2440 void BuildVMIClassTypeInfo(const CXXRecordDecl *RD);
2441
2442 /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct, used
2443 /// for pointer types.
2444 void BuildPointerTypeInfo(QualType PointeeTy);
2445
2446 /// BuildObjCObjectTypeInfo - Build the appropriate kind of
2447 /// type_info for an object type.
2448 void BuildObjCObjectTypeInfo(const ObjCObjectType *Ty);
2449
2450 /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
2451 /// struct, used for member pointer types.
2452 void BuildPointerToMemberTypeInfo(const MemberPointerType *Ty);
2453
2454public:
2455 ItaniumRTTIBuilder(const ItaniumCXXABI &ABI)
2456 : CGM(ABI.CGM), VMContext(CGM.getModule().getContext()), CXXABI(ABI) {}
2457
2458 // Pointer type info flags.
2459 enum {
2460 /// PTI_Const - Type has const qualifier.
2461 PTI_Const = 0x1,
2462
2463 /// PTI_Volatile - Type has volatile qualifier.
2464 PTI_Volatile = 0x2,
2465
2466 /// PTI_Restrict - Type has restrict qualifier.
2467 PTI_Restrict = 0x4,
2468
2469 /// PTI_Incomplete - Type is incomplete.
2470 PTI_Incomplete = 0x8,
2471
2472 /// PTI_ContainingClassIncomplete - Containing class is incomplete.
2473 /// (in pointer to member).
2474 PTI_ContainingClassIncomplete = 0x10
2475 };
2476
2477 // VMI type info flags.
2478 enum {
2479 /// VMI_NonDiamondRepeat - Class has non-diamond repeated inheritance.
2480 VMI_NonDiamondRepeat = 0x1,
2481
2482 /// VMI_DiamondShaped - Class is diamond shaped.
2483 VMI_DiamondShaped = 0x2
2484 };
2485
2486 // Base class type info flags.
2487 enum {
2488 /// BCTI_Virtual - Base class is virtual.
2489 BCTI_Virtual = 0x1,
2490
2491 /// BCTI_Public - Base class is public.
2492 BCTI_Public = 0x2
2493 };
2494
2495 /// BuildTypeInfo - Build the RTTI type info struct for the given type.
2496 ///
2497 /// \param Force - true to force the creation of this RTTI value
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00002498 /// \param DLLExport - true to mark the RTTI value as DLLExport
2499 llvm::Constant *BuildTypeInfo(QualType Ty, bool Force = false,
2500 bool DLLExport = false);
David Majnemere2cb8d12014-07-07 06:20:47 +00002501};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002502}
David Majnemere2cb8d12014-07-07 06:20:47 +00002503
2504llvm::GlobalVariable *ItaniumRTTIBuilder::GetAddrOfTypeName(
2505 QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage) {
Yaron Kerene46f7ed2015-07-29 14:21:47 +00002506 SmallString<256> Name;
2507 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00002508 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00002509
2510 // We know that the mangled name of the type starts at index 4 of the
2511 // mangled name of the typename, so we can just index into it in order to
2512 // get the mangled name of the type.
2513 llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,
2514 Name.substr(4));
2515
2516 llvm::GlobalVariable *GV =
2517 CGM.CreateOrReplaceCXXRuntimeVariable(Name, Init->getType(), Linkage);
2518
2519 GV->setInitializer(Init);
2520
2521 return GV;
2522}
2523
2524llvm::Constant *
2525ItaniumRTTIBuilder::GetAddrOfExternalRTTIDescriptor(QualType Ty) {
2526 // Mangle the RTTI name.
Yaron Kerene46f7ed2015-07-29 14:21:47 +00002527 SmallString<256> Name;
2528 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00002529 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00002530
2531 // Look for an existing global.
2532 llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name);
2533
2534 if (!GV) {
2535 // Create a new global variable.
2536 GV = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
2537 /*Constant=*/true,
2538 llvm::GlobalValue::ExternalLinkage, nullptr,
2539 Name);
David Majnemer1fb1a042014-11-07 07:26:38 +00002540 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2541 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
2542 if (RD->hasAttr<DLLImportAttr>())
2543 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
2544 }
David Majnemere2cb8d12014-07-07 06:20:47 +00002545 }
2546
2547 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
2548}
2549
2550/// TypeInfoIsInStandardLibrary - Given a builtin type, returns whether the type
2551/// info for that type is defined in the standard library.
2552static bool TypeInfoIsInStandardLibrary(const BuiltinType *Ty) {
2553 // Itanium C++ ABI 2.9.2:
2554 // Basic type information (e.g. for "int", "bool", etc.) will be kept in
2555 // the run-time support library. Specifically, the run-time support
2556 // library should contain type_info objects for the types X, X* and
2557 // X const*, for every X in: void, std::nullptr_t, bool, wchar_t, char,
2558 // unsigned char, signed char, short, unsigned short, int, unsigned int,
2559 // long, unsigned long, long long, unsigned long long, float, double,
2560 // long double, char16_t, char32_t, and the IEEE 754r decimal and
2561 // half-precision floating point types.
Richard Smith4a382012016-02-03 01:32:42 +00002562 //
2563 // GCC also emits RTTI for __int128.
2564 // FIXME: We do not emit RTTI information for decimal types here.
2565
2566 // Types added here must also be added to EmitFundamentalRTTIDescriptors.
David Majnemere2cb8d12014-07-07 06:20:47 +00002567 switch (Ty->getKind()) {
2568 case BuiltinType::Void:
2569 case BuiltinType::NullPtr:
2570 case BuiltinType::Bool:
2571 case BuiltinType::WChar_S:
2572 case BuiltinType::WChar_U:
2573 case BuiltinType::Char_U:
2574 case BuiltinType::Char_S:
2575 case BuiltinType::UChar:
2576 case BuiltinType::SChar:
2577 case BuiltinType::Short:
2578 case BuiltinType::UShort:
2579 case BuiltinType::Int:
2580 case BuiltinType::UInt:
2581 case BuiltinType::Long:
2582 case BuiltinType::ULong:
2583 case BuiltinType::LongLong:
2584 case BuiltinType::ULongLong:
2585 case BuiltinType::Half:
2586 case BuiltinType::Float:
2587 case BuiltinType::Double:
2588 case BuiltinType::LongDouble:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002589 case BuiltinType::Float128:
David Majnemere2cb8d12014-07-07 06:20:47 +00002590 case BuiltinType::Char16:
2591 case BuiltinType::Char32:
2592 case BuiltinType::Int128:
2593 case BuiltinType::UInt128:
Richard Smith4a382012016-02-03 01:32:42 +00002594 return true;
2595
Alexey Bader954ba212016-04-08 13:40:33 +00002596#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2597 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00002598#include "clang/Basic/OpenCLImageTypes.def"
David Majnemere2cb8d12014-07-07 06:20:47 +00002599 case BuiltinType::OCLSampler:
2600 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00002601 case BuiltinType::OCLClkEvent:
2602 case BuiltinType::OCLQueue:
2603 case BuiltinType::OCLNDRange:
2604 case BuiltinType::OCLReserveID:
Richard Smith4a382012016-02-03 01:32:42 +00002605 return false;
David Majnemere2cb8d12014-07-07 06:20:47 +00002606
2607 case BuiltinType::Dependent:
2608#define BUILTIN_TYPE(Id, SingletonId)
2609#define PLACEHOLDER_TYPE(Id, SingletonId) \
2610 case BuiltinType::Id:
2611#include "clang/AST/BuiltinTypes.def"
2612 llvm_unreachable("asking for RRTI for a placeholder type!");
2613
2614 case BuiltinType::ObjCId:
2615 case BuiltinType::ObjCClass:
2616 case BuiltinType::ObjCSel:
2617 llvm_unreachable("FIXME: Objective-C types are unsupported!");
2618 }
2619
2620 llvm_unreachable("Invalid BuiltinType Kind!");
2621}
2622
2623static bool TypeInfoIsInStandardLibrary(const PointerType *PointerTy) {
2624 QualType PointeeTy = PointerTy->getPointeeType();
2625 const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(PointeeTy);
2626 if (!BuiltinTy)
2627 return false;
2628
2629 // Check the qualifiers.
2630 Qualifiers Quals = PointeeTy.getQualifiers();
2631 Quals.removeConst();
2632
2633 if (!Quals.empty())
2634 return false;
2635
2636 return TypeInfoIsInStandardLibrary(BuiltinTy);
2637}
2638
2639/// IsStandardLibraryRTTIDescriptor - Returns whether the type
2640/// information for the given type exists in the standard library.
2641static bool IsStandardLibraryRTTIDescriptor(QualType Ty) {
2642 // Type info for builtin types is defined in the standard library.
2643 if (const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(Ty))
2644 return TypeInfoIsInStandardLibrary(BuiltinTy);
2645
2646 // Type info for some pointer types to builtin types is defined in the
2647 // standard library.
2648 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2649 return TypeInfoIsInStandardLibrary(PointerTy);
2650
2651 return false;
2652}
2653
2654/// ShouldUseExternalRTTIDescriptor - Returns whether the type information for
2655/// the given type exists somewhere else, and that we should not emit the type
2656/// information in this translation unit. Assumes that it is not a
2657/// standard-library type.
2658static bool ShouldUseExternalRTTIDescriptor(CodeGenModule &CGM,
2659 QualType Ty) {
2660 ASTContext &Context = CGM.getContext();
2661
2662 // If RTTI is disabled, assume it might be disabled in the
2663 // translation unit that defines any potential key function, too.
2664 if (!Context.getLangOpts().RTTI) return false;
2665
2666 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2667 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
2668 if (!RD->hasDefinition())
2669 return false;
2670
2671 if (!RD->isDynamicClass())
2672 return false;
2673
2674 // FIXME: this may need to be reconsidered if the key function
2675 // changes.
David Majnemerbe9022c2015-08-06 20:56:55 +00002676 // N.B. We must always emit the RTTI data ourselves if there exists a key
2677 // function.
2678 bool IsDLLImport = RD->hasAttr<DLLImportAttr>();
David Majnemer1fb1a042014-11-07 07:26:38 +00002679 if (CGM.getVTables().isVTableExternal(RD))
David Majnemerbe9022c2015-08-06 20:56:55 +00002680 return IsDLLImport ? false : true;
David Majnemer1fb1a042014-11-07 07:26:38 +00002681
David Majnemerbe9022c2015-08-06 20:56:55 +00002682 if (IsDLLImport)
David Majnemer1fb1a042014-11-07 07:26:38 +00002683 return true;
David Majnemere2cb8d12014-07-07 06:20:47 +00002684 }
2685
2686 return false;
2687}
2688
2689/// IsIncompleteClassType - Returns whether the given record type is incomplete.
2690static bool IsIncompleteClassType(const RecordType *RecordTy) {
2691 return !RecordTy->getDecl()->isCompleteDefinition();
2692}
2693
2694/// ContainsIncompleteClassType - Returns whether the given type contains an
2695/// incomplete class type. This is true if
2696///
2697/// * The given type is an incomplete class type.
2698/// * The given type is a pointer type whose pointee type contains an
2699/// incomplete class type.
2700/// * The given type is a member pointer type whose class is an incomplete
2701/// class type.
2702/// * The given type is a member pointer type whoise pointee type contains an
2703/// incomplete class type.
2704/// is an indirect or direct pointer to an incomplete class type.
2705static bool ContainsIncompleteClassType(QualType Ty) {
2706 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2707 if (IsIncompleteClassType(RecordTy))
2708 return true;
2709 }
2710
2711 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2712 return ContainsIncompleteClassType(PointerTy->getPointeeType());
2713
2714 if (const MemberPointerType *MemberPointerTy =
2715 dyn_cast<MemberPointerType>(Ty)) {
2716 // Check if the class type is incomplete.
2717 const RecordType *ClassType = cast<RecordType>(MemberPointerTy->getClass());
2718 if (IsIncompleteClassType(ClassType))
2719 return true;
2720
2721 return ContainsIncompleteClassType(MemberPointerTy->getPointeeType());
2722 }
2723
2724 return false;
2725}
2726
2727// CanUseSingleInheritance - Return whether the given record decl has a "single,
2728// public, non-virtual base at offset zero (i.e. the derived class is dynamic
2729// iff the base is)", according to Itanium C++ ABI, 2.95p6b.
2730static bool CanUseSingleInheritance(const CXXRecordDecl *RD) {
2731 // Check the number of bases.
2732 if (RD->getNumBases() != 1)
2733 return false;
2734
2735 // Get the base.
2736 CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin();
2737
2738 // Check that the base is not virtual.
2739 if (Base->isVirtual())
2740 return false;
2741
2742 // Check that the base is public.
2743 if (Base->getAccessSpecifier() != AS_public)
2744 return false;
2745
2746 // Check that the class is dynamic iff the base is.
2747 const CXXRecordDecl *BaseDecl =
2748 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2749 if (!BaseDecl->isEmpty() &&
2750 BaseDecl->isDynamicClass() != RD->isDynamicClass())
2751 return false;
2752
2753 return true;
2754}
2755
2756void ItaniumRTTIBuilder::BuildVTablePointer(const Type *Ty) {
2757 // abi::__class_type_info.
2758 static const char * const ClassTypeInfo =
2759 "_ZTVN10__cxxabiv117__class_type_infoE";
2760 // abi::__si_class_type_info.
2761 static const char * const SIClassTypeInfo =
2762 "_ZTVN10__cxxabiv120__si_class_type_infoE";
2763 // abi::__vmi_class_type_info.
2764 static const char * const VMIClassTypeInfo =
2765 "_ZTVN10__cxxabiv121__vmi_class_type_infoE";
2766
2767 const char *VTableName = nullptr;
2768
2769 switch (Ty->getTypeClass()) {
2770#define TYPE(Class, Base)
2771#define ABSTRACT_TYPE(Class, Base)
2772#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2773#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2774#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2775#include "clang/AST/TypeNodes.def"
2776 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
2777
2778 case Type::LValueReference:
2779 case Type::RValueReference:
2780 llvm_unreachable("References shouldn't get here");
2781
2782 case Type::Auto:
2783 llvm_unreachable("Undeduced auto type shouldn't get here");
2784
Xiuli Pan9c14e282016-01-09 12:53:17 +00002785 case Type::Pipe:
2786 llvm_unreachable("Pipe types shouldn't get here");
2787
David Majnemere2cb8d12014-07-07 06:20:47 +00002788 case Type::Builtin:
2789 // GCC treats vector and complex types as fundamental types.
2790 case Type::Vector:
2791 case Type::ExtVector:
2792 case Type::Complex:
2793 case Type::Atomic:
2794 // FIXME: GCC treats block pointers as fundamental types?!
2795 case Type::BlockPointer:
2796 // abi::__fundamental_type_info.
2797 VTableName = "_ZTVN10__cxxabiv123__fundamental_type_infoE";
2798 break;
2799
2800 case Type::ConstantArray:
2801 case Type::IncompleteArray:
2802 case Type::VariableArray:
2803 // abi::__array_type_info.
2804 VTableName = "_ZTVN10__cxxabiv117__array_type_infoE";
2805 break;
2806
2807 case Type::FunctionNoProto:
2808 case Type::FunctionProto:
2809 // abi::__function_type_info.
2810 VTableName = "_ZTVN10__cxxabiv120__function_type_infoE";
2811 break;
2812
2813 case Type::Enum:
2814 // abi::__enum_type_info.
2815 VTableName = "_ZTVN10__cxxabiv116__enum_type_infoE";
2816 break;
2817
2818 case Type::Record: {
2819 const CXXRecordDecl *RD =
2820 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
2821
2822 if (!RD->hasDefinition() || !RD->getNumBases()) {
2823 VTableName = ClassTypeInfo;
2824 } else if (CanUseSingleInheritance(RD)) {
2825 VTableName = SIClassTypeInfo;
2826 } else {
2827 VTableName = VMIClassTypeInfo;
2828 }
2829
2830 break;
2831 }
2832
2833 case Type::ObjCObject:
2834 // Ignore protocol qualifiers.
2835 Ty = cast<ObjCObjectType>(Ty)->getBaseType().getTypePtr();
2836
2837 // Handle id and Class.
2838 if (isa<BuiltinType>(Ty)) {
2839 VTableName = ClassTypeInfo;
2840 break;
2841 }
2842
2843 assert(isa<ObjCInterfaceType>(Ty));
2844 // Fall through.
2845
2846 case Type::ObjCInterface:
2847 if (cast<ObjCInterfaceType>(Ty)->getDecl()->getSuperClass()) {
2848 VTableName = SIClassTypeInfo;
2849 } else {
2850 VTableName = ClassTypeInfo;
2851 }
2852 break;
2853
2854 case Type::ObjCObjectPointer:
2855 case Type::Pointer:
2856 // abi::__pointer_type_info.
2857 VTableName = "_ZTVN10__cxxabiv119__pointer_type_infoE";
2858 break;
2859
2860 case Type::MemberPointer:
2861 // abi::__pointer_to_member_type_info.
2862 VTableName = "_ZTVN10__cxxabiv129__pointer_to_member_type_infoE";
2863 break;
2864 }
2865
2866 llvm::Constant *VTable =
2867 CGM.getModule().getOrInsertGlobal(VTableName, CGM.Int8PtrTy);
2868
2869 llvm::Type *PtrDiffTy =
2870 CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
2871
2872 // The vtable address point is 2.
2873 llvm::Constant *Two = llvm::ConstantInt::get(PtrDiffTy, 2);
David Blaikiee3b172a2015-04-02 18:55:21 +00002874 VTable =
2875 llvm::ConstantExpr::getInBoundsGetElementPtr(CGM.Int8PtrTy, VTable, Two);
David Majnemere2cb8d12014-07-07 06:20:47 +00002876 VTable = llvm::ConstantExpr::getBitCast(VTable, CGM.Int8PtrTy);
2877
2878 Fields.push_back(VTable);
2879}
2880
2881/// \brief Return the linkage that the type info and type info name constants
2882/// should have for the given type.
2883static llvm::GlobalVariable::LinkageTypes getTypeInfoLinkage(CodeGenModule &CGM,
2884 QualType Ty) {
2885 // Itanium C++ ABI 2.9.5p7:
2886 // In addition, it and all of the intermediate abi::__pointer_type_info
2887 // structs in the chain down to the abi::__class_type_info for the
2888 // incomplete class type must be prevented from resolving to the
2889 // corresponding type_info structs for the complete class type, possibly
2890 // by making them local static objects. Finally, a dummy class RTTI is
2891 // generated for the incomplete type that will not resolve to the final
2892 // complete class RTTI (because the latter need not exist), possibly by
2893 // making it a local static object.
2894 if (ContainsIncompleteClassType(Ty))
2895 return llvm::GlobalValue::InternalLinkage;
2896
2897 switch (Ty->getLinkage()) {
2898 case NoLinkage:
2899 case InternalLinkage:
2900 case UniqueExternalLinkage:
2901 return llvm::GlobalValue::InternalLinkage;
2902
2903 case VisibleNoLinkage:
2904 case ExternalLinkage:
2905 if (!CGM.getLangOpts().RTTI) {
2906 // RTTI is not enabled, which means that this type info struct is going
2907 // to be used for exception handling. Give it linkonce_odr linkage.
2908 return llvm::GlobalValue::LinkOnceODRLinkage;
2909 }
2910
2911 if (const RecordType *Record = dyn_cast<RecordType>(Ty)) {
2912 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2913 if (RD->hasAttr<WeakAttr>())
2914 return llvm::GlobalValue::WeakODRLinkage;
David Majnemerbe9022c2015-08-06 20:56:55 +00002915 if (RD->isDynamicClass()) {
2916 llvm::GlobalValue::LinkageTypes LT = CGM.getVTableLinkage(RD);
2917 // MinGW won't export the RTTI information when there is a key function.
2918 // Make sure we emit our own copy instead of attempting to dllimport it.
2919 if (RD->hasAttr<DLLImportAttr>() &&
2920 llvm::GlobalValue::isAvailableExternallyLinkage(LT))
2921 LT = llvm::GlobalValue::LinkOnceODRLinkage;
2922 return LT;
2923 }
David Majnemere2cb8d12014-07-07 06:20:47 +00002924 }
2925
2926 return llvm::GlobalValue::LinkOnceODRLinkage;
2927 }
2928
2929 llvm_unreachable("Invalid linkage!");
2930}
2931
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00002932llvm::Constant *ItaniumRTTIBuilder::BuildTypeInfo(QualType Ty, bool Force,
2933 bool DLLExport) {
David Majnemere2cb8d12014-07-07 06:20:47 +00002934 // We want to operate on the canonical type.
Yaron Kerenebd14262016-03-16 12:14:43 +00002935 Ty = Ty.getCanonicalType();
David Majnemere2cb8d12014-07-07 06:20:47 +00002936
2937 // Check if we've already emitted an RTTI descriptor for this type.
Yaron Kerene46f7ed2015-07-29 14:21:47 +00002938 SmallString<256> Name;
2939 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00002940 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00002941
2942 llvm::GlobalVariable *OldGV = CGM.getModule().getNamedGlobal(Name);
2943 if (OldGV && !OldGV->isDeclaration()) {
2944 assert(!OldGV->hasAvailableExternallyLinkage() &&
2945 "available_externally typeinfos not yet implemented");
2946
2947 return llvm::ConstantExpr::getBitCast(OldGV, CGM.Int8PtrTy);
2948 }
2949
2950 // Check if there is already an external RTTI descriptor for this type.
2951 bool IsStdLib = IsStandardLibraryRTTIDescriptor(Ty);
2952 if (!Force && (IsStdLib || ShouldUseExternalRTTIDescriptor(CGM, Ty)))
2953 return GetAddrOfExternalRTTIDescriptor(Ty);
2954
2955 // Emit the standard library with external linkage.
2956 llvm::GlobalVariable::LinkageTypes Linkage;
2957 if (IsStdLib)
2958 Linkage = llvm::GlobalValue::ExternalLinkage;
2959 else
2960 Linkage = getTypeInfoLinkage(CGM, Ty);
2961
2962 // Add the vtable pointer.
2963 BuildVTablePointer(cast<Type>(Ty));
2964
2965 // And the name.
2966 llvm::GlobalVariable *TypeName = GetAddrOfTypeName(Ty, Linkage);
2967 llvm::Constant *TypeNameField;
2968
2969 // If we're supposed to demote the visibility, be sure to set a flag
2970 // to use a string comparison for type_info comparisons.
2971 ItaniumCXXABI::RTTIUniquenessKind RTTIUniqueness =
2972 CXXABI.classifyRTTIUniqueness(Ty, Linkage);
2973 if (RTTIUniqueness != ItaniumCXXABI::RUK_Unique) {
2974 // The flag is the sign bit, which on ARM64 is defined to be clear
2975 // for global pointers. This is very ARM64-specific.
2976 TypeNameField = llvm::ConstantExpr::getPtrToInt(TypeName, CGM.Int64Ty);
2977 llvm::Constant *flag =
2978 llvm::ConstantInt::get(CGM.Int64Ty, ((uint64_t)1) << 63);
2979 TypeNameField = llvm::ConstantExpr::getAdd(TypeNameField, flag);
2980 TypeNameField =
2981 llvm::ConstantExpr::getIntToPtr(TypeNameField, CGM.Int8PtrTy);
2982 } else {
2983 TypeNameField = llvm::ConstantExpr::getBitCast(TypeName, CGM.Int8PtrTy);
2984 }
2985 Fields.push_back(TypeNameField);
2986
2987 switch (Ty->getTypeClass()) {
2988#define TYPE(Class, Base)
2989#define ABSTRACT_TYPE(Class, Base)
2990#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2991#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2992#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2993#include "clang/AST/TypeNodes.def"
2994 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
2995
2996 // GCC treats vector types as fundamental types.
2997 case Type::Builtin:
2998 case Type::Vector:
2999 case Type::ExtVector:
3000 case Type::Complex:
3001 case Type::BlockPointer:
3002 // Itanium C++ ABI 2.9.5p4:
3003 // abi::__fundamental_type_info adds no data members to std::type_info.
3004 break;
3005
3006 case Type::LValueReference:
3007 case Type::RValueReference:
3008 llvm_unreachable("References shouldn't get here");
3009
3010 case Type::Auto:
3011 llvm_unreachable("Undeduced auto type shouldn't get here");
3012
Xiuli Pan9c14e282016-01-09 12:53:17 +00003013 case Type::Pipe:
3014 llvm_unreachable("Pipe type shouldn't get here");
3015
David Majnemere2cb8d12014-07-07 06:20:47 +00003016 case Type::ConstantArray:
3017 case Type::IncompleteArray:
3018 case Type::VariableArray:
3019 // Itanium C++ ABI 2.9.5p5:
3020 // abi::__array_type_info adds no data members to std::type_info.
3021 break;
3022
3023 case Type::FunctionNoProto:
3024 case Type::FunctionProto:
3025 // Itanium C++ ABI 2.9.5p5:
3026 // abi::__function_type_info adds no data members to std::type_info.
3027 break;
3028
3029 case Type::Enum:
3030 // Itanium C++ ABI 2.9.5p5:
3031 // abi::__enum_type_info adds no data members to std::type_info.
3032 break;
3033
3034 case Type::Record: {
3035 const CXXRecordDecl *RD =
3036 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
3037 if (!RD->hasDefinition() || !RD->getNumBases()) {
3038 // We don't need to emit any fields.
3039 break;
3040 }
3041
3042 if (CanUseSingleInheritance(RD))
3043 BuildSIClassTypeInfo(RD);
3044 else
3045 BuildVMIClassTypeInfo(RD);
3046
3047 break;
3048 }
3049
3050 case Type::ObjCObject:
3051 case Type::ObjCInterface:
3052 BuildObjCObjectTypeInfo(cast<ObjCObjectType>(Ty));
3053 break;
3054
3055 case Type::ObjCObjectPointer:
3056 BuildPointerTypeInfo(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
3057 break;
3058
3059 case Type::Pointer:
3060 BuildPointerTypeInfo(cast<PointerType>(Ty)->getPointeeType());
3061 break;
3062
3063 case Type::MemberPointer:
3064 BuildPointerToMemberTypeInfo(cast<MemberPointerType>(Ty));
3065 break;
3066
3067 case Type::Atomic:
3068 // No fields, at least for the moment.
3069 break;
3070 }
3071
3072 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Fields);
3073
Rafael Espindolacb92c192015-01-15 23:18:01 +00003074 llvm::Module &M = CGM.getModule();
David Majnemere2cb8d12014-07-07 06:20:47 +00003075 llvm::GlobalVariable *GV =
Rafael Espindolacb92c192015-01-15 23:18:01 +00003076 new llvm::GlobalVariable(M, Init->getType(),
3077 /*Constant=*/true, Linkage, Init, Name);
3078
David Majnemere2cb8d12014-07-07 06:20:47 +00003079 // If there's already an old global variable, replace it with the new one.
3080 if (OldGV) {
3081 GV->takeName(OldGV);
3082 llvm::Constant *NewPtr =
3083 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
3084 OldGV->replaceAllUsesWith(NewPtr);
3085 OldGV->eraseFromParent();
3086 }
3087
Yaron Keren04da2382015-07-29 15:42:28 +00003088 if (CGM.supportsCOMDAT() && GV->isWeakForLinker())
3089 GV->setComdat(M.getOrInsertComdat(GV->getName()));
3090
David Majnemere2cb8d12014-07-07 06:20:47 +00003091 // The Itanium ABI specifies that type_info objects must be globally
3092 // unique, with one exception: if the type is an incomplete class
3093 // type or a (possibly indirect) pointer to one. That exception
3094 // affects the general case of comparing type_info objects produced
3095 // by the typeid operator, which is why the comparison operators on
3096 // std::type_info generally use the type_info name pointers instead
3097 // of the object addresses. However, the language's built-in uses
3098 // of RTTI generally require class types to be complete, even when
3099 // manipulating pointers to those class types. This allows the
3100 // implementation of dynamic_cast to rely on address equality tests,
3101 // which is much faster.
3102
3103 // All of this is to say that it's important that both the type_info
3104 // object and the type_info name be uniqued when weakly emitted.
3105
3106 // Give the type_info object and name the formal visibility of the
3107 // type itself.
3108 llvm::GlobalValue::VisibilityTypes llvmVisibility;
3109 if (llvm::GlobalValue::isLocalLinkage(Linkage))
3110 // If the linkage is local, only default visibility makes sense.
3111 llvmVisibility = llvm::GlobalValue::DefaultVisibility;
3112 else if (RTTIUniqueness == ItaniumCXXABI::RUK_NonUniqueHidden)
3113 llvmVisibility = llvm::GlobalValue::HiddenVisibility;
3114 else
3115 llvmVisibility = CodeGenModule::GetLLVMVisibility(Ty->getVisibility());
3116 TypeName->setVisibility(llvmVisibility);
3117 GV->setVisibility(llvmVisibility);
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00003118 if (DLLExport)
3119 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
David Majnemere2cb8d12014-07-07 06:20:47 +00003120
3121 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
3122}
3123
3124/// ComputeQualifierFlags - Compute the pointer type info flags from the
3125/// given qualifier.
3126static unsigned ComputeQualifierFlags(Qualifiers Quals) {
3127 unsigned Flags = 0;
3128
3129 if (Quals.hasConst())
3130 Flags |= ItaniumRTTIBuilder::PTI_Const;
3131 if (Quals.hasVolatile())
3132 Flags |= ItaniumRTTIBuilder::PTI_Volatile;
3133 if (Quals.hasRestrict())
3134 Flags |= ItaniumRTTIBuilder::PTI_Restrict;
3135
3136 return Flags;
3137}
3138
3139/// BuildObjCObjectTypeInfo - Build the appropriate kind of type_info
3140/// for the given Objective-C object type.
3141void ItaniumRTTIBuilder::BuildObjCObjectTypeInfo(const ObjCObjectType *OT) {
3142 // Drop qualifiers.
3143 const Type *T = OT->getBaseType().getTypePtr();
3144 assert(isa<BuiltinType>(T) || isa<ObjCInterfaceType>(T));
3145
3146 // The builtin types are abi::__class_type_infos and don't require
3147 // extra fields.
3148 if (isa<BuiltinType>(T)) return;
3149
3150 ObjCInterfaceDecl *Class = cast<ObjCInterfaceType>(T)->getDecl();
3151 ObjCInterfaceDecl *Super = Class->getSuperClass();
3152
3153 // Root classes are also __class_type_info.
3154 if (!Super) return;
3155
3156 QualType SuperTy = CGM.getContext().getObjCInterfaceType(Super);
3157
3158 // Everything else is single inheritance.
3159 llvm::Constant *BaseTypeInfo =
3160 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(SuperTy);
3161 Fields.push_back(BaseTypeInfo);
3162}
3163
3164/// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
3165/// inheritance, according to the Itanium C++ ABI, 2.95p6b.
3166void ItaniumRTTIBuilder::BuildSIClassTypeInfo(const CXXRecordDecl *RD) {
3167 // Itanium C++ ABI 2.9.5p6b:
3168 // It adds to abi::__class_type_info a single member pointing to the
3169 // type_info structure for the base type,
3170 llvm::Constant *BaseTypeInfo =
3171 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(RD->bases_begin()->getType());
3172 Fields.push_back(BaseTypeInfo);
3173}
3174
3175namespace {
3176 /// SeenBases - Contains virtual and non-virtual bases seen when traversing
3177 /// a class hierarchy.
3178 struct SeenBases {
3179 llvm::SmallPtrSet<const CXXRecordDecl *, 16> NonVirtualBases;
3180 llvm::SmallPtrSet<const CXXRecordDecl *, 16> VirtualBases;
3181 };
3182}
3183
3184/// ComputeVMIClassTypeInfoFlags - Compute the value of the flags member in
3185/// abi::__vmi_class_type_info.
3186///
3187static unsigned ComputeVMIClassTypeInfoFlags(const CXXBaseSpecifier *Base,
3188 SeenBases &Bases) {
3189
3190 unsigned Flags = 0;
3191
3192 const CXXRecordDecl *BaseDecl =
3193 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
3194
3195 if (Base->isVirtual()) {
3196 // Mark the virtual base as seen.
David Blaikie82e95a32014-11-19 07:49:47 +00003197 if (!Bases.VirtualBases.insert(BaseDecl).second) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003198 // If this virtual base has been seen before, then the class is diamond
3199 // shaped.
3200 Flags |= ItaniumRTTIBuilder::VMI_DiamondShaped;
3201 } else {
3202 if (Bases.NonVirtualBases.count(BaseDecl))
3203 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3204 }
3205 } else {
3206 // Mark the non-virtual base as seen.
David Blaikie82e95a32014-11-19 07:49:47 +00003207 if (!Bases.NonVirtualBases.insert(BaseDecl).second) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003208 // If this non-virtual base has been seen before, then the class has non-
3209 // diamond shaped repeated inheritance.
3210 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3211 } else {
3212 if (Bases.VirtualBases.count(BaseDecl))
3213 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3214 }
3215 }
3216
3217 // Walk all bases.
3218 for (const auto &I : BaseDecl->bases())
3219 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
3220
3221 return Flags;
3222}
3223
3224static unsigned ComputeVMIClassTypeInfoFlags(const CXXRecordDecl *RD) {
3225 unsigned Flags = 0;
3226 SeenBases Bases;
3227
3228 // Walk all bases.
3229 for (const auto &I : RD->bases())
3230 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
3231
3232 return Flags;
3233}
3234
3235/// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
3236/// classes with bases that do not satisfy the abi::__si_class_type_info
3237/// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
3238void ItaniumRTTIBuilder::BuildVMIClassTypeInfo(const CXXRecordDecl *RD) {
3239 llvm::Type *UnsignedIntLTy =
3240 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3241
3242 // Itanium C++ ABI 2.9.5p6c:
3243 // __flags is a word with flags describing details about the class
3244 // structure, which may be referenced by using the __flags_masks
3245 // enumeration. These flags refer to both direct and indirect bases.
3246 unsigned Flags = ComputeVMIClassTypeInfoFlags(RD);
3247 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3248
3249 // Itanium C++ ABI 2.9.5p6c:
3250 // __base_count is a word with the number of direct proper base class
3251 // descriptions that follow.
3252 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, RD->getNumBases()));
3253
3254 if (!RD->getNumBases())
3255 return;
3256
David Majnemere2cb8d12014-07-07 06:20:47 +00003257 // Now add the base class descriptions.
3258
3259 // Itanium C++ ABI 2.9.5p6c:
3260 // __base_info[] is an array of base class descriptions -- one for every
3261 // direct proper base. Each description is of the type:
3262 //
3263 // struct abi::__base_class_type_info {
3264 // public:
3265 // const __class_type_info *__base_type;
3266 // long __offset_flags;
3267 //
3268 // enum __offset_flags_masks {
3269 // __virtual_mask = 0x1,
3270 // __public_mask = 0x2,
3271 // __offset_shift = 8
3272 // };
3273 // };
Reid Klecknerd8b04662016-08-25 22:16:30 +00003274
3275 // If we're in mingw and 'long' isn't wide enough for a pointer, use 'long
3276 // long' instead of 'long' for __offset_flags. libstdc++abi uses long long on
3277 // LLP64 platforms.
3278 // FIXME: Consider updating libc++abi to match, and extend this logic to all
3279 // LLP64 platforms.
3280 QualType OffsetFlagsTy = CGM.getContext().LongTy;
3281 const TargetInfo &TI = CGM.getContext().getTargetInfo();
3282 if (TI.getTriple().isOSCygMing() && TI.getPointerWidth(0) > TI.getLongWidth())
3283 OffsetFlagsTy = CGM.getContext().LongLongTy;
3284 llvm::Type *OffsetFlagsLTy =
3285 CGM.getTypes().ConvertType(OffsetFlagsTy);
3286
David Majnemere2cb8d12014-07-07 06:20:47 +00003287 for (const auto &Base : RD->bases()) {
3288 // The __base_type member points to the RTTI for the base type.
3289 Fields.push_back(ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(Base.getType()));
3290
3291 const CXXRecordDecl *BaseDecl =
3292 cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
3293
3294 int64_t OffsetFlags = 0;
3295
3296 // All but the lower 8 bits of __offset_flags are a signed offset.
3297 // For a non-virtual base, this is the offset in the object of the base
3298 // subobject. For a virtual base, this is the offset in the virtual table of
3299 // the virtual base offset for the virtual base referenced (negative).
3300 CharUnits Offset;
3301 if (Base.isVirtual())
3302 Offset =
3303 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(RD, BaseDecl);
3304 else {
3305 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
3306 Offset = Layout.getBaseClassOffset(BaseDecl);
3307 };
3308
3309 OffsetFlags = uint64_t(Offset.getQuantity()) << 8;
3310
3311 // The low-order byte of __offset_flags contains flags, as given by the
3312 // masks from the enumeration __offset_flags_masks.
3313 if (Base.isVirtual())
3314 OffsetFlags |= BCTI_Virtual;
3315 if (Base.getAccessSpecifier() == AS_public)
3316 OffsetFlags |= BCTI_Public;
3317
Reid Klecknerd8b04662016-08-25 22:16:30 +00003318 Fields.push_back(llvm::ConstantInt::get(OffsetFlagsLTy, OffsetFlags));
David Majnemere2cb8d12014-07-07 06:20:47 +00003319 }
3320}
3321
3322/// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct,
3323/// used for pointer types.
3324void ItaniumRTTIBuilder::BuildPointerTypeInfo(QualType PointeeTy) {
3325 Qualifiers Quals;
3326 QualType UnqualifiedPointeeTy =
3327 CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals);
3328
3329 // Itanium C++ ABI 2.9.5p7:
3330 // __flags is a flag word describing the cv-qualification and other
3331 // attributes of the type pointed to
3332 unsigned Flags = ComputeQualifierFlags(Quals);
3333
3334 // Itanium C++ ABI 2.9.5p7:
3335 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
3336 // incomplete class type, the incomplete target type flag is set.
3337 if (ContainsIncompleteClassType(UnqualifiedPointeeTy))
3338 Flags |= PTI_Incomplete;
3339
3340 llvm::Type *UnsignedIntLTy =
3341 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3342 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3343
3344 // Itanium C++ ABI 2.9.5p7:
3345 // __pointee is a pointer to the std::type_info derivation for the
3346 // unqualified type being pointed to.
3347 llvm::Constant *PointeeTypeInfo =
3348 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(UnqualifiedPointeeTy);
3349 Fields.push_back(PointeeTypeInfo);
3350}
3351
3352/// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
3353/// struct, used for member pointer types.
3354void
3355ItaniumRTTIBuilder::BuildPointerToMemberTypeInfo(const MemberPointerType *Ty) {
3356 QualType PointeeTy = Ty->getPointeeType();
3357
3358 Qualifiers Quals;
3359 QualType UnqualifiedPointeeTy =
3360 CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals);
3361
3362 // Itanium C++ ABI 2.9.5p7:
3363 // __flags is a flag word describing the cv-qualification and other
3364 // attributes of the type pointed to.
3365 unsigned Flags = ComputeQualifierFlags(Quals);
3366
3367 const RecordType *ClassType = cast<RecordType>(Ty->getClass());
3368
3369 // Itanium C++ ABI 2.9.5p7:
3370 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
3371 // incomplete class type, the incomplete target type flag is set.
3372 if (ContainsIncompleteClassType(UnqualifiedPointeeTy))
3373 Flags |= PTI_Incomplete;
3374
3375 if (IsIncompleteClassType(ClassType))
3376 Flags |= PTI_ContainingClassIncomplete;
3377
3378 llvm::Type *UnsignedIntLTy =
3379 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3380 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3381
3382 // Itanium C++ ABI 2.9.5p7:
3383 // __pointee is a pointer to the std::type_info derivation for the
3384 // unqualified type being pointed to.
3385 llvm::Constant *PointeeTypeInfo =
3386 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(UnqualifiedPointeeTy);
3387 Fields.push_back(PointeeTypeInfo);
3388
3389 // Itanium C++ ABI 2.9.5p9:
3390 // __context is a pointer to an abi::__class_type_info corresponding to the
3391 // class type containing the member pointed to
3392 // (e.g., the "A" in "int A::*").
3393 Fields.push_back(
3394 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(QualType(ClassType, 0)));
3395}
3396
David Majnemer443250f2015-03-17 20:35:00 +00003397llvm::Constant *ItaniumCXXABI::getAddrOfRTTIDescriptor(QualType Ty) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003398 return ItaniumRTTIBuilder(*this).BuildTypeInfo(Ty);
3399}
3400
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00003401void ItaniumCXXABI::EmitFundamentalRTTIDescriptor(QualType Type,
3402 bool DLLExport) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003403 QualType PointerType = getContext().getPointerType(Type);
3404 QualType PointerTypeConst = getContext().getPointerType(Type.withConst());
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00003405 ItaniumRTTIBuilder(*this).BuildTypeInfo(Type, /*Force=*/true, DLLExport);
3406 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerType, /*Force=*/true,
3407 DLLExport);
3408 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerTypeConst, /*Force=*/true,
3409 DLLExport);
David Majnemere2cb8d12014-07-07 06:20:47 +00003410}
3411
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00003412void ItaniumCXXABI::EmitFundamentalRTTIDescriptors(bool DLLExport) {
Richard Smith4a382012016-02-03 01:32:42 +00003413 // Types added here must also be added to TypeInfoIsInStandardLibrary.
David Majnemere2cb8d12014-07-07 06:20:47 +00003414 QualType FundamentalTypes[] = {
3415 getContext().VoidTy, getContext().NullPtrTy,
3416 getContext().BoolTy, getContext().WCharTy,
3417 getContext().CharTy, getContext().UnsignedCharTy,
3418 getContext().SignedCharTy, getContext().ShortTy,
3419 getContext().UnsignedShortTy, getContext().IntTy,
3420 getContext().UnsignedIntTy, getContext().LongTy,
3421 getContext().UnsignedLongTy, getContext().LongLongTy,
Richard Smith4a382012016-02-03 01:32:42 +00003422 getContext().UnsignedLongLongTy, getContext().Int128Ty,
3423 getContext().UnsignedInt128Ty, getContext().HalfTy,
David Majnemere2cb8d12014-07-07 06:20:47 +00003424 getContext().FloatTy, getContext().DoubleTy,
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00003425 getContext().LongDoubleTy, getContext().Float128Ty,
3426 getContext().Char16Ty, getContext().Char32Ty
David Majnemere2cb8d12014-07-07 06:20:47 +00003427 };
3428 for (const QualType &FundamentalType : FundamentalTypes)
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00003429 EmitFundamentalRTTIDescriptor(FundamentalType, DLLExport);
David Majnemere2cb8d12014-07-07 06:20:47 +00003430}
3431
3432/// What sort of uniqueness rules should we use for the RTTI for the
3433/// given type?
3434ItaniumCXXABI::RTTIUniquenessKind ItaniumCXXABI::classifyRTTIUniqueness(
3435 QualType CanTy, llvm::GlobalValue::LinkageTypes Linkage) const {
3436 if (shouldRTTIBeUnique())
3437 return RUK_Unique;
3438
3439 // It's only necessary for linkonce_odr or weak_odr linkage.
3440 if (Linkage != llvm::GlobalValue::LinkOnceODRLinkage &&
3441 Linkage != llvm::GlobalValue::WeakODRLinkage)
3442 return RUK_Unique;
3443
3444 // It's only necessary with default visibility.
3445 if (CanTy->getVisibility() != DefaultVisibility)
3446 return RUK_Unique;
3447
3448 // If we're not required to publish this symbol, hide it.
3449 if (Linkage == llvm::GlobalValue::LinkOnceODRLinkage)
3450 return RUK_NonUniqueHidden;
3451
3452 // If we're required to publish this symbol, as we might be under an
3453 // explicit instantiation, leave it with default visibility but
3454 // enable string-comparisons.
3455 assert(Linkage == llvm::GlobalValue::WeakODRLinkage);
3456 return RUK_NonUniqueVisible;
3457}
Rafael Espindola91f68b42014-09-15 19:20:10 +00003458
Rafael Espindola1e4df922014-09-16 15:18:21 +00003459// Find out how to codegen the complete destructor and constructor
3460namespace {
3461enum class StructorCodegen { Emit, RAUW, Alias, COMDAT };
3462}
3463static StructorCodegen getCodegenToUse(CodeGenModule &CGM,
3464 const CXXMethodDecl *MD) {
3465 if (!CGM.getCodeGenOpts().CXXCtorDtorAliases)
3466 return StructorCodegen::Emit;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003467
Rafael Espindola1e4df922014-09-16 15:18:21 +00003468 // The complete and base structors are not equivalent if there are any virtual
3469 // bases, so emit separate functions.
3470 if (MD->getParent()->getNumVBases())
3471 return StructorCodegen::Emit;
3472
3473 GlobalDecl AliasDecl;
3474 if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) {
3475 AliasDecl = GlobalDecl(DD, Dtor_Complete);
3476 } else {
3477 const auto *CD = cast<CXXConstructorDecl>(MD);
3478 AliasDecl = GlobalDecl(CD, Ctor_Complete);
3479 }
3480 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3481
3482 if (llvm::GlobalValue::isDiscardableIfUnused(Linkage))
3483 return StructorCodegen::RAUW;
3484
3485 // FIXME: Should we allow available_externally aliases?
3486 if (!llvm::GlobalAlias::isValidLinkage(Linkage))
3487 return StructorCodegen::RAUW;
3488
Rafael Espindola0806f982014-09-16 20:19:43 +00003489 if (llvm::GlobalValue::isWeakForLinker(Linkage)) {
3490 // Only ELF supports COMDATs with arbitrary names (C5/D5).
3491 if (CGM.getTarget().getTriple().isOSBinFormatELF())
3492 return StructorCodegen::COMDAT;
3493 return StructorCodegen::Emit;
3494 }
Rafael Espindola1e4df922014-09-16 15:18:21 +00003495
3496 return StructorCodegen::Alias;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003497}
3498
Rafael Espindola1e4df922014-09-16 15:18:21 +00003499static void emitConstructorDestructorAlias(CodeGenModule &CGM,
3500 GlobalDecl AliasDecl,
3501 GlobalDecl TargetDecl) {
3502 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3503
3504 StringRef MangledName = CGM.getMangledName(AliasDecl);
3505 llvm::GlobalValue *Entry = CGM.GetGlobalValue(MangledName);
3506 if (Entry && !Entry->isDeclaration())
3507 return;
3508
3509 auto *Aliasee = cast<llvm::GlobalValue>(CGM.GetAddrOfGlobal(TargetDecl));
Rafael Espindola1e4df922014-09-16 15:18:21 +00003510
3511 // Create the alias with no name.
David Blaikie2a791d72015-09-14 18:38:22 +00003512 auto *Alias = llvm::GlobalAlias::create(Linkage, "", Aliasee);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003513
3514 // Switch any previous uses to the alias.
3515 if (Entry) {
NAKAMURA Takumie9621042015-09-15 01:39:27 +00003516 assert(Entry->getType() == Aliasee->getType() &&
Rafael Espindola1e4df922014-09-16 15:18:21 +00003517 "declaration exists with different type");
3518 Alias->takeName(Entry);
3519 Entry->replaceAllUsesWith(Alias);
3520 Entry->eraseFromParent();
3521 } else {
3522 Alias->setName(MangledName);
3523 }
3524
3525 // Finally, set up the alias with its proper name and attributes.
Dario Domiziolic4fb8ca72014-09-19 22:06:24 +00003526 CGM.setAliasAttributes(cast<NamedDecl>(AliasDecl.getDecl()), Alias);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003527}
3528
3529void ItaniumCXXABI::emitCXXStructor(const CXXMethodDecl *MD,
3530 StructorType Type) {
3531 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
3532 const CXXDestructorDecl *DD = CD ? nullptr : cast<CXXDestructorDecl>(MD);
3533
3534 StructorCodegen CGType = getCodegenToUse(CGM, MD);
3535
3536 if (Type == StructorType::Complete) {
3537 GlobalDecl CompleteDecl;
3538 GlobalDecl BaseDecl;
3539 if (CD) {
3540 CompleteDecl = GlobalDecl(CD, Ctor_Complete);
3541 BaseDecl = GlobalDecl(CD, Ctor_Base);
3542 } else {
3543 CompleteDecl = GlobalDecl(DD, Dtor_Complete);
3544 BaseDecl = GlobalDecl(DD, Dtor_Base);
3545 }
3546
3547 if (CGType == StructorCodegen::Alias || CGType == StructorCodegen::COMDAT) {
3548 emitConstructorDestructorAlias(CGM, CompleteDecl, BaseDecl);
3549 return;
3550 }
3551
3552 if (CGType == StructorCodegen::RAUW) {
3553 StringRef MangledName = CGM.getMangledName(CompleteDecl);
Andrey Bokhankocab58582015-08-31 13:20:44 +00003554 auto *Aliasee = CGM.GetAddrOfGlobal(BaseDecl);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003555 CGM.addReplacement(MangledName, Aliasee);
3556 return;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003557 }
3558 }
3559
3560 // The base destructor is equivalent to the base destructor of its
3561 // base class if there is exactly one non-virtual base class with a
3562 // non-trivial destructor, there are no fields with a non-trivial
3563 // destructor, and the body of the destructor is trivial.
Rafael Espindola1e4df922014-09-16 15:18:21 +00003564 if (DD && Type == StructorType::Base && CGType != StructorCodegen::COMDAT &&
3565 !CGM.TryEmitBaseDestructorAsAlias(DD))
Rafael Espindola91f68b42014-09-15 19:20:10 +00003566 return;
3567
Rafael Espindola1e4df922014-09-16 15:18:21 +00003568 llvm::Function *Fn = CGM.codegenCXXStructor(MD, Type);
Rafael Espindola91f68b42014-09-15 19:20:10 +00003569
Rafael Espindola1e4df922014-09-16 15:18:21 +00003570 if (CGType == StructorCodegen::COMDAT) {
3571 SmallString<256> Buffer;
3572 llvm::raw_svector_ostream Out(Buffer);
3573 if (DD)
3574 getMangleContext().mangleCXXDtorComdat(DD, Out);
3575 else
3576 getMangleContext().mangleCXXCtorComdat(CD, Out);
3577 llvm::Comdat *C = CGM.getModule().getOrInsertComdat(Out.str());
3578 Fn->setComdat(C);
Rafael Espindoladbee8a72015-01-15 21:36:08 +00003579 } else {
3580 CGM.maybeSetTrivialComdat(*MD, *Fn);
Rafael Espindola91f68b42014-09-15 19:20:10 +00003581 }
Rafael Espindola91f68b42014-09-15 19:20:10 +00003582}
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003583
3584static llvm::Constant *getBeginCatchFn(CodeGenModule &CGM) {
3585 // void *__cxa_begin_catch(void*);
3586 llvm::FunctionType *FTy = llvm::FunctionType::get(
3587 CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3588
3589 return CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
3590}
3591
3592static llvm::Constant *getEndCatchFn(CodeGenModule &CGM) {
3593 // void __cxa_end_catch();
3594 llvm::FunctionType *FTy =
3595 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
3596
3597 return CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
3598}
3599
3600static llvm::Constant *getGetExceptionPtrFn(CodeGenModule &CGM) {
3601 // void *__cxa_get_exception_ptr(void*);
3602 llvm::FunctionType *FTy = llvm::FunctionType::get(
3603 CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3604
3605 return CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
3606}
3607
3608namespace {
3609 /// A cleanup to call __cxa_end_catch. In many cases, the caught
3610 /// exception type lets us state definitively that the thrown exception
3611 /// type does not have a destructor. In particular:
3612 /// - Catch-alls tell us nothing, so we have to conservatively
3613 /// assume that the thrown exception might have a destructor.
3614 /// - Catches by reference behave according to their base types.
3615 /// - Catches of non-record types will only trigger for exceptions
3616 /// of non-record types, which never have destructors.
3617 /// - Catches of record types can trigger for arbitrary subclasses
3618 /// of the caught type, so we have to assume the actual thrown
3619 /// exception type might have a throwing destructor, even if the
3620 /// caught type's destructor is trivial or nothrow.
David Blaikie7e70d682015-08-18 22:40:54 +00003621 struct CallEndCatch final : EHScopeStack::Cleanup {
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003622 CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
3623 bool MightThrow;
3624
3625 void Emit(CodeGenFunction &CGF, Flags flags) override {
3626 if (!MightThrow) {
3627 CGF.EmitNounwindRuntimeCall(getEndCatchFn(CGF.CGM));
3628 return;
3629 }
3630
3631 CGF.EmitRuntimeCallOrInvoke(getEndCatchFn(CGF.CGM));
3632 }
3633 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003634}
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003635
3636/// Emits a call to __cxa_begin_catch and enters a cleanup to call
3637/// __cxa_end_catch.
3638///
3639/// \param EndMightThrow - true if __cxa_end_catch might throw
3640static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
3641 llvm::Value *Exn,
3642 bool EndMightThrow) {
3643 llvm::CallInst *call =
3644 CGF.EmitNounwindRuntimeCall(getBeginCatchFn(CGF.CGM), Exn);
3645
3646 CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
3647
3648 return call;
3649}
3650
3651/// A "special initializer" callback for initializing a catch
3652/// parameter during catch initialization.
3653static void InitCatchParam(CodeGenFunction &CGF,
3654 const VarDecl &CatchParam,
John McCall7f416cc2015-09-08 08:05:57 +00003655 Address ParamAddr,
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003656 SourceLocation Loc) {
3657 // Load the exception from where the landing pad saved it.
3658 llvm::Value *Exn = CGF.getExceptionFromSlot();
3659
3660 CanQualType CatchType =
3661 CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
3662 llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
3663
3664 // If we're catching by reference, we can just cast the object
3665 // pointer to the appropriate pointer.
3666 if (isa<ReferenceType>(CatchType)) {
3667 QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
3668 bool EndCatchMightThrow = CaughtType->isRecordType();
3669
3670 // __cxa_begin_catch returns the adjusted object pointer.
3671 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
3672
3673 // We have no way to tell the personality function that we're
3674 // catching by reference, so if we're catching a pointer,
3675 // __cxa_begin_catch will actually return that pointer by value.
3676 if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
3677 QualType PointeeType = PT->getPointeeType();
3678
3679 // When catching by reference, generally we should just ignore
3680 // this by-value pointer and use the exception object instead.
3681 if (!PointeeType->isRecordType()) {
3682
3683 // Exn points to the struct _Unwind_Exception header, which
3684 // we have to skip past in order to reach the exception data.
3685 unsigned HeaderSize =
3686 CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
3687 AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
3688
3689 // However, if we're catching a pointer-to-record type that won't
3690 // work, because the personality function might have adjusted
3691 // the pointer. There's actually no way for us to fully satisfy
3692 // the language/ABI contract here: we can't use Exn because it
3693 // might have the wrong adjustment, but we can't use the by-value
3694 // pointer because it's off by a level of abstraction.
3695 //
3696 // The current solution is to dump the adjusted pointer into an
3697 // alloca, which breaks language semantics (because changing the
3698 // pointer doesn't change the exception) but at least works.
3699 // The better solution would be to filter out non-exact matches
3700 // and rethrow them, but this is tricky because the rethrow
3701 // really needs to be catchable by other sites at this landing
3702 // pad. The best solution is to fix the personality function.
3703 } else {
3704 // Pull the pointer for the reference type off.
3705 llvm::Type *PtrTy =
3706 cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
3707
3708 // Create the temporary and write the adjusted pointer into it.
John McCall7f416cc2015-09-08 08:05:57 +00003709 Address ExnPtrTmp =
3710 CGF.CreateTempAlloca(PtrTy, CGF.getPointerAlign(), "exn.byref.tmp");
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003711 llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
3712 CGF.Builder.CreateStore(Casted, ExnPtrTmp);
3713
3714 // Bind the reference to the temporary.
John McCall7f416cc2015-09-08 08:05:57 +00003715 AdjustedExn = ExnPtrTmp.getPointer();
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003716 }
3717 }
3718
3719 llvm::Value *ExnCast =
3720 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
3721 CGF.Builder.CreateStore(ExnCast, ParamAddr);
3722 return;
3723 }
3724
3725 // Scalars and complexes.
3726 TypeEvaluationKind TEK = CGF.getEvaluationKind(CatchType);
3727 if (TEK != TEK_Aggregate) {
3728 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
3729
3730 // If the catch type is a pointer type, __cxa_begin_catch returns
3731 // the pointer by value.
3732 if (CatchType->hasPointerRepresentation()) {
3733 llvm::Value *CastExn =
3734 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
3735
3736 switch (CatchType.getQualifiers().getObjCLifetime()) {
3737 case Qualifiers::OCL_Strong:
3738 CastExn = CGF.EmitARCRetainNonBlock(CastExn);
3739 // fallthrough
3740
3741 case Qualifiers::OCL_None:
3742 case Qualifiers::OCL_ExplicitNone:
3743 case Qualifiers::OCL_Autoreleasing:
3744 CGF.Builder.CreateStore(CastExn, ParamAddr);
3745 return;
3746
3747 case Qualifiers::OCL_Weak:
3748 CGF.EmitARCInitWeak(ParamAddr, CastExn);
3749 return;
3750 }
3751 llvm_unreachable("bad ownership qualifier!");
3752 }
3753
3754 // Otherwise, it returns a pointer into the exception object.
3755
3756 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
3757 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
3758
3759 LValue srcLV = CGF.MakeNaturalAlignAddrLValue(Cast, CatchType);
John McCall7f416cc2015-09-08 08:05:57 +00003760 LValue destLV = CGF.MakeAddrLValue(ParamAddr, CatchType);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003761 switch (TEK) {
3762 case TEK_Complex:
3763 CGF.EmitStoreOfComplex(CGF.EmitLoadOfComplex(srcLV, Loc), destLV,
3764 /*init*/ true);
3765 return;
3766 case TEK_Scalar: {
3767 llvm::Value *ExnLoad = CGF.EmitLoadOfScalar(srcLV, Loc);
3768 CGF.EmitStoreOfScalar(ExnLoad, destLV, /*init*/ true);
3769 return;
3770 }
3771 case TEK_Aggregate:
3772 llvm_unreachable("evaluation kind filtered out!");
3773 }
3774 llvm_unreachable("bad evaluation kind");
3775 }
3776
3777 assert(isa<RecordType>(CatchType) && "unexpected catch type!");
John McCall7f416cc2015-09-08 08:05:57 +00003778 auto catchRD = CatchType->getAsCXXRecordDecl();
3779 CharUnits caughtExnAlignment = CGF.CGM.getClassPointerAlignment(catchRD);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003780
3781 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
3782
3783 // Check for a copy expression. If we don't have a copy expression,
3784 // that means a trivial copy is okay.
3785 const Expr *copyExpr = CatchParam.getInit();
3786 if (!copyExpr) {
3787 llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true);
John McCall7f416cc2015-09-08 08:05:57 +00003788 Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy),
3789 caughtExnAlignment);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003790 CGF.EmitAggregateCopy(ParamAddr, adjustedExn, CatchType);
3791 return;
3792 }
3793
3794 // We have to call __cxa_get_exception_ptr to get the adjusted
3795 // pointer before copying.
3796 llvm::CallInst *rawAdjustedExn =
3797 CGF.EmitNounwindRuntimeCall(getGetExceptionPtrFn(CGF.CGM), Exn);
3798
3799 // Cast that to the appropriate type.
John McCall7f416cc2015-09-08 08:05:57 +00003800 Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy),
3801 caughtExnAlignment);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003802
3803 // The copy expression is defined in terms of an OpaqueValueExpr.
3804 // Find it and map it to the adjusted expression.
3805 CodeGenFunction::OpaqueValueMapping
3806 opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr),
3807 CGF.MakeAddrLValue(adjustedExn, CatchParam.getType()));
3808
3809 // Call the copy ctor in a terminate scope.
3810 CGF.EHStack.pushTerminate();
3811
3812 // Perform the copy construction.
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003813 CGF.EmitAggExpr(copyExpr,
John McCall7f416cc2015-09-08 08:05:57 +00003814 AggValueSlot::forAddr(ParamAddr, Qualifiers(),
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003815 AggValueSlot::IsNotDestructed,
3816 AggValueSlot::DoesNotNeedGCBarriers,
3817 AggValueSlot::IsNotAliased));
3818
3819 // Leave the terminate scope.
3820 CGF.EHStack.popTerminate();
3821
3822 // Undo the opaque value mapping.
3823 opaque.pop();
3824
3825 // Finally we can call __cxa_begin_catch.
3826 CallBeginCatch(CGF, Exn, true);
3827}
3828
3829/// Begins a catch statement by initializing the catch variable and
3830/// calling __cxa_begin_catch.
3831void ItaniumCXXABI::emitBeginCatch(CodeGenFunction &CGF,
3832 const CXXCatchStmt *S) {
3833 // We have to be very careful with the ordering of cleanups here:
3834 // C++ [except.throw]p4:
3835 // The destruction [of the exception temporary] occurs
3836 // immediately after the destruction of the object declared in
3837 // the exception-declaration in the handler.
3838 //
3839 // So the precise ordering is:
3840 // 1. Construct catch variable.
3841 // 2. __cxa_begin_catch
3842 // 3. Enter __cxa_end_catch cleanup
3843 // 4. Enter dtor cleanup
3844 //
3845 // We do this by using a slightly abnormal initialization process.
3846 // Delegation sequence:
3847 // - ExitCXXTryStmt opens a RunCleanupsScope
3848 // - EmitAutoVarAlloca creates the variable and debug info
3849 // - InitCatchParam initializes the variable from the exception
3850 // - CallBeginCatch calls __cxa_begin_catch
3851 // - CallBeginCatch enters the __cxa_end_catch cleanup
3852 // - EmitAutoVarCleanups enters the variable destructor cleanup
3853 // - EmitCXXTryStmt emits the code for the catch body
3854 // - EmitCXXTryStmt close the RunCleanupsScope
3855
3856 VarDecl *CatchParam = S->getExceptionDecl();
3857 if (!CatchParam) {
3858 llvm::Value *Exn = CGF.getExceptionFromSlot();
3859 CallBeginCatch(CGF, Exn, true);
3860 return;
3861 }
3862
3863 // Emit the local.
3864 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
3865 InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF), S->getLocStart());
3866 CGF.EmitAutoVarCleanups(var);
3867}
3868
3869/// Get or define the following function:
3870/// void @__clang_call_terminate(i8* %exn) nounwind noreturn
3871/// This code is used only in C++.
3872static llvm::Constant *getClangCallTerminateFn(CodeGenModule &CGM) {
3873 llvm::FunctionType *fnTy =
3874 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3875 llvm::Constant *fnRef =
3876 CGM.CreateRuntimeFunction(fnTy, "__clang_call_terminate");
3877
3878 llvm::Function *fn = dyn_cast<llvm::Function>(fnRef);
3879 if (fn && fn->empty()) {
3880 fn->setDoesNotThrow();
3881 fn->setDoesNotReturn();
3882
3883 // What we really want is to massively penalize inlining without
3884 // forbidding it completely. The difference between that and
3885 // 'noinline' is negligible.
3886 fn->addFnAttr(llvm::Attribute::NoInline);
3887
3888 // Allow this function to be shared across translation units, but
3889 // we don't want it to turn into an exported symbol.
3890 fn->setLinkage(llvm::Function::LinkOnceODRLinkage);
3891 fn->setVisibility(llvm::Function::HiddenVisibility);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00003892 if (CGM.supportsCOMDAT())
3893 fn->setComdat(CGM.getModule().getOrInsertComdat(fn->getName()));
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003894
3895 // Set up the function.
3896 llvm::BasicBlock *entry =
3897 llvm::BasicBlock::Create(CGM.getLLVMContext(), "", fn);
John McCall7f416cc2015-09-08 08:05:57 +00003898 CGBuilderTy builder(CGM, entry);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003899
3900 // Pull the exception pointer out of the parameter list.
3901 llvm::Value *exn = &*fn->arg_begin();
3902
3903 // Call __cxa_begin_catch(exn).
3904 llvm::CallInst *catchCall = builder.CreateCall(getBeginCatchFn(CGM), exn);
3905 catchCall->setDoesNotThrow();
3906 catchCall->setCallingConv(CGM.getRuntimeCC());
3907
3908 // Call std::terminate().
David Blaikie4ba525b2015-07-14 17:27:39 +00003909 llvm::CallInst *termCall = builder.CreateCall(CGM.getTerminateFn());
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003910 termCall->setDoesNotThrow();
3911 termCall->setDoesNotReturn();
3912 termCall->setCallingConv(CGM.getRuntimeCC());
3913
3914 // std::terminate cannot return.
3915 builder.CreateUnreachable();
3916 }
3917
3918 return fnRef;
3919}
3920
3921llvm::CallInst *
3922ItaniumCXXABI::emitTerminateForUnexpectedException(CodeGenFunction &CGF,
3923 llvm::Value *Exn) {
3924 // In C++, we want to call __cxa_begin_catch() before terminating.
3925 if (Exn) {
3926 assert(CGF.CGM.getLangOpts().CPlusPlus);
3927 return CGF.EmitNounwindRuntimeCall(getClangCallTerminateFn(CGF.CGM), Exn);
3928 }
3929 return CGF.EmitNounwindRuntimeCall(CGF.CGM.getTerminateFn());
3930}