blob: 24d187f2330d85482cb24e7411b2155099d1e27b [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
Craig Topper4f12f102014-03-12 06:41:41 +0000117 llvm::Value *
118 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
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000266 llvm::Value *getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
John McCall7f416cc2015-09-08 08:05:57 +0000267 Address This, llvm::Type *Ty,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +0000268 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.
David Majnemer2b0d66d2014-02-20 23:22:07 +0000523llvm::Value *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);
Jay Foad20c0f022011-03-30 11:28:58 +0000612 llvm::PHINode *Callee = Builder.CreatePHI(FTy->getPointerTo(), 2);
John McCall475999d2010-08-22 00:05:51 +0000613 Callee->addIncoming(VirtualFn, FnVirtual);
614 Callee->addIncoming(NonVirtualFn, FnNonVirtual);
615 return Callee;
616}
John McCalla8bbb822010-08-22 03:04:22 +0000617
John McCallc134eb52010-08-31 21:07:20 +0000618/// Compute an l-value by applying the given pointer-to-member to a
619/// base object.
David Majnemer2b0d66d2014-02-20 23:22:07 +0000620llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(
John McCall7f416cc2015-09-08 08:05:57 +0000621 CodeGenFunction &CGF, const Expr *E, Address Base, llvm::Value *MemPtr,
David Majnemer2b0d66d2014-02-20 23:22:07 +0000622 const MemberPointerType *MPT) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000623 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCallc134eb52010-08-31 21:07:20 +0000624
625 CGBuilderTy &Builder = CGF.Builder;
626
John McCallc134eb52010-08-31 21:07:20 +0000627 // Cast to char*.
John McCall7f416cc2015-09-08 08:05:57 +0000628 Base = Builder.CreateElementBitCast(Base, CGF.Int8Ty);
John McCallc134eb52010-08-31 21:07:20 +0000629
630 // Apply the offset, which we assume is non-null.
John McCall7f416cc2015-09-08 08:05:57 +0000631 llvm::Value *Addr =
632 Builder.CreateInBoundsGEP(Base.getPointer(), MemPtr, "memptr.offset");
John McCallc134eb52010-08-31 21:07:20 +0000633
634 // Cast the address to the appropriate pointer type, adopting the
635 // address space of the base pointer.
John McCall7f416cc2015-09-08 08:05:57 +0000636 llvm::Type *PType = CGF.ConvertTypeForMem(MPT->getPointeeType())
637 ->getPointerTo(Base.getAddressSpace());
John McCallc134eb52010-08-31 21:07:20 +0000638 return Builder.CreateBitCast(Addr, PType);
639}
640
John McCallc62bb392012-02-15 01:22:51 +0000641/// Perform a bitcast, derived-to-base, or base-to-derived member pointer
642/// conversion.
643///
644/// Bitcast conversions are always a no-op under Itanium.
John McCall7a9aac22010-08-23 01:21:21 +0000645///
646/// Obligatory offset/adjustment diagram:
647/// <-- offset --> <-- adjustment -->
648/// |--------------------------|----------------------|--------------------|
649/// ^Derived address point ^Base address point ^Member address point
650///
651/// So when converting a base member pointer to a derived member pointer,
652/// we add the offset to the adjustment because the address point has
653/// decreased; and conversely, when converting a derived MP to a base MP
654/// we subtract the offset from the adjustment because the address point
655/// has increased.
656///
657/// The standard forbids (at compile time) conversion to and from
658/// virtual bases, which is why we don't have to consider them here.
659///
660/// The standard forbids (at run time) casting a derived MP to a base
661/// MP when the derived MP does not point to a member of the base.
662/// This is why -1 is a reasonable choice for null data member
663/// pointers.
John McCalla1dee5302010-08-22 10:59:02 +0000664llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000665ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
666 const CastExpr *E,
John McCallc62bb392012-02-15 01:22:51 +0000667 llvm::Value *src) {
John McCalle3027922010-08-25 11:45:40 +0000668 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
John McCallc62bb392012-02-15 01:22:51 +0000669 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
670 E->getCastKind() == CK_ReinterpretMemberPointer);
671
672 // Under Itanium, reinterprets don't require any additional processing.
673 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
674
675 // Use constant emission if we can.
676 if (isa<llvm::Constant>(src))
677 return EmitMemberPointerConversion(E, cast<llvm::Constant>(src));
678
679 llvm::Constant *adj = getMemberPointerAdjustment(E);
680 if (!adj) return src;
John McCalla8bbb822010-08-22 03:04:22 +0000681
682 CGBuilderTy &Builder = CGF.Builder;
John McCallc62bb392012-02-15 01:22:51 +0000683 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
John McCalla8bbb822010-08-22 03:04:22 +0000684
John McCallc62bb392012-02-15 01:22:51 +0000685 const MemberPointerType *destTy =
686 E->getType()->castAs<MemberPointerType>();
John McCall1c456c82010-08-22 06:43:33 +0000687
John McCall7a9aac22010-08-23 01:21:21 +0000688 // For member data pointers, this is just a matter of adding the
689 // offset if the source is non-null.
John McCallc62bb392012-02-15 01:22:51 +0000690 if (destTy->isMemberDataPointer()) {
691 llvm::Value *dst;
692 if (isDerivedToBase)
693 dst = Builder.CreateNSWSub(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000694 else
John McCallc62bb392012-02-15 01:22:51 +0000695 dst = Builder.CreateNSWAdd(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000696
697 // Null check.
John McCallc62bb392012-02-15 01:22:51 +0000698 llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType());
699 llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull");
700 return Builder.CreateSelect(isNull, src, dst);
John McCall7a9aac22010-08-23 01:21:21 +0000701 }
702
John McCalla1dee5302010-08-22 10:59:02 +0000703 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000704 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000705 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
706 offset <<= 1;
707 adj = llvm::ConstantInt::get(adj->getType(), offset);
John McCalla1dee5302010-08-22 10:59:02 +0000708 }
709
John McCallc62bb392012-02-15 01:22:51 +0000710 llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj");
711 llvm::Value *dstAdj;
712 if (isDerivedToBase)
713 dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000714 else
John McCallc62bb392012-02-15 01:22:51 +0000715 dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000716
John McCallc62bb392012-02-15 01:22:51 +0000717 return Builder.CreateInsertValue(src, dstAdj, 1);
718}
719
720llvm::Constant *
721ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E,
722 llvm::Constant *src) {
723 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
724 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
725 E->getCastKind() == CK_ReinterpretMemberPointer);
726
727 // Under Itanium, reinterprets don't require any additional processing.
728 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
729
730 // If the adjustment is trivial, we don't need to do anything.
731 llvm::Constant *adj = getMemberPointerAdjustment(E);
732 if (!adj) return src;
733
734 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
735
736 const MemberPointerType *destTy =
737 E->getType()->castAs<MemberPointerType>();
738
739 // For member data pointers, this is just a matter of adding the
740 // offset if the source is non-null.
741 if (destTy->isMemberDataPointer()) {
742 // null maps to null.
743 if (src->isAllOnesValue()) return src;
744
745 if (isDerivedToBase)
746 return llvm::ConstantExpr::getNSWSub(src, adj);
747 else
748 return llvm::ConstantExpr::getNSWAdd(src, adj);
749 }
750
751 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000752 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000753 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
754 offset <<= 1;
755 adj = llvm::ConstantInt::get(adj->getType(), offset);
756 }
757
758 llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1);
759 llvm::Constant *dstAdj;
760 if (isDerivedToBase)
761 dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj);
762 else
763 dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj);
764
765 return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1);
John McCalla8bbb822010-08-22 03:04:22 +0000766}
John McCall84fa5102010-08-22 04:16:24 +0000767
768llvm::Constant *
John McCall7a9aac22010-08-23 01:21:21 +0000769ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
John McCall7a9aac22010-08-23 01:21:21 +0000770 // Itanium C++ ABI 2.3:
771 // A NULL pointer is represented as -1.
772 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000773 return llvm::ConstantInt::get(CGM.PtrDiffTy, -1ULL, /*isSigned=*/true);
John McCalla1dee5302010-08-22 10:59:02 +0000774
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000775 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.PtrDiffTy, 0);
John McCalla1dee5302010-08-22 10:59:02 +0000776 llvm::Constant *Values[2] = { Zero, Zero };
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000777 return llvm::ConstantStruct::getAnon(Values);
John McCall84fa5102010-08-22 04:16:24 +0000778}
779
John McCallf3a88602011-02-03 08:15:49 +0000780llvm::Constant *
781ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
782 CharUnits offset) {
John McCall7a9aac22010-08-23 01:21:21 +0000783 // Itanium C++ ABI 2.3:
784 // A pointer to data member is an offset from the base address of
785 // the class object containing it, represented as a ptrdiff_t
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000786 return llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity());
John McCall7a9aac22010-08-23 01:21:21 +0000787}
788
David Majnemere2be95b2015-06-23 07:31:01 +0000789llvm::Constant *
790ItaniumCXXABI::EmitMemberFunctionPointer(const CXXMethodDecl *MD) {
Richard Smithdafff942012-01-14 04:30:29 +0000791 return BuildMemberPointer(MD, CharUnits::Zero());
792}
793
794llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD,
795 CharUnits ThisAdjustment) {
John McCalla1dee5302010-08-22 10:59:02 +0000796 assert(MD->isInstance() && "Member function must not be static!");
797 MD = MD->getCanonicalDecl();
798
799 CodeGenTypes &Types = CGM.getTypes();
John McCalla1dee5302010-08-22 10:59:02 +0000800
801 // Get the function pointer (or index if this is a virtual function).
802 llvm::Constant *MemPtr[2];
803 if (MD->isVirtual()) {
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000804 uint64_t Index = CGM.getItaniumVTableContext().getMethodVTableIndex(MD);
John McCalla1dee5302010-08-22 10:59:02 +0000805
Ken Dyckdf016282011-04-09 01:30:02 +0000806 const ASTContext &Context = getContext();
807 CharUnits PointerWidth =
Douglas Gregore8bbc122011-09-02 00:18:52 +0000808 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Ken Dyckdf016282011-04-09 01:30:02 +0000809 uint64_t VTableOffset = (Index * PointerWidth.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000810
Mark Seabornedf0d382013-07-24 16:25:13 +0000811 if (UseARMMethodPtrABI) {
John McCalla1dee5302010-08-22 10:59:02 +0000812 // ARM C++ ABI 3.2.1:
813 // This ABI specifies that adj contains twice the this
814 // adjustment, plus 1 if the member function is virtual. The
815 // least significant bit of adj then makes exactly the same
816 // discrimination as the least significant bit of ptr does for
817 // Itanium.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000818 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset);
819 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000820 2 * ThisAdjustment.getQuantity() + 1);
John McCalla1dee5302010-08-22 10:59:02 +0000821 } else {
822 // Itanium C++ ABI 2.3:
823 // For a virtual function, [the pointer field] is 1 plus the
824 // virtual table offset (in bytes) of the function,
825 // represented as a ptrdiff_t.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000826 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset + 1);
827 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000828 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000829 }
830 } else {
John McCall2979fe02011-04-12 00:42:48 +0000831 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
Chris Lattner2192fe52011-07-18 04:24:23 +0000832 llvm::Type *Ty;
John McCall2979fe02011-04-12 00:42:48 +0000833 // Check whether the function has a computable LLVM signature.
Chris Lattner8806e322011-07-10 00:18:59 +0000834 if (Types.isFuncTypeConvertible(FPT)) {
John McCall2979fe02011-04-12 00:42:48 +0000835 // The function has a computable LLVM signature; use the correct type.
John McCalla729c622012-02-17 03:33:10 +0000836 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
John McCalla1dee5302010-08-22 10:59:02 +0000837 } else {
John McCall2979fe02011-04-12 00:42:48 +0000838 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
839 // function type is incomplete.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000840 Ty = CGM.PtrDiffTy;
John McCalla1dee5302010-08-22 10:59:02 +0000841 }
John McCall2979fe02011-04-12 00:42:48 +0000842 llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty);
John McCalla1dee5302010-08-22 10:59:02 +0000843
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000844 MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, CGM.PtrDiffTy);
Mark Seabornedf0d382013-07-24 16:25:13 +0000845 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
846 (UseARMMethodPtrABI ? 2 : 1) *
Richard Smithdafff942012-01-14 04:30:29 +0000847 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000848 }
John McCall1c456c82010-08-22 06:43:33 +0000849
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000850 return llvm::ConstantStruct::getAnon(MemPtr);
John McCall1c456c82010-08-22 06:43:33 +0000851}
852
Richard Smithdafff942012-01-14 04:30:29 +0000853llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP,
854 QualType MPType) {
855 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
856 const ValueDecl *MPD = MP.getMemberPointerDecl();
857 if (!MPD)
858 return EmitNullMemberPointer(MPT);
859
Reid Kleckner452abac2013-05-09 21:01:17 +0000860 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
Richard Smithdafff942012-01-14 04:30:29 +0000861
862 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
863 return BuildMemberPointer(MD, ThisAdjustment);
864
865 CharUnits FieldOffset =
866 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
867 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
868}
869
John McCall131d97d2010-08-22 08:30:07 +0000870/// The comparison algorithm is pretty easy: the member pointers are
871/// the same if they're either bitwise identical *or* both null.
872///
873/// ARM is different here only because null-ness is more complicated.
874llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000875ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
876 llvm::Value *L,
877 llvm::Value *R,
878 const MemberPointerType *MPT,
879 bool Inequality) {
John McCall131d97d2010-08-22 08:30:07 +0000880 CGBuilderTy &Builder = CGF.Builder;
881
John McCall131d97d2010-08-22 08:30:07 +0000882 llvm::ICmpInst::Predicate Eq;
883 llvm::Instruction::BinaryOps And, Or;
884 if (Inequality) {
885 Eq = llvm::ICmpInst::ICMP_NE;
886 And = llvm::Instruction::Or;
887 Or = llvm::Instruction::And;
888 } else {
889 Eq = llvm::ICmpInst::ICMP_EQ;
890 And = llvm::Instruction::And;
891 Or = llvm::Instruction::Or;
892 }
893
John McCall7a9aac22010-08-23 01:21:21 +0000894 // Member data pointers are easy because there's a unique null
895 // value, so it just comes down to bitwise equality.
896 if (MPT->isMemberDataPointer())
897 return Builder.CreateICmp(Eq, L, R);
898
899 // For member function pointers, the tautologies are more complex.
900 // The Itanium tautology is:
John McCall61a14882010-08-23 06:56:36 +0000901 // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
John McCall7a9aac22010-08-23 01:21:21 +0000902 // The ARM tautology is:
John McCall61a14882010-08-23 06:56:36 +0000903 // (L == R) <==> (L.ptr == R.ptr &&
904 // (L.adj == R.adj ||
905 // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
John McCall7a9aac22010-08-23 01:21:21 +0000906 // The inequality tautologies have exactly the same structure, except
907 // applying De Morgan's laws.
908
909 llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
910 llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
911
John McCall131d97d2010-08-22 08:30:07 +0000912 // This condition tests whether L.ptr == R.ptr. This must always be
913 // true for equality to hold.
914 llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
915
916 // This condition, together with the assumption that L.ptr == R.ptr,
917 // tests whether the pointers are both null. ARM imposes an extra
918 // condition.
919 llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
920 llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
921
922 // This condition tests whether L.adj == R.adj. If this isn't
923 // true, the pointers are unequal unless they're both null.
John McCalla1dee5302010-08-22 10:59:02 +0000924 llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
925 llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000926 llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
927
928 // Null member function pointers on ARM clear the low bit of Adj,
929 // so the zero condition has to check that neither low bit is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000930 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000931 llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
932
933 // Compute (l.adj | r.adj) & 1 and test it against zero.
934 llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
935 llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
936 llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
937 "cmp.or.adj");
938 EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
939 }
940
941 // Tie together all our conditions.
942 llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
943 Result = Builder.CreateBinOp(And, PtrEq, Result,
944 Inequality ? "memptr.ne" : "memptr.eq");
945 return Result;
946}
947
948llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000949ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
950 llvm::Value *MemPtr,
951 const MemberPointerType *MPT) {
John McCall131d97d2010-08-22 08:30:07 +0000952 CGBuilderTy &Builder = CGF.Builder;
John McCall7a9aac22010-08-23 01:21:21 +0000953
954 /// For member data pointers, this is just a check against -1.
955 if (MPT->isMemberDataPointer()) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000956 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCall7a9aac22010-08-23 01:21:21 +0000957 llvm::Value *NegativeOne =
958 llvm::Constant::getAllOnesValue(MemPtr->getType());
959 return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
960 }
John McCall131d97d2010-08-22 08:30:07 +0000961
Daniel Dunbar914bc412011-04-19 23:10:47 +0000962 // In Itanium, a member function pointer is not null if 'ptr' is not null.
John McCalla1dee5302010-08-22 10:59:02 +0000963 llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
John McCall131d97d2010-08-22 08:30:07 +0000964
965 llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
966 llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
967
Daniel Dunbar914bc412011-04-19 23:10:47 +0000968 // On ARM, a member function pointer is also non-null if the low bit of 'adj'
969 // (the virtual bit) is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000970 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000971 llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
John McCalla1dee5302010-08-22 10:59:02 +0000972 llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000973 llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
Daniel Dunbar914bc412011-04-19 23:10:47 +0000974 llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero,
975 "memptr.isvirtual");
976 Result = Builder.CreateOr(Result, IsVirtual);
John McCall131d97d2010-08-22 08:30:07 +0000977 }
978
979 return Result;
980}
John McCall1c456c82010-08-22 06:43:33 +0000981
Reid Kleckner40ca9132014-05-13 22:05:45 +0000982bool ItaniumCXXABI::classifyReturnType(CGFunctionInfo &FI) const {
983 const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl();
984 if (!RD)
985 return false;
986
Reid Klecknerd355ca72014-05-15 01:26:32 +0000987 // Return indirectly if we have a non-trivial copy ctor or non-trivial dtor.
988 // FIXME: Use canCopyArgument() when it is fixed to handle lazily declared
989 // special members.
990 if (RD->hasNonTrivialDestructor() || RD->hasNonTrivialCopyConstructor()) {
John McCall7f416cc2015-09-08 08:05:57 +0000991 auto Align = CGM.getContext().getTypeAlignInChars(FI.getReturnType());
992 FI.getReturnInfo() = ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
Reid Kleckner40ca9132014-05-13 22:05:45 +0000993 return true;
994 }
Reid Kleckner40ca9132014-05-13 22:05:45 +0000995 return false;
996}
997
John McCall614dbdc2010-08-22 21:01:12 +0000998/// The Itanium ABI requires non-zero initialization only for data
999/// member pointers, for which '0' is a valid offset.
1000bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
David Majnemer5fd33e02015-04-24 01:25:08 +00001001 return MPT->isMemberFunctionPointer();
John McCall84fa5102010-08-22 04:16:24 +00001002}
John McCall5d865c322010-08-31 07:33:07 +00001003
John McCall82fb8922012-09-25 10:10:39 +00001004/// The Itanium ABI always places an offset to the complete object
1005/// at entry -2 in the vtable.
David Majnemer08681372014-11-01 07:37:17 +00001006void ItaniumCXXABI::emitVirtualObjectDelete(CodeGenFunction &CGF,
1007 const CXXDeleteExpr *DE,
John McCall7f416cc2015-09-08 08:05:57 +00001008 Address Ptr,
David Majnemer08681372014-11-01 07:37:17 +00001009 QualType ElementType,
1010 const CXXDestructorDecl *Dtor) {
1011 bool UseGlobalDelete = DE->isGlobalDelete();
David Majnemer0c0b6d92014-10-31 20:09:12 +00001012 if (UseGlobalDelete) {
1013 // Derive the complete-object pointer, which is what we need
1014 // to pass to the deallocation function.
John McCall82fb8922012-09-25 10:10:39 +00001015
David Majnemer0c0b6d92014-10-31 20:09:12 +00001016 // Grab the vtable pointer as an intptr_t*.
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001017 auto *ClassDecl =
1018 cast<CXXRecordDecl>(ElementType->getAs<RecordType>()->getDecl());
1019 llvm::Value *VTable =
1020 CGF.GetVTablePtr(Ptr, CGF.IntPtrTy->getPointerTo(), ClassDecl);
John McCall82fb8922012-09-25 10:10:39 +00001021
David Majnemer0c0b6d92014-10-31 20:09:12 +00001022 // Track back to entry -2 and pull out the offset there.
1023 llvm::Value *OffsetPtr = CGF.Builder.CreateConstInBoundsGEP1_64(
1024 VTable, -2, "complete-offset.ptr");
John McCall7f416cc2015-09-08 08:05:57 +00001025 llvm::Value *Offset =
1026 CGF.Builder.CreateAlignedLoad(OffsetPtr, CGF.getPointerAlign());
David Majnemer0c0b6d92014-10-31 20:09:12 +00001027
1028 // Apply the offset.
John McCall7f416cc2015-09-08 08:05:57 +00001029 llvm::Value *CompletePtr =
1030 CGF.Builder.CreateBitCast(Ptr.getPointer(), CGF.Int8PtrTy);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001031 CompletePtr = CGF.Builder.CreateInBoundsGEP(CompletePtr, Offset);
1032
1033 // If we're supposed to call the global delete, make sure we do so
1034 // even if the destructor throws.
David Majnemer08681372014-11-01 07:37:17 +00001035 CGF.pushCallObjectDeleteCleanup(DE->getOperatorDelete(), CompletePtr,
1036 ElementType);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001037 }
1038
1039 // FIXME: Provide a source location here even though there's no
1040 // CXXMemberCallExpr for dtor call.
1041 CXXDtorType DtorType = UseGlobalDelete ? Dtor_Complete : Dtor_Deleting;
1042 EmitVirtualDestructorCall(CGF, Dtor, DtorType, Ptr, /*CE=*/nullptr);
1043
1044 if (UseGlobalDelete)
1045 CGF.PopCleanupBlock();
John McCall82fb8922012-09-25 10:10:39 +00001046}
1047
David Majnemer442d0a22014-11-25 07:20:20 +00001048void ItaniumCXXABI::emitRethrow(CodeGenFunction &CGF, bool isNoReturn) {
1049 // void __cxa_rethrow();
1050
1051 llvm::FunctionType *FTy =
1052 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
1053
1054 llvm::Constant *Fn = CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow");
1055
1056 if (isNoReturn)
1057 CGF.EmitNoreturnRuntimeCallOrInvoke(Fn, None);
1058 else
1059 CGF.EmitRuntimeCallOrInvoke(Fn);
1060}
1061
David Majnemer7c237072015-03-05 00:46:22 +00001062static llvm::Constant *getAllocateExceptionFn(CodeGenModule &CGM) {
1063 // void *__cxa_allocate_exception(size_t thrown_size);
1064
1065 llvm::FunctionType *FTy =
1066 llvm::FunctionType::get(CGM.Int8PtrTy, CGM.SizeTy, /*IsVarArgs=*/false);
1067
1068 return CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
1069}
1070
1071static llvm::Constant *getThrowFn(CodeGenModule &CGM) {
1072 // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
1073 // void (*dest) (void *));
1074
1075 llvm::Type *Args[3] = { CGM.Int8PtrTy, CGM.Int8PtrTy, CGM.Int8PtrTy };
1076 llvm::FunctionType *FTy =
1077 llvm::FunctionType::get(CGM.VoidTy, Args, /*IsVarArgs=*/false);
1078
1079 return CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
1080}
1081
1082void ItaniumCXXABI::emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) {
1083 QualType ThrowType = E->getSubExpr()->getType();
1084 // Now allocate the exception object.
1085 llvm::Type *SizeTy = CGF.ConvertType(getContext().getSizeType());
1086 uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
1087
1088 llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(CGM);
1089 llvm::CallInst *ExceptionPtr = CGF.EmitNounwindRuntimeCall(
1090 AllocExceptionFn, llvm::ConstantInt::get(SizeTy, TypeSize), "exception");
1091
John McCall7f416cc2015-09-08 08:05:57 +00001092 CharUnits ExnAlign = getAlignmentOfExnObject();
1093 CGF.EmitAnyExprToExn(E->getSubExpr(), Address(ExceptionPtr, ExnAlign));
David Majnemer7c237072015-03-05 00:46:22 +00001094
1095 // Now throw the exception.
1096 llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType,
1097 /*ForEH=*/true);
1098
1099 // The address of the destructor. If the exception type has a
1100 // trivial destructor (or isn't a record), we just pass null.
1101 llvm::Constant *Dtor = nullptr;
1102 if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
1103 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
1104 if (!Record->hasTrivialDestructor()) {
1105 CXXDestructorDecl *DtorD = Record->getDestructor();
1106 Dtor = CGM.getAddrOfCXXStructor(DtorD, StructorType::Complete);
1107 Dtor = llvm::ConstantExpr::getBitCast(Dtor, CGM.Int8PtrTy);
1108 }
1109 }
1110 if (!Dtor) Dtor = llvm::Constant::getNullValue(CGM.Int8PtrTy);
1111
1112 llvm::Value *args[] = { ExceptionPtr, TypeInfo, Dtor };
1113 CGF.EmitNoreturnRuntimeCallOrInvoke(getThrowFn(CGM), args);
1114}
1115
David Majnemer1162d252014-06-22 19:05:33 +00001116static llvm::Constant *getItaniumDynamicCastFn(CodeGenFunction &CGF) {
1117 // void *__dynamic_cast(const void *sub,
1118 // const abi::__class_type_info *src,
1119 // const abi::__class_type_info *dst,
1120 // std::ptrdiff_t src2dst_offset);
1121
1122 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
1123 llvm::Type *PtrDiffTy =
1124 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1125
1126 llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
1127
1128 llvm::FunctionType *FTy = llvm::FunctionType::get(Int8PtrTy, Args, false);
1129
1130 // Mark the function as nounwind readonly.
1131 llvm::Attribute::AttrKind FuncAttrs[] = { llvm::Attribute::NoUnwind,
1132 llvm::Attribute::ReadOnly };
1133 llvm::AttributeSet Attrs = llvm::AttributeSet::get(
1134 CGF.getLLVMContext(), llvm::AttributeSet::FunctionIndex, FuncAttrs);
1135
1136 return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast", Attrs);
1137}
1138
1139static llvm::Constant *getBadCastFn(CodeGenFunction &CGF) {
1140 // void __cxa_bad_cast();
1141 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1142 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
1143}
1144
1145/// \brief Compute the src2dst_offset hint as described in the
1146/// Itanium C++ ABI [2.9.7]
1147static CharUnits computeOffsetHint(ASTContext &Context,
1148 const CXXRecordDecl *Src,
1149 const CXXRecordDecl *Dst) {
1150 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1151 /*DetectVirtual=*/false);
1152
1153 // If Dst is not derived from Src we can skip the whole computation below and
1154 // return that Src is not a public base of Dst. Record all inheritance paths.
1155 if (!Dst->isDerivedFrom(Src, Paths))
1156 return CharUnits::fromQuantity(-2ULL);
1157
1158 unsigned NumPublicPaths = 0;
1159 CharUnits Offset;
1160
1161 // Now walk all possible inheritance paths.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001162 for (const CXXBasePath &Path : Paths) {
1163 if (Path.Access != AS_public) // Ignore non-public inheritance.
David Majnemer1162d252014-06-22 19:05:33 +00001164 continue;
1165
1166 ++NumPublicPaths;
1167
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001168 for (const CXXBasePathElement &PathElement : Path) {
David Majnemer1162d252014-06-22 19:05:33 +00001169 // If the path contains a virtual base class we can't give any hint.
1170 // -1: no hint.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001171 if (PathElement.Base->isVirtual())
David Majnemer1162d252014-06-22 19:05:33 +00001172 return CharUnits::fromQuantity(-1ULL);
1173
1174 if (NumPublicPaths > 1) // Won't use offsets, skip computation.
1175 continue;
1176
1177 // Accumulate the base class offsets.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001178 const ASTRecordLayout &L = Context.getASTRecordLayout(PathElement.Class);
1179 Offset += L.getBaseClassOffset(
1180 PathElement.Base->getType()->getAsCXXRecordDecl());
David Majnemer1162d252014-06-22 19:05:33 +00001181 }
1182 }
1183
1184 // -2: Src is not a public base of Dst.
1185 if (NumPublicPaths == 0)
1186 return CharUnits::fromQuantity(-2ULL);
1187
1188 // -3: Src is a multiple public base type but never a virtual base type.
1189 if (NumPublicPaths > 1)
1190 return CharUnits::fromQuantity(-3ULL);
1191
1192 // Otherwise, the Src type is a unique public nonvirtual base type of Dst.
1193 // Return the offset of Src from the origin of Dst.
1194 return Offset;
1195}
1196
1197static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) {
1198 // void __cxa_bad_typeid();
1199 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1200
1201 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
1202}
1203
1204bool ItaniumCXXABI::shouldTypeidBeNullChecked(bool IsDeref,
1205 QualType SrcRecordTy) {
1206 return IsDeref;
1207}
1208
1209void ItaniumCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) {
1210 llvm::Value *Fn = getBadTypeidFn(CGF);
1211 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
1212 CGF.Builder.CreateUnreachable();
1213}
1214
1215llvm::Value *ItaniumCXXABI::EmitTypeid(CodeGenFunction &CGF,
1216 QualType SrcRecordTy,
John McCall7f416cc2015-09-08 08:05:57 +00001217 Address ThisPtr,
David Majnemer1162d252014-06-22 19:05:33 +00001218 llvm::Type *StdTypeInfoPtrTy) {
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001219 auto *ClassDecl =
1220 cast<CXXRecordDecl>(SrcRecordTy->getAs<RecordType>()->getDecl());
David Majnemer1162d252014-06-22 19:05:33 +00001221 llvm::Value *Value =
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001222 CGF.GetVTablePtr(ThisPtr, StdTypeInfoPtrTy->getPointerTo(), ClassDecl);
David Majnemer1162d252014-06-22 19:05:33 +00001223
1224 // Load the type info.
1225 Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL);
John McCall7f416cc2015-09-08 08:05:57 +00001226 return CGF.Builder.CreateAlignedLoad(Value, CGF.getPointerAlign());
David Majnemer1162d252014-06-22 19:05:33 +00001227}
1228
1229bool ItaniumCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
1230 QualType SrcRecordTy) {
1231 return SrcIsPtr;
1232}
1233
1234llvm::Value *ItaniumCXXABI::EmitDynamicCastCall(
John McCall7f416cc2015-09-08 08:05:57 +00001235 CodeGenFunction &CGF, Address ThisAddr, QualType SrcRecordTy,
David Majnemer1162d252014-06-22 19:05:33 +00001236 QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) {
1237 llvm::Type *PtrDiffLTy =
1238 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1239 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1240
1241 llvm::Value *SrcRTTI =
1242 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
1243 llvm::Value *DestRTTI =
1244 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
1245
1246 // Compute the offset hint.
1247 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
1248 const CXXRecordDecl *DestDecl = DestRecordTy->getAsCXXRecordDecl();
1249 llvm::Value *OffsetHint = llvm::ConstantInt::get(
1250 PtrDiffLTy,
1251 computeOffsetHint(CGF.getContext(), SrcDecl, DestDecl).getQuantity());
1252
1253 // Emit the call to __dynamic_cast.
John McCall7f416cc2015-09-08 08:05:57 +00001254 llvm::Value *Value = ThisAddr.getPointer();
David Majnemer1162d252014-06-22 19:05:33 +00001255 Value = CGF.EmitCastToVoidPtr(Value);
1256
1257 llvm::Value *args[] = {Value, SrcRTTI, DestRTTI, OffsetHint};
1258 Value = CGF.EmitNounwindRuntimeCall(getItaniumDynamicCastFn(CGF), args);
1259 Value = CGF.Builder.CreateBitCast(Value, DestLTy);
1260
1261 /// C++ [expr.dynamic.cast]p9:
1262 /// A failed cast to reference type throws std::bad_cast
1263 if (DestTy->isReferenceType()) {
1264 llvm::BasicBlock *BadCastBlock =
1265 CGF.createBasicBlock("dynamic_cast.bad_cast");
1266
1267 llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
1268 CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
1269
1270 CGF.EmitBlock(BadCastBlock);
1271 EmitBadCastCall(CGF);
1272 }
1273
1274 return Value;
1275}
1276
1277llvm::Value *ItaniumCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001278 Address ThisAddr,
David Majnemer1162d252014-06-22 19:05:33 +00001279 QualType SrcRecordTy,
1280 QualType DestTy) {
1281 llvm::Type *PtrDiffLTy =
1282 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1283 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1284
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001285 auto *ClassDecl =
1286 cast<CXXRecordDecl>(SrcRecordTy->getAs<RecordType>()->getDecl());
David Majnemer1162d252014-06-22 19:05:33 +00001287 // Get the vtable pointer.
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001288 llvm::Value *VTable = CGF.GetVTablePtr(ThisAddr, PtrDiffLTy->getPointerTo(),
1289 ClassDecl);
David Majnemer1162d252014-06-22 19:05:33 +00001290
1291 // Get the offset-to-top from the vtable.
1292 llvm::Value *OffsetToTop =
1293 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL);
John McCall7f416cc2015-09-08 08:05:57 +00001294 OffsetToTop =
1295 CGF.Builder.CreateAlignedLoad(OffsetToTop, CGF.getPointerAlign(),
1296 "offset.to.top");
David Majnemer1162d252014-06-22 19:05:33 +00001297
1298 // Finally, add the offset to the pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001299 llvm::Value *Value = ThisAddr.getPointer();
David Majnemer1162d252014-06-22 19:05:33 +00001300 Value = CGF.EmitCastToVoidPtr(Value);
1301 Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop);
1302
1303 return CGF.Builder.CreateBitCast(Value, DestLTy);
1304}
1305
1306bool ItaniumCXXABI::EmitBadCastCall(CodeGenFunction &CGF) {
1307 llvm::Value *Fn = getBadCastFn(CGF);
1308 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
1309 CGF.Builder.CreateUnreachable();
1310 return true;
1311}
1312
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001313llvm::Value *
1314ItaniumCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001315 Address This,
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001316 const CXXRecordDecl *ClassDecl,
1317 const CXXRecordDecl *BaseClassDecl) {
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001318 llvm::Value *VTablePtr = CGF.GetVTablePtr(This, CGM.Int8PtrTy, ClassDecl);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001319 CharUnits VBaseOffsetOffset =
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001320 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(ClassDecl,
1321 BaseClassDecl);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001322
1323 llvm::Value *VBaseOffsetPtr =
1324 CGF.Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
1325 "vbase.offset.ptr");
1326 VBaseOffsetPtr = CGF.Builder.CreateBitCast(VBaseOffsetPtr,
1327 CGM.PtrDiffTy->getPointerTo());
1328
1329 llvm::Value *VBaseOffset =
John McCall7f416cc2015-09-08 08:05:57 +00001330 CGF.Builder.CreateAlignedLoad(VBaseOffsetPtr, CGF.getPointerAlign(),
1331 "vbase.offset");
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001332
1333 return VBaseOffset;
1334}
1335
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001336void ItaniumCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
1337 // Just make sure we're in sync with TargetCXXABI.
1338 assert(CGM.getTarget().getCXXABI().hasConstructorVariants());
1339
Rafael Espindolac3cde362013-12-09 14:51:17 +00001340 // The constructor used for constructing this as a base class;
1341 // ignores virtual bases.
1342 CGM.EmitGlobal(GlobalDecl(D, Ctor_Base));
1343
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001344 // The constructor used for constructing this as a complete class;
Nico Weber4c2ffb22015-01-07 05:25:05 +00001345 // constructs the virtual bases, then calls the base constructor.
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001346 if (!D->getParent()->isAbstract()) {
1347 // We don't need to emit the complete ctor if the class is abstract.
1348 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
1349 }
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001350}
1351
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001352void
1353ItaniumCXXABI::buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
1354 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9bca9232010-09-02 10:25:57 +00001355 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001356
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001357 // All parameters are already in place except VTT, which goes after 'this'.
1358 // These are Clang types, so we don't need to worry about sret yet.
John McCall5d865c322010-08-31 07:33:07 +00001359
1360 // Check if we need to add a VTT parameter (which has type void **).
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001361 if (T == StructorType::Base && MD->getParent()->getNumVBases() != 0)
1362 ArgTys.insert(ArgTys.begin() + 1,
1363 Context.getPointerType(Context.VoidPtrTy));
John McCall5d865c322010-08-31 07:33:07 +00001364}
1365
Reid Klecknere7de47e2013-07-22 13:51:44 +00001366void ItaniumCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
Rafael Espindolac3cde362013-12-09 14:51:17 +00001367 // The destructor used for destructing this as a base class; ignores
1368 // virtual bases.
1369 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001370
1371 // The destructor used for destructing this as a most-derived class;
1372 // call the base destructor and then destructs any virtual bases.
1373 CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));
1374
Rafael Espindolac3cde362013-12-09 14:51:17 +00001375 // The destructor in a virtual table is always a 'deleting'
1376 // destructor, which calls the complete destructor and then uses the
1377 // appropriate operator delete.
1378 if (D->isVirtual())
1379 CGM.EmitGlobal(GlobalDecl(D, Dtor_Deleting));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001380}
1381
Reid Kleckner89077a12013-12-17 19:46:40 +00001382void ItaniumCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
1383 QualType &ResTy,
1384 FunctionArgList &Params) {
John McCall5d865c322010-08-31 07:33:07 +00001385 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
Reid Kleckner89077a12013-12-17 19:46:40 +00001386 assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
John McCall5d865c322010-08-31 07:33:07 +00001387
1388 // Check if we need a VTT parameter as well.
Peter Collingbourne66f82e62013-06-28 20:45:28 +00001389 if (NeedsVTTParameter(CGF.CurGD)) {
John McCall9bca9232010-09-02 10:25:57 +00001390 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001391
1392 // FIXME: avoid the fake decl
1393 QualType T = Context.getPointerType(Context.VoidPtrTy);
1394 ImplicitParamDecl *VTTDecl
Craig Topper8a13c412014-05-21 05:09:00 +00001395 = ImplicitParamDecl::Create(Context, nullptr, MD->getLocation(),
John McCall5d865c322010-08-31 07:33:07 +00001396 &Context.Idents.get("vtt"), T);
Reid Kleckner89077a12013-12-17 19:46:40 +00001397 Params.insert(Params.begin() + 1, VTTDecl);
Reid Kleckner2af6d732013-12-13 00:09:59 +00001398 getStructorImplicitParamDecl(CGF) = VTTDecl;
John McCall5d865c322010-08-31 07:33:07 +00001399 }
1400}
1401
John McCall5d865c322010-08-31 07:33:07 +00001402void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
Justin Lebared4f1722016-07-27 22:04:24 +00001403 // Naked functions have no prolog.
1404 if (CGF.CurFuncDecl && CGF.CurFuncDecl->hasAttr<NakedAttr>())
1405 return;
1406
John McCall5d865c322010-08-31 07:33:07 +00001407 /// Initialize the 'this' slot.
1408 EmitThisParam(CGF);
1409
1410 /// Initialize the 'vtt' slot if needed.
Reid Kleckner2af6d732013-12-13 00:09:59 +00001411 if (getStructorImplicitParamDecl(CGF)) {
1412 getStructorImplicitParamValue(CGF) = CGF.Builder.CreateLoad(
1413 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), "vtt");
John McCall5d865c322010-08-31 07:33:07 +00001414 }
John McCall5d865c322010-08-31 07:33:07 +00001415
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001416 /// If this is a function that the ABI specifies returns 'this', initialize
1417 /// the return slot to 'this' at the start of the function.
1418 ///
1419 /// Unlike the setting of return types, this is done within the ABI
1420 /// implementation instead of by clients of CGCXXABI because:
1421 /// 1) getThisValue is currently protected
1422 /// 2) in theory, an ABI could implement 'this' returns some other way;
1423 /// HasThisReturn only specifies a contract, not the implementation
John McCall5d865c322010-08-31 07:33:07 +00001424 if (HasThisReturn(CGF.CurGD))
Eli Friedman9fbeba02012-02-11 02:57:39 +00001425 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
John McCall5d865c322010-08-31 07:33:07 +00001426}
1427
Reid Kleckner89077a12013-12-17 19:46:40 +00001428unsigned ItaniumCXXABI::addImplicitConstructorArgs(
1429 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
1430 bool ForVirtualBase, bool Delegating, CallArgList &Args) {
1431 if (!NeedsVTTParameter(GlobalDecl(D, Type)))
1432 return 0;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001433
Reid Kleckner89077a12013-12-17 19:46:40 +00001434 // Insert the implicit 'vtt' argument as the second argument.
1435 llvm::Value *VTT =
1436 CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase, Delegating);
1437 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1438 Args.insert(Args.begin() + 1,
1439 CallArg(RValue::get(VTT), VTTTy, /*needscopy=*/false));
1440 return 1; // Added one arg.
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001441}
1442
1443void ItaniumCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
1444 const CXXDestructorDecl *DD,
1445 CXXDtorType Type, bool ForVirtualBase,
John McCall7f416cc2015-09-08 08:05:57 +00001446 bool Delegating, Address This) {
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001447 GlobalDecl GD(DD, Type);
1448 llvm::Value *VTT = CGF.GetVTTParameter(GD, ForVirtualBase, Delegating);
1449 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1450
Craig Topper8a13c412014-05-21 05:09:00 +00001451 llvm::Value *Callee = nullptr;
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001452 if (getContext().getLangOpts().AppleKext)
1453 Callee = CGF.BuildAppleKextVirtualDestructorCall(DD, Type, DD->getParent());
1454
1455 if (!Callee)
Rafael Espindola1ac0ec82014-09-11 15:42:06 +00001456 Callee = CGM.getAddrOfCXXStructor(DD, getFromDtorType(Type));
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001457
John McCall7f416cc2015-09-08 08:05:57 +00001458 CGF.EmitCXXMemberOrOperatorCall(DD, Callee, ReturnValueSlot(),
Richard Smith762672a2016-09-28 19:09:10 +00001459 This.getPointer(), VTT, VTTTy,
1460 nullptr, nullptr);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001461}
1462
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001463void ItaniumCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
1464 const CXXRecordDecl *RD) {
1465 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, CharUnits());
1466 if (VTable->hasInitializer())
1467 return;
1468
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001469 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001470 const VTableLayout &VTLayout = VTContext.getVTableLayout(RD);
1471 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
David Majnemerd905da42014-07-01 20:30:31 +00001472 llvm::Constant *RTTI =
1473 CGM.GetAddrOfRTTIDescriptor(CGM.getContext().getTagDeclType(RD));
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001474
1475 // Create and set the initializer.
Peter Collingbournee53683f2016-09-08 01:14:39 +00001476 llvm::Constant *Init = CGVT.CreateVTableInitializer(VTLayout, RTTI);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001477 VTable->setInitializer(Init);
1478
1479 // Set the correct linkage.
1480 VTable->setLinkage(Linkage);
1481
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00001482 if (CGM.supportsCOMDAT() && VTable->isWeakForLinker())
1483 VTable->setComdat(CGM.getModule().getOrInsertComdat(VTable->getName()));
Rafael Espindolacb92c192015-01-15 23:18:01 +00001484
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001485 // Set the right visibility.
John McCall8f80a612014-02-08 00:41:16 +00001486 CGM.setGlobalVisibility(VTable, RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001487
Benjamin Kramer5d34a2b2014-09-10 12:50:59 +00001488 // Use pointer alignment for the vtable. Otherwise we would align them based
1489 // on the size of the initializer which doesn't make sense as only single
1490 // values are read.
1491 unsigned PAlign = CGM.getTarget().getPointerAlign(0);
1492 VTable->setAlignment(getContext().toCharUnitsFromBits(PAlign).getQuantity());
1493
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001494 // If this is the magic class __cxxabiv1::__fundamental_type_info,
1495 // we will emit the typeinfo for the fundamental types. This is the
1496 // same behaviour as GCC.
1497 const DeclContext *DC = RD->getDeclContext();
1498 if (RD->getIdentifier() &&
1499 RD->getIdentifier()->isStr("__fundamental_type_info") &&
1500 isa<NamespaceDecl>(DC) && cast<NamespaceDecl>(DC)->getIdentifier() &&
1501 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
1502 DC->getParent()->isTranslationUnit())
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00001503 EmitFundamentalRTTIDescriptors(RD->hasAttr<DLLExportAttr>());
Peter Collingbournea4ccff32015-02-20 20:30:56 +00001504
Evgeniy Stepanov93987df2016-01-23 01:20:18 +00001505 if (!VTable->isDeclarationForLinker())
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00001506 CGM.EmitVTableTypeMetadata(VTable, VTLayout);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001507}
1508
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001509bool ItaniumCXXABI::isVirtualOffsetNeededForVTableField(
1510 CodeGenFunction &CGF, CodeGenFunction::VPtr Vptr) {
1511 if (Vptr.NearestVBase == nullptr)
1512 return false;
1513 return NeedsVTTParameter(CGF.CurGD);
Piotr Padlewski255652e2015-09-09 22:20:28 +00001514}
1515
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001516llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructor(
1517 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1518 const CXXRecordDecl *NearestVBase) {
1519
1520 if ((Base.getBase()->getNumVBases() || NearestVBase != nullptr) &&
1521 NeedsVTTParameter(CGF.CurGD)) {
1522 return getVTableAddressPointInStructorWithVTT(CGF, VTableClass, Base,
1523 NearestVBase);
1524 }
1525 return getVTableAddressPoint(Base, VTableClass);
1526}
1527
1528llvm::Constant *
1529ItaniumCXXABI::getVTableAddressPoint(BaseSubobject Base,
1530 const CXXRecordDecl *VTableClass) {
1531 llvm::GlobalValue *VTable = getAddrOfVTable(VTableClass, CharUnits());
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001532
1533 // Find the appropriate vtable within the vtable group.
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001534 uint64_t AddressPoint = CGM.getItaniumVTableContext()
1535 .getVTableLayout(VTableClass)
1536 .getAddressPoint(Base);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001537 llvm::Value *Indices[] = {
Peter Collingbourne4e6a5402016-03-14 19:07:10 +00001538 llvm::ConstantInt::get(CGM.Int32Ty, 0),
1539 llvm::ConstantInt::get(CGM.Int32Ty, AddressPoint)
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001540 };
1541
David Blaikiee3b172a2015-04-02 18:55:21 +00001542 return llvm::ConstantExpr::getInBoundsGetElementPtr(VTable->getValueType(),
1543 VTable, Indices);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001544}
1545
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001546llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructorWithVTT(
1547 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1548 const CXXRecordDecl *NearestVBase) {
1549 assert((Base.getBase()->getNumVBases() || NearestVBase != nullptr) &&
1550 NeedsVTTParameter(CGF.CurGD) && "This class doesn't have VTT");
1551
1552 // Get the secondary vpointer index.
1553 uint64_t VirtualPointerIndex =
1554 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1555
1556 /// Load the VTT.
1557 llvm::Value *VTT = CGF.LoadCXXVTT();
1558 if (VirtualPointerIndex)
1559 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1560
1561 // And load the address point from the VTT.
1562 return CGF.Builder.CreateAlignedLoad(VTT, CGF.getPointerAlign());
1563}
1564
1565llvm::Constant *ItaniumCXXABI::getVTableAddressPointForConstExpr(
1566 BaseSubobject Base, const CXXRecordDecl *VTableClass) {
1567 return getVTableAddressPoint(Base, VTableClass);
1568}
1569
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001570llvm::GlobalVariable *ItaniumCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
1571 CharUnits VPtrOffset) {
1572 assert(VPtrOffset.isZero() && "Itanium ABI only supports zero vptr offsets");
1573
1574 llvm::GlobalVariable *&VTable = VTables[RD];
1575 if (VTable)
1576 return VTable;
1577
Eric Christopherd160c502016-01-29 01:35:53 +00001578 // Queue up this vtable for possible deferred emission.
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001579 CGM.addDeferredVTable(RD);
1580
Yaron Kerene46f7ed2015-07-29 14:21:47 +00001581 SmallString<256> Name;
1582 llvm::raw_svector_ostream Out(Name);
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00001583 getMangleContext().mangleCXXVTable(RD, Out);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001584
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001585 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001586 llvm::ArrayType *ArrayType = llvm::ArrayType::get(
Peter Collingbournee53683f2016-09-08 01:14:39 +00001587 CGM.Int8PtrTy, VTContext.getVTableLayout(RD).vtable_components().size());
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001588
1589 VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
1590 Name, ArrayType, llvm::GlobalValue::ExternalLinkage);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00001591 VTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Hans Wennborgda24e9c2014-06-02 23:13:03 +00001592
1593 if (RD->hasAttr<DLLImportAttr>())
1594 VTable->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1595 else if (RD->hasAttr<DLLExportAttr>())
1596 VTable->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1597
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001598 return VTable;
1599}
1600
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001601llvm::Value *ItaniumCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
1602 GlobalDecl GD,
John McCall7f416cc2015-09-08 08:05:57 +00001603 Address This,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00001604 llvm::Type *Ty,
1605 SourceLocation Loc) {
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001606 GD = GD.getCanonicalDecl();
1607 Ty = Ty->getPointerTo()->getPointerTo();
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001608 auto *MethodDecl = cast<CXXMethodDecl>(GD.getDecl());
1609 llvm::Value *VTable = CGF.GetVTablePtr(This, Ty, MethodDecl->getParent());
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001610
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001611 uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
Peter Collingbourne0ca03632016-06-25 00:24:06 +00001612 if (CGF.ShouldEmitVTableTypeCheckedLoad(MethodDecl->getParent())) {
1613 return CGF.EmitVTableTypeCheckedLoad(
1614 MethodDecl->getParent(), VTable,
1615 VTableIndex * CGM.getContext().getTargetInfo().getPointerWidth(0) / 8);
1616 } else {
1617 CGF.EmitTypeMetadataCodeForVCall(MethodDecl->getParent(), VTable, Loc);
1618
1619 llvm::Value *VFuncPtr =
1620 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfn");
1621 return CGF.Builder.CreateAlignedLoad(VFuncPtr, CGF.getPointerAlign());
1622 }
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001623}
1624
David Majnemer0c0b6d92014-10-31 20:09:12 +00001625llvm::Value *ItaniumCXXABI::EmitVirtualDestructorCall(
1626 CodeGenFunction &CGF, const CXXDestructorDecl *Dtor, CXXDtorType DtorType,
John McCall7f416cc2015-09-08 08:05:57 +00001627 Address This, const CXXMemberCallExpr *CE) {
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001628 assert(CE == nullptr || CE->arg_begin() == CE->arg_end());
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001629 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
1630
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001631 const CGFunctionInfo *FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
1632 Dtor, getFromDtorType(DtorType));
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001633 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001634 llvm::Value *Callee =
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00001635 getVirtualFunctionPointer(CGF, GlobalDecl(Dtor, DtorType), This, Ty,
1636 CE ? CE->getLocStart() : SourceLocation());
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001637
John McCall7f416cc2015-09-08 08:05:57 +00001638 CGF.EmitCXXMemberOrOperatorCall(Dtor, Callee, ReturnValueSlot(),
1639 This.getPointer(), /*ImplicitParam=*/nullptr,
Richard Smith762672a2016-09-28 19:09:10 +00001640 QualType(), CE, nullptr);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001641 return nullptr;
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001642}
1643
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001644void ItaniumCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
Reid Kleckner7810af02013-06-19 15:20:38 +00001645 CodeGenVTables &VTables = CGM.getVTables();
1646 llvm::GlobalVariable *VTT = VTables.GetAddrOfVTT(RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001647 VTables.EmitVTTDefinition(VTT, CGM.getVTableLinkage(RD), RD);
Reid Kleckner7810af02013-06-19 15:20:38 +00001648}
1649
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001650bool ItaniumCXXABI::canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const {
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001651 // We don't emit available_externally vtables if we are in -fapple-kext mode
1652 // because kext mode does not permit devirtualization.
1653 if (CGM.getLangOpts().AppleKext)
1654 return false;
1655
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001656 // If we don't have any inline virtual functions, and if vtable is not hidden,
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001657 // then we are safe to emit available_externally copy of vtable.
1658 // FIXME we can still emit a copy of the vtable if we
1659 // can emit definition of the inline functions.
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001660 return !hasAnyUsedVirtualInlineFunction(RD) && !isVTableHidden(RD);
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001661}
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001662static llvm::Value *performTypeAdjustment(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001663 Address InitialPtr,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001664 int64_t NonVirtualAdjustment,
1665 int64_t VirtualAdjustment,
1666 bool IsReturnAdjustment) {
1667 if (!NonVirtualAdjustment && !VirtualAdjustment)
John McCall7f416cc2015-09-08 08:05:57 +00001668 return InitialPtr.getPointer();
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001669
John McCall7f416cc2015-09-08 08:05:57 +00001670 Address V = CGF.Builder.CreateElementBitCast(InitialPtr, CGF.Int8Ty);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001671
John McCall7f416cc2015-09-08 08:05:57 +00001672 // In a base-to-derived cast, the non-virtual adjustment is applied first.
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001673 if (NonVirtualAdjustment && !IsReturnAdjustment) {
John McCall7f416cc2015-09-08 08:05:57 +00001674 V = CGF.Builder.CreateConstInBoundsByteGEP(V,
1675 CharUnits::fromQuantity(NonVirtualAdjustment));
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001676 }
1677
John McCall7f416cc2015-09-08 08:05:57 +00001678 // Perform the virtual adjustment if we have one.
1679 llvm::Value *ResultPtr;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001680 if (VirtualAdjustment) {
1681 llvm::Type *PtrDiffTy =
1682 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1683
John McCall7f416cc2015-09-08 08:05:57 +00001684 Address VTablePtrPtr = CGF.Builder.CreateElementBitCast(V, CGF.Int8PtrTy);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001685 llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr);
1686
1687 llvm::Value *OffsetPtr =
1688 CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
1689
1690 OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo());
1691
1692 // Load the adjustment offset from the vtable.
John McCall7f416cc2015-09-08 08:05:57 +00001693 llvm::Value *Offset =
1694 CGF.Builder.CreateAlignedLoad(OffsetPtr, CGF.getPointerAlign());
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001695
1696 // Adjust our pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001697 ResultPtr = CGF.Builder.CreateInBoundsGEP(V.getPointer(), Offset);
1698 } else {
1699 ResultPtr = V.getPointer();
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001700 }
1701
John McCall7f416cc2015-09-08 08:05:57 +00001702 // In a derived-to-base conversion, the non-virtual adjustment is
1703 // applied second.
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001704 if (NonVirtualAdjustment && IsReturnAdjustment) {
John McCall7f416cc2015-09-08 08:05:57 +00001705 ResultPtr = CGF.Builder.CreateConstInBoundsGEP1_64(ResultPtr,
1706 NonVirtualAdjustment);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001707 }
1708
1709 // Cast back to the original type.
John McCall7f416cc2015-09-08 08:05:57 +00001710 return CGF.Builder.CreateBitCast(ResultPtr, InitialPtr.getType());
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001711}
1712
1713llvm::Value *ItaniumCXXABI::performThisAdjustment(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001714 Address This,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001715 const ThisAdjustment &TA) {
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00001716 return performTypeAdjustment(CGF, This, TA.NonVirtual,
1717 TA.Virtual.Itanium.VCallOffsetOffset,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001718 /*IsReturnAdjustment=*/false);
1719}
1720
1721llvm::Value *
John McCall7f416cc2015-09-08 08:05:57 +00001722ItaniumCXXABI::performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001723 const ReturnAdjustment &RA) {
1724 return performTypeAdjustment(CGF, Ret, RA.NonVirtual,
1725 RA.Virtual.Itanium.VBaseOffsetOffset,
1726 /*IsReturnAdjustment=*/true);
1727}
1728
John McCall5d865c322010-08-31 07:33:07 +00001729void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
1730 RValue RV, QualType ResultType) {
1731 if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
1732 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
1733
1734 // Destructor thunks in the ARM ABI have indeterminate results.
John McCall7f416cc2015-09-08 08:05:57 +00001735 llvm::Type *T = CGF.ReturnValue.getElementType();
John McCall5d865c322010-08-31 07:33:07 +00001736 RValue Undef = RValue::get(llvm::UndefValue::get(T));
1737 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
1738}
John McCall8ed55a52010-09-02 09:58:18 +00001739
1740/************************** Array allocation cookies **************************/
1741
John McCallb91cd662012-05-01 05:23:51 +00001742CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
1743 // The array cookie is a size_t; pad that up to the element alignment.
1744 // The cookie is actually right-justified in that space.
1745 return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
1746 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001747}
1748
John McCall7f416cc2015-09-08 08:05:57 +00001749Address ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1750 Address NewPtr,
1751 llvm::Value *NumElements,
1752 const CXXNewExpr *expr,
1753 QualType ElementType) {
John McCallb91cd662012-05-01 05:23:51 +00001754 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001755
John McCall7f416cc2015-09-08 08:05:57 +00001756 unsigned AS = NewPtr.getAddressSpace();
John McCall8ed55a52010-09-02 09:58:18 +00001757
John McCall9bca9232010-09-02 10:25:57 +00001758 ASTContext &Ctx = getContext();
John McCall7f416cc2015-09-08 08:05:57 +00001759 CharUnits SizeSize = CGF.getSizeSize();
John McCall8ed55a52010-09-02 09:58:18 +00001760
1761 // The size of the cookie.
1762 CharUnits CookieSize =
1763 std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
John McCallb91cd662012-05-01 05:23:51 +00001764 assert(CookieSize == getArrayCookieSizeImpl(ElementType));
John McCall8ed55a52010-09-02 09:58:18 +00001765
1766 // Compute an offset to the cookie.
John McCall7f416cc2015-09-08 08:05:57 +00001767 Address CookiePtr = NewPtr;
John McCall8ed55a52010-09-02 09:58:18 +00001768 CharUnits CookieOffset = CookieSize - SizeSize;
1769 if (!CookieOffset.isZero())
John McCall7f416cc2015-09-08 08:05:57 +00001770 CookiePtr = CGF.Builder.CreateConstInBoundsByteGEP(CookiePtr, CookieOffset);
John McCall8ed55a52010-09-02 09:58:18 +00001771
1772 // Write the number of elements into the appropriate slot.
John McCall7f416cc2015-09-08 08:05:57 +00001773 Address NumElementsPtr =
1774 CGF.Builder.CreateElementBitCast(CookiePtr, CGF.SizeTy);
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001775 llvm::Instruction *SI = CGF.Builder.CreateStore(NumElements, NumElementsPtr);
John McCall7f416cc2015-09-08 08:05:57 +00001776
1777 // Handle the array cookie specially in ASan.
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001778 if (CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) && AS == 0 &&
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001779 expr->getOperatorNew()->isReplaceableGlobalAllocationFunction()) {
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001780 // The store to the CookiePtr does not need to be instrumented.
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001781 CGM.getSanitizerMetadata()->disableSanitizerForInstruction(SI);
1782 llvm::FunctionType *FTy =
John McCall7f416cc2015-09-08 08:05:57 +00001783 llvm::FunctionType::get(CGM.VoidTy, NumElementsPtr.getType(), false);
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001784 llvm::Constant *F =
1785 CGM.CreateRuntimeFunction(FTy, "__asan_poison_cxx_array_cookie");
John McCall7f416cc2015-09-08 08:05:57 +00001786 CGF.Builder.CreateCall(F, NumElementsPtr.getPointer());
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001787 }
John McCall8ed55a52010-09-02 09:58:18 +00001788
1789 // Finally, compute a pointer to the actual data buffer by skipping
1790 // over the cookie completely.
John McCall7f416cc2015-09-08 08:05:57 +00001791 return CGF.Builder.CreateConstInBoundsByteGEP(NewPtr, CookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001792}
1793
John McCallb91cd662012-05-01 05:23:51 +00001794llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001795 Address allocPtr,
John McCallb91cd662012-05-01 05:23:51 +00001796 CharUnits cookieSize) {
1797 // The element size is right-justified in the cookie.
John McCall7f416cc2015-09-08 08:05:57 +00001798 Address numElementsPtr = allocPtr;
1799 CharUnits numElementsOffset = cookieSize - CGF.getSizeSize();
John McCallb91cd662012-05-01 05:23:51 +00001800 if (!numElementsOffset.isZero())
1801 numElementsPtr =
John McCall7f416cc2015-09-08 08:05:57 +00001802 CGF.Builder.CreateConstInBoundsByteGEP(numElementsPtr, numElementsOffset);
John McCall8ed55a52010-09-02 09:58:18 +00001803
John McCall7f416cc2015-09-08 08:05:57 +00001804 unsigned AS = allocPtr.getAddressSpace();
1805 numElementsPtr = CGF.Builder.CreateElementBitCast(numElementsPtr, CGF.SizeTy);
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001806 if (!CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) || AS != 0)
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001807 return CGF.Builder.CreateLoad(numElementsPtr);
1808 // In asan mode emit a function call instead of a regular load and let the
1809 // run-time deal with it: if the shadow is properly poisoned return the
1810 // cookie, otherwise return 0 to avoid an infinite loop calling DTORs.
1811 // We can't simply ignore this load using nosanitize metadata because
1812 // the metadata may be lost.
1813 llvm::FunctionType *FTy =
1814 llvm::FunctionType::get(CGF.SizeTy, CGF.SizeTy->getPointerTo(0), false);
1815 llvm::Constant *F =
1816 CGM.CreateRuntimeFunction(FTy, "__asan_load_cxx_array_cookie");
John McCall7f416cc2015-09-08 08:05:57 +00001817 return CGF.Builder.CreateCall(F, numElementsPtr.getPointer());
John McCall8ed55a52010-09-02 09:58:18 +00001818}
1819
John McCallb91cd662012-05-01 05:23:51 +00001820CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
John McCallc19c7062013-01-25 23:36:19 +00001821 // ARM says that the cookie is always:
John McCall8ed55a52010-09-02 09:58:18 +00001822 // struct array_cookie {
1823 // std::size_t element_size; // element_size != 0
1824 // std::size_t element_count;
1825 // };
John McCallc19c7062013-01-25 23:36:19 +00001826 // But the base ABI doesn't give anything an alignment greater than
1827 // 8, so we can dismiss this as typical ABI-author blindness to
1828 // actual language complexity and round up to the element alignment.
1829 return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes),
1830 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001831}
1832
John McCall7f416cc2015-09-08 08:05:57 +00001833Address ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1834 Address newPtr,
1835 llvm::Value *numElements,
1836 const CXXNewExpr *expr,
1837 QualType elementType) {
John McCallb91cd662012-05-01 05:23:51 +00001838 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001839
John McCall8ed55a52010-09-02 09:58:18 +00001840 // The cookie is always at the start of the buffer.
John McCall7f416cc2015-09-08 08:05:57 +00001841 Address cookie = newPtr;
John McCall8ed55a52010-09-02 09:58:18 +00001842
1843 // The first element is the element size.
John McCall7f416cc2015-09-08 08:05:57 +00001844 cookie = CGF.Builder.CreateElementBitCast(cookie, CGF.SizeTy);
John McCallc19c7062013-01-25 23:36:19 +00001845 llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy,
1846 getContext().getTypeSizeInChars(elementType).getQuantity());
1847 CGF.Builder.CreateStore(elementSize, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001848
1849 // The second element is the element count.
John McCall7f416cc2015-09-08 08:05:57 +00001850 cookie = CGF.Builder.CreateConstInBoundsGEP(cookie, 1, CGF.getSizeSize());
John McCallc19c7062013-01-25 23:36:19 +00001851 CGF.Builder.CreateStore(numElements, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001852
1853 // Finally, compute a pointer to the actual data buffer by skipping
1854 // over the cookie completely.
John McCallc19c7062013-01-25 23:36:19 +00001855 CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType);
John McCall7f416cc2015-09-08 08:05:57 +00001856 return CGF.Builder.CreateConstInBoundsByteGEP(newPtr, cookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001857}
1858
John McCallb91cd662012-05-01 05:23:51 +00001859llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001860 Address allocPtr,
John McCallb91cd662012-05-01 05:23:51 +00001861 CharUnits cookieSize) {
1862 // The number of elements is at offset sizeof(size_t) relative to
1863 // the allocated pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001864 Address numElementsPtr
1865 = CGF.Builder.CreateConstInBoundsByteGEP(allocPtr, CGF.getSizeSize());
John McCall8ed55a52010-09-02 09:58:18 +00001866
John McCall7f416cc2015-09-08 08:05:57 +00001867 numElementsPtr = CGF.Builder.CreateElementBitCast(numElementsPtr, CGF.SizeTy);
John McCallb91cd662012-05-01 05:23:51 +00001868 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall8ed55a52010-09-02 09:58:18 +00001869}
1870
John McCall68ff0372010-09-08 01:44:27 +00001871/*********************** Static local initialization **************************/
1872
1873static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001874 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001875 // int __cxa_guard_acquire(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001876 llvm::FunctionType *FTy =
John McCall68ff0372010-09-08 01:44:27 +00001877 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
Jay Foad5709f7c2011-07-29 13:56:53 +00001878 GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001879 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_acquire",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001880 llvm::AttributeSet::get(CGM.getLLVMContext(),
1881 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001882 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001883}
1884
1885static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001886 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001887 // void __cxa_guard_release(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001888 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001889 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001890 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_release",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001891 llvm::AttributeSet::get(CGM.getLLVMContext(),
1892 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001893 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001894}
1895
1896static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001897 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001898 // void __cxa_guard_abort(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001899 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001900 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001901 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_abort",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001902 llvm::AttributeSet::get(CGM.getLLVMContext(),
1903 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001904 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001905}
1906
1907namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001908 struct CallGuardAbort final : EHScopeStack::Cleanup {
John McCall68ff0372010-09-08 01:44:27 +00001909 llvm::GlobalVariable *Guard;
Chandler Carruth84537952012-03-30 19:44:53 +00001910 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
John McCall68ff0372010-09-08 01:44:27 +00001911
Craig Topper4f12f102014-03-12 06:41:41 +00001912 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall882987f2013-02-28 19:01:20 +00001913 CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()),
1914 Guard);
John McCall68ff0372010-09-08 01:44:27 +00001915 }
1916 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001917}
John McCall68ff0372010-09-08 01:44:27 +00001918
1919/// The ARM code here follows the Itanium code closely enough that we
1920/// just special-case it at particular places.
John McCallcdf7ef52010-11-06 09:44:32 +00001921void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
1922 const VarDecl &D,
John McCallb88a5662012-03-30 21:00:39 +00001923 llvm::GlobalVariable *var,
1924 bool shouldPerformInit) {
John McCall68ff0372010-09-08 01:44:27 +00001925 CGBuilderTy &Builder = CGF.Builder;
John McCallcdf7ef52010-11-06 09:44:32 +00001926
Richard Smith62f19e72016-06-25 00:15:56 +00001927 // Inline variables that weren't instantiated from variable templates have
1928 // partially-ordered initialization within their translation unit.
1929 bool NonTemplateInline =
1930 D.isInline() &&
1931 !isTemplateInstantiation(D.getTemplateSpecializationKind());
1932
1933 // We only need to use thread-safe statics for local non-TLS variables and
1934 // inline variables; other global initialization is always single-threaded
1935 // or (through lazy dynamic loading in multiple threads) unsequenced.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001936 bool threadsafe = getContext().getLangOpts().ThreadsafeStatics &&
Richard Smith62f19e72016-06-25 00:15:56 +00001937 (D.isLocalVarDecl() || NonTemplateInline) &&
1938 !D.getTLSKind();
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001939
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001940 // If we have a global variable with internal linkage and thread-safe statics
1941 // are disabled, we can just let the guard variable be of type i8.
John McCallb88a5662012-03-30 21:00:39 +00001942 bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
1943
1944 llvm::IntegerType *guardTy;
John McCall7f416cc2015-09-08 08:05:57 +00001945 CharUnits guardAlignment;
John McCall5aa52592011-06-17 07:33:57 +00001946 if (useInt8GuardVariable) {
John McCallb88a5662012-03-30 21:00:39 +00001947 guardTy = CGF.Int8Ty;
John McCall7f416cc2015-09-08 08:05:57 +00001948 guardAlignment = CharUnits::One();
John McCall5aa52592011-06-17 07:33:57 +00001949 } else {
Tim Northover9bb857a2013-01-31 12:13:10 +00001950 // Guard variables are 64 bits in the generic ABI and size width on ARM
1951 // (i.e. 32-bit on AArch32, 64-bit on AArch64).
John McCall7f416cc2015-09-08 08:05:57 +00001952 if (UseARMGuardVarABI) {
1953 guardTy = CGF.SizeTy;
1954 guardAlignment = CGF.getSizeAlign();
1955 } else {
1956 guardTy = CGF.Int64Ty;
1957 guardAlignment = CharUnits::fromQuantity(
1958 CGM.getDataLayout().getABITypeAlignment(guardTy));
1959 }
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001960 }
John McCallb88a5662012-03-30 21:00:39 +00001961 llvm::PointerType *guardPtrTy = guardTy->getPointerTo();
John McCall68ff0372010-09-08 01:44:27 +00001962
John McCallb88a5662012-03-30 21:00:39 +00001963 // Create the guard variable if we don't already have it (as we
1964 // might if we're double-emitting this function body).
1965 llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
1966 if (!guard) {
1967 // Mangle the name for the guard.
1968 SmallString<256> guardName;
1969 {
1970 llvm::raw_svector_ostream out(guardName);
Reid Klecknerd8110b62013-09-10 20:14:30 +00001971 getMangleContext().mangleStaticGuardVariable(&D, out);
John McCallb88a5662012-03-30 21:00:39 +00001972 }
John McCall8e7cb6d2010-11-02 21:04:24 +00001973
John McCallb88a5662012-03-30 21:00:39 +00001974 // Create the guard variable with a zero-initializer.
1975 // Just absorb linkage and visibility from the guarded variable.
1976 guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
1977 false, var->getLinkage(),
1978 llvm::ConstantInt::get(guardTy, 0),
1979 guardName.str());
1980 guard->setVisibility(var->getVisibility());
Richard Smithdbf74ba2013-04-14 23:01:42 +00001981 // If the variable is thread-local, so is its guard variable.
1982 guard->setThreadLocalMode(var->getThreadLocalMode());
John McCall7f416cc2015-09-08 08:05:57 +00001983 guard->setAlignment(guardAlignment.getQuantity());
John McCallb88a5662012-03-30 21:00:39 +00001984
Yaron Keren5bfa1082015-09-03 20:33:29 +00001985 // The ABI says: "It is suggested that it be emitted in the same COMDAT
1986 // group as the associated data object." In practice, this doesn't work for
1987 // non-ELF object formats, so only do it for ELF.
Rafael Espindola0d4fb982015-01-12 22:13:53 +00001988 llvm::Comdat *C = var->getComdat();
Yaron Keren5bfa1082015-09-03 20:33:29 +00001989 if (!D.isLocalVarDecl() && C &&
1990 CGM.getTarget().getTriple().isOSBinFormatELF()) {
Rafael Espindola2ae4b632014-09-19 19:43:18 +00001991 guard->setComdat(C);
Richard Smith62f19e72016-06-25 00:15:56 +00001992 // An inline variable's guard function is run from the per-TU
1993 // initialization function, not via a dedicated global ctor function, so
1994 // we can't put it in a comdat.
1995 if (!NonTemplateInline)
1996 CGF.CurFn->setComdat(C);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00001997 } else if (CGM.supportsCOMDAT() && guard->isWeakForLinker()) {
1998 guard->setComdat(CGM.getModule().getOrInsertComdat(guard->getName()));
Rafael Espindola2ae4b632014-09-19 19:43:18 +00001999 }
2000
John McCallb88a5662012-03-30 21:00:39 +00002001 CGM.setStaticLocalDeclGuardAddress(&D, guard);
2002 }
John McCall87590e62012-03-30 07:09:50 +00002003
John McCall7f416cc2015-09-08 08:05:57 +00002004 Address guardAddr = Address(guard, guardAlignment);
2005
John McCall68ff0372010-09-08 01:44:27 +00002006 // Test whether the variable has completed initialization.
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002007 //
John McCall68ff0372010-09-08 01:44:27 +00002008 // Itanium C++ ABI 3.3.2:
2009 // The following is pseudo-code showing how these functions can be used:
2010 // if (obj_guard.first_byte == 0) {
2011 // if ( __cxa_guard_acquire (&obj_guard) ) {
2012 // try {
2013 // ... initialize the object ...;
2014 // } catch (...) {
2015 // __cxa_guard_abort (&obj_guard);
2016 // throw;
2017 // }
2018 // ... queue object destructor with __cxa_atexit() ...;
2019 // __cxa_guard_release (&obj_guard);
2020 // }
2021 // }
Tim Northovera2ee4332014-03-29 15:09:45 +00002022
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002023 // Load the first byte of the guard variable.
2024 llvm::LoadInst *LI =
John McCall7f416cc2015-09-08 08:05:57 +00002025 Builder.CreateLoad(Builder.CreateElementBitCast(guardAddr, CGM.Int8Ty));
John McCall68ff0372010-09-08 01:44:27 +00002026
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002027 // Itanium ABI:
2028 // An implementation supporting thread-safety on multiprocessor
2029 // systems must also guarantee that references to the initialized
2030 // object do not occur before the load of the initialization flag.
2031 //
2032 // In LLVM, we do this by marking the load Acquire.
2033 if (threadsafe)
JF Bastien92f4ef12016-04-06 17:26:42 +00002034 LI->setAtomic(llvm::AtomicOrdering::Acquire);
Eli Friedman84d28122011-09-13 22:21:56 +00002035
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002036 // For ARM, we should only check the first bit, rather than the entire byte:
2037 //
2038 // ARM C++ ABI 3.2.3.1:
2039 // To support the potential use of initialization guard variables
2040 // as semaphores that are the target of ARM SWP and LDREX/STREX
2041 // synchronizing instructions we define a static initialization
2042 // guard variable to be a 4-byte aligned, 4-byte word with the
2043 // following inline access protocol.
2044 // #define INITIALIZED 1
2045 // if ((obj_guard & INITIALIZED) != INITIALIZED) {
2046 // if (__cxa_guard_acquire(&obj_guard))
2047 // ...
2048 // }
2049 //
2050 // and similarly for ARM64:
2051 //
2052 // ARM64 C++ ABI 3.2.2:
2053 // This ABI instead only specifies the value bit 0 of the static guard
2054 // variable; all other bits are platform defined. Bit 0 shall be 0 when the
2055 // variable is not initialized and 1 when it is.
2056 llvm::Value *V =
2057 (UseARMGuardVarABI && !useInt8GuardVariable)
2058 ? Builder.CreateAnd(LI, llvm::ConstantInt::get(CGM.Int8Ty, 1))
2059 : LI;
2060 llvm::Value *isInitialized = Builder.CreateIsNull(V, "guard.uninitialized");
John McCall68ff0372010-09-08 01:44:27 +00002061
2062 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
2063 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
2064
2065 // Check if the first byte of the guard variable is zero.
John McCallb88a5662012-03-30 21:00:39 +00002066 Builder.CreateCondBr(isInitialized, InitCheckBlock, EndBlock);
John McCall68ff0372010-09-08 01:44:27 +00002067
2068 CGF.EmitBlock(InitCheckBlock);
2069
2070 // Variables used when coping with thread-safe statics and exceptions.
John McCall5aa52592011-06-17 07:33:57 +00002071 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00002072 // Call __cxa_guard_acquire.
2073 llvm::Value *V
John McCall882987f2013-02-28 19:01:20 +00002074 = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
John McCall68ff0372010-09-08 01:44:27 +00002075
2076 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
2077
2078 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
2079 InitBlock, EndBlock);
2080
2081 // Call __cxa_guard_abort along the exceptional edge.
John McCallb88a5662012-03-30 21:00:39 +00002082 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
John McCall68ff0372010-09-08 01:44:27 +00002083
2084 CGF.EmitBlock(InitBlock);
2085 }
2086
2087 // Emit the initializer and add a global destructor if appropriate.
John McCallb88a5662012-03-30 21:00:39 +00002088 CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
John McCall68ff0372010-09-08 01:44:27 +00002089
John McCall5aa52592011-06-17 07:33:57 +00002090 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00002091 // Pop the guard-abort cleanup if we pushed one.
2092 CGF.PopCleanupBlock();
2093
2094 // Call __cxa_guard_release. This cannot throw.
John McCall7f416cc2015-09-08 08:05:57 +00002095 CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy),
2096 guardAddr.getPointer());
John McCall68ff0372010-09-08 01:44:27 +00002097 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002098 Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guardAddr);
John McCall68ff0372010-09-08 01:44:27 +00002099 }
2100
2101 CGF.EmitBlock(EndBlock);
2102}
John McCallc84ed6a2012-05-01 06:13:13 +00002103
2104/// Register a global destructor using __cxa_atexit.
2105static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
2106 llvm::Constant *dtor,
Richard Smithdbf74ba2013-04-14 23:01:42 +00002107 llvm::Constant *addr,
2108 bool TLS) {
Bill Wendling95cae882013-05-02 19:18:03 +00002109 const char *Name = "__cxa_atexit";
2110 if (TLS) {
2111 const llvm::Triple &T = CGF.getTarget().getTriple();
Manman Renf93fff22015-11-11 23:08:18 +00002112 Name = T.isOSDarwin() ? "_tlv_atexit" : "__cxa_thread_atexit";
Bill Wendling95cae882013-05-02 19:18:03 +00002113 }
Richard Smithdbf74ba2013-04-14 23:01:42 +00002114
John McCallc84ed6a2012-05-01 06:13:13 +00002115 // We're assuming that the destructor function is something we can
2116 // reasonably call with the default CC. Go ahead and cast it to the
2117 // right prototype.
2118 llvm::Type *dtorTy =
2119 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo();
2120
2121 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
2122 llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
2123 llvm::FunctionType *atexitTy =
2124 llvm::FunctionType::get(CGF.IntTy, paramTys, false);
2125
2126 // Fetch the actual function.
Richard Smithdbf74ba2013-04-14 23:01:42 +00002127 llvm::Constant *atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name);
John McCallc84ed6a2012-05-01 06:13:13 +00002128 if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit))
2129 fn->setDoesNotThrow();
2130
2131 // Create a variable that binds the atexit to this shared object.
2132 llvm::Constant *handle =
2133 CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
2134
2135 llvm::Value *args[] = {
2136 llvm::ConstantExpr::getBitCast(dtor, dtorTy),
2137 llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy),
2138 handle
2139 };
John McCall882987f2013-02-28 19:01:20 +00002140 CGF.EmitNounwindRuntimeCall(atexit, args);
John McCallc84ed6a2012-05-01 06:13:13 +00002141}
2142
2143/// Register a global destructor as best as we know how.
2144void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF,
Richard Smithdbf74ba2013-04-14 23:01:42 +00002145 const VarDecl &D,
John McCallc84ed6a2012-05-01 06:13:13 +00002146 llvm::Constant *dtor,
2147 llvm::Constant *addr) {
2148 // Use __cxa_atexit if available.
Richard Smithdbf74ba2013-04-14 23:01:42 +00002149 if (CGM.getCodeGenOpts().CXAAtExit)
2150 return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind());
2151
2152 if (D.getTLSKind())
2153 CGM.ErrorUnsupported(&D, "non-trivial TLS destruction");
John McCallc84ed6a2012-05-01 06:13:13 +00002154
2155 // In Apple kexts, we want to add a global destructor entry.
2156 // FIXME: shouldn't this be guarded by some variable?
Richard Smith9c6890a2012-11-01 22:30:59 +00002157 if (CGM.getLangOpts().AppleKext) {
John McCallc84ed6a2012-05-01 06:13:13 +00002158 // Generate a global destructor entry.
2159 return CGM.AddCXXDtorEntry(dtor, addr);
2160 }
2161
David Blaikieebe87e12013-08-27 23:57:18 +00002162 CGF.registerGlobalDtorWithAtExit(D, dtor, addr);
John McCallc84ed6a2012-05-01 06:13:13 +00002163}
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002164
David Majnemer9b21c332014-07-11 20:28:10 +00002165static bool isThreadWrapperReplaceable(const VarDecl *VD,
2166 CodeGen::CodeGenModule &CGM) {
2167 assert(!VD->isStaticLocal() && "static local VarDecls don't need wrappers!");
Manman Renf93fff22015-11-11 23:08:18 +00002168 // Darwin prefers to have references to thread local variables to go through
David Majnemer9b21c332014-07-11 20:28:10 +00002169 // the thread wrapper instead of directly referencing the backing variable.
2170 return VD->getTLSKind() == VarDecl::TLS_Dynamic &&
Manman Renf93fff22015-11-11 23:08:18 +00002171 CGM.getTarget().getTriple().isOSDarwin();
David Majnemer9b21c332014-07-11 20:28:10 +00002172}
2173
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002174/// Get the appropriate linkage for the wrapper function. This is essentially
David Majnemer4632e1e2014-06-27 16:56:27 +00002175/// the weak form of the variable's linkage; every translation unit which needs
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002176/// the wrapper emits a copy, and we want the linker to merge them.
David Majnemer35ab3282014-06-11 04:08:55 +00002177static llvm::GlobalValue::LinkageTypes
2178getThreadLocalWrapperLinkage(const VarDecl *VD, CodeGen::CodeGenModule &CGM) {
2179 llvm::GlobalValue::LinkageTypes VarLinkage =
2180 CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false);
2181
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002182 // For internal linkage variables, we don't need an external or weak wrapper.
2183 if (llvm::GlobalValue::isLocalLinkage(VarLinkage))
2184 return VarLinkage;
David Majnemer35ab3282014-06-11 04:08:55 +00002185
David Majnemer9b21c332014-07-11 20:28:10 +00002186 // If the thread wrapper is replaceable, give it appropriate linkage.
Manman Ren68150262015-11-11 22:42:31 +00002187 if (isThreadWrapperReplaceable(VD, CGM))
2188 if (!llvm::GlobalVariable::isLinkOnceLinkage(VarLinkage) &&
2189 !llvm::GlobalVariable::isWeakODRLinkage(VarLinkage))
2190 return VarLinkage;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002191 return llvm::GlobalValue::WeakODRLinkage;
2192}
2193
2194llvm::Function *
2195ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD,
Alexander Musmanf94c3182014-09-26 06:28:25 +00002196 llvm::Value *Val) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002197 // Mangle the name for the thread_local wrapper function.
2198 SmallString<256> WrapperName;
2199 {
2200 llvm::raw_svector_ostream Out(WrapperName);
2201 getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002202 }
2203
Akira Hatanaka26907f92016-01-15 03:34:06 +00002204 // FIXME: If VD is a definition, we should regenerate the function attributes
2205 // before returning.
Alexander Musmanf94c3182014-09-26 06:28:25 +00002206 if (llvm::Value *V = CGM.getModule().getNamedValue(WrapperName))
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002207 return cast<llvm::Function>(V);
2208
Akira Hatanaka26907f92016-01-15 03:34:06 +00002209 QualType RetQT = VD->getType();
2210 if (RetQT->isReferenceType())
2211 RetQT = RetQT.getNonReferenceType();
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002212
John McCallc56a8b32016-03-11 04:30:31 +00002213 const CGFunctionInfo &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
2214 getContext().getPointerType(RetQT), FunctionArgList());
Akira Hatanaka26907f92016-01-15 03:34:06 +00002215
2216 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FI);
David Majnemer35ab3282014-06-11 04:08:55 +00002217 llvm::Function *Wrapper =
2218 llvm::Function::Create(FnTy, getThreadLocalWrapperLinkage(VD, CGM),
2219 WrapperName.str(), &CGM.getModule());
Akira Hatanaka26907f92016-01-15 03:34:06 +00002220
2221 CGM.SetLLVMFunctionAttributes(nullptr, FI, Wrapper);
2222
2223 if (VD->hasDefinition())
2224 CGM.SetLLVMFunctionAttributesForDefinition(nullptr, Wrapper);
2225
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002226 // Always resolve references to the wrapper at link time.
Manman Ren68150262015-11-11 22:42:31 +00002227 if (!Wrapper->hasLocalLinkage() && !(isThreadWrapperReplaceable(VD, CGM) &&
2228 !llvm::GlobalVariable::isLinkOnceLinkage(Wrapper->getLinkage()) &&
2229 !llvm::GlobalVariable::isWeakODRLinkage(Wrapper->getLinkage())))
Duncan P. N. Exon Smith4434d362014-05-07 22:36:11 +00002230 Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
Manman Renb0b3af72015-12-17 00:42:36 +00002231
2232 if (isThreadWrapperReplaceable(VD, CGM)) {
2233 Wrapper->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2234 Wrapper->addFnAttr(llvm::Attribute::NoUnwind);
2235 }
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002236 return Wrapper;
2237}
2238
2239void ItaniumCXXABI::EmitThreadLocalInitFuncs(
Richard Smith5a99c492015-12-01 01:10:48 +00002240 CodeGenModule &CGM, ArrayRef<const VarDecl *> CXXThreadLocals,
2241 ArrayRef<llvm::Function *> CXXThreadLocalInits,
2242 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) {
David Majnemerb3341ea2014-10-05 05:05:40 +00002243 llvm::Function *InitFunc = nullptr;
2244 if (!CXXThreadLocalInits.empty()) {
2245 // Generate a guarded initialization function.
2246 llvm::FunctionType *FTy =
2247 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002248 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
2249 InitFunc = CGM.CreateGlobalInitOrDestructFunction(FTy, "__tls_init", FI,
Alexey Samsonov1444bb92014-10-17 00:20:19 +00002250 SourceLocation(),
David Majnemerb3341ea2014-10-05 05:05:40 +00002251 /*TLS=*/true);
2252 llvm::GlobalVariable *Guard = new llvm::GlobalVariable(
2253 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false,
2254 llvm::GlobalVariable::InternalLinkage,
2255 llvm::ConstantInt::get(CGM.Int8Ty, 0), "__tls_guard");
2256 Guard->setThreadLocal(true);
John McCall7f416cc2015-09-08 08:05:57 +00002257
2258 CharUnits GuardAlign = CharUnits::One();
2259 Guard->setAlignment(GuardAlign.getQuantity());
2260
David Majnemerb3341ea2014-10-05 05:05:40 +00002261 CodeGenFunction(CGM)
John McCall7f416cc2015-09-08 08:05:57 +00002262 .GenerateCXXGlobalInitFunc(InitFunc, CXXThreadLocalInits,
2263 Address(Guard, GuardAlign));
Manman Ren5e5d0462016-03-18 23:35:21 +00002264 // On Darwin platforms, use CXX_FAST_TLS calling convention.
2265 if (CGM.getTarget().getTriple().isOSDarwin()) {
2266 InitFunc->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2267 InitFunc->addFnAttr(llvm::Attribute::NoUnwind);
2268 }
David Majnemerb3341ea2014-10-05 05:05:40 +00002269 }
Richard Smith5a99c492015-12-01 01:10:48 +00002270 for (const VarDecl *VD : CXXThreadLocals) {
2271 llvm::GlobalVariable *Var =
2272 cast<llvm::GlobalVariable>(CGM.GetGlobalValue(CGM.getMangledName(VD)));
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002273
David Majnemer9b21c332014-07-11 20:28:10 +00002274 // Some targets require that all access to thread local variables go through
2275 // the thread wrapper. This means that we cannot attempt to create a thread
2276 // wrapper or a thread helper.
2277 if (isThreadWrapperReplaceable(VD, CGM) && !VD->hasDefinition())
2278 continue;
2279
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002280 // Mangle the name for the thread_local initialization function.
2281 SmallString<256> InitFnName;
2282 {
2283 llvm::raw_svector_ostream Out(InitFnName);
2284 getMangleContext().mangleItaniumThreadLocalInit(VD, Out);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002285 }
2286
2287 // If we have a definition for the variable, emit the initialization
2288 // function as an alias to the global Init function (if any). Otherwise,
2289 // produce a declaration of the initialization function.
Craig Topper8a13c412014-05-21 05:09:00 +00002290 llvm::GlobalValue *Init = nullptr;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002291 bool InitIsInitFunc = false;
2292 if (VD->hasDefinition()) {
2293 InitIsInitFunc = true;
2294 if (InitFunc)
Rafael Espindola234405b2014-05-17 21:30:14 +00002295 Init = llvm::GlobalAlias::create(Var->getLinkage(), InitFnName.str(),
2296 InitFunc);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002297 } else {
2298 // Emit a weak global function referring to the initialization function.
2299 // This function will not exist if the TU defining the thread_local
2300 // variable in question does not need any dynamic initialization for
2301 // its thread_local variables.
2302 llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, false);
2303 Init = llvm::Function::Create(
2304 FnTy, llvm::GlobalVariable::ExternalWeakLinkage, InitFnName.str(),
2305 &CGM.getModule());
John McCallc56a8b32016-03-11 04:30:31 +00002306 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
Akira Hatanaka26907f92016-01-15 03:34:06 +00002307 CGM.SetLLVMFunctionAttributes(nullptr, FI, cast<llvm::Function>(Init));
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002308 }
2309
2310 if (Init)
2311 Init->setVisibility(Var->getVisibility());
2312
2313 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Var);
2314 llvm::LLVMContext &Context = CGM.getModule().getContext();
2315 llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper);
John McCall7f416cc2015-09-08 08:05:57 +00002316 CGBuilderTy Builder(CGM, Entry);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002317 if (InitIsInitFunc) {
Manman Ren5e5d0462016-03-18 23:35:21 +00002318 if (Init) {
2319 llvm::CallInst *CallVal = Builder.CreateCall(Init);
2320 if (isThreadWrapperReplaceable(VD, CGM))
2321 CallVal->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2322 }
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002323 } else {
2324 // Don't know whether we have an init function. Call it if it exists.
2325 llvm::Value *Have = Builder.CreateIsNotNull(Init);
2326 llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2327 llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2328 Builder.CreateCondBr(Have, InitBB, ExitBB);
2329
2330 Builder.SetInsertPoint(InitBB);
David Blaikie4ba525b2015-07-14 17:27:39 +00002331 Builder.CreateCall(Init);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002332 Builder.CreateBr(ExitBB);
2333
2334 Builder.SetInsertPoint(ExitBB);
2335 }
2336
2337 // For a reference, the result of the wrapper function is a pointer to
2338 // the referenced object.
2339 llvm::Value *Val = Var;
2340 if (VD->getType()->isReferenceType()) {
John McCall7f416cc2015-09-08 08:05:57 +00002341 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2342 Val = Builder.CreateAlignedLoad(Val, Align);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002343 }
Alexander Musmanf94c3182014-09-26 06:28:25 +00002344 if (Val->getType() != Wrapper->getReturnType())
2345 Val = Builder.CreatePointerBitCastOrAddrSpaceCast(
2346 Val, Wrapper->getReturnType(), "");
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002347 Builder.CreateRet(Val);
2348 }
2349}
2350
Richard Smith0f383742014-03-26 22:48:22 +00002351LValue ItaniumCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
2352 const VarDecl *VD,
2353 QualType LValType) {
Richard Smith5a99c492015-12-01 01:10:48 +00002354 llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD);
Alexander Musmanf94c3182014-09-26 06:28:25 +00002355 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Val);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002356
Manman Renb0b3af72015-12-17 00:42:36 +00002357 llvm::CallInst *CallVal = CGF.Builder.CreateCall(Wrapper);
Saleem Abdulrasool4a7130a2016-08-01 21:31:24 +00002358 CallVal->setCallingConv(Wrapper->getCallingConv());
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002359
2360 LValue LV;
2361 if (VD->getType()->isReferenceType())
Manman Renb0b3af72015-12-17 00:42:36 +00002362 LV = CGF.MakeNaturalAlignAddrLValue(CallVal, LValType);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002363 else
Manman Renb0b3af72015-12-17 00:42:36 +00002364 LV = CGF.MakeAddrLValue(CallVal, LValType,
2365 CGF.getContext().getDeclAlign(VD));
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002366 // FIXME: need setObjCGCLValueClass?
2367 return LV;
2368}
Peter Collingbourne66f82e62013-06-28 20:45:28 +00002369
2370/// Return whether the given global decl needs a VTT parameter, which it does
2371/// if it's a base constructor or destructor with virtual bases.
2372bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) {
2373 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
2374
2375 // We don't have any virtual bases, just return early.
2376 if (!MD->getParent()->getNumVBases())
2377 return false;
2378
2379 // Check if we have a base constructor.
2380 if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base)
2381 return true;
2382
2383 // Check if we have a base destructor.
2384 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
2385 return true;
2386
2387 return false;
2388}
David Majnemere2cb8d12014-07-07 06:20:47 +00002389
2390namespace {
2391class ItaniumRTTIBuilder {
2392 CodeGenModule &CGM; // Per-module state.
2393 llvm::LLVMContext &VMContext;
2394 const ItaniumCXXABI &CXXABI; // Per-module state.
2395
2396 /// Fields - The fields of the RTTI descriptor currently being built.
2397 SmallVector<llvm::Constant *, 16> Fields;
2398
2399 /// GetAddrOfTypeName - Returns the mangled type name of the given type.
2400 llvm::GlobalVariable *
2401 GetAddrOfTypeName(QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage);
2402
2403 /// GetAddrOfExternalRTTIDescriptor - Returns the constant for the RTTI
2404 /// descriptor of the given type.
2405 llvm::Constant *GetAddrOfExternalRTTIDescriptor(QualType Ty);
2406
2407 /// BuildVTablePointer - Build the vtable pointer for the given type.
2408 void BuildVTablePointer(const Type *Ty);
2409
2410 /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
2411 /// inheritance, according to the Itanium C++ ABI, 2.9.5p6b.
2412 void BuildSIClassTypeInfo(const CXXRecordDecl *RD);
2413
2414 /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
2415 /// classes with bases that do not satisfy the abi::__si_class_type_info
2416 /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
2417 void BuildVMIClassTypeInfo(const CXXRecordDecl *RD);
2418
2419 /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct, used
2420 /// for pointer types.
2421 void BuildPointerTypeInfo(QualType PointeeTy);
2422
2423 /// BuildObjCObjectTypeInfo - Build the appropriate kind of
2424 /// type_info for an object type.
2425 void BuildObjCObjectTypeInfo(const ObjCObjectType *Ty);
2426
2427 /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
2428 /// struct, used for member pointer types.
2429 void BuildPointerToMemberTypeInfo(const MemberPointerType *Ty);
2430
2431public:
2432 ItaniumRTTIBuilder(const ItaniumCXXABI &ABI)
2433 : CGM(ABI.CGM), VMContext(CGM.getModule().getContext()), CXXABI(ABI) {}
2434
2435 // Pointer type info flags.
2436 enum {
2437 /// PTI_Const - Type has const qualifier.
2438 PTI_Const = 0x1,
2439
2440 /// PTI_Volatile - Type has volatile qualifier.
2441 PTI_Volatile = 0x2,
2442
2443 /// PTI_Restrict - Type has restrict qualifier.
2444 PTI_Restrict = 0x4,
2445
2446 /// PTI_Incomplete - Type is incomplete.
2447 PTI_Incomplete = 0x8,
2448
2449 /// PTI_ContainingClassIncomplete - Containing class is incomplete.
2450 /// (in pointer to member).
2451 PTI_ContainingClassIncomplete = 0x10
2452 };
2453
2454 // VMI type info flags.
2455 enum {
2456 /// VMI_NonDiamondRepeat - Class has non-diamond repeated inheritance.
2457 VMI_NonDiamondRepeat = 0x1,
2458
2459 /// VMI_DiamondShaped - Class is diamond shaped.
2460 VMI_DiamondShaped = 0x2
2461 };
2462
2463 // Base class type info flags.
2464 enum {
2465 /// BCTI_Virtual - Base class is virtual.
2466 BCTI_Virtual = 0x1,
2467
2468 /// BCTI_Public - Base class is public.
2469 BCTI_Public = 0x2
2470 };
2471
2472 /// BuildTypeInfo - Build the RTTI type info struct for the given type.
2473 ///
2474 /// \param Force - true to force the creation of this RTTI value
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00002475 /// \param DLLExport - true to mark the RTTI value as DLLExport
2476 llvm::Constant *BuildTypeInfo(QualType Ty, bool Force = false,
2477 bool DLLExport = false);
David Majnemere2cb8d12014-07-07 06:20:47 +00002478};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002479}
David Majnemere2cb8d12014-07-07 06:20:47 +00002480
2481llvm::GlobalVariable *ItaniumRTTIBuilder::GetAddrOfTypeName(
2482 QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage) {
Yaron Kerene46f7ed2015-07-29 14:21:47 +00002483 SmallString<256> Name;
2484 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00002485 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00002486
2487 // We know that the mangled name of the type starts at index 4 of the
2488 // mangled name of the typename, so we can just index into it in order to
2489 // get the mangled name of the type.
2490 llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,
2491 Name.substr(4));
2492
2493 llvm::GlobalVariable *GV =
2494 CGM.CreateOrReplaceCXXRuntimeVariable(Name, Init->getType(), Linkage);
2495
2496 GV->setInitializer(Init);
2497
2498 return GV;
2499}
2500
2501llvm::Constant *
2502ItaniumRTTIBuilder::GetAddrOfExternalRTTIDescriptor(QualType Ty) {
2503 // Mangle the RTTI name.
Yaron Kerene46f7ed2015-07-29 14:21:47 +00002504 SmallString<256> Name;
2505 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00002506 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00002507
2508 // Look for an existing global.
2509 llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name);
2510
2511 if (!GV) {
2512 // Create a new global variable.
2513 GV = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
2514 /*Constant=*/true,
2515 llvm::GlobalValue::ExternalLinkage, nullptr,
2516 Name);
David Majnemer1fb1a042014-11-07 07:26:38 +00002517 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2518 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
2519 if (RD->hasAttr<DLLImportAttr>())
2520 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
2521 }
David Majnemere2cb8d12014-07-07 06:20:47 +00002522 }
2523
2524 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
2525}
2526
2527/// TypeInfoIsInStandardLibrary - Given a builtin type, returns whether the type
2528/// info for that type is defined in the standard library.
2529static bool TypeInfoIsInStandardLibrary(const BuiltinType *Ty) {
2530 // Itanium C++ ABI 2.9.2:
2531 // Basic type information (e.g. for "int", "bool", etc.) will be kept in
2532 // the run-time support library. Specifically, the run-time support
2533 // library should contain type_info objects for the types X, X* and
2534 // X const*, for every X in: void, std::nullptr_t, bool, wchar_t, char,
2535 // unsigned char, signed char, short, unsigned short, int, unsigned int,
2536 // long, unsigned long, long long, unsigned long long, float, double,
2537 // long double, char16_t, char32_t, and the IEEE 754r decimal and
2538 // half-precision floating point types.
Richard Smith4a382012016-02-03 01:32:42 +00002539 //
2540 // GCC also emits RTTI for __int128.
2541 // FIXME: We do not emit RTTI information for decimal types here.
2542
2543 // Types added here must also be added to EmitFundamentalRTTIDescriptors.
David Majnemere2cb8d12014-07-07 06:20:47 +00002544 switch (Ty->getKind()) {
2545 case BuiltinType::Void:
2546 case BuiltinType::NullPtr:
2547 case BuiltinType::Bool:
2548 case BuiltinType::WChar_S:
2549 case BuiltinType::WChar_U:
2550 case BuiltinType::Char_U:
2551 case BuiltinType::Char_S:
2552 case BuiltinType::UChar:
2553 case BuiltinType::SChar:
2554 case BuiltinType::Short:
2555 case BuiltinType::UShort:
2556 case BuiltinType::Int:
2557 case BuiltinType::UInt:
2558 case BuiltinType::Long:
2559 case BuiltinType::ULong:
2560 case BuiltinType::LongLong:
2561 case BuiltinType::ULongLong:
2562 case BuiltinType::Half:
2563 case BuiltinType::Float:
2564 case BuiltinType::Double:
2565 case BuiltinType::LongDouble:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002566 case BuiltinType::Float128:
David Majnemere2cb8d12014-07-07 06:20:47 +00002567 case BuiltinType::Char16:
2568 case BuiltinType::Char32:
2569 case BuiltinType::Int128:
2570 case BuiltinType::UInt128:
Richard Smith4a382012016-02-03 01:32:42 +00002571 return true;
2572
Alexey Bader954ba212016-04-08 13:40:33 +00002573#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2574 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00002575#include "clang/Basic/OpenCLImageTypes.def"
David Majnemere2cb8d12014-07-07 06:20:47 +00002576 case BuiltinType::OCLSampler:
2577 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00002578 case BuiltinType::OCLClkEvent:
2579 case BuiltinType::OCLQueue:
2580 case BuiltinType::OCLNDRange:
2581 case BuiltinType::OCLReserveID:
Richard Smith4a382012016-02-03 01:32:42 +00002582 return false;
David Majnemere2cb8d12014-07-07 06:20:47 +00002583
2584 case BuiltinType::Dependent:
2585#define BUILTIN_TYPE(Id, SingletonId)
2586#define PLACEHOLDER_TYPE(Id, SingletonId) \
2587 case BuiltinType::Id:
2588#include "clang/AST/BuiltinTypes.def"
2589 llvm_unreachable("asking for RRTI for a placeholder type!");
2590
2591 case BuiltinType::ObjCId:
2592 case BuiltinType::ObjCClass:
2593 case BuiltinType::ObjCSel:
2594 llvm_unreachable("FIXME: Objective-C types are unsupported!");
2595 }
2596
2597 llvm_unreachable("Invalid BuiltinType Kind!");
2598}
2599
2600static bool TypeInfoIsInStandardLibrary(const PointerType *PointerTy) {
2601 QualType PointeeTy = PointerTy->getPointeeType();
2602 const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(PointeeTy);
2603 if (!BuiltinTy)
2604 return false;
2605
2606 // Check the qualifiers.
2607 Qualifiers Quals = PointeeTy.getQualifiers();
2608 Quals.removeConst();
2609
2610 if (!Quals.empty())
2611 return false;
2612
2613 return TypeInfoIsInStandardLibrary(BuiltinTy);
2614}
2615
2616/// IsStandardLibraryRTTIDescriptor - Returns whether the type
2617/// information for the given type exists in the standard library.
2618static bool IsStandardLibraryRTTIDescriptor(QualType Ty) {
2619 // Type info for builtin types is defined in the standard library.
2620 if (const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(Ty))
2621 return TypeInfoIsInStandardLibrary(BuiltinTy);
2622
2623 // Type info for some pointer types to builtin types is defined in the
2624 // standard library.
2625 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2626 return TypeInfoIsInStandardLibrary(PointerTy);
2627
2628 return false;
2629}
2630
2631/// ShouldUseExternalRTTIDescriptor - Returns whether the type information for
2632/// the given type exists somewhere else, and that we should not emit the type
2633/// information in this translation unit. Assumes that it is not a
2634/// standard-library type.
2635static bool ShouldUseExternalRTTIDescriptor(CodeGenModule &CGM,
2636 QualType Ty) {
2637 ASTContext &Context = CGM.getContext();
2638
2639 // If RTTI is disabled, assume it might be disabled in the
2640 // translation unit that defines any potential key function, too.
2641 if (!Context.getLangOpts().RTTI) return false;
2642
2643 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2644 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
2645 if (!RD->hasDefinition())
2646 return false;
2647
2648 if (!RD->isDynamicClass())
2649 return false;
2650
2651 // FIXME: this may need to be reconsidered if the key function
2652 // changes.
David Majnemerbe9022c2015-08-06 20:56:55 +00002653 // N.B. We must always emit the RTTI data ourselves if there exists a key
2654 // function.
2655 bool IsDLLImport = RD->hasAttr<DLLImportAttr>();
David Majnemer1fb1a042014-11-07 07:26:38 +00002656 if (CGM.getVTables().isVTableExternal(RD))
David Majnemerbe9022c2015-08-06 20:56:55 +00002657 return IsDLLImport ? false : true;
David Majnemer1fb1a042014-11-07 07:26:38 +00002658
David Majnemerbe9022c2015-08-06 20:56:55 +00002659 if (IsDLLImport)
David Majnemer1fb1a042014-11-07 07:26:38 +00002660 return true;
David Majnemere2cb8d12014-07-07 06:20:47 +00002661 }
2662
2663 return false;
2664}
2665
2666/// IsIncompleteClassType - Returns whether the given record type is incomplete.
2667static bool IsIncompleteClassType(const RecordType *RecordTy) {
2668 return !RecordTy->getDecl()->isCompleteDefinition();
2669}
2670
2671/// ContainsIncompleteClassType - Returns whether the given type contains an
2672/// incomplete class type. This is true if
2673///
2674/// * The given type is an incomplete class type.
2675/// * The given type is a pointer type whose pointee type contains an
2676/// incomplete class type.
2677/// * The given type is a member pointer type whose class is an incomplete
2678/// class type.
2679/// * The given type is a member pointer type whoise pointee type contains an
2680/// incomplete class type.
2681/// is an indirect or direct pointer to an incomplete class type.
2682static bool ContainsIncompleteClassType(QualType Ty) {
2683 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2684 if (IsIncompleteClassType(RecordTy))
2685 return true;
2686 }
2687
2688 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2689 return ContainsIncompleteClassType(PointerTy->getPointeeType());
2690
2691 if (const MemberPointerType *MemberPointerTy =
2692 dyn_cast<MemberPointerType>(Ty)) {
2693 // Check if the class type is incomplete.
2694 const RecordType *ClassType = cast<RecordType>(MemberPointerTy->getClass());
2695 if (IsIncompleteClassType(ClassType))
2696 return true;
2697
2698 return ContainsIncompleteClassType(MemberPointerTy->getPointeeType());
2699 }
2700
2701 return false;
2702}
2703
2704// CanUseSingleInheritance - Return whether the given record decl has a "single,
2705// public, non-virtual base at offset zero (i.e. the derived class is dynamic
2706// iff the base is)", according to Itanium C++ ABI, 2.95p6b.
2707static bool CanUseSingleInheritance(const CXXRecordDecl *RD) {
2708 // Check the number of bases.
2709 if (RD->getNumBases() != 1)
2710 return false;
2711
2712 // Get the base.
2713 CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin();
2714
2715 // Check that the base is not virtual.
2716 if (Base->isVirtual())
2717 return false;
2718
2719 // Check that the base is public.
2720 if (Base->getAccessSpecifier() != AS_public)
2721 return false;
2722
2723 // Check that the class is dynamic iff the base is.
2724 const CXXRecordDecl *BaseDecl =
2725 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2726 if (!BaseDecl->isEmpty() &&
2727 BaseDecl->isDynamicClass() != RD->isDynamicClass())
2728 return false;
2729
2730 return true;
2731}
2732
2733void ItaniumRTTIBuilder::BuildVTablePointer(const Type *Ty) {
2734 // abi::__class_type_info.
2735 static const char * const ClassTypeInfo =
2736 "_ZTVN10__cxxabiv117__class_type_infoE";
2737 // abi::__si_class_type_info.
2738 static const char * const SIClassTypeInfo =
2739 "_ZTVN10__cxxabiv120__si_class_type_infoE";
2740 // abi::__vmi_class_type_info.
2741 static const char * const VMIClassTypeInfo =
2742 "_ZTVN10__cxxabiv121__vmi_class_type_infoE";
2743
2744 const char *VTableName = nullptr;
2745
2746 switch (Ty->getTypeClass()) {
2747#define TYPE(Class, Base)
2748#define ABSTRACT_TYPE(Class, Base)
2749#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2750#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2751#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2752#include "clang/AST/TypeNodes.def"
2753 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
2754
2755 case Type::LValueReference:
2756 case Type::RValueReference:
2757 llvm_unreachable("References shouldn't get here");
2758
2759 case Type::Auto:
2760 llvm_unreachable("Undeduced auto type shouldn't get here");
2761
Xiuli Pan9c14e282016-01-09 12:53:17 +00002762 case Type::Pipe:
2763 llvm_unreachable("Pipe types shouldn't get here");
2764
David Majnemere2cb8d12014-07-07 06:20:47 +00002765 case Type::Builtin:
2766 // GCC treats vector and complex types as fundamental types.
2767 case Type::Vector:
2768 case Type::ExtVector:
2769 case Type::Complex:
2770 case Type::Atomic:
2771 // FIXME: GCC treats block pointers as fundamental types?!
2772 case Type::BlockPointer:
2773 // abi::__fundamental_type_info.
2774 VTableName = "_ZTVN10__cxxabiv123__fundamental_type_infoE";
2775 break;
2776
2777 case Type::ConstantArray:
2778 case Type::IncompleteArray:
2779 case Type::VariableArray:
2780 // abi::__array_type_info.
2781 VTableName = "_ZTVN10__cxxabiv117__array_type_infoE";
2782 break;
2783
2784 case Type::FunctionNoProto:
2785 case Type::FunctionProto:
2786 // abi::__function_type_info.
2787 VTableName = "_ZTVN10__cxxabiv120__function_type_infoE";
2788 break;
2789
2790 case Type::Enum:
2791 // abi::__enum_type_info.
2792 VTableName = "_ZTVN10__cxxabiv116__enum_type_infoE";
2793 break;
2794
2795 case Type::Record: {
2796 const CXXRecordDecl *RD =
2797 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
2798
2799 if (!RD->hasDefinition() || !RD->getNumBases()) {
2800 VTableName = ClassTypeInfo;
2801 } else if (CanUseSingleInheritance(RD)) {
2802 VTableName = SIClassTypeInfo;
2803 } else {
2804 VTableName = VMIClassTypeInfo;
2805 }
2806
2807 break;
2808 }
2809
2810 case Type::ObjCObject:
2811 // Ignore protocol qualifiers.
2812 Ty = cast<ObjCObjectType>(Ty)->getBaseType().getTypePtr();
2813
2814 // Handle id and Class.
2815 if (isa<BuiltinType>(Ty)) {
2816 VTableName = ClassTypeInfo;
2817 break;
2818 }
2819
2820 assert(isa<ObjCInterfaceType>(Ty));
2821 // Fall through.
2822
2823 case Type::ObjCInterface:
2824 if (cast<ObjCInterfaceType>(Ty)->getDecl()->getSuperClass()) {
2825 VTableName = SIClassTypeInfo;
2826 } else {
2827 VTableName = ClassTypeInfo;
2828 }
2829 break;
2830
2831 case Type::ObjCObjectPointer:
2832 case Type::Pointer:
2833 // abi::__pointer_type_info.
2834 VTableName = "_ZTVN10__cxxabiv119__pointer_type_infoE";
2835 break;
2836
2837 case Type::MemberPointer:
2838 // abi::__pointer_to_member_type_info.
2839 VTableName = "_ZTVN10__cxxabiv129__pointer_to_member_type_infoE";
2840 break;
2841 }
2842
2843 llvm::Constant *VTable =
2844 CGM.getModule().getOrInsertGlobal(VTableName, CGM.Int8PtrTy);
2845
2846 llvm::Type *PtrDiffTy =
2847 CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
2848
2849 // The vtable address point is 2.
2850 llvm::Constant *Two = llvm::ConstantInt::get(PtrDiffTy, 2);
David Blaikiee3b172a2015-04-02 18:55:21 +00002851 VTable =
2852 llvm::ConstantExpr::getInBoundsGetElementPtr(CGM.Int8PtrTy, VTable, Two);
David Majnemere2cb8d12014-07-07 06:20:47 +00002853 VTable = llvm::ConstantExpr::getBitCast(VTable, CGM.Int8PtrTy);
2854
2855 Fields.push_back(VTable);
2856}
2857
2858/// \brief Return the linkage that the type info and type info name constants
2859/// should have for the given type.
2860static llvm::GlobalVariable::LinkageTypes getTypeInfoLinkage(CodeGenModule &CGM,
2861 QualType Ty) {
2862 // Itanium C++ ABI 2.9.5p7:
2863 // In addition, it and all of the intermediate abi::__pointer_type_info
2864 // structs in the chain down to the abi::__class_type_info for the
2865 // incomplete class type must be prevented from resolving to the
2866 // corresponding type_info structs for the complete class type, possibly
2867 // by making them local static objects. Finally, a dummy class RTTI is
2868 // generated for the incomplete type that will not resolve to the final
2869 // complete class RTTI (because the latter need not exist), possibly by
2870 // making it a local static object.
2871 if (ContainsIncompleteClassType(Ty))
2872 return llvm::GlobalValue::InternalLinkage;
2873
2874 switch (Ty->getLinkage()) {
2875 case NoLinkage:
2876 case InternalLinkage:
2877 case UniqueExternalLinkage:
2878 return llvm::GlobalValue::InternalLinkage;
2879
2880 case VisibleNoLinkage:
2881 case ExternalLinkage:
2882 if (!CGM.getLangOpts().RTTI) {
2883 // RTTI is not enabled, which means that this type info struct is going
2884 // to be used for exception handling. Give it linkonce_odr linkage.
2885 return llvm::GlobalValue::LinkOnceODRLinkage;
2886 }
2887
2888 if (const RecordType *Record = dyn_cast<RecordType>(Ty)) {
2889 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2890 if (RD->hasAttr<WeakAttr>())
2891 return llvm::GlobalValue::WeakODRLinkage;
David Majnemerbe9022c2015-08-06 20:56:55 +00002892 if (RD->isDynamicClass()) {
2893 llvm::GlobalValue::LinkageTypes LT = CGM.getVTableLinkage(RD);
2894 // MinGW won't export the RTTI information when there is a key function.
2895 // Make sure we emit our own copy instead of attempting to dllimport it.
2896 if (RD->hasAttr<DLLImportAttr>() &&
2897 llvm::GlobalValue::isAvailableExternallyLinkage(LT))
2898 LT = llvm::GlobalValue::LinkOnceODRLinkage;
2899 return LT;
2900 }
David Majnemere2cb8d12014-07-07 06:20:47 +00002901 }
2902
2903 return llvm::GlobalValue::LinkOnceODRLinkage;
2904 }
2905
2906 llvm_unreachable("Invalid linkage!");
2907}
2908
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00002909llvm::Constant *ItaniumRTTIBuilder::BuildTypeInfo(QualType Ty, bool Force,
2910 bool DLLExport) {
David Majnemere2cb8d12014-07-07 06:20:47 +00002911 // We want to operate on the canonical type.
Yaron Kerenebd14262016-03-16 12:14:43 +00002912 Ty = Ty.getCanonicalType();
David Majnemere2cb8d12014-07-07 06:20:47 +00002913
2914 // Check if we've already emitted an RTTI descriptor for this type.
Yaron Kerene46f7ed2015-07-29 14:21:47 +00002915 SmallString<256> Name;
2916 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00002917 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00002918
2919 llvm::GlobalVariable *OldGV = CGM.getModule().getNamedGlobal(Name);
2920 if (OldGV && !OldGV->isDeclaration()) {
2921 assert(!OldGV->hasAvailableExternallyLinkage() &&
2922 "available_externally typeinfos not yet implemented");
2923
2924 return llvm::ConstantExpr::getBitCast(OldGV, CGM.Int8PtrTy);
2925 }
2926
2927 // Check if there is already an external RTTI descriptor for this type.
2928 bool IsStdLib = IsStandardLibraryRTTIDescriptor(Ty);
2929 if (!Force && (IsStdLib || ShouldUseExternalRTTIDescriptor(CGM, Ty)))
2930 return GetAddrOfExternalRTTIDescriptor(Ty);
2931
2932 // Emit the standard library with external linkage.
2933 llvm::GlobalVariable::LinkageTypes Linkage;
2934 if (IsStdLib)
2935 Linkage = llvm::GlobalValue::ExternalLinkage;
2936 else
2937 Linkage = getTypeInfoLinkage(CGM, Ty);
2938
2939 // Add the vtable pointer.
2940 BuildVTablePointer(cast<Type>(Ty));
2941
2942 // And the name.
2943 llvm::GlobalVariable *TypeName = GetAddrOfTypeName(Ty, Linkage);
2944 llvm::Constant *TypeNameField;
2945
2946 // If we're supposed to demote the visibility, be sure to set a flag
2947 // to use a string comparison for type_info comparisons.
2948 ItaniumCXXABI::RTTIUniquenessKind RTTIUniqueness =
2949 CXXABI.classifyRTTIUniqueness(Ty, Linkage);
2950 if (RTTIUniqueness != ItaniumCXXABI::RUK_Unique) {
2951 // The flag is the sign bit, which on ARM64 is defined to be clear
2952 // for global pointers. This is very ARM64-specific.
2953 TypeNameField = llvm::ConstantExpr::getPtrToInt(TypeName, CGM.Int64Ty);
2954 llvm::Constant *flag =
2955 llvm::ConstantInt::get(CGM.Int64Ty, ((uint64_t)1) << 63);
2956 TypeNameField = llvm::ConstantExpr::getAdd(TypeNameField, flag);
2957 TypeNameField =
2958 llvm::ConstantExpr::getIntToPtr(TypeNameField, CGM.Int8PtrTy);
2959 } else {
2960 TypeNameField = llvm::ConstantExpr::getBitCast(TypeName, CGM.Int8PtrTy);
2961 }
2962 Fields.push_back(TypeNameField);
2963
2964 switch (Ty->getTypeClass()) {
2965#define TYPE(Class, Base)
2966#define ABSTRACT_TYPE(Class, Base)
2967#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2968#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2969#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2970#include "clang/AST/TypeNodes.def"
2971 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
2972
2973 // GCC treats vector types as fundamental types.
2974 case Type::Builtin:
2975 case Type::Vector:
2976 case Type::ExtVector:
2977 case Type::Complex:
2978 case Type::BlockPointer:
2979 // Itanium C++ ABI 2.9.5p4:
2980 // abi::__fundamental_type_info adds no data members to std::type_info.
2981 break;
2982
2983 case Type::LValueReference:
2984 case Type::RValueReference:
2985 llvm_unreachable("References shouldn't get here");
2986
2987 case Type::Auto:
2988 llvm_unreachable("Undeduced auto type shouldn't get here");
2989
Xiuli Pan9c14e282016-01-09 12:53:17 +00002990 case Type::Pipe:
2991 llvm_unreachable("Pipe type shouldn't get here");
2992
David Majnemere2cb8d12014-07-07 06:20:47 +00002993 case Type::ConstantArray:
2994 case Type::IncompleteArray:
2995 case Type::VariableArray:
2996 // Itanium C++ ABI 2.9.5p5:
2997 // abi::__array_type_info adds no data members to std::type_info.
2998 break;
2999
3000 case Type::FunctionNoProto:
3001 case Type::FunctionProto:
3002 // Itanium C++ ABI 2.9.5p5:
3003 // abi::__function_type_info adds no data members to std::type_info.
3004 break;
3005
3006 case Type::Enum:
3007 // Itanium C++ ABI 2.9.5p5:
3008 // abi::__enum_type_info adds no data members to std::type_info.
3009 break;
3010
3011 case Type::Record: {
3012 const CXXRecordDecl *RD =
3013 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
3014 if (!RD->hasDefinition() || !RD->getNumBases()) {
3015 // We don't need to emit any fields.
3016 break;
3017 }
3018
3019 if (CanUseSingleInheritance(RD))
3020 BuildSIClassTypeInfo(RD);
3021 else
3022 BuildVMIClassTypeInfo(RD);
3023
3024 break;
3025 }
3026
3027 case Type::ObjCObject:
3028 case Type::ObjCInterface:
3029 BuildObjCObjectTypeInfo(cast<ObjCObjectType>(Ty));
3030 break;
3031
3032 case Type::ObjCObjectPointer:
3033 BuildPointerTypeInfo(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
3034 break;
3035
3036 case Type::Pointer:
3037 BuildPointerTypeInfo(cast<PointerType>(Ty)->getPointeeType());
3038 break;
3039
3040 case Type::MemberPointer:
3041 BuildPointerToMemberTypeInfo(cast<MemberPointerType>(Ty));
3042 break;
3043
3044 case Type::Atomic:
3045 // No fields, at least for the moment.
3046 break;
3047 }
3048
3049 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Fields);
3050
Rafael Espindolacb92c192015-01-15 23:18:01 +00003051 llvm::Module &M = CGM.getModule();
David Majnemere2cb8d12014-07-07 06:20:47 +00003052 llvm::GlobalVariable *GV =
Rafael Espindolacb92c192015-01-15 23:18:01 +00003053 new llvm::GlobalVariable(M, Init->getType(),
3054 /*Constant=*/true, Linkage, Init, Name);
3055
David Majnemere2cb8d12014-07-07 06:20:47 +00003056 // If there's already an old global variable, replace it with the new one.
3057 if (OldGV) {
3058 GV->takeName(OldGV);
3059 llvm::Constant *NewPtr =
3060 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
3061 OldGV->replaceAllUsesWith(NewPtr);
3062 OldGV->eraseFromParent();
3063 }
3064
Yaron Keren04da2382015-07-29 15:42:28 +00003065 if (CGM.supportsCOMDAT() && GV->isWeakForLinker())
3066 GV->setComdat(M.getOrInsertComdat(GV->getName()));
3067
David Majnemere2cb8d12014-07-07 06:20:47 +00003068 // The Itanium ABI specifies that type_info objects must be globally
3069 // unique, with one exception: if the type is an incomplete class
3070 // type or a (possibly indirect) pointer to one. That exception
3071 // affects the general case of comparing type_info objects produced
3072 // by the typeid operator, which is why the comparison operators on
3073 // std::type_info generally use the type_info name pointers instead
3074 // of the object addresses. However, the language's built-in uses
3075 // of RTTI generally require class types to be complete, even when
3076 // manipulating pointers to those class types. This allows the
3077 // implementation of dynamic_cast to rely on address equality tests,
3078 // which is much faster.
3079
3080 // All of this is to say that it's important that both the type_info
3081 // object and the type_info name be uniqued when weakly emitted.
3082
3083 // Give the type_info object and name the formal visibility of the
3084 // type itself.
3085 llvm::GlobalValue::VisibilityTypes llvmVisibility;
3086 if (llvm::GlobalValue::isLocalLinkage(Linkage))
3087 // If the linkage is local, only default visibility makes sense.
3088 llvmVisibility = llvm::GlobalValue::DefaultVisibility;
3089 else if (RTTIUniqueness == ItaniumCXXABI::RUK_NonUniqueHidden)
3090 llvmVisibility = llvm::GlobalValue::HiddenVisibility;
3091 else
3092 llvmVisibility = CodeGenModule::GetLLVMVisibility(Ty->getVisibility());
3093 TypeName->setVisibility(llvmVisibility);
3094 GV->setVisibility(llvmVisibility);
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00003095 if (DLLExport)
3096 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
David Majnemere2cb8d12014-07-07 06:20:47 +00003097
3098 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
3099}
3100
3101/// ComputeQualifierFlags - Compute the pointer type info flags from the
3102/// given qualifier.
3103static unsigned ComputeQualifierFlags(Qualifiers Quals) {
3104 unsigned Flags = 0;
3105
3106 if (Quals.hasConst())
3107 Flags |= ItaniumRTTIBuilder::PTI_Const;
3108 if (Quals.hasVolatile())
3109 Flags |= ItaniumRTTIBuilder::PTI_Volatile;
3110 if (Quals.hasRestrict())
3111 Flags |= ItaniumRTTIBuilder::PTI_Restrict;
3112
3113 return Flags;
3114}
3115
3116/// BuildObjCObjectTypeInfo - Build the appropriate kind of type_info
3117/// for the given Objective-C object type.
3118void ItaniumRTTIBuilder::BuildObjCObjectTypeInfo(const ObjCObjectType *OT) {
3119 // Drop qualifiers.
3120 const Type *T = OT->getBaseType().getTypePtr();
3121 assert(isa<BuiltinType>(T) || isa<ObjCInterfaceType>(T));
3122
3123 // The builtin types are abi::__class_type_infos and don't require
3124 // extra fields.
3125 if (isa<BuiltinType>(T)) return;
3126
3127 ObjCInterfaceDecl *Class = cast<ObjCInterfaceType>(T)->getDecl();
3128 ObjCInterfaceDecl *Super = Class->getSuperClass();
3129
3130 // Root classes are also __class_type_info.
3131 if (!Super) return;
3132
3133 QualType SuperTy = CGM.getContext().getObjCInterfaceType(Super);
3134
3135 // Everything else is single inheritance.
3136 llvm::Constant *BaseTypeInfo =
3137 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(SuperTy);
3138 Fields.push_back(BaseTypeInfo);
3139}
3140
3141/// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
3142/// inheritance, according to the Itanium C++ ABI, 2.95p6b.
3143void ItaniumRTTIBuilder::BuildSIClassTypeInfo(const CXXRecordDecl *RD) {
3144 // Itanium C++ ABI 2.9.5p6b:
3145 // It adds to abi::__class_type_info a single member pointing to the
3146 // type_info structure for the base type,
3147 llvm::Constant *BaseTypeInfo =
3148 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(RD->bases_begin()->getType());
3149 Fields.push_back(BaseTypeInfo);
3150}
3151
3152namespace {
3153 /// SeenBases - Contains virtual and non-virtual bases seen when traversing
3154 /// a class hierarchy.
3155 struct SeenBases {
3156 llvm::SmallPtrSet<const CXXRecordDecl *, 16> NonVirtualBases;
3157 llvm::SmallPtrSet<const CXXRecordDecl *, 16> VirtualBases;
3158 };
3159}
3160
3161/// ComputeVMIClassTypeInfoFlags - Compute the value of the flags member in
3162/// abi::__vmi_class_type_info.
3163///
3164static unsigned ComputeVMIClassTypeInfoFlags(const CXXBaseSpecifier *Base,
3165 SeenBases &Bases) {
3166
3167 unsigned Flags = 0;
3168
3169 const CXXRecordDecl *BaseDecl =
3170 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
3171
3172 if (Base->isVirtual()) {
3173 // Mark the virtual base as seen.
David Blaikie82e95a32014-11-19 07:49:47 +00003174 if (!Bases.VirtualBases.insert(BaseDecl).second) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003175 // If this virtual base has been seen before, then the class is diamond
3176 // shaped.
3177 Flags |= ItaniumRTTIBuilder::VMI_DiamondShaped;
3178 } else {
3179 if (Bases.NonVirtualBases.count(BaseDecl))
3180 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3181 }
3182 } else {
3183 // Mark the non-virtual base as seen.
David Blaikie82e95a32014-11-19 07:49:47 +00003184 if (!Bases.NonVirtualBases.insert(BaseDecl).second) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003185 // If this non-virtual base has been seen before, then the class has non-
3186 // diamond shaped repeated inheritance.
3187 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3188 } else {
3189 if (Bases.VirtualBases.count(BaseDecl))
3190 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3191 }
3192 }
3193
3194 // Walk all bases.
3195 for (const auto &I : BaseDecl->bases())
3196 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
3197
3198 return Flags;
3199}
3200
3201static unsigned ComputeVMIClassTypeInfoFlags(const CXXRecordDecl *RD) {
3202 unsigned Flags = 0;
3203 SeenBases Bases;
3204
3205 // Walk all bases.
3206 for (const auto &I : RD->bases())
3207 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
3208
3209 return Flags;
3210}
3211
3212/// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
3213/// classes with bases that do not satisfy the abi::__si_class_type_info
3214/// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
3215void ItaniumRTTIBuilder::BuildVMIClassTypeInfo(const CXXRecordDecl *RD) {
3216 llvm::Type *UnsignedIntLTy =
3217 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3218
3219 // Itanium C++ ABI 2.9.5p6c:
3220 // __flags is a word with flags describing details about the class
3221 // structure, which may be referenced by using the __flags_masks
3222 // enumeration. These flags refer to both direct and indirect bases.
3223 unsigned Flags = ComputeVMIClassTypeInfoFlags(RD);
3224 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3225
3226 // Itanium C++ ABI 2.9.5p6c:
3227 // __base_count is a word with the number of direct proper base class
3228 // descriptions that follow.
3229 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, RD->getNumBases()));
3230
3231 if (!RD->getNumBases())
3232 return;
3233
David Majnemere2cb8d12014-07-07 06:20:47 +00003234 // Now add the base class descriptions.
3235
3236 // Itanium C++ ABI 2.9.5p6c:
3237 // __base_info[] is an array of base class descriptions -- one for every
3238 // direct proper base. Each description is of the type:
3239 //
3240 // struct abi::__base_class_type_info {
3241 // public:
3242 // const __class_type_info *__base_type;
3243 // long __offset_flags;
3244 //
3245 // enum __offset_flags_masks {
3246 // __virtual_mask = 0x1,
3247 // __public_mask = 0x2,
3248 // __offset_shift = 8
3249 // };
3250 // };
Reid Klecknerd8b04662016-08-25 22:16:30 +00003251
3252 // If we're in mingw and 'long' isn't wide enough for a pointer, use 'long
3253 // long' instead of 'long' for __offset_flags. libstdc++abi uses long long on
3254 // LLP64 platforms.
3255 // FIXME: Consider updating libc++abi to match, and extend this logic to all
3256 // LLP64 platforms.
3257 QualType OffsetFlagsTy = CGM.getContext().LongTy;
3258 const TargetInfo &TI = CGM.getContext().getTargetInfo();
3259 if (TI.getTriple().isOSCygMing() && TI.getPointerWidth(0) > TI.getLongWidth())
3260 OffsetFlagsTy = CGM.getContext().LongLongTy;
3261 llvm::Type *OffsetFlagsLTy =
3262 CGM.getTypes().ConvertType(OffsetFlagsTy);
3263
David Majnemere2cb8d12014-07-07 06:20:47 +00003264 for (const auto &Base : RD->bases()) {
3265 // The __base_type member points to the RTTI for the base type.
3266 Fields.push_back(ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(Base.getType()));
3267
3268 const CXXRecordDecl *BaseDecl =
3269 cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
3270
3271 int64_t OffsetFlags = 0;
3272
3273 // All but the lower 8 bits of __offset_flags are a signed offset.
3274 // For a non-virtual base, this is the offset in the object of the base
3275 // subobject. For a virtual base, this is the offset in the virtual table of
3276 // the virtual base offset for the virtual base referenced (negative).
3277 CharUnits Offset;
3278 if (Base.isVirtual())
3279 Offset =
3280 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(RD, BaseDecl);
3281 else {
3282 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
3283 Offset = Layout.getBaseClassOffset(BaseDecl);
3284 };
3285
3286 OffsetFlags = uint64_t(Offset.getQuantity()) << 8;
3287
3288 // The low-order byte of __offset_flags contains flags, as given by the
3289 // masks from the enumeration __offset_flags_masks.
3290 if (Base.isVirtual())
3291 OffsetFlags |= BCTI_Virtual;
3292 if (Base.getAccessSpecifier() == AS_public)
3293 OffsetFlags |= BCTI_Public;
3294
Reid Klecknerd8b04662016-08-25 22:16:30 +00003295 Fields.push_back(llvm::ConstantInt::get(OffsetFlagsLTy, OffsetFlags));
David Majnemere2cb8d12014-07-07 06:20:47 +00003296 }
3297}
3298
3299/// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct,
3300/// used for pointer types.
3301void ItaniumRTTIBuilder::BuildPointerTypeInfo(QualType PointeeTy) {
3302 Qualifiers Quals;
3303 QualType UnqualifiedPointeeTy =
3304 CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals);
3305
3306 // Itanium C++ ABI 2.9.5p7:
3307 // __flags is a flag word describing the cv-qualification and other
3308 // attributes of the type pointed to
3309 unsigned Flags = ComputeQualifierFlags(Quals);
3310
3311 // Itanium C++ ABI 2.9.5p7:
3312 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
3313 // incomplete class type, the incomplete target type flag is set.
3314 if (ContainsIncompleteClassType(UnqualifiedPointeeTy))
3315 Flags |= PTI_Incomplete;
3316
3317 llvm::Type *UnsignedIntLTy =
3318 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3319 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3320
3321 // Itanium C++ ABI 2.9.5p7:
3322 // __pointee is a pointer to the std::type_info derivation for the
3323 // unqualified type being pointed to.
3324 llvm::Constant *PointeeTypeInfo =
3325 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(UnqualifiedPointeeTy);
3326 Fields.push_back(PointeeTypeInfo);
3327}
3328
3329/// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
3330/// struct, used for member pointer types.
3331void
3332ItaniumRTTIBuilder::BuildPointerToMemberTypeInfo(const MemberPointerType *Ty) {
3333 QualType PointeeTy = Ty->getPointeeType();
3334
3335 Qualifiers Quals;
3336 QualType UnqualifiedPointeeTy =
3337 CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals);
3338
3339 // Itanium C++ ABI 2.9.5p7:
3340 // __flags is a flag word describing the cv-qualification and other
3341 // attributes of the type pointed to.
3342 unsigned Flags = ComputeQualifierFlags(Quals);
3343
3344 const RecordType *ClassType = cast<RecordType>(Ty->getClass());
3345
3346 // Itanium C++ ABI 2.9.5p7:
3347 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
3348 // incomplete class type, the incomplete target type flag is set.
3349 if (ContainsIncompleteClassType(UnqualifiedPointeeTy))
3350 Flags |= PTI_Incomplete;
3351
3352 if (IsIncompleteClassType(ClassType))
3353 Flags |= PTI_ContainingClassIncomplete;
3354
3355 llvm::Type *UnsignedIntLTy =
3356 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3357 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3358
3359 // Itanium C++ ABI 2.9.5p7:
3360 // __pointee is a pointer to the std::type_info derivation for the
3361 // unqualified type being pointed to.
3362 llvm::Constant *PointeeTypeInfo =
3363 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(UnqualifiedPointeeTy);
3364 Fields.push_back(PointeeTypeInfo);
3365
3366 // Itanium C++ ABI 2.9.5p9:
3367 // __context is a pointer to an abi::__class_type_info corresponding to the
3368 // class type containing the member pointed to
3369 // (e.g., the "A" in "int A::*").
3370 Fields.push_back(
3371 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(QualType(ClassType, 0)));
3372}
3373
David Majnemer443250f2015-03-17 20:35:00 +00003374llvm::Constant *ItaniumCXXABI::getAddrOfRTTIDescriptor(QualType Ty) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003375 return ItaniumRTTIBuilder(*this).BuildTypeInfo(Ty);
3376}
3377
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00003378void ItaniumCXXABI::EmitFundamentalRTTIDescriptor(QualType Type,
3379 bool DLLExport) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003380 QualType PointerType = getContext().getPointerType(Type);
3381 QualType PointerTypeConst = getContext().getPointerType(Type.withConst());
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00003382 ItaniumRTTIBuilder(*this).BuildTypeInfo(Type, /*Force=*/true, DLLExport);
3383 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerType, /*Force=*/true,
3384 DLLExport);
3385 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerTypeConst, /*Force=*/true,
3386 DLLExport);
David Majnemere2cb8d12014-07-07 06:20:47 +00003387}
3388
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00003389void ItaniumCXXABI::EmitFundamentalRTTIDescriptors(bool DLLExport) {
Richard Smith4a382012016-02-03 01:32:42 +00003390 // Types added here must also be added to TypeInfoIsInStandardLibrary.
David Majnemere2cb8d12014-07-07 06:20:47 +00003391 QualType FundamentalTypes[] = {
3392 getContext().VoidTy, getContext().NullPtrTy,
3393 getContext().BoolTy, getContext().WCharTy,
3394 getContext().CharTy, getContext().UnsignedCharTy,
3395 getContext().SignedCharTy, getContext().ShortTy,
3396 getContext().UnsignedShortTy, getContext().IntTy,
3397 getContext().UnsignedIntTy, getContext().LongTy,
3398 getContext().UnsignedLongTy, getContext().LongLongTy,
Richard Smith4a382012016-02-03 01:32:42 +00003399 getContext().UnsignedLongLongTy, getContext().Int128Ty,
3400 getContext().UnsignedInt128Ty, getContext().HalfTy,
David Majnemere2cb8d12014-07-07 06:20:47 +00003401 getContext().FloatTy, getContext().DoubleTy,
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00003402 getContext().LongDoubleTy, getContext().Float128Ty,
3403 getContext().Char16Ty, getContext().Char32Ty
David Majnemere2cb8d12014-07-07 06:20:47 +00003404 };
3405 for (const QualType &FundamentalType : FundamentalTypes)
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00003406 EmitFundamentalRTTIDescriptor(FundamentalType, DLLExport);
David Majnemere2cb8d12014-07-07 06:20:47 +00003407}
3408
3409/// What sort of uniqueness rules should we use for the RTTI for the
3410/// given type?
3411ItaniumCXXABI::RTTIUniquenessKind ItaniumCXXABI::classifyRTTIUniqueness(
3412 QualType CanTy, llvm::GlobalValue::LinkageTypes Linkage) const {
3413 if (shouldRTTIBeUnique())
3414 return RUK_Unique;
3415
3416 // It's only necessary for linkonce_odr or weak_odr linkage.
3417 if (Linkage != llvm::GlobalValue::LinkOnceODRLinkage &&
3418 Linkage != llvm::GlobalValue::WeakODRLinkage)
3419 return RUK_Unique;
3420
3421 // It's only necessary with default visibility.
3422 if (CanTy->getVisibility() != DefaultVisibility)
3423 return RUK_Unique;
3424
3425 // If we're not required to publish this symbol, hide it.
3426 if (Linkage == llvm::GlobalValue::LinkOnceODRLinkage)
3427 return RUK_NonUniqueHidden;
3428
3429 // If we're required to publish this symbol, as we might be under an
3430 // explicit instantiation, leave it with default visibility but
3431 // enable string-comparisons.
3432 assert(Linkage == llvm::GlobalValue::WeakODRLinkage);
3433 return RUK_NonUniqueVisible;
3434}
Rafael Espindola91f68b42014-09-15 19:20:10 +00003435
Rafael Espindola1e4df922014-09-16 15:18:21 +00003436// Find out how to codegen the complete destructor and constructor
3437namespace {
3438enum class StructorCodegen { Emit, RAUW, Alias, COMDAT };
3439}
3440static StructorCodegen getCodegenToUse(CodeGenModule &CGM,
3441 const CXXMethodDecl *MD) {
3442 if (!CGM.getCodeGenOpts().CXXCtorDtorAliases)
3443 return StructorCodegen::Emit;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003444
Rafael Espindola1e4df922014-09-16 15:18:21 +00003445 // The complete and base structors are not equivalent if there are any virtual
3446 // bases, so emit separate functions.
3447 if (MD->getParent()->getNumVBases())
3448 return StructorCodegen::Emit;
3449
3450 GlobalDecl AliasDecl;
3451 if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) {
3452 AliasDecl = GlobalDecl(DD, Dtor_Complete);
3453 } else {
3454 const auto *CD = cast<CXXConstructorDecl>(MD);
3455 AliasDecl = GlobalDecl(CD, Ctor_Complete);
3456 }
3457 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3458
3459 if (llvm::GlobalValue::isDiscardableIfUnused(Linkage))
3460 return StructorCodegen::RAUW;
3461
3462 // FIXME: Should we allow available_externally aliases?
3463 if (!llvm::GlobalAlias::isValidLinkage(Linkage))
3464 return StructorCodegen::RAUW;
3465
Rafael Espindola0806f982014-09-16 20:19:43 +00003466 if (llvm::GlobalValue::isWeakForLinker(Linkage)) {
3467 // Only ELF supports COMDATs with arbitrary names (C5/D5).
3468 if (CGM.getTarget().getTriple().isOSBinFormatELF())
3469 return StructorCodegen::COMDAT;
3470 return StructorCodegen::Emit;
3471 }
Rafael Espindola1e4df922014-09-16 15:18:21 +00003472
3473 return StructorCodegen::Alias;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003474}
3475
Rafael Espindola1e4df922014-09-16 15:18:21 +00003476static void emitConstructorDestructorAlias(CodeGenModule &CGM,
3477 GlobalDecl AliasDecl,
3478 GlobalDecl TargetDecl) {
3479 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3480
3481 StringRef MangledName = CGM.getMangledName(AliasDecl);
3482 llvm::GlobalValue *Entry = CGM.GetGlobalValue(MangledName);
3483 if (Entry && !Entry->isDeclaration())
3484 return;
3485
3486 auto *Aliasee = cast<llvm::GlobalValue>(CGM.GetAddrOfGlobal(TargetDecl));
Rafael Espindola1e4df922014-09-16 15:18:21 +00003487
3488 // Create the alias with no name.
David Blaikie2a791d72015-09-14 18:38:22 +00003489 auto *Alias = llvm::GlobalAlias::create(Linkage, "", Aliasee);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003490
3491 // Switch any previous uses to the alias.
3492 if (Entry) {
NAKAMURA Takumie9621042015-09-15 01:39:27 +00003493 assert(Entry->getType() == Aliasee->getType() &&
Rafael Espindola1e4df922014-09-16 15:18:21 +00003494 "declaration exists with different type");
3495 Alias->takeName(Entry);
3496 Entry->replaceAllUsesWith(Alias);
3497 Entry->eraseFromParent();
3498 } else {
3499 Alias->setName(MangledName);
3500 }
3501
3502 // Finally, set up the alias with its proper name and attributes.
Dario Domiziolic4fb8ca72014-09-19 22:06:24 +00003503 CGM.setAliasAttributes(cast<NamedDecl>(AliasDecl.getDecl()), Alias);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003504}
3505
3506void ItaniumCXXABI::emitCXXStructor(const CXXMethodDecl *MD,
3507 StructorType Type) {
3508 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
3509 const CXXDestructorDecl *DD = CD ? nullptr : cast<CXXDestructorDecl>(MD);
3510
3511 StructorCodegen CGType = getCodegenToUse(CGM, MD);
3512
3513 if (Type == StructorType::Complete) {
3514 GlobalDecl CompleteDecl;
3515 GlobalDecl BaseDecl;
3516 if (CD) {
3517 CompleteDecl = GlobalDecl(CD, Ctor_Complete);
3518 BaseDecl = GlobalDecl(CD, Ctor_Base);
3519 } else {
3520 CompleteDecl = GlobalDecl(DD, Dtor_Complete);
3521 BaseDecl = GlobalDecl(DD, Dtor_Base);
3522 }
3523
3524 if (CGType == StructorCodegen::Alias || CGType == StructorCodegen::COMDAT) {
3525 emitConstructorDestructorAlias(CGM, CompleteDecl, BaseDecl);
3526 return;
3527 }
3528
3529 if (CGType == StructorCodegen::RAUW) {
3530 StringRef MangledName = CGM.getMangledName(CompleteDecl);
Andrey Bokhankocab58582015-08-31 13:20:44 +00003531 auto *Aliasee = CGM.GetAddrOfGlobal(BaseDecl);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003532 CGM.addReplacement(MangledName, Aliasee);
3533 return;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003534 }
3535 }
3536
3537 // The base destructor is equivalent to the base destructor of its
3538 // base class if there is exactly one non-virtual base class with a
3539 // non-trivial destructor, there are no fields with a non-trivial
3540 // destructor, and the body of the destructor is trivial.
Rafael Espindola1e4df922014-09-16 15:18:21 +00003541 if (DD && Type == StructorType::Base && CGType != StructorCodegen::COMDAT &&
3542 !CGM.TryEmitBaseDestructorAsAlias(DD))
Rafael Espindola91f68b42014-09-15 19:20:10 +00003543 return;
3544
Rafael Espindola1e4df922014-09-16 15:18:21 +00003545 llvm::Function *Fn = CGM.codegenCXXStructor(MD, Type);
Rafael Espindola91f68b42014-09-15 19:20:10 +00003546
Rafael Espindola1e4df922014-09-16 15:18:21 +00003547 if (CGType == StructorCodegen::COMDAT) {
3548 SmallString<256> Buffer;
3549 llvm::raw_svector_ostream Out(Buffer);
3550 if (DD)
3551 getMangleContext().mangleCXXDtorComdat(DD, Out);
3552 else
3553 getMangleContext().mangleCXXCtorComdat(CD, Out);
3554 llvm::Comdat *C = CGM.getModule().getOrInsertComdat(Out.str());
3555 Fn->setComdat(C);
Rafael Espindoladbee8a72015-01-15 21:36:08 +00003556 } else {
3557 CGM.maybeSetTrivialComdat(*MD, *Fn);
Rafael Espindola91f68b42014-09-15 19:20:10 +00003558 }
Rafael Espindola91f68b42014-09-15 19:20:10 +00003559}
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003560
3561static llvm::Constant *getBeginCatchFn(CodeGenModule &CGM) {
3562 // void *__cxa_begin_catch(void*);
3563 llvm::FunctionType *FTy = llvm::FunctionType::get(
3564 CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3565
3566 return CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
3567}
3568
3569static llvm::Constant *getEndCatchFn(CodeGenModule &CGM) {
3570 // void __cxa_end_catch();
3571 llvm::FunctionType *FTy =
3572 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
3573
3574 return CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
3575}
3576
3577static llvm::Constant *getGetExceptionPtrFn(CodeGenModule &CGM) {
3578 // void *__cxa_get_exception_ptr(void*);
3579 llvm::FunctionType *FTy = llvm::FunctionType::get(
3580 CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3581
3582 return CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
3583}
3584
3585namespace {
3586 /// A cleanup to call __cxa_end_catch. In many cases, the caught
3587 /// exception type lets us state definitively that the thrown exception
3588 /// type does not have a destructor. In particular:
3589 /// - Catch-alls tell us nothing, so we have to conservatively
3590 /// assume that the thrown exception might have a destructor.
3591 /// - Catches by reference behave according to their base types.
3592 /// - Catches of non-record types will only trigger for exceptions
3593 /// of non-record types, which never have destructors.
3594 /// - Catches of record types can trigger for arbitrary subclasses
3595 /// of the caught type, so we have to assume the actual thrown
3596 /// exception type might have a throwing destructor, even if the
3597 /// caught type's destructor is trivial or nothrow.
David Blaikie7e70d682015-08-18 22:40:54 +00003598 struct CallEndCatch final : EHScopeStack::Cleanup {
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003599 CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
3600 bool MightThrow;
3601
3602 void Emit(CodeGenFunction &CGF, Flags flags) override {
3603 if (!MightThrow) {
3604 CGF.EmitNounwindRuntimeCall(getEndCatchFn(CGF.CGM));
3605 return;
3606 }
3607
3608 CGF.EmitRuntimeCallOrInvoke(getEndCatchFn(CGF.CGM));
3609 }
3610 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003611}
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003612
3613/// Emits a call to __cxa_begin_catch and enters a cleanup to call
3614/// __cxa_end_catch.
3615///
3616/// \param EndMightThrow - true if __cxa_end_catch might throw
3617static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
3618 llvm::Value *Exn,
3619 bool EndMightThrow) {
3620 llvm::CallInst *call =
3621 CGF.EmitNounwindRuntimeCall(getBeginCatchFn(CGF.CGM), Exn);
3622
3623 CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
3624
3625 return call;
3626}
3627
3628/// A "special initializer" callback for initializing a catch
3629/// parameter during catch initialization.
3630static void InitCatchParam(CodeGenFunction &CGF,
3631 const VarDecl &CatchParam,
John McCall7f416cc2015-09-08 08:05:57 +00003632 Address ParamAddr,
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003633 SourceLocation Loc) {
3634 // Load the exception from where the landing pad saved it.
3635 llvm::Value *Exn = CGF.getExceptionFromSlot();
3636
3637 CanQualType CatchType =
3638 CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
3639 llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
3640
3641 // If we're catching by reference, we can just cast the object
3642 // pointer to the appropriate pointer.
3643 if (isa<ReferenceType>(CatchType)) {
3644 QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
3645 bool EndCatchMightThrow = CaughtType->isRecordType();
3646
3647 // __cxa_begin_catch returns the adjusted object pointer.
3648 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
3649
3650 // We have no way to tell the personality function that we're
3651 // catching by reference, so if we're catching a pointer,
3652 // __cxa_begin_catch will actually return that pointer by value.
3653 if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
3654 QualType PointeeType = PT->getPointeeType();
3655
3656 // When catching by reference, generally we should just ignore
3657 // this by-value pointer and use the exception object instead.
3658 if (!PointeeType->isRecordType()) {
3659
3660 // Exn points to the struct _Unwind_Exception header, which
3661 // we have to skip past in order to reach the exception data.
3662 unsigned HeaderSize =
3663 CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
3664 AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
3665
3666 // However, if we're catching a pointer-to-record type that won't
3667 // work, because the personality function might have adjusted
3668 // the pointer. There's actually no way for us to fully satisfy
3669 // the language/ABI contract here: we can't use Exn because it
3670 // might have the wrong adjustment, but we can't use the by-value
3671 // pointer because it's off by a level of abstraction.
3672 //
3673 // The current solution is to dump the adjusted pointer into an
3674 // alloca, which breaks language semantics (because changing the
3675 // pointer doesn't change the exception) but at least works.
3676 // The better solution would be to filter out non-exact matches
3677 // and rethrow them, but this is tricky because the rethrow
3678 // really needs to be catchable by other sites at this landing
3679 // pad. The best solution is to fix the personality function.
3680 } else {
3681 // Pull the pointer for the reference type off.
3682 llvm::Type *PtrTy =
3683 cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
3684
3685 // Create the temporary and write the adjusted pointer into it.
John McCall7f416cc2015-09-08 08:05:57 +00003686 Address ExnPtrTmp =
3687 CGF.CreateTempAlloca(PtrTy, CGF.getPointerAlign(), "exn.byref.tmp");
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003688 llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
3689 CGF.Builder.CreateStore(Casted, ExnPtrTmp);
3690
3691 // Bind the reference to the temporary.
John McCall7f416cc2015-09-08 08:05:57 +00003692 AdjustedExn = ExnPtrTmp.getPointer();
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003693 }
3694 }
3695
3696 llvm::Value *ExnCast =
3697 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
3698 CGF.Builder.CreateStore(ExnCast, ParamAddr);
3699 return;
3700 }
3701
3702 // Scalars and complexes.
3703 TypeEvaluationKind TEK = CGF.getEvaluationKind(CatchType);
3704 if (TEK != TEK_Aggregate) {
3705 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
3706
3707 // If the catch type is a pointer type, __cxa_begin_catch returns
3708 // the pointer by value.
3709 if (CatchType->hasPointerRepresentation()) {
3710 llvm::Value *CastExn =
3711 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
3712
3713 switch (CatchType.getQualifiers().getObjCLifetime()) {
3714 case Qualifiers::OCL_Strong:
3715 CastExn = CGF.EmitARCRetainNonBlock(CastExn);
3716 // fallthrough
3717
3718 case Qualifiers::OCL_None:
3719 case Qualifiers::OCL_ExplicitNone:
3720 case Qualifiers::OCL_Autoreleasing:
3721 CGF.Builder.CreateStore(CastExn, ParamAddr);
3722 return;
3723
3724 case Qualifiers::OCL_Weak:
3725 CGF.EmitARCInitWeak(ParamAddr, CastExn);
3726 return;
3727 }
3728 llvm_unreachable("bad ownership qualifier!");
3729 }
3730
3731 // Otherwise, it returns a pointer into the exception object.
3732
3733 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
3734 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
3735
3736 LValue srcLV = CGF.MakeNaturalAlignAddrLValue(Cast, CatchType);
John McCall7f416cc2015-09-08 08:05:57 +00003737 LValue destLV = CGF.MakeAddrLValue(ParamAddr, CatchType);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003738 switch (TEK) {
3739 case TEK_Complex:
3740 CGF.EmitStoreOfComplex(CGF.EmitLoadOfComplex(srcLV, Loc), destLV,
3741 /*init*/ true);
3742 return;
3743 case TEK_Scalar: {
3744 llvm::Value *ExnLoad = CGF.EmitLoadOfScalar(srcLV, Loc);
3745 CGF.EmitStoreOfScalar(ExnLoad, destLV, /*init*/ true);
3746 return;
3747 }
3748 case TEK_Aggregate:
3749 llvm_unreachable("evaluation kind filtered out!");
3750 }
3751 llvm_unreachable("bad evaluation kind");
3752 }
3753
3754 assert(isa<RecordType>(CatchType) && "unexpected catch type!");
John McCall7f416cc2015-09-08 08:05:57 +00003755 auto catchRD = CatchType->getAsCXXRecordDecl();
3756 CharUnits caughtExnAlignment = CGF.CGM.getClassPointerAlignment(catchRD);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003757
3758 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
3759
3760 // Check for a copy expression. If we don't have a copy expression,
3761 // that means a trivial copy is okay.
3762 const Expr *copyExpr = CatchParam.getInit();
3763 if (!copyExpr) {
3764 llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true);
John McCall7f416cc2015-09-08 08:05:57 +00003765 Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy),
3766 caughtExnAlignment);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003767 CGF.EmitAggregateCopy(ParamAddr, adjustedExn, CatchType);
3768 return;
3769 }
3770
3771 // We have to call __cxa_get_exception_ptr to get the adjusted
3772 // pointer before copying.
3773 llvm::CallInst *rawAdjustedExn =
3774 CGF.EmitNounwindRuntimeCall(getGetExceptionPtrFn(CGF.CGM), Exn);
3775
3776 // Cast that to the appropriate type.
John McCall7f416cc2015-09-08 08:05:57 +00003777 Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy),
3778 caughtExnAlignment);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003779
3780 // The copy expression is defined in terms of an OpaqueValueExpr.
3781 // Find it and map it to the adjusted expression.
3782 CodeGenFunction::OpaqueValueMapping
3783 opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr),
3784 CGF.MakeAddrLValue(adjustedExn, CatchParam.getType()));
3785
3786 // Call the copy ctor in a terminate scope.
3787 CGF.EHStack.pushTerminate();
3788
3789 // Perform the copy construction.
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003790 CGF.EmitAggExpr(copyExpr,
John McCall7f416cc2015-09-08 08:05:57 +00003791 AggValueSlot::forAddr(ParamAddr, Qualifiers(),
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003792 AggValueSlot::IsNotDestructed,
3793 AggValueSlot::DoesNotNeedGCBarriers,
3794 AggValueSlot::IsNotAliased));
3795
3796 // Leave the terminate scope.
3797 CGF.EHStack.popTerminate();
3798
3799 // Undo the opaque value mapping.
3800 opaque.pop();
3801
3802 // Finally we can call __cxa_begin_catch.
3803 CallBeginCatch(CGF, Exn, true);
3804}
3805
3806/// Begins a catch statement by initializing the catch variable and
3807/// calling __cxa_begin_catch.
3808void ItaniumCXXABI::emitBeginCatch(CodeGenFunction &CGF,
3809 const CXXCatchStmt *S) {
3810 // We have to be very careful with the ordering of cleanups here:
3811 // C++ [except.throw]p4:
3812 // The destruction [of the exception temporary] occurs
3813 // immediately after the destruction of the object declared in
3814 // the exception-declaration in the handler.
3815 //
3816 // So the precise ordering is:
3817 // 1. Construct catch variable.
3818 // 2. __cxa_begin_catch
3819 // 3. Enter __cxa_end_catch cleanup
3820 // 4. Enter dtor cleanup
3821 //
3822 // We do this by using a slightly abnormal initialization process.
3823 // Delegation sequence:
3824 // - ExitCXXTryStmt opens a RunCleanupsScope
3825 // - EmitAutoVarAlloca creates the variable and debug info
3826 // - InitCatchParam initializes the variable from the exception
3827 // - CallBeginCatch calls __cxa_begin_catch
3828 // - CallBeginCatch enters the __cxa_end_catch cleanup
3829 // - EmitAutoVarCleanups enters the variable destructor cleanup
3830 // - EmitCXXTryStmt emits the code for the catch body
3831 // - EmitCXXTryStmt close the RunCleanupsScope
3832
3833 VarDecl *CatchParam = S->getExceptionDecl();
3834 if (!CatchParam) {
3835 llvm::Value *Exn = CGF.getExceptionFromSlot();
3836 CallBeginCatch(CGF, Exn, true);
3837 return;
3838 }
3839
3840 // Emit the local.
3841 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
3842 InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF), S->getLocStart());
3843 CGF.EmitAutoVarCleanups(var);
3844}
3845
3846/// Get or define the following function:
3847/// void @__clang_call_terminate(i8* %exn) nounwind noreturn
3848/// This code is used only in C++.
3849static llvm::Constant *getClangCallTerminateFn(CodeGenModule &CGM) {
3850 llvm::FunctionType *fnTy =
3851 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3852 llvm::Constant *fnRef =
3853 CGM.CreateRuntimeFunction(fnTy, "__clang_call_terminate");
3854
3855 llvm::Function *fn = dyn_cast<llvm::Function>(fnRef);
3856 if (fn && fn->empty()) {
3857 fn->setDoesNotThrow();
3858 fn->setDoesNotReturn();
3859
3860 // What we really want is to massively penalize inlining without
3861 // forbidding it completely. The difference between that and
3862 // 'noinline' is negligible.
3863 fn->addFnAttr(llvm::Attribute::NoInline);
3864
3865 // Allow this function to be shared across translation units, but
3866 // we don't want it to turn into an exported symbol.
3867 fn->setLinkage(llvm::Function::LinkOnceODRLinkage);
3868 fn->setVisibility(llvm::Function::HiddenVisibility);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00003869 if (CGM.supportsCOMDAT())
3870 fn->setComdat(CGM.getModule().getOrInsertComdat(fn->getName()));
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003871
3872 // Set up the function.
3873 llvm::BasicBlock *entry =
3874 llvm::BasicBlock::Create(CGM.getLLVMContext(), "", fn);
John McCall7f416cc2015-09-08 08:05:57 +00003875 CGBuilderTy builder(CGM, entry);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003876
3877 // Pull the exception pointer out of the parameter list.
3878 llvm::Value *exn = &*fn->arg_begin();
3879
3880 // Call __cxa_begin_catch(exn).
3881 llvm::CallInst *catchCall = builder.CreateCall(getBeginCatchFn(CGM), exn);
3882 catchCall->setDoesNotThrow();
3883 catchCall->setCallingConv(CGM.getRuntimeCC());
3884
3885 // Call std::terminate().
David Blaikie4ba525b2015-07-14 17:27:39 +00003886 llvm::CallInst *termCall = builder.CreateCall(CGM.getTerminateFn());
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003887 termCall->setDoesNotThrow();
3888 termCall->setDoesNotReturn();
3889 termCall->setCallingConv(CGM.getRuntimeCC());
3890
3891 // std::terminate cannot return.
3892 builder.CreateUnreachable();
3893 }
3894
3895 return fnRef;
3896}
3897
3898llvm::CallInst *
3899ItaniumCXXABI::emitTerminateForUnexpectedException(CodeGenFunction &CGF,
3900 llvm::Value *Exn) {
3901 // In C++, we want to call __cxa_begin_catch() before terminating.
3902 if (Exn) {
3903 assert(CGF.CGM.getLangOpts().CPlusPlus);
3904 return CGF.EmitNounwindRuntimeCall(getClangCallTerminateFn(CGF.CGM), Exn);
3905 }
3906 return CGF.EmitNounwindRuntimeCall(CGF.CGM.getTerminateFn());
3907}