blob: b28ffbf3b77a2efb68ba83ead3234dad14920a36 [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 McCall7a9aac22010-08-23 01:21:21 +000048
Timur Iskhodzhanov67455222013-10-03 06:26:13 +000049 ItaniumMangleContext &getMangleContext() {
50 return cast<ItaniumMangleContext>(CodeGen::CGCXXABI::getMangleContext());
51 }
52
Charles Davis4e786dd2010-05-25 19:52:27 +000053public:
Mark Seabornedf0d382013-07-24 16:25:13 +000054 ItaniumCXXABI(CodeGen::CodeGenModule &CGM,
55 bool UseARMMethodPtrABI = false,
56 bool UseARMGuardVarABI = false) :
57 CGCXXABI(CGM), UseARMMethodPtrABI(UseARMMethodPtrABI),
58 UseARMGuardVarABI(UseARMGuardVarABI) { }
John McCall475999d2010-08-22 00:05:51 +000059
Reid Kleckner40ca9132014-05-13 22:05:45 +000060 bool classifyReturnType(CGFunctionInfo &FI) const override;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000061
Craig Topper4f12f102014-03-12 06:41:41 +000062 RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const override {
Reid Klecknerd355ca72014-05-15 01:26:32 +000063 // Structures with either a non-trivial destructor or a non-trivial
64 // copy constructor are always indirect.
65 // FIXME: Use canCopyArgument() when it is fixed to handle lazily declared
66 // special members.
67 if (RD->hasNonTrivialDestructor() || RD->hasNonTrivialCopyConstructor())
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000068 return RAA_Indirect;
69 return RAA_Default;
70 }
71
Craig Topper4f12f102014-03-12 06:41:41 +000072 bool isZeroInitializable(const MemberPointerType *MPT) override;
John McCall84fa5102010-08-22 04:16:24 +000073
Craig Topper4f12f102014-03-12 06:41:41 +000074 llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT) override;
John McCall7a9aac22010-08-23 01:21:21 +000075
Craig Topper4f12f102014-03-12 06:41:41 +000076 llvm::Value *
77 EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
78 const Expr *E,
79 llvm::Value *&This,
80 llvm::Value *MemFnPtr,
81 const MemberPointerType *MPT) override;
John McCalla8bbb822010-08-22 03:04:22 +000082
Craig Topper4f12f102014-03-12 06:41:41 +000083 llvm::Value *
84 EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E,
85 llvm::Value *Base,
86 llvm::Value *MemPtr,
87 const MemberPointerType *MPT) override;
John McCallc134eb52010-08-31 21:07:20 +000088
John McCall7a9aac22010-08-23 01:21:21 +000089 llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
90 const CastExpr *E,
Craig Topper4f12f102014-03-12 06:41:41 +000091 llvm::Value *Src) override;
John McCallc62bb392012-02-15 01:22:51 +000092 llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
Craig Topper4f12f102014-03-12 06:41:41 +000093 llvm::Constant *Src) override;
John McCall84fa5102010-08-22 04:16:24 +000094
Craig Topper4f12f102014-03-12 06:41:41 +000095 llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT) override;
John McCall84fa5102010-08-22 04:16:24 +000096
David Majnemere2be95b2015-06-23 07:31:01 +000097 llvm::Constant *EmitMemberFunctionPointer(const CXXMethodDecl *MD) override;
John McCallf3a88602011-02-03 08:15:49 +000098 llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
Craig Topper4f12f102014-03-12 06:41:41 +000099 CharUnits offset) override;
100 llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT) override;
Richard Smithdafff942012-01-14 04:30:29 +0000101 llvm::Constant *BuildMemberPointer(const CXXMethodDecl *MD,
102 CharUnits ThisAdjustment);
John McCall1c456c82010-08-22 06:43:33 +0000103
John McCall7a9aac22010-08-23 01:21:21 +0000104 llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000105 llvm::Value *L, llvm::Value *R,
John McCall7a9aac22010-08-23 01:21:21 +0000106 const MemberPointerType *MPT,
Craig Topper4f12f102014-03-12 06:41:41 +0000107 bool Inequality) override;
John McCall131d97d2010-08-22 08:30:07 +0000108
John McCall7a9aac22010-08-23 01:21:21 +0000109 llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000110 llvm::Value *Addr,
111 const MemberPointerType *MPT) override;
John McCall5d865c322010-08-31 07:33:07 +0000112
David Majnemer08681372014-11-01 07:37:17 +0000113 void emitVirtualObjectDelete(CodeGenFunction &CGF, const CXXDeleteExpr *DE,
David Majnemer0c0b6d92014-10-31 20:09:12 +0000114 llvm::Value *Ptr, QualType ElementType,
David Majnemer0c0b6d92014-10-31 20:09:12 +0000115 const CXXDestructorDecl *Dtor) override;
John McCall82fb8922012-09-25 10:10:39 +0000116
David Majnemer442d0a22014-11-25 07:20:20 +0000117 void emitRethrow(CodeGenFunction &CGF, bool isNoReturn) override;
David Majnemer7c237072015-03-05 00:46:22 +0000118 void emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) override;
David Majnemer442d0a22014-11-25 07:20:20 +0000119
Reid Klecknerfff8e7f2015-03-03 19:21:04 +0000120 void emitBeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *C) override;
121
122 llvm::CallInst *
123 emitTerminateForUnexpectedException(CodeGenFunction &CGF,
124 llvm::Value *Exn) override;
125
David Majnemere2cb8d12014-07-07 06:20:47 +0000126 void EmitFundamentalRTTIDescriptor(QualType Type);
127 void EmitFundamentalRTTIDescriptors();
David Majnemer443250f2015-03-17 20:35:00 +0000128 llvm::Constant *getAddrOfRTTIDescriptor(QualType Ty) override;
Justin Bogner0729afa2015-03-17 22:31:34 +0000129 llvm::Constant *
David Majnemer37b417f2015-03-29 21:55:10 +0000130 getAddrOfCXXCatchHandlerType(QualType Ty,
131 QualType CatchHandlerType) override {
David Majnemer443250f2015-03-17 20:35:00 +0000132 return getAddrOfRTTIDescriptor(Ty);
133 }
David Majnemere2cb8d12014-07-07 06:20:47 +0000134
David Majnemer1162d252014-06-22 19:05:33 +0000135 bool shouldTypeidBeNullChecked(bool IsDeref, QualType SrcRecordTy) override;
136 void EmitBadTypeidCall(CodeGenFunction &CGF) override;
137 llvm::Value *EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy,
138 llvm::Value *ThisPtr,
139 llvm::Type *StdTypeInfoPtrTy) override;
140
141 bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
142 QualType SrcRecordTy) override;
143
144 llvm::Value *EmitDynamicCastCall(CodeGenFunction &CGF, llvm::Value *Value,
145 QualType SrcRecordTy, QualType DestTy,
146 QualType DestRecordTy,
147 llvm::BasicBlock *CastEnd) override;
148
149 llvm::Value *EmitDynamicCastToVoid(CodeGenFunction &CGF, llvm::Value *Value,
150 QualType SrcRecordTy,
151 QualType DestTy) override;
152
153 bool EmitBadCastCall(CodeGenFunction &CGF) override;
154
Craig Topper4f12f102014-03-12 06:41:41 +0000155 llvm::Value *
156 GetVirtualBaseClassOffset(CodeGenFunction &CGF, llvm::Value *This,
157 const CXXRecordDecl *ClassDecl,
158 const CXXRecordDecl *BaseClassDecl) override;
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000159
Craig Topper4f12f102014-03-12 06:41:41 +0000160 void EmitCXXConstructors(const CXXConstructorDecl *D) override;
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +0000161
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000162 void buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
163 SmallVectorImpl<CanQualType> &ArgTys) override;
John McCall5d865c322010-08-31 07:33:07 +0000164
Reid Klecknere7de47e2013-07-22 13:51:44 +0000165 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
Craig Topper4f12f102014-03-12 06:41:41 +0000166 CXXDtorType DT) const override {
Reid Klecknere7de47e2013-07-22 13:51:44 +0000167 // Itanium does not emit any destructor variant as an inline thunk.
168 // Delegating may occur as an optimization, but all variants are either
169 // emitted with external linkage or as linkonce if they are inline and used.
170 return false;
171 }
172
Craig Topper4f12f102014-03-12 06:41:41 +0000173 void EmitCXXDestructors(const CXXDestructorDecl *D) override;
Reid Klecknere7de47e2013-07-22 13:51:44 +0000174
Reid Kleckner89077a12013-12-17 19:46:40 +0000175 void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
Craig Topper4f12f102014-03-12 06:41:41 +0000176 FunctionArgList &Params) override;
John McCall5d865c322010-08-31 07:33:07 +0000177
Craig Topper4f12f102014-03-12 06:41:41 +0000178 void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override;
John McCall8ed55a52010-09-02 09:58:18 +0000179
Reid Kleckner89077a12013-12-17 19:46:40 +0000180 unsigned addImplicitConstructorArgs(CodeGenFunction &CGF,
181 const CXXConstructorDecl *D,
182 CXXCtorType Type, bool ForVirtualBase,
Craig Topper4f12f102014-03-12 06:41:41 +0000183 bool Delegating,
184 CallArgList &Args) override;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000185
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000186 void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD,
187 CXXDtorType Type, bool ForVirtualBase,
Craig Topper4f12f102014-03-12 06:41:41 +0000188 bool Delegating, llvm::Value *This) override;
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000189
Craig Topper4f12f102014-03-12 06:41:41 +0000190 void emitVTableDefinitions(CodeGenVTables &CGVT,
191 const CXXRecordDecl *RD) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000192
193 llvm::Value *getVTableAddressPointInStructor(
194 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
Steven Wu5528da72015-08-28 07:14:10 +0000195 BaseSubobject Base, const CXXRecordDecl *NearestVBase,
196 bool &NeedsVirtualOffset) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000197
198 llvm::Constant *
199 getVTableAddressPointForConstExpr(BaseSubobject Base,
Craig Topper4f12f102014-03-12 06:41:41 +0000200 const CXXRecordDecl *VTableClass) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000201
202 llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
Craig Topper4f12f102014-03-12 06:41:41 +0000203 CharUnits VPtrOffset) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000204
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000205 llvm::Value *getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
Craig Topper4f12f102014-03-12 06:41:41 +0000206 llvm::Value *This,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +0000207 llvm::Type *Ty,
208 SourceLocation Loc) override;
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000209
David Majnemer0c0b6d92014-10-31 20:09:12 +0000210 llvm::Value *EmitVirtualDestructorCall(CodeGenFunction &CGF,
211 const CXXDestructorDecl *Dtor,
212 CXXDtorType DtorType,
213 llvm::Value *This,
214 const CXXMemberCallExpr *CE) override;
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000215
Craig Topper4f12f102014-03-12 06:41:41 +0000216 void emitVirtualInheritanceTables(const CXXRecordDecl *RD) override;
Reid Kleckner7810af02013-06-19 15:20:38 +0000217
Steven Wu5528da72015-08-28 07:14:10 +0000218 bool canEmitAvailableExternallyVTable(const CXXRecordDecl *RD) const override;
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000219
Hans Wennborgc94391d2014-06-06 20:04:01 +0000220 void setThunkLinkage(llvm::Function *Thunk, bool ForVTable, GlobalDecl GD,
221 bool ReturnAdjustment) override {
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000222 // Allow inlining of thunks by emitting them with available_externally
223 // linkage together with vtables when needed.
Peter Collingbourne8fabc1b2015-07-01 02:10:26 +0000224 if (ForVTable && !Thunk->hasLocalLinkage())
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000225 Thunk->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
226 }
227
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000228 llvm::Value *performThisAdjustment(CodeGenFunction &CGF, llvm::Value *This,
Craig Topper4f12f102014-03-12 06:41:41 +0000229 const ThisAdjustment &TA) override;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000230
231 llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
Craig Topper4f12f102014-03-12 06:41:41 +0000232 const ReturnAdjustment &RA) override;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000233
David Majnemer196ac332014-09-11 23:05:02 +0000234 size_t getSrcArgforCopyCtor(const CXXConstructorDecl *,
235 FunctionArgList &Args) const override {
236 assert(!Args.empty() && "expected the arglist to not be empty!");
237 return Args.size() - 1;
238 }
239
Craig Topper4f12f102014-03-12 06:41:41 +0000240 StringRef GetPureVirtualCallName() override { return "__cxa_pure_virtual"; }
241 StringRef GetDeletedVirtualCallName() override
242 { return "__cxa_deleted_virtual"; }
Joao Matos2ce88ef2012-07-17 17:10:11 +0000243
Craig Topper4f12f102014-03-12 06:41:41 +0000244 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
John McCall8ed55a52010-09-02 09:58:18 +0000245 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
246 llvm::Value *NewPtr,
247 llvm::Value *NumElements,
John McCall284c48f2011-01-27 09:37:56 +0000248 const CXXNewExpr *expr,
Craig Topper4f12f102014-03-12 06:41:41 +0000249 QualType ElementType) override;
John McCallb91cd662012-05-01 05:23:51 +0000250 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
251 llvm::Value *allocPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000252 CharUnits cookieSize) override;
John McCall68ff0372010-09-08 01:44:27 +0000253
John McCallcdf7ef52010-11-06 09:44:32 +0000254 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
Craig Topper4f12f102014-03-12 06:41:41 +0000255 llvm::GlobalVariable *DeclPtr,
256 bool PerformInit) override;
Richard Smithdbf74ba2013-04-14 23:01:42 +0000257 void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
Craig Topper4f12f102014-03-12 06:41:41 +0000258 llvm::Constant *dtor, llvm::Constant *addr) override;
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000259
260 llvm::Function *getOrCreateThreadLocalWrapper(const VarDecl *VD,
Alexander Musmanf94c3182014-09-26 06:28:25 +0000261 llvm::Value *Val);
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000262 void EmitThreadLocalInitFuncs(
David Majnemerb3341ea2014-10-05 05:05:40 +0000263 CodeGenModule &CGM,
264 ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *>>
265 CXXThreadLocals,
266 ArrayRef<llvm::Function *> CXXThreadLocalInits,
267 ArrayRef<llvm::GlobalVariable *> CXXThreadLocalInitVars) override;
268
269 bool usesThreadWrapperFunction() const override { return true; }
Richard Smith0f383742014-03-26 22:48:22 +0000270 LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD,
271 QualType LValType) override;
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000272
Craig Topper4f12f102014-03-12 06:41:41 +0000273 bool NeedsVTTParameter(GlobalDecl GD) override;
David Majnemere2cb8d12014-07-07 06:20:47 +0000274
275 /**************************** RTTI Uniqueness ******************************/
276
277protected:
278 /// Returns true if the ABI requires RTTI type_info objects to be unique
279 /// across a program.
280 virtual bool shouldRTTIBeUnique() const { return true; }
281
282public:
283 /// What sort of unique-RTTI behavior should we use?
284 enum RTTIUniquenessKind {
285 /// We are guaranteeing, or need to guarantee, that the RTTI string
286 /// is unique.
287 RUK_Unique,
288
289 /// We are not guaranteeing uniqueness for the RTTI string, so we
290 /// can demote to hidden visibility but must use string comparisons.
291 RUK_NonUniqueHidden,
292
293 /// We are not guaranteeing uniqueness for the RTTI string, so we
294 /// have to use string comparisons, but we also have to emit it with
295 /// non-hidden visibility.
296 RUK_NonUniqueVisible
297 };
298
299 /// Return the required visibility status for the given type and linkage in
300 /// the current ABI.
301 RTTIUniquenessKind
302 classifyRTTIUniqueness(QualType CanTy,
303 llvm::GlobalValue::LinkageTypes Linkage) const;
304 friend class ItaniumRTTIBuilder;
Rafael Espindola91f68b42014-09-15 19:20:10 +0000305
306 void emitCXXStructor(const CXXMethodDecl *MD, StructorType Type) override;
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000307
308 private:
Piotr Padlewski1d02f682015-08-19 20:09:09 +0000309 bool hasAnyUsedVirtualInlineFunction(const CXXRecordDecl *RD) const {
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000310 const auto &VtableLayout =
311 CGM.getItaniumVTableContext().getVTableLayout(RD);
312
313 for (const auto &VtableComponent : VtableLayout.vtable_components()) {
Piotr Padlewski1d02f682015-08-19 20:09:09 +0000314 if (!VtableComponent.isUsedFunctionPointerKind())
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000315 continue;
316
Piotr Padlewski1d02f682015-08-19 20:09:09 +0000317 const CXXMethodDecl *Method = VtableComponent.getFunctionDecl();
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000318 if (Method->getCanonicalDecl()->isInlined())
319 return true;
320 }
321 return false;
322 }
Charles Davis4e786dd2010-05-25 19:52:27 +0000323};
John McCall86353412010-08-21 22:46:04 +0000324
325class ARMCXXABI : public ItaniumCXXABI {
326public:
Mark Seabornedf0d382013-07-24 16:25:13 +0000327 ARMCXXABI(CodeGen::CodeGenModule &CGM) :
328 ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
329 /* UseARMGuardVarABI = */ true) {}
John McCall5d865c322010-08-31 07:33:07 +0000330
Craig Topper4f12f102014-03-12 06:41:41 +0000331 bool HasThisReturn(GlobalDecl GD) const override {
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000332 return (isa<CXXConstructorDecl>(GD.getDecl()) || (
333 isa<CXXDestructorDecl>(GD.getDecl()) &&
334 GD.getDtorType() != Dtor_Deleting));
335 }
John McCall5d865c322010-08-31 07:33:07 +0000336
Craig Topper4f12f102014-03-12 06:41:41 +0000337 void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV,
338 QualType ResTy) override;
John McCall5d865c322010-08-31 07:33:07 +0000339
Craig Topper4f12f102014-03-12 06:41:41 +0000340 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
John McCall8ed55a52010-09-02 09:58:18 +0000341 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
342 llvm::Value *NewPtr,
343 llvm::Value *NumElements,
John McCall284c48f2011-01-27 09:37:56 +0000344 const CXXNewExpr *expr,
Craig Topper4f12f102014-03-12 06:41:41 +0000345 QualType ElementType) override;
John McCallb91cd662012-05-01 05:23:51 +0000346 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, llvm::Value *allocPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000347 CharUnits cookieSize) override;
John McCall86353412010-08-21 22:46:04 +0000348};
Tim Northovera2ee4332014-03-29 15:09:45 +0000349
350class iOS64CXXABI : public ARMCXXABI {
351public:
352 iOS64CXXABI(CodeGen::CodeGenModule &CGM) : ARMCXXABI(CGM) {}
Tim Northover65f582f2014-03-30 17:32:48 +0000353
354 // ARM64 libraries are prepared for non-unique RTTI.
David Majnemere2cb8d12014-07-07 06:20:47 +0000355 bool shouldRTTIBeUnique() const override { return false; }
Tim Northovera2ee4332014-03-29 15:09:45 +0000356};
Dan Gohmanc2853072015-09-03 22:51:53 +0000357
358class WebAssemblyCXXABI final : public ItaniumCXXABI {
359public:
360 explicit WebAssemblyCXXABI(CodeGen::CodeGenModule &CGM)
361 : ItaniumCXXABI(CGM, /*UseARMMethodPtrABI=*/true,
362 /*UseARMGuardVarABI=*/true) {}
363
364private:
365 bool HasThisReturn(GlobalDecl GD) const override {
366 return isa<CXXConstructorDecl>(GD.getDecl()) ||
367 (isa<CXXDestructorDecl>(GD.getDecl()) &&
368 GD.getDtorType() != Dtor_Deleting);
369 }
370};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000371}
Charles Davis4e786dd2010-05-25 19:52:27 +0000372
Charles Davis53c59df2010-08-16 03:33:14 +0000373CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
John McCallc8e01702013-04-16 22:48:15 +0000374 switch (CGM.getTarget().getCXXABI().getKind()) {
John McCall57625922013-01-25 23:36:14 +0000375 // For IR-generation purposes, there's no significant difference
376 // between the ARM and iOS ABIs.
377 case TargetCXXABI::GenericARM:
378 case TargetCXXABI::iOS:
379 return new ARMCXXABI(CGM);
Charles Davis4e786dd2010-05-25 19:52:27 +0000380
Tim Northovera2ee4332014-03-29 15:09:45 +0000381 case TargetCXXABI::iOS64:
382 return new iOS64CXXABI(CGM);
383
Tim Northover9bb857a2013-01-31 12:13:10 +0000384 // Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't
385 // include the other 32-bit ARM oddities: constructor/destructor return values
386 // and array cookies.
387 case TargetCXXABI::GenericAArch64:
Mark Seabornedf0d382013-07-24 16:25:13 +0000388 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
389 /* UseARMGuardVarABI = */ true);
Tim Northover9bb857a2013-01-31 12:13:10 +0000390
Zoran Jovanovic26a12162015-02-18 15:21:35 +0000391 case TargetCXXABI::GenericMIPS:
392 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true);
393
Dan Gohmanc2853072015-09-03 22:51:53 +0000394 case TargetCXXABI::WebAssembly:
395 return new WebAssemblyCXXABI(CGM);
396
John McCall57625922013-01-25 23:36:14 +0000397 case TargetCXXABI::GenericItanium:
Mark Seabornedf0d382013-07-24 16:25:13 +0000398 if (CGM.getContext().getTargetInfo().getTriple().getArch()
399 == llvm::Triple::le32) {
400 // For PNaCl, use ARM-style method pointers so that PNaCl code
401 // does not assume anything about the alignment of function
402 // pointers.
403 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
404 /* UseARMGuardVarABI = */ false);
405 }
John McCall57625922013-01-25 23:36:14 +0000406 return new ItaniumCXXABI(CGM);
407
408 case TargetCXXABI::Microsoft:
409 llvm_unreachable("Microsoft ABI is not Itanium-based");
410 }
411 llvm_unreachable("bad ABI kind");
John McCall86353412010-08-21 22:46:04 +0000412}
413
Chris Lattnera5f58b02011-07-09 17:41:47 +0000414llvm::Type *
John McCall7a9aac22010-08-23 01:21:21 +0000415ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
416 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000417 return CGM.PtrDiffTy;
Reid Kleckneree7cf842014-12-01 22:02:27 +0000418 return llvm::StructType::get(CGM.PtrDiffTy, CGM.PtrDiffTy, nullptr);
John McCall1c456c82010-08-22 06:43:33 +0000419}
420
John McCalld9c6c0b2010-08-22 00:59:17 +0000421/// In the Itanium and ARM ABIs, method pointers have the form:
422/// struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
423///
424/// In the Itanium ABI:
425/// - method pointers are virtual if (memptr.ptr & 1) is nonzero
426/// - the this-adjustment is (memptr.adj)
427/// - the virtual offset is (memptr.ptr - 1)
428///
429/// In the ARM ABI:
430/// - method pointers are virtual if (memptr.adj & 1) is nonzero
431/// - the this-adjustment is (memptr.adj >> 1)
432/// - the virtual offset is (memptr.ptr)
433/// ARM uses 'adj' for the virtual flag because Thumb functions
434/// may be only single-byte aligned.
435///
436/// If the member is virtual, the adjusted 'this' pointer points
437/// to a vtable pointer from which the virtual offset is applied.
438///
439/// If the member is non-virtual, memptr.ptr is the address of
440/// the function to call.
David Majnemer2b0d66d2014-02-20 23:22:07 +0000441llvm::Value *ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(
442 CodeGenFunction &CGF, const Expr *E, llvm::Value *&This,
443 llvm::Value *MemFnPtr, const MemberPointerType *MPT) {
John McCall475999d2010-08-22 00:05:51 +0000444 CGBuilderTy &Builder = CGF.Builder;
445
446 const FunctionProtoType *FPT =
447 MPT->getPointeeType()->getAs<FunctionProtoType>();
448 const CXXRecordDecl *RD =
449 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
450
Chris Lattner2192fe52011-07-18 04:24:23 +0000451 llvm::FunctionType *FTy =
John McCalla729c622012-02-17 03:33:10 +0000452 CGM.getTypes().GetFunctionType(
453 CGM.getTypes().arrangeCXXMethodType(RD, FPT));
John McCall475999d2010-08-22 00:05:51 +0000454
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000455 llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(CGM.PtrDiffTy, 1);
John McCall475999d2010-08-22 00:05:51 +0000456
John McCalld9c6c0b2010-08-22 00:59:17 +0000457 llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
458 llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
459 llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
460
John McCalla1dee5302010-08-22 10:59:02 +0000461 // Extract memptr.adj, which is in the second field.
462 llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
John McCalld9c6c0b2010-08-22 00:59:17 +0000463
464 // Compute the true adjustment.
465 llvm::Value *Adj = RawAdj;
Mark Seabornedf0d382013-07-24 16:25:13 +0000466 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000467 Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
John McCall475999d2010-08-22 00:05:51 +0000468
469 // Apply the adjustment and cast back to the original struct type
470 // for consistency.
John McCalld9c6c0b2010-08-22 00:59:17 +0000471 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
472 Ptr = Builder.CreateInBoundsGEP(Ptr, Adj);
473 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
John McCall475999d2010-08-22 00:05:51 +0000474
475 // Load the function pointer.
John McCalla1dee5302010-08-22 10:59:02 +0000476 llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
John McCall475999d2010-08-22 00:05:51 +0000477
478 // If the LSB in the function pointer is 1, the function pointer points to
479 // a virtual function.
John McCalld9c6c0b2010-08-22 00:59:17 +0000480 llvm::Value *IsVirtual;
Mark Seabornedf0d382013-07-24 16:25:13 +0000481 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000482 IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
483 else
484 IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
485 IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
John McCall475999d2010-08-22 00:05:51 +0000486 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
487
488 // In the virtual path, the adjustment left 'This' pointing to the
489 // vtable of the correct base subobject. The "function pointer" is an
John McCalld9c6c0b2010-08-22 00:59:17 +0000490 // offset within the vtable (+1 for the virtual flag on non-ARM).
John McCall475999d2010-08-22 00:05:51 +0000491 CGF.EmitBlock(FnVirtual);
492
493 // Cast the adjusted this to a pointer to vtable pointer and load.
Chris Lattner2192fe52011-07-18 04:24:23 +0000494 llvm::Type *VTableTy = Builder.getInt8PtrTy();
Richard Smith0fc7bdc2014-03-12 18:26:14 +0000495 llvm::Value *VTable = CGF.GetVTablePtr(This, VTableTy);
John McCall475999d2010-08-22 00:05:51 +0000496
497 // Apply the offset.
John McCalld9c6c0b2010-08-22 00:59:17 +0000498 llvm::Value *VTableOffset = FnAsInt;
Mark Seabornedf0d382013-07-24 16:25:13 +0000499 if (!UseARMMethodPtrABI)
500 VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
John McCalld9c6c0b2010-08-22 00:59:17 +0000501 VTable = Builder.CreateGEP(VTable, VTableOffset);
John McCall475999d2010-08-22 00:05:51 +0000502
503 // Load the virtual function to call.
504 VTable = Builder.CreateBitCast(VTable, FTy->getPointerTo()->getPointerTo());
John McCalld9c6c0b2010-08-22 00:59:17 +0000505 llvm::Value *VirtualFn = Builder.CreateLoad(VTable, "memptr.virtualfn");
John McCall475999d2010-08-22 00:05:51 +0000506 CGF.EmitBranch(FnEnd);
507
508 // In the non-virtual path, the function pointer is actually a
509 // function pointer.
510 CGF.EmitBlock(FnNonVirtual);
511 llvm::Value *NonVirtualFn =
John McCalld9c6c0b2010-08-22 00:59:17 +0000512 Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn");
John McCall475999d2010-08-22 00:05:51 +0000513
514 // We're done.
515 CGF.EmitBlock(FnEnd);
Jay Foad20c0f022011-03-30 11:28:58 +0000516 llvm::PHINode *Callee = Builder.CreatePHI(FTy->getPointerTo(), 2);
John McCall475999d2010-08-22 00:05:51 +0000517 Callee->addIncoming(VirtualFn, FnVirtual);
518 Callee->addIncoming(NonVirtualFn, FnNonVirtual);
519 return Callee;
520}
John McCalla8bbb822010-08-22 03:04:22 +0000521
John McCallc134eb52010-08-31 21:07:20 +0000522/// Compute an l-value by applying the given pointer-to-member to a
523/// base object.
David Majnemer2b0d66d2014-02-20 23:22:07 +0000524llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(
525 CodeGenFunction &CGF, const Expr *E, llvm::Value *Base, llvm::Value *MemPtr,
526 const MemberPointerType *MPT) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000527 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCallc134eb52010-08-31 21:07:20 +0000528
529 CGBuilderTy &Builder = CGF.Builder;
530
Micah Villmowea2fea22012-10-25 15:39:14 +0000531 unsigned AS = Base->getType()->getPointerAddressSpace();
John McCallc134eb52010-08-31 21:07:20 +0000532
533 // Cast to char*.
534 Base = Builder.CreateBitCast(Base, Builder.getInt8Ty()->getPointerTo(AS));
535
536 // Apply the offset, which we assume is non-null.
537 llvm::Value *Addr = Builder.CreateInBoundsGEP(Base, MemPtr, "memptr.offset");
538
539 // Cast the address to the appropriate pointer type, adopting the
540 // address space of the base pointer.
Chris Lattner2192fe52011-07-18 04:24:23 +0000541 llvm::Type *PType
Douglas Gregor04f36212010-09-02 17:38:50 +0000542 = CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
John McCallc134eb52010-08-31 21:07:20 +0000543 return Builder.CreateBitCast(Addr, PType);
544}
545
John McCallc62bb392012-02-15 01:22:51 +0000546/// Perform a bitcast, derived-to-base, or base-to-derived member pointer
547/// conversion.
548///
549/// Bitcast conversions are always a no-op under Itanium.
John McCall7a9aac22010-08-23 01:21:21 +0000550///
551/// Obligatory offset/adjustment diagram:
552/// <-- offset --> <-- adjustment -->
553/// |--------------------------|----------------------|--------------------|
554/// ^Derived address point ^Base address point ^Member address point
555///
556/// So when converting a base member pointer to a derived member pointer,
557/// we add the offset to the adjustment because the address point has
558/// decreased; and conversely, when converting a derived MP to a base MP
559/// we subtract the offset from the adjustment because the address point
560/// has increased.
561///
562/// The standard forbids (at compile time) conversion to and from
563/// virtual bases, which is why we don't have to consider them here.
564///
565/// The standard forbids (at run time) casting a derived MP to a base
566/// MP when the derived MP does not point to a member of the base.
567/// This is why -1 is a reasonable choice for null data member
568/// pointers.
John McCalla1dee5302010-08-22 10:59:02 +0000569llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000570ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
571 const CastExpr *E,
John McCallc62bb392012-02-15 01:22:51 +0000572 llvm::Value *src) {
John McCalle3027922010-08-25 11:45:40 +0000573 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
John McCallc62bb392012-02-15 01:22:51 +0000574 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
575 E->getCastKind() == CK_ReinterpretMemberPointer);
576
577 // Under Itanium, reinterprets don't require any additional processing.
578 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
579
580 // Use constant emission if we can.
581 if (isa<llvm::Constant>(src))
582 return EmitMemberPointerConversion(E, cast<llvm::Constant>(src));
583
584 llvm::Constant *adj = getMemberPointerAdjustment(E);
585 if (!adj) return src;
John McCalla8bbb822010-08-22 03:04:22 +0000586
587 CGBuilderTy &Builder = CGF.Builder;
John McCallc62bb392012-02-15 01:22:51 +0000588 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
John McCalla8bbb822010-08-22 03:04:22 +0000589
John McCallc62bb392012-02-15 01:22:51 +0000590 const MemberPointerType *destTy =
591 E->getType()->castAs<MemberPointerType>();
John McCall1c456c82010-08-22 06:43:33 +0000592
John McCall7a9aac22010-08-23 01:21:21 +0000593 // For member data pointers, this is just a matter of adding the
594 // offset if the source is non-null.
John McCallc62bb392012-02-15 01:22:51 +0000595 if (destTy->isMemberDataPointer()) {
596 llvm::Value *dst;
597 if (isDerivedToBase)
598 dst = Builder.CreateNSWSub(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000599 else
John McCallc62bb392012-02-15 01:22:51 +0000600 dst = Builder.CreateNSWAdd(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000601
602 // Null check.
John McCallc62bb392012-02-15 01:22:51 +0000603 llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType());
604 llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull");
605 return Builder.CreateSelect(isNull, src, dst);
John McCall7a9aac22010-08-23 01:21:21 +0000606 }
607
John McCalla1dee5302010-08-22 10:59:02 +0000608 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000609 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000610 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
611 offset <<= 1;
612 adj = llvm::ConstantInt::get(adj->getType(), offset);
John McCalla1dee5302010-08-22 10:59:02 +0000613 }
614
John McCallc62bb392012-02-15 01:22:51 +0000615 llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj");
616 llvm::Value *dstAdj;
617 if (isDerivedToBase)
618 dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000619 else
John McCallc62bb392012-02-15 01:22:51 +0000620 dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000621
John McCallc62bb392012-02-15 01:22:51 +0000622 return Builder.CreateInsertValue(src, dstAdj, 1);
623}
624
625llvm::Constant *
626ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E,
627 llvm::Constant *src) {
628 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
629 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
630 E->getCastKind() == CK_ReinterpretMemberPointer);
631
632 // Under Itanium, reinterprets don't require any additional processing.
633 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
634
635 // If the adjustment is trivial, we don't need to do anything.
636 llvm::Constant *adj = getMemberPointerAdjustment(E);
637 if (!adj) return src;
638
639 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
640
641 const MemberPointerType *destTy =
642 E->getType()->castAs<MemberPointerType>();
643
644 // For member data pointers, this is just a matter of adding the
645 // offset if the source is non-null.
646 if (destTy->isMemberDataPointer()) {
647 // null maps to null.
648 if (src->isAllOnesValue()) return src;
649
650 if (isDerivedToBase)
651 return llvm::ConstantExpr::getNSWSub(src, adj);
652 else
653 return llvm::ConstantExpr::getNSWAdd(src, adj);
654 }
655
656 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000657 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000658 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
659 offset <<= 1;
660 adj = llvm::ConstantInt::get(adj->getType(), offset);
661 }
662
663 llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1);
664 llvm::Constant *dstAdj;
665 if (isDerivedToBase)
666 dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj);
667 else
668 dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj);
669
670 return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1);
John McCalla8bbb822010-08-22 03:04:22 +0000671}
John McCall84fa5102010-08-22 04:16:24 +0000672
673llvm::Constant *
John McCall7a9aac22010-08-23 01:21:21 +0000674ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
John McCall7a9aac22010-08-23 01:21:21 +0000675 // Itanium C++ ABI 2.3:
676 // A NULL pointer is represented as -1.
677 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000678 return llvm::ConstantInt::get(CGM.PtrDiffTy, -1ULL, /*isSigned=*/true);
John McCalla1dee5302010-08-22 10:59:02 +0000679
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000680 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.PtrDiffTy, 0);
John McCalla1dee5302010-08-22 10:59:02 +0000681 llvm::Constant *Values[2] = { Zero, Zero };
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000682 return llvm::ConstantStruct::getAnon(Values);
John McCall84fa5102010-08-22 04:16:24 +0000683}
684
John McCallf3a88602011-02-03 08:15:49 +0000685llvm::Constant *
686ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
687 CharUnits offset) {
John McCall7a9aac22010-08-23 01:21:21 +0000688 // Itanium C++ ABI 2.3:
689 // A pointer to data member is an offset from the base address of
690 // the class object containing it, represented as a ptrdiff_t
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000691 return llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity());
John McCall7a9aac22010-08-23 01:21:21 +0000692}
693
David Majnemere2be95b2015-06-23 07:31:01 +0000694llvm::Constant *
695ItaniumCXXABI::EmitMemberFunctionPointer(const CXXMethodDecl *MD) {
Richard Smithdafff942012-01-14 04:30:29 +0000696 return BuildMemberPointer(MD, CharUnits::Zero());
697}
698
699llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD,
700 CharUnits ThisAdjustment) {
John McCalla1dee5302010-08-22 10:59:02 +0000701 assert(MD->isInstance() && "Member function must not be static!");
702 MD = MD->getCanonicalDecl();
703
704 CodeGenTypes &Types = CGM.getTypes();
John McCalla1dee5302010-08-22 10:59:02 +0000705
706 // Get the function pointer (or index if this is a virtual function).
707 llvm::Constant *MemPtr[2];
708 if (MD->isVirtual()) {
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000709 uint64_t Index = CGM.getItaniumVTableContext().getMethodVTableIndex(MD);
John McCalla1dee5302010-08-22 10:59:02 +0000710
Ken Dyckdf016282011-04-09 01:30:02 +0000711 const ASTContext &Context = getContext();
712 CharUnits PointerWidth =
Douglas Gregore8bbc122011-09-02 00:18:52 +0000713 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Ken Dyckdf016282011-04-09 01:30:02 +0000714 uint64_t VTableOffset = (Index * PointerWidth.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000715
Mark Seabornedf0d382013-07-24 16:25:13 +0000716 if (UseARMMethodPtrABI) {
John McCalla1dee5302010-08-22 10:59:02 +0000717 // ARM C++ ABI 3.2.1:
718 // This ABI specifies that adj contains twice the this
719 // adjustment, plus 1 if the member function is virtual. The
720 // least significant bit of adj then makes exactly the same
721 // discrimination as the least significant bit of ptr does for
722 // Itanium.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000723 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset);
724 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000725 2 * ThisAdjustment.getQuantity() + 1);
John McCalla1dee5302010-08-22 10:59:02 +0000726 } else {
727 // Itanium C++ ABI 2.3:
728 // For a virtual function, [the pointer field] is 1 plus the
729 // virtual table offset (in bytes) of the function,
730 // represented as a ptrdiff_t.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000731 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset + 1);
732 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000733 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000734 }
735 } else {
John McCall2979fe02011-04-12 00:42:48 +0000736 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
Chris Lattner2192fe52011-07-18 04:24:23 +0000737 llvm::Type *Ty;
John McCall2979fe02011-04-12 00:42:48 +0000738 // Check whether the function has a computable LLVM signature.
Chris Lattner8806e322011-07-10 00:18:59 +0000739 if (Types.isFuncTypeConvertible(FPT)) {
John McCall2979fe02011-04-12 00:42:48 +0000740 // The function has a computable LLVM signature; use the correct type.
John McCalla729c622012-02-17 03:33:10 +0000741 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
John McCalla1dee5302010-08-22 10:59:02 +0000742 } else {
John McCall2979fe02011-04-12 00:42:48 +0000743 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
744 // function type is incomplete.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000745 Ty = CGM.PtrDiffTy;
John McCalla1dee5302010-08-22 10:59:02 +0000746 }
John McCall2979fe02011-04-12 00:42:48 +0000747 llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty);
John McCalla1dee5302010-08-22 10:59:02 +0000748
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000749 MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, CGM.PtrDiffTy);
Mark Seabornedf0d382013-07-24 16:25:13 +0000750 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
751 (UseARMMethodPtrABI ? 2 : 1) *
Richard Smithdafff942012-01-14 04:30:29 +0000752 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000753 }
John McCall1c456c82010-08-22 06:43:33 +0000754
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000755 return llvm::ConstantStruct::getAnon(MemPtr);
John McCall1c456c82010-08-22 06:43:33 +0000756}
757
Richard Smithdafff942012-01-14 04:30:29 +0000758llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP,
759 QualType MPType) {
760 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
761 const ValueDecl *MPD = MP.getMemberPointerDecl();
762 if (!MPD)
763 return EmitNullMemberPointer(MPT);
764
Reid Kleckner452abac2013-05-09 21:01:17 +0000765 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
Richard Smithdafff942012-01-14 04:30:29 +0000766
767 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
768 return BuildMemberPointer(MD, ThisAdjustment);
769
770 CharUnits FieldOffset =
771 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
772 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
773}
774
John McCall131d97d2010-08-22 08:30:07 +0000775/// The comparison algorithm is pretty easy: the member pointers are
776/// the same if they're either bitwise identical *or* both null.
777///
778/// ARM is different here only because null-ness is more complicated.
779llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000780ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
781 llvm::Value *L,
782 llvm::Value *R,
783 const MemberPointerType *MPT,
784 bool Inequality) {
John McCall131d97d2010-08-22 08:30:07 +0000785 CGBuilderTy &Builder = CGF.Builder;
786
John McCall131d97d2010-08-22 08:30:07 +0000787 llvm::ICmpInst::Predicate Eq;
788 llvm::Instruction::BinaryOps And, Or;
789 if (Inequality) {
790 Eq = llvm::ICmpInst::ICMP_NE;
791 And = llvm::Instruction::Or;
792 Or = llvm::Instruction::And;
793 } else {
794 Eq = llvm::ICmpInst::ICMP_EQ;
795 And = llvm::Instruction::And;
796 Or = llvm::Instruction::Or;
797 }
798
John McCall7a9aac22010-08-23 01:21:21 +0000799 // Member data pointers are easy because there's a unique null
800 // value, so it just comes down to bitwise equality.
801 if (MPT->isMemberDataPointer())
802 return Builder.CreateICmp(Eq, L, R);
803
804 // For member function pointers, the tautologies are more complex.
805 // The Itanium tautology is:
John McCall61a14882010-08-23 06:56:36 +0000806 // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
John McCall7a9aac22010-08-23 01:21:21 +0000807 // The ARM tautology is:
John McCall61a14882010-08-23 06:56:36 +0000808 // (L == R) <==> (L.ptr == R.ptr &&
809 // (L.adj == R.adj ||
810 // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
John McCall7a9aac22010-08-23 01:21:21 +0000811 // The inequality tautologies have exactly the same structure, except
812 // applying De Morgan's laws.
813
814 llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
815 llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
816
John McCall131d97d2010-08-22 08:30:07 +0000817 // This condition tests whether L.ptr == R.ptr. This must always be
818 // true for equality to hold.
819 llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
820
821 // This condition, together with the assumption that L.ptr == R.ptr,
822 // tests whether the pointers are both null. ARM imposes an extra
823 // condition.
824 llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
825 llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
826
827 // This condition tests whether L.adj == R.adj. If this isn't
828 // true, the pointers are unequal unless they're both null.
John McCalla1dee5302010-08-22 10:59:02 +0000829 llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
830 llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000831 llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
832
833 // Null member function pointers on ARM clear the low bit of Adj,
834 // so the zero condition has to check that neither low bit is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000835 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000836 llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
837
838 // Compute (l.adj | r.adj) & 1 and test it against zero.
839 llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
840 llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
841 llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
842 "cmp.or.adj");
843 EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
844 }
845
846 // Tie together all our conditions.
847 llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
848 Result = Builder.CreateBinOp(And, PtrEq, Result,
849 Inequality ? "memptr.ne" : "memptr.eq");
850 return Result;
851}
852
853llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000854ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
855 llvm::Value *MemPtr,
856 const MemberPointerType *MPT) {
John McCall131d97d2010-08-22 08:30:07 +0000857 CGBuilderTy &Builder = CGF.Builder;
John McCall7a9aac22010-08-23 01:21:21 +0000858
859 /// For member data pointers, this is just a check against -1.
860 if (MPT->isMemberDataPointer()) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000861 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCall7a9aac22010-08-23 01:21:21 +0000862 llvm::Value *NegativeOne =
863 llvm::Constant::getAllOnesValue(MemPtr->getType());
864 return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
865 }
John McCall131d97d2010-08-22 08:30:07 +0000866
Daniel Dunbar914bc412011-04-19 23:10:47 +0000867 // In Itanium, a member function pointer is not null if 'ptr' is not null.
John McCalla1dee5302010-08-22 10:59:02 +0000868 llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
John McCall131d97d2010-08-22 08:30:07 +0000869
870 llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
871 llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
872
Daniel Dunbar914bc412011-04-19 23:10:47 +0000873 // On ARM, a member function pointer is also non-null if the low bit of 'adj'
874 // (the virtual bit) is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000875 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000876 llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
John McCalla1dee5302010-08-22 10:59:02 +0000877 llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000878 llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
Daniel Dunbar914bc412011-04-19 23:10:47 +0000879 llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero,
880 "memptr.isvirtual");
881 Result = Builder.CreateOr(Result, IsVirtual);
John McCall131d97d2010-08-22 08:30:07 +0000882 }
883
884 return Result;
885}
John McCall1c456c82010-08-22 06:43:33 +0000886
Reid Kleckner40ca9132014-05-13 22:05:45 +0000887bool ItaniumCXXABI::classifyReturnType(CGFunctionInfo &FI) const {
888 const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl();
889 if (!RD)
890 return false;
891
Reid Klecknerd355ca72014-05-15 01:26:32 +0000892 // Return indirectly if we have a non-trivial copy ctor or non-trivial dtor.
893 // FIXME: Use canCopyArgument() when it is fixed to handle lazily declared
894 // special members.
895 if (RD->hasNonTrivialDestructor() || RD->hasNonTrivialCopyConstructor()) {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000896 FI.getReturnInfo() = ABIArgInfo::getIndirect(0, /*ByVal=*/false);
897 return true;
898 }
Reid Kleckner40ca9132014-05-13 22:05:45 +0000899 return false;
900}
901
John McCall614dbdc2010-08-22 21:01:12 +0000902/// The Itanium ABI requires non-zero initialization only for data
903/// member pointers, for which '0' is a valid offset.
904bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
David Majnemer5fd33e02015-04-24 01:25:08 +0000905 return MPT->isMemberFunctionPointer();
John McCall84fa5102010-08-22 04:16:24 +0000906}
John McCall5d865c322010-08-31 07:33:07 +0000907
John McCall82fb8922012-09-25 10:10:39 +0000908/// The Itanium ABI always places an offset to the complete object
909/// at entry -2 in the vtable.
David Majnemer08681372014-11-01 07:37:17 +0000910void ItaniumCXXABI::emitVirtualObjectDelete(CodeGenFunction &CGF,
911 const CXXDeleteExpr *DE,
912 llvm::Value *Ptr,
913 QualType ElementType,
914 const CXXDestructorDecl *Dtor) {
915 bool UseGlobalDelete = DE->isGlobalDelete();
David Majnemer0c0b6d92014-10-31 20:09:12 +0000916 if (UseGlobalDelete) {
917 // Derive the complete-object pointer, which is what we need
918 // to pass to the deallocation function.
John McCall82fb8922012-09-25 10:10:39 +0000919
David Majnemer0c0b6d92014-10-31 20:09:12 +0000920 // Grab the vtable pointer as an intptr_t*.
921 llvm::Value *VTable = CGF.GetVTablePtr(Ptr, CGF.IntPtrTy->getPointerTo());
John McCall82fb8922012-09-25 10:10:39 +0000922
David Majnemer0c0b6d92014-10-31 20:09:12 +0000923 // Track back to entry -2 and pull out the offset there.
924 llvm::Value *OffsetPtr = CGF.Builder.CreateConstInBoundsGEP1_64(
925 VTable, -2, "complete-offset.ptr");
926 llvm::LoadInst *Offset = CGF.Builder.CreateLoad(OffsetPtr);
927 Offset->setAlignment(CGF.PointerAlignInBytes);
928
929 // Apply the offset.
930 llvm::Value *CompletePtr = CGF.Builder.CreateBitCast(Ptr, CGF.Int8PtrTy);
931 CompletePtr = CGF.Builder.CreateInBoundsGEP(CompletePtr, Offset);
932
933 // If we're supposed to call the global delete, make sure we do so
934 // even if the destructor throws.
David Majnemer08681372014-11-01 07:37:17 +0000935 CGF.pushCallObjectDeleteCleanup(DE->getOperatorDelete(), CompletePtr,
936 ElementType);
David Majnemer0c0b6d92014-10-31 20:09:12 +0000937 }
938
939 // FIXME: Provide a source location here even though there's no
940 // CXXMemberCallExpr for dtor call.
941 CXXDtorType DtorType = UseGlobalDelete ? Dtor_Complete : Dtor_Deleting;
942 EmitVirtualDestructorCall(CGF, Dtor, DtorType, Ptr, /*CE=*/nullptr);
943
944 if (UseGlobalDelete)
945 CGF.PopCleanupBlock();
John McCall82fb8922012-09-25 10:10:39 +0000946}
947
David Majnemer442d0a22014-11-25 07:20:20 +0000948void ItaniumCXXABI::emitRethrow(CodeGenFunction &CGF, bool isNoReturn) {
949 // void __cxa_rethrow();
950
951 llvm::FunctionType *FTy =
952 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
953
954 llvm::Constant *Fn = CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow");
955
956 if (isNoReturn)
957 CGF.EmitNoreturnRuntimeCallOrInvoke(Fn, None);
958 else
959 CGF.EmitRuntimeCallOrInvoke(Fn);
960}
961
David Majnemer7c237072015-03-05 00:46:22 +0000962static llvm::Constant *getAllocateExceptionFn(CodeGenModule &CGM) {
963 // void *__cxa_allocate_exception(size_t thrown_size);
964
965 llvm::FunctionType *FTy =
966 llvm::FunctionType::get(CGM.Int8PtrTy, CGM.SizeTy, /*IsVarArgs=*/false);
967
968 return CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
969}
970
971static llvm::Constant *getThrowFn(CodeGenModule &CGM) {
972 // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
973 // void (*dest) (void *));
974
975 llvm::Type *Args[3] = { CGM.Int8PtrTy, CGM.Int8PtrTy, CGM.Int8PtrTy };
976 llvm::FunctionType *FTy =
977 llvm::FunctionType::get(CGM.VoidTy, Args, /*IsVarArgs=*/false);
978
979 return CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
980}
981
982void ItaniumCXXABI::emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) {
983 QualType ThrowType = E->getSubExpr()->getType();
984 // Now allocate the exception object.
985 llvm::Type *SizeTy = CGF.ConvertType(getContext().getSizeType());
986 uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
987
988 llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(CGM);
989 llvm::CallInst *ExceptionPtr = CGF.EmitNounwindRuntimeCall(
990 AllocExceptionFn, llvm::ConstantInt::get(SizeTy, TypeSize), "exception");
991
992 CGF.EmitAnyExprToExn(E->getSubExpr(), ExceptionPtr);
993
994 // Now throw the exception.
995 llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType,
996 /*ForEH=*/true);
997
998 // The address of the destructor. If the exception type has a
999 // trivial destructor (or isn't a record), we just pass null.
1000 llvm::Constant *Dtor = nullptr;
1001 if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
1002 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
1003 if (!Record->hasTrivialDestructor()) {
1004 CXXDestructorDecl *DtorD = Record->getDestructor();
1005 Dtor = CGM.getAddrOfCXXStructor(DtorD, StructorType::Complete);
1006 Dtor = llvm::ConstantExpr::getBitCast(Dtor, CGM.Int8PtrTy);
1007 }
1008 }
1009 if (!Dtor) Dtor = llvm::Constant::getNullValue(CGM.Int8PtrTy);
1010
1011 llvm::Value *args[] = { ExceptionPtr, TypeInfo, Dtor };
1012 CGF.EmitNoreturnRuntimeCallOrInvoke(getThrowFn(CGM), args);
1013}
1014
David Majnemer1162d252014-06-22 19:05:33 +00001015static llvm::Constant *getItaniumDynamicCastFn(CodeGenFunction &CGF) {
1016 // void *__dynamic_cast(const void *sub,
1017 // const abi::__class_type_info *src,
1018 // const abi::__class_type_info *dst,
1019 // std::ptrdiff_t src2dst_offset);
1020
1021 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
1022 llvm::Type *PtrDiffTy =
1023 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1024
1025 llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
1026
1027 llvm::FunctionType *FTy = llvm::FunctionType::get(Int8PtrTy, Args, false);
1028
1029 // Mark the function as nounwind readonly.
1030 llvm::Attribute::AttrKind FuncAttrs[] = { llvm::Attribute::NoUnwind,
1031 llvm::Attribute::ReadOnly };
1032 llvm::AttributeSet Attrs = llvm::AttributeSet::get(
1033 CGF.getLLVMContext(), llvm::AttributeSet::FunctionIndex, FuncAttrs);
1034
1035 return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast", Attrs);
1036}
1037
1038static llvm::Constant *getBadCastFn(CodeGenFunction &CGF) {
1039 // void __cxa_bad_cast();
1040 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1041 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
1042}
1043
1044/// \brief Compute the src2dst_offset hint as described in the
1045/// Itanium C++ ABI [2.9.7]
1046static CharUnits computeOffsetHint(ASTContext &Context,
1047 const CXXRecordDecl *Src,
1048 const CXXRecordDecl *Dst) {
1049 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1050 /*DetectVirtual=*/false);
1051
1052 // If Dst is not derived from Src we can skip the whole computation below and
1053 // return that Src is not a public base of Dst. Record all inheritance paths.
1054 if (!Dst->isDerivedFrom(Src, Paths))
1055 return CharUnits::fromQuantity(-2ULL);
1056
1057 unsigned NumPublicPaths = 0;
1058 CharUnits Offset;
1059
1060 // Now walk all possible inheritance paths.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001061 for (const CXXBasePath &Path : Paths) {
1062 if (Path.Access != AS_public) // Ignore non-public inheritance.
David Majnemer1162d252014-06-22 19:05:33 +00001063 continue;
1064
1065 ++NumPublicPaths;
1066
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001067 for (const CXXBasePathElement &PathElement : Path) {
David Majnemer1162d252014-06-22 19:05:33 +00001068 // If the path contains a virtual base class we can't give any hint.
1069 // -1: no hint.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001070 if (PathElement.Base->isVirtual())
David Majnemer1162d252014-06-22 19:05:33 +00001071 return CharUnits::fromQuantity(-1ULL);
1072
1073 if (NumPublicPaths > 1) // Won't use offsets, skip computation.
1074 continue;
1075
1076 // Accumulate the base class offsets.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001077 const ASTRecordLayout &L = Context.getASTRecordLayout(PathElement.Class);
1078 Offset += L.getBaseClassOffset(
1079 PathElement.Base->getType()->getAsCXXRecordDecl());
David Majnemer1162d252014-06-22 19:05:33 +00001080 }
1081 }
1082
1083 // -2: Src is not a public base of Dst.
1084 if (NumPublicPaths == 0)
1085 return CharUnits::fromQuantity(-2ULL);
1086
1087 // -3: Src is a multiple public base type but never a virtual base type.
1088 if (NumPublicPaths > 1)
1089 return CharUnits::fromQuantity(-3ULL);
1090
1091 // Otherwise, the Src type is a unique public nonvirtual base type of Dst.
1092 // Return the offset of Src from the origin of Dst.
1093 return Offset;
1094}
1095
1096static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) {
1097 // void __cxa_bad_typeid();
1098 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1099
1100 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
1101}
1102
1103bool ItaniumCXXABI::shouldTypeidBeNullChecked(bool IsDeref,
1104 QualType SrcRecordTy) {
1105 return IsDeref;
1106}
1107
1108void ItaniumCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) {
1109 llvm::Value *Fn = getBadTypeidFn(CGF);
1110 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
1111 CGF.Builder.CreateUnreachable();
1112}
1113
1114llvm::Value *ItaniumCXXABI::EmitTypeid(CodeGenFunction &CGF,
1115 QualType SrcRecordTy,
1116 llvm::Value *ThisPtr,
1117 llvm::Type *StdTypeInfoPtrTy) {
1118 llvm::Value *Value =
1119 CGF.GetVTablePtr(ThisPtr, StdTypeInfoPtrTy->getPointerTo());
1120
1121 // Load the type info.
1122 Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL);
1123 return CGF.Builder.CreateLoad(Value);
1124}
1125
1126bool ItaniumCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
1127 QualType SrcRecordTy) {
1128 return SrcIsPtr;
1129}
1130
1131llvm::Value *ItaniumCXXABI::EmitDynamicCastCall(
1132 CodeGenFunction &CGF, llvm::Value *Value, QualType SrcRecordTy,
1133 QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) {
1134 llvm::Type *PtrDiffLTy =
1135 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1136 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1137
1138 llvm::Value *SrcRTTI =
1139 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
1140 llvm::Value *DestRTTI =
1141 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
1142
1143 // Compute the offset hint.
1144 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
1145 const CXXRecordDecl *DestDecl = DestRecordTy->getAsCXXRecordDecl();
1146 llvm::Value *OffsetHint = llvm::ConstantInt::get(
1147 PtrDiffLTy,
1148 computeOffsetHint(CGF.getContext(), SrcDecl, DestDecl).getQuantity());
1149
1150 // Emit the call to __dynamic_cast.
1151 Value = CGF.EmitCastToVoidPtr(Value);
1152
1153 llvm::Value *args[] = {Value, SrcRTTI, DestRTTI, OffsetHint};
1154 Value = CGF.EmitNounwindRuntimeCall(getItaniumDynamicCastFn(CGF), args);
1155 Value = CGF.Builder.CreateBitCast(Value, DestLTy);
1156
1157 /// C++ [expr.dynamic.cast]p9:
1158 /// A failed cast to reference type throws std::bad_cast
1159 if (DestTy->isReferenceType()) {
1160 llvm::BasicBlock *BadCastBlock =
1161 CGF.createBasicBlock("dynamic_cast.bad_cast");
1162
1163 llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
1164 CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
1165
1166 CGF.EmitBlock(BadCastBlock);
1167 EmitBadCastCall(CGF);
1168 }
1169
1170 return Value;
1171}
1172
1173llvm::Value *ItaniumCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF,
1174 llvm::Value *Value,
1175 QualType SrcRecordTy,
1176 QualType DestTy) {
1177 llvm::Type *PtrDiffLTy =
1178 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1179 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1180
1181 // Get the vtable pointer.
1182 llvm::Value *VTable = CGF.GetVTablePtr(Value, PtrDiffLTy->getPointerTo());
1183
1184 // Get the offset-to-top from the vtable.
1185 llvm::Value *OffsetToTop =
1186 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL);
1187 OffsetToTop = CGF.Builder.CreateLoad(OffsetToTop, "offset.to.top");
1188
1189 // Finally, add the offset to the pointer.
1190 Value = CGF.EmitCastToVoidPtr(Value);
1191 Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop);
1192
1193 return CGF.Builder.CreateBitCast(Value, DestLTy);
1194}
1195
1196bool ItaniumCXXABI::EmitBadCastCall(CodeGenFunction &CGF) {
1197 llvm::Value *Fn = getBadCastFn(CGF);
1198 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
1199 CGF.Builder.CreateUnreachable();
1200 return true;
1201}
1202
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001203llvm::Value *
1204ItaniumCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
1205 llvm::Value *This,
1206 const CXXRecordDecl *ClassDecl,
1207 const CXXRecordDecl *BaseClassDecl) {
1208 llvm::Value *VTablePtr = CGF.GetVTablePtr(This, CGM.Int8PtrTy);
1209 CharUnits VBaseOffsetOffset =
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001210 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(ClassDecl,
1211 BaseClassDecl);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001212
1213 llvm::Value *VBaseOffsetPtr =
1214 CGF.Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
1215 "vbase.offset.ptr");
1216 VBaseOffsetPtr = CGF.Builder.CreateBitCast(VBaseOffsetPtr,
1217 CGM.PtrDiffTy->getPointerTo());
1218
1219 llvm::Value *VBaseOffset =
1220 CGF.Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
1221
1222 return VBaseOffset;
1223}
1224
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001225void ItaniumCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
1226 // Just make sure we're in sync with TargetCXXABI.
1227 assert(CGM.getTarget().getCXXABI().hasConstructorVariants());
1228
Rafael Espindolac3cde362013-12-09 14:51:17 +00001229 // The constructor used for constructing this as a base class;
1230 // ignores virtual bases.
1231 CGM.EmitGlobal(GlobalDecl(D, Ctor_Base));
1232
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001233 // The constructor used for constructing this as a complete class;
Nico Weber4c2ffb22015-01-07 05:25:05 +00001234 // constructs the virtual bases, then calls the base constructor.
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001235 if (!D->getParent()->isAbstract()) {
1236 // We don't need to emit the complete ctor if the class is abstract.
1237 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
1238 }
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001239}
1240
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001241void
1242ItaniumCXXABI::buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
1243 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9bca9232010-09-02 10:25:57 +00001244 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001245
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001246 // All parameters are already in place except VTT, which goes after 'this'.
1247 // These are Clang types, so we don't need to worry about sret yet.
John McCall5d865c322010-08-31 07:33:07 +00001248
1249 // Check if we need to add a VTT parameter (which has type void **).
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001250 if (T == StructorType::Base && MD->getParent()->getNumVBases() != 0)
1251 ArgTys.insert(ArgTys.begin() + 1,
1252 Context.getPointerType(Context.VoidPtrTy));
John McCall5d865c322010-08-31 07:33:07 +00001253}
1254
Reid Klecknere7de47e2013-07-22 13:51:44 +00001255void ItaniumCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
Rafael Espindolac3cde362013-12-09 14:51:17 +00001256 // The destructor used for destructing this as a base class; ignores
1257 // virtual bases.
1258 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001259
1260 // The destructor used for destructing this as a most-derived class;
1261 // call the base destructor and then destructs any virtual bases.
1262 CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));
1263
Rafael Espindolac3cde362013-12-09 14:51:17 +00001264 // The destructor in a virtual table is always a 'deleting'
1265 // destructor, which calls the complete destructor and then uses the
1266 // appropriate operator delete.
1267 if (D->isVirtual())
1268 CGM.EmitGlobal(GlobalDecl(D, Dtor_Deleting));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001269}
1270
Reid Kleckner89077a12013-12-17 19:46:40 +00001271void ItaniumCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
1272 QualType &ResTy,
1273 FunctionArgList &Params) {
John McCall5d865c322010-08-31 07:33:07 +00001274 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
Reid Kleckner89077a12013-12-17 19:46:40 +00001275 assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
John McCall5d865c322010-08-31 07:33:07 +00001276
1277 // Check if we need a VTT parameter as well.
Peter Collingbourne66f82e62013-06-28 20:45:28 +00001278 if (NeedsVTTParameter(CGF.CurGD)) {
John McCall9bca9232010-09-02 10:25:57 +00001279 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001280
1281 // FIXME: avoid the fake decl
1282 QualType T = Context.getPointerType(Context.VoidPtrTy);
1283 ImplicitParamDecl *VTTDecl
Craig Topper8a13c412014-05-21 05:09:00 +00001284 = ImplicitParamDecl::Create(Context, nullptr, MD->getLocation(),
John McCall5d865c322010-08-31 07:33:07 +00001285 &Context.Idents.get("vtt"), T);
Reid Kleckner89077a12013-12-17 19:46:40 +00001286 Params.insert(Params.begin() + 1, VTTDecl);
Reid Kleckner2af6d732013-12-13 00:09:59 +00001287 getStructorImplicitParamDecl(CGF) = VTTDecl;
John McCall5d865c322010-08-31 07:33:07 +00001288 }
1289}
1290
John McCall5d865c322010-08-31 07:33:07 +00001291void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
1292 /// Initialize the 'this' slot.
1293 EmitThisParam(CGF);
1294
1295 /// Initialize the 'vtt' slot if needed.
Reid Kleckner2af6d732013-12-13 00:09:59 +00001296 if (getStructorImplicitParamDecl(CGF)) {
1297 getStructorImplicitParamValue(CGF) = CGF.Builder.CreateLoad(
1298 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), "vtt");
John McCall5d865c322010-08-31 07:33:07 +00001299 }
John McCall5d865c322010-08-31 07:33:07 +00001300
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001301 /// If this is a function that the ABI specifies returns 'this', initialize
1302 /// the return slot to 'this' at the start of the function.
1303 ///
1304 /// Unlike the setting of return types, this is done within the ABI
1305 /// implementation instead of by clients of CGCXXABI because:
1306 /// 1) getThisValue is currently protected
1307 /// 2) in theory, an ABI could implement 'this' returns some other way;
1308 /// HasThisReturn only specifies a contract, not the implementation
John McCall5d865c322010-08-31 07:33:07 +00001309 if (HasThisReturn(CGF.CurGD))
Eli Friedman9fbeba02012-02-11 02:57:39 +00001310 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
John McCall5d865c322010-08-31 07:33:07 +00001311}
1312
Reid Kleckner89077a12013-12-17 19:46:40 +00001313unsigned ItaniumCXXABI::addImplicitConstructorArgs(
1314 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
1315 bool ForVirtualBase, bool Delegating, CallArgList &Args) {
1316 if (!NeedsVTTParameter(GlobalDecl(D, Type)))
1317 return 0;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001318
Reid Kleckner89077a12013-12-17 19:46:40 +00001319 // Insert the implicit 'vtt' argument as the second argument.
1320 llvm::Value *VTT =
1321 CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase, Delegating);
1322 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1323 Args.insert(Args.begin() + 1,
1324 CallArg(RValue::get(VTT), VTTTy, /*needscopy=*/false));
1325 return 1; // Added one arg.
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001326}
1327
1328void ItaniumCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
1329 const CXXDestructorDecl *DD,
1330 CXXDtorType Type, bool ForVirtualBase,
1331 bool Delegating, llvm::Value *This) {
1332 GlobalDecl GD(DD, Type);
1333 llvm::Value *VTT = CGF.GetVTTParameter(GD, ForVirtualBase, Delegating);
1334 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1335
Craig Topper8a13c412014-05-21 05:09:00 +00001336 llvm::Value *Callee = nullptr;
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001337 if (getContext().getLangOpts().AppleKext)
1338 Callee = CGF.BuildAppleKextVirtualDestructorCall(DD, Type, DD->getParent());
1339
1340 if (!Callee)
Rafael Espindola1ac0ec82014-09-11 15:42:06 +00001341 Callee = CGM.getAddrOfCXXStructor(DD, getFromDtorType(Type));
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001342
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001343 CGF.EmitCXXMemberOrOperatorCall(DD, Callee, ReturnValueSlot(), This, VTT,
1344 VTTTy, nullptr);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001345}
1346
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001347void ItaniumCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
1348 const CXXRecordDecl *RD) {
1349 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, CharUnits());
1350 if (VTable->hasInitializer())
1351 return;
1352
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001353 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001354 const VTableLayout &VTLayout = VTContext.getVTableLayout(RD);
1355 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
David Majnemerd905da42014-07-01 20:30:31 +00001356 llvm::Constant *RTTI =
1357 CGM.GetAddrOfRTTIDescriptor(CGM.getContext().getTagDeclType(RD));
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001358
1359 // Create and set the initializer.
1360 llvm::Constant *Init = CGVT.CreateVTableInitializer(
1361 RD, VTLayout.vtable_component_begin(), VTLayout.getNumVTableComponents(),
David Majnemerd905da42014-07-01 20:30:31 +00001362 VTLayout.vtable_thunk_begin(), VTLayout.getNumVTableThunks(), RTTI);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001363 VTable->setInitializer(Init);
1364
1365 // Set the correct linkage.
1366 VTable->setLinkage(Linkage);
1367
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00001368 if (CGM.supportsCOMDAT() && VTable->isWeakForLinker())
1369 VTable->setComdat(CGM.getModule().getOrInsertComdat(VTable->getName()));
Rafael Espindolacb92c192015-01-15 23:18:01 +00001370
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001371 // Set the right visibility.
John McCall8f80a612014-02-08 00:41:16 +00001372 CGM.setGlobalVisibility(VTable, RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001373
Benjamin Kramer5d34a2b2014-09-10 12:50:59 +00001374 // Use pointer alignment for the vtable. Otherwise we would align them based
1375 // on the size of the initializer which doesn't make sense as only single
1376 // values are read.
1377 unsigned PAlign = CGM.getTarget().getPointerAlign(0);
1378 VTable->setAlignment(getContext().toCharUnitsFromBits(PAlign).getQuantity());
1379
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001380 // If this is the magic class __cxxabiv1::__fundamental_type_info,
1381 // we will emit the typeinfo for the fundamental types. This is the
1382 // same behaviour as GCC.
1383 const DeclContext *DC = RD->getDeclContext();
1384 if (RD->getIdentifier() &&
1385 RD->getIdentifier()->isStr("__fundamental_type_info") &&
1386 isa<NamespaceDecl>(DC) && cast<NamespaceDecl>(DC)->getIdentifier() &&
1387 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
1388 DC->getParent()->isTranslationUnit())
David Majnemere2cb8d12014-07-07 06:20:47 +00001389 EmitFundamentalRTTIDescriptors();
Peter Collingbournea4ccff32015-02-20 20:30:56 +00001390
1391 CGM.EmitVTableBitSetEntries(VTable, VTLayout);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001392}
1393
Piotr Padlewski525f7462015-08-27 21:35:37 +00001394llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructor(
1395 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
Steven Wu5528da72015-08-28 07:14:10 +00001396 const CXXRecordDecl *NearestVBase, bool &NeedsVirtualOffset) {
1397 bool NeedsVTTParam = CGM.getCXXABI().NeedsVTTParameter(CGF.CurGD);
1398 NeedsVirtualOffset = (NeedsVTTParam && NearestVBase);
Piotr Padlewski525f7462015-08-27 21:35:37 +00001399
Steven Wu5528da72015-08-28 07:14:10 +00001400 llvm::Value *VTableAddressPoint;
1401 if (NeedsVTTParam && (Base.getBase()->getNumVBases() || NearestVBase)) {
1402 // Get the secondary vpointer index.
1403 uint64_t VirtualPointerIndex =
1404 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1405
1406 /// Load the VTT.
1407 llvm::Value *VTT = CGF.LoadCXXVTT();
1408 if (VirtualPointerIndex)
1409 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1410
1411 // And load the address point from the VTT.
1412 VTableAddressPoint = CGF.Builder.CreateLoad(VTT);
1413 } else {
1414 llvm::Constant *VTable =
1415 CGM.getCXXABI().getAddrOfVTable(VTableClass, CharUnits());
1416 uint64_t AddressPoint = CGM.getItaniumVTableContext()
1417 .getVTableLayout(VTableClass)
1418 .getAddressPoint(Base);
1419 VTableAddressPoint =
1420 CGF.Builder.CreateConstInBoundsGEP2_64(VTable, 0, AddressPoint);
Piotr Padlewski525f7462015-08-27 21:35:37 +00001421 }
Steven Wu5528da72015-08-28 07:14:10 +00001422
1423 return VTableAddressPoint;
Piotr Padlewski525f7462015-08-27 21:35:37 +00001424}
1425
Steven Wu5528da72015-08-28 07:14:10 +00001426llvm::Constant *ItaniumCXXABI::getVTableAddressPointForConstExpr(
1427 BaseSubobject Base, const CXXRecordDecl *VTableClass) {
1428 auto *VTable = getAddrOfVTable(VTableClass, CharUnits());
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001429
1430 // Find the appropriate vtable within the vtable group.
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001431 uint64_t AddressPoint = CGM.getItaniumVTableContext()
1432 .getVTableLayout(VTableClass)
1433 .getAddressPoint(Base);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001434 llvm::Value *Indices[] = {
1435 llvm::ConstantInt::get(CGM.Int64Ty, 0),
1436 llvm::ConstantInt::get(CGM.Int64Ty, AddressPoint)
1437 };
1438
David Blaikiee3b172a2015-04-02 18:55:21 +00001439 return llvm::ConstantExpr::getInBoundsGetElementPtr(VTable->getValueType(),
1440 VTable, Indices);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001441}
1442
1443llvm::GlobalVariable *ItaniumCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
1444 CharUnits VPtrOffset) {
1445 assert(VPtrOffset.isZero() && "Itanium ABI only supports zero vptr offsets");
1446
1447 llvm::GlobalVariable *&VTable = VTables[RD];
1448 if (VTable)
1449 return VTable;
1450
1451 // Queue up this v-table for possible deferred emission.
1452 CGM.addDeferredVTable(RD);
1453
Yaron Kerene46f7ed2015-07-29 14:21:47 +00001454 SmallString<256> Name;
1455 llvm::raw_svector_ostream Out(Name);
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00001456 getMangleContext().mangleCXXVTable(RD, Out);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001457
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001458 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001459 llvm::ArrayType *ArrayType = llvm::ArrayType::get(
1460 CGM.Int8PtrTy, VTContext.getVTableLayout(RD).getNumVTableComponents());
1461
1462 VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
1463 Name, ArrayType, llvm::GlobalValue::ExternalLinkage);
1464 VTable->setUnnamedAddr(true);
Hans Wennborgda24e9c2014-06-02 23:13:03 +00001465
1466 if (RD->hasAttr<DLLImportAttr>())
1467 VTable->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1468 else if (RD->hasAttr<DLLExportAttr>())
1469 VTable->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1470
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001471 return VTable;
1472}
1473
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001474llvm::Value *ItaniumCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
1475 GlobalDecl GD,
1476 llvm::Value *This,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00001477 llvm::Type *Ty,
1478 SourceLocation Loc) {
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001479 GD = GD.getCanonicalDecl();
1480 Ty = Ty->getPointerTo()->getPointerTo();
1481 llvm::Value *VTable = CGF.GetVTablePtr(This, Ty);
1482
Peter Collingbourne1a7488a2015-04-02 00:23:30 +00001483 if (CGF.SanOpts.has(SanitizerKind::CFIVCall))
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00001484 CGF.EmitVTablePtrCheckForCall(cast<CXXMethodDecl>(GD.getDecl()), VTable,
1485 CodeGenFunction::CFITCK_VCall, Loc);
Peter Collingbournea4ccff32015-02-20 20:30:56 +00001486
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001487 uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001488 llvm::Value *VFuncPtr =
1489 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfn");
1490 return CGF.Builder.CreateLoad(VFuncPtr);
1491}
1492
David Majnemer0c0b6d92014-10-31 20:09:12 +00001493llvm::Value *ItaniumCXXABI::EmitVirtualDestructorCall(
1494 CodeGenFunction &CGF, const CXXDestructorDecl *Dtor, CXXDtorType DtorType,
1495 llvm::Value *This, const CXXMemberCallExpr *CE) {
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001496 assert(CE == nullptr || CE->arg_begin() == CE->arg_end());
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001497 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
1498
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001499 const CGFunctionInfo *FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
1500 Dtor, getFromDtorType(DtorType));
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001501 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001502 llvm::Value *Callee =
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00001503 getVirtualFunctionPointer(CGF, GlobalDecl(Dtor, DtorType), This, Ty,
1504 CE ? CE->getLocStart() : SourceLocation());
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001505
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001506 CGF.EmitCXXMemberOrOperatorCall(Dtor, Callee, ReturnValueSlot(), This,
1507 /*ImplicitParam=*/nullptr, QualType(), CE);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001508 return nullptr;
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001509}
1510
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001511void ItaniumCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
Reid Kleckner7810af02013-06-19 15:20:38 +00001512 CodeGenVTables &VTables = CGM.getVTables();
1513 llvm::GlobalVariable *VTT = VTables.GetAddrOfVTT(RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001514 VTables.EmitVTTDefinition(VTT, CGM.getVTableLinkage(RD), RD);
Reid Kleckner7810af02013-06-19 15:20:38 +00001515}
1516
Steven Wu5528da72015-08-28 07:14:10 +00001517bool ItaniumCXXABI::canEmitAvailableExternallyVTable(
1518 const CXXRecordDecl *RD) const {
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001519 // We don't emit available_externally vtables if we are in -fapple-kext mode
1520 // because kext mode does not permit devirtualization.
1521 if (CGM.getLangOpts().AppleKext)
1522 return false;
1523
1524 // If we don't have any inline virtual functions,
1525 // then we are safe to emit available_externally copy of vtable.
1526 // FIXME we can still emit a copy of the vtable if we
1527 // can emit definition of the inline functions.
Piotr Padlewski1d02f682015-08-19 20:09:09 +00001528 return !hasAnyUsedVirtualInlineFunction(RD);
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001529}
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001530static llvm::Value *performTypeAdjustment(CodeGenFunction &CGF,
1531 llvm::Value *Ptr,
1532 int64_t NonVirtualAdjustment,
1533 int64_t VirtualAdjustment,
1534 bool IsReturnAdjustment) {
1535 if (!NonVirtualAdjustment && !VirtualAdjustment)
1536 return Ptr;
1537
1538 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
1539 llvm::Value *V = CGF.Builder.CreateBitCast(Ptr, Int8PtrTy);
1540
1541 if (NonVirtualAdjustment && !IsReturnAdjustment) {
1542 // Perform the non-virtual adjustment for a base-to-derived cast.
1543 V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
1544 }
1545
1546 if (VirtualAdjustment) {
1547 llvm::Type *PtrDiffTy =
1548 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1549
1550 // Perform the virtual adjustment.
1551 llvm::Value *VTablePtrPtr =
1552 CGF.Builder.CreateBitCast(V, Int8PtrTy->getPointerTo());
1553
1554 llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr);
1555
1556 llvm::Value *OffsetPtr =
1557 CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
1558
1559 OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo());
1560
1561 // Load the adjustment offset from the vtable.
1562 llvm::Value *Offset = CGF.Builder.CreateLoad(OffsetPtr);
1563
1564 // Adjust our pointer.
1565 V = CGF.Builder.CreateInBoundsGEP(V, Offset);
1566 }
1567
1568 if (NonVirtualAdjustment && IsReturnAdjustment) {
1569 // Perform the non-virtual adjustment for a derived-to-base cast.
1570 V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
1571 }
1572
1573 // Cast back to the original type.
1574 return CGF.Builder.CreateBitCast(V, Ptr->getType());
1575}
1576
1577llvm::Value *ItaniumCXXABI::performThisAdjustment(CodeGenFunction &CGF,
1578 llvm::Value *This,
1579 const ThisAdjustment &TA) {
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00001580 return performTypeAdjustment(CGF, This, TA.NonVirtual,
1581 TA.Virtual.Itanium.VCallOffsetOffset,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001582 /*IsReturnAdjustment=*/false);
1583}
1584
1585llvm::Value *
1586ItaniumCXXABI::performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
1587 const ReturnAdjustment &RA) {
1588 return performTypeAdjustment(CGF, Ret, RA.NonVirtual,
1589 RA.Virtual.Itanium.VBaseOffsetOffset,
1590 /*IsReturnAdjustment=*/true);
1591}
1592
John McCall5d865c322010-08-31 07:33:07 +00001593void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
1594 RValue RV, QualType ResultType) {
1595 if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
1596 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
1597
1598 // Destructor thunks in the ARM ABI have indeterminate results.
Chris Lattner2192fe52011-07-18 04:24:23 +00001599 llvm::Type *T =
John McCall5d865c322010-08-31 07:33:07 +00001600 cast<llvm::PointerType>(CGF.ReturnValue->getType())->getElementType();
1601 RValue Undef = RValue::get(llvm::UndefValue::get(T));
1602 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
1603}
John McCall8ed55a52010-09-02 09:58:18 +00001604
1605/************************** Array allocation cookies **************************/
1606
John McCallb91cd662012-05-01 05:23:51 +00001607CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
1608 // The array cookie is a size_t; pad that up to the element alignment.
1609 // The cookie is actually right-justified in that space.
1610 return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
1611 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001612}
1613
1614llvm::Value *ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1615 llvm::Value *NewPtr,
1616 llvm::Value *NumElements,
John McCall284c48f2011-01-27 09:37:56 +00001617 const CXXNewExpr *expr,
John McCall8ed55a52010-09-02 09:58:18 +00001618 QualType ElementType) {
John McCallb91cd662012-05-01 05:23:51 +00001619 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001620
Micah Villmowea2fea22012-10-25 15:39:14 +00001621 unsigned AS = NewPtr->getType()->getPointerAddressSpace();
John McCall8ed55a52010-09-02 09:58:18 +00001622
John McCall9bca9232010-09-02 10:25:57 +00001623 ASTContext &Ctx = getContext();
John McCall8ed55a52010-09-02 09:58:18 +00001624 QualType SizeTy = Ctx.getSizeType();
1625 CharUnits SizeSize = Ctx.getTypeSizeInChars(SizeTy);
1626
1627 // The size of the cookie.
1628 CharUnits CookieSize =
1629 std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
John McCallb91cd662012-05-01 05:23:51 +00001630 assert(CookieSize == getArrayCookieSizeImpl(ElementType));
John McCall8ed55a52010-09-02 09:58:18 +00001631
1632 // Compute an offset to the cookie.
1633 llvm::Value *CookiePtr = NewPtr;
1634 CharUnits CookieOffset = CookieSize - SizeSize;
1635 if (!CookieOffset.isZero())
1636 CookiePtr = CGF.Builder.CreateConstInBoundsGEP1_64(CookiePtr,
1637 CookieOffset.getQuantity());
1638
1639 // Write the number of elements into the appropriate slot.
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001640 llvm::Type *NumElementsTy = CGF.ConvertType(SizeTy)->getPointerTo(AS);
1641 llvm::Value *NumElementsPtr =
1642 CGF.Builder.CreateBitCast(CookiePtr, NumElementsTy);
1643 llvm::Instruction *SI = CGF.Builder.CreateStore(NumElements, NumElementsPtr);
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001644 if (CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) && AS == 0 &&
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001645 expr->getOperatorNew()->isReplaceableGlobalAllocationFunction()) {
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001646 // The store to the CookiePtr does not need to be instrumented.
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001647 CGM.getSanitizerMetadata()->disableSanitizerForInstruction(SI);
1648 llvm::FunctionType *FTy =
1649 llvm::FunctionType::get(CGM.VoidTy, NumElementsTy, false);
1650 llvm::Constant *F =
1651 CGM.CreateRuntimeFunction(FTy, "__asan_poison_cxx_array_cookie");
1652 CGF.Builder.CreateCall(F, NumElementsPtr);
1653 }
John McCall8ed55a52010-09-02 09:58:18 +00001654
1655 // Finally, compute a pointer to the actual data buffer by skipping
1656 // over the cookie completely.
1657 return CGF.Builder.CreateConstInBoundsGEP1_64(NewPtr,
1658 CookieSize.getQuantity());
1659}
1660
John McCallb91cd662012-05-01 05:23:51 +00001661llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1662 llvm::Value *allocPtr,
1663 CharUnits cookieSize) {
1664 // The element size is right-justified in the cookie.
1665 llvm::Value *numElementsPtr = allocPtr;
1666 CharUnits numElementsOffset =
1667 cookieSize - CharUnits::fromQuantity(CGF.SizeSizeInBytes);
1668 if (!numElementsOffset.isZero())
1669 numElementsPtr =
1670 CGF.Builder.CreateConstInBoundsGEP1_64(numElementsPtr,
1671 numElementsOffset.getQuantity());
John McCall8ed55a52010-09-02 09:58:18 +00001672
Micah Villmowea2fea22012-10-25 15:39:14 +00001673 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCallb91cd662012-05-01 05:23:51 +00001674 numElementsPtr =
1675 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001676 if (!CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) || AS != 0)
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001677 return CGF.Builder.CreateLoad(numElementsPtr);
1678 // In asan mode emit a function call instead of a regular load and let the
1679 // run-time deal with it: if the shadow is properly poisoned return the
1680 // cookie, otherwise return 0 to avoid an infinite loop calling DTORs.
1681 // We can't simply ignore this load using nosanitize metadata because
1682 // the metadata may be lost.
1683 llvm::FunctionType *FTy =
1684 llvm::FunctionType::get(CGF.SizeTy, CGF.SizeTy->getPointerTo(0), false);
1685 llvm::Constant *F =
1686 CGM.CreateRuntimeFunction(FTy, "__asan_load_cxx_array_cookie");
1687 return CGF.Builder.CreateCall(F, numElementsPtr);
John McCall8ed55a52010-09-02 09:58:18 +00001688}
1689
John McCallb91cd662012-05-01 05:23:51 +00001690CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
John McCallc19c7062013-01-25 23:36:19 +00001691 // ARM says that the cookie is always:
John McCall8ed55a52010-09-02 09:58:18 +00001692 // struct array_cookie {
1693 // std::size_t element_size; // element_size != 0
1694 // std::size_t element_count;
1695 // };
John McCallc19c7062013-01-25 23:36:19 +00001696 // But the base ABI doesn't give anything an alignment greater than
1697 // 8, so we can dismiss this as typical ABI-author blindness to
1698 // actual language complexity and round up to the element alignment.
1699 return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes),
1700 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001701}
1702
1703llvm::Value *ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
John McCallc19c7062013-01-25 23:36:19 +00001704 llvm::Value *newPtr,
1705 llvm::Value *numElements,
John McCall284c48f2011-01-27 09:37:56 +00001706 const CXXNewExpr *expr,
John McCallc19c7062013-01-25 23:36:19 +00001707 QualType elementType) {
John McCallb91cd662012-05-01 05:23:51 +00001708 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001709
John McCallc19c7062013-01-25 23:36:19 +00001710 // NewPtr is a char*, but we generalize to arbitrary addrspaces.
1711 unsigned AS = newPtr->getType()->getPointerAddressSpace();
John McCall8ed55a52010-09-02 09:58:18 +00001712
1713 // The cookie is always at the start of the buffer.
John McCallc19c7062013-01-25 23:36:19 +00001714 llvm::Value *cookie = newPtr;
John McCall8ed55a52010-09-02 09:58:18 +00001715
1716 // The first element is the element size.
John McCallc19c7062013-01-25 23:36:19 +00001717 cookie = CGF.Builder.CreateBitCast(cookie, CGF.SizeTy->getPointerTo(AS));
1718 llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy,
1719 getContext().getTypeSizeInChars(elementType).getQuantity());
1720 CGF.Builder.CreateStore(elementSize, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001721
1722 // The second element is the element count.
David Blaikiefb901c7a2015-04-04 15:12:29 +00001723 cookie = CGF.Builder.CreateConstInBoundsGEP1_32(CGF.SizeTy, cookie, 1);
John McCallc19c7062013-01-25 23:36:19 +00001724 CGF.Builder.CreateStore(numElements, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001725
1726 // Finally, compute a pointer to the actual data buffer by skipping
1727 // over the cookie completely.
John McCallc19c7062013-01-25 23:36:19 +00001728 CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType);
1729 return CGF.Builder.CreateConstInBoundsGEP1_64(newPtr,
1730 cookieSize.getQuantity());
John McCall8ed55a52010-09-02 09:58:18 +00001731}
1732
John McCallb91cd662012-05-01 05:23:51 +00001733llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1734 llvm::Value *allocPtr,
1735 CharUnits cookieSize) {
1736 // The number of elements is at offset sizeof(size_t) relative to
1737 // the allocated pointer.
1738 llvm::Value *numElementsPtr
1739 = CGF.Builder.CreateConstInBoundsGEP1_64(allocPtr, CGF.SizeSizeInBytes);
John McCall8ed55a52010-09-02 09:58:18 +00001740
Micah Villmowea2fea22012-10-25 15:39:14 +00001741 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCallb91cd662012-05-01 05:23:51 +00001742 numElementsPtr =
1743 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
1744 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall8ed55a52010-09-02 09:58:18 +00001745}
1746
John McCall68ff0372010-09-08 01:44:27 +00001747/*********************** Static local initialization **************************/
1748
1749static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001750 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001751 // int __cxa_guard_acquire(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001752 llvm::FunctionType *FTy =
John McCall68ff0372010-09-08 01:44:27 +00001753 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
Jay Foad5709f7c2011-07-29 13:56:53 +00001754 GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001755 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_acquire",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001756 llvm::AttributeSet::get(CGM.getLLVMContext(),
1757 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001758 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001759}
1760
1761static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001762 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001763 // void __cxa_guard_release(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001764 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001765 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001766 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_release",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001767 llvm::AttributeSet::get(CGM.getLLVMContext(),
1768 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001769 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001770}
1771
1772static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001773 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001774 // void __cxa_guard_abort(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001775 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001776 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001777 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_abort",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001778 llvm::AttributeSet::get(CGM.getLLVMContext(),
1779 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001780 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001781}
1782
1783namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001784 struct CallGuardAbort final : EHScopeStack::Cleanup {
John McCall68ff0372010-09-08 01:44:27 +00001785 llvm::GlobalVariable *Guard;
Chandler Carruth84537952012-03-30 19:44:53 +00001786 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
John McCall68ff0372010-09-08 01:44:27 +00001787
Craig Topper4f12f102014-03-12 06:41:41 +00001788 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall882987f2013-02-28 19:01:20 +00001789 CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()),
1790 Guard);
John McCall68ff0372010-09-08 01:44:27 +00001791 }
1792 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001793}
John McCall68ff0372010-09-08 01:44:27 +00001794
1795/// The ARM code here follows the Itanium code closely enough that we
1796/// just special-case it at particular places.
John McCallcdf7ef52010-11-06 09:44:32 +00001797void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
1798 const VarDecl &D,
John McCallb88a5662012-03-30 21:00:39 +00001799 llvm::GlobalVariable *var,
1800 bool shouldPerformInit) {
John McCall68ff0372010-09-08 01:44:27 +00001801 CGBuilderTy &Builder = CGF.Builder;
John McCallcdf7ef52010-11-06 09:44:32 +00001802
Richard Smithdbf74ba2013-04-14 23:01:42 +00001803 // We only need to use thread-safe statics for local non-TLS variables;
John McCallcdf7ef52010-11-06 09:44:32 +00001804 // global initialization is always single-threaded.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001805 bool threadsafe = getContext().getLangOpts().ThreadsafeStatics &&
1806 D.isLocalVarDecl() && !D.getTLSKind();
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001807
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001808 // If we have a global variable with internal linkage and thread-safe statics
1809 // are disabled, we can just let the guard variable be of type i8.
John McCallb88a5662012-03-30 21:00:39 +00001810 bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
1811
1812 llvm::IntegerType *guardTy;
John McCall5aa52592011-06-17 07:33:57 +00001813 if (useInt8GuardVariable) {
John McCallb88a5662012-03-30 21:00:39 +00001814 guardTy = CGF.Int8Ty;
John McCall5aa52592011-06-17 07:33:57 +00001815 } else {
Tim Northover9bb857a2013-01-31 12:13:10 +00001816 // Guard variables are 64 bits in the generic ABI and size width on ARM
1817 // (i.e. 32-bit on AArch32, 64-bit on AArch64).
Mark Seabornedf0d382013-07-24 16:25:13 +00001818 guardTy = (UseARMGuardVarABI ? CGF.SizeTy : CGF.Int64Ty);
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001819 }
John McCallb88a5662012-03-30 21:00:39 +00001820 llvm::PointerType *guardPtrTy = guardTy->getPointerTo();
John McCall68ff0372010-09-08 01:44:27 +00001821
John McCallb88a5662012-03-30 21:00:39 +00001822 // Create the guard variable if we don't already have it (as we
1823 // might if we're double-emitting this function body).
1824 llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
1825 if (!guard) {
1826 // Mangle the name for the guard.
1827 SmallString<256> guardName;
1828 {
1829 llvm::raw_svector_ostream out(guardName);
Reid Klecknerd8110b62013-09-10 20:14:30 +00001830 getMangleContext().mangleStaticGuardVariable(&D, out);
John McCallb88a5662012-03-30 21:00:39 +00001831 }
John McCall8e7cb6d2010-11-02 21:04:24 +00001832
John McCallb88a5662012-03-30 21:00:39 +00001833 // Create the guard variable with a zero-initializer.
1834 // Just absorb linkage and visibility from the guarded variable.
1835 guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
1836 false, var->getLinkage(),
1837 llvm::ConstantInt::get(guardTy, 0),
1838 guardName.str());
1839 guard->setVisibility(var->getVisibility());
Richard Smithdbf74ba2013-04-14 23:01:42 +00001840 // If the variable is thread-local, so is its guard variable.
1841 guard->setThreadLocalMode(var->getThreadLocalMode());
John McCallb88a5662012-03-30 21:00:39 +00001842
Yaron Keren5bfa1082015-09-03 20:33:29 +00001843 // The ABI says: "It is suggested that it be emitted in the same COMDAT
1844 // group as the associated data object." In practice, this doesn't work for
1845 // non-ELF object formats, so only do it for ELF.
Rafael Espindola0d4fb982015-01-12 22:13:53 +00001846 llvm::Comdat *C = var->getComdat();
Yaron Keren5bfa1082015-09-03 20:33:29 +00001847 if (!D.isLocalVarDecl() && C &&
1848 CGM.getTarget().getTriple().isOSBinFormatELF()) {
Rafael Espindola2ae4b632014-09-19 19:43:18 +00001849 guard->setComdat(C);
Rafael Espindola2ae4b632014-09-19 19:43:18 +00001850 CGF.CurFn->setComdat(C);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00001851 } else if (CGM.supportsCOMDAT() && guard->isWeakForLinker()) {
1852 guard->setComdat(CGM.getModule().getOrInsertComdat(guard->getName()));
Rafael Espindola2ae4b632014-09-19 19:43:18 +00001853 }
1854
John McCallb88a5662012-03-30 21:00:39 +00001855 CGM.setStaticLocalDeclGuardAddress(&D, guard);
1856 }
John McCall87590e62012-03-30 07:09:50 +00001857
John McCall68ff0372010-09-08 01:44:27 +00001858 // Test whether the variable has completed initialization.
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001859 //
John McCall68ff0372010-09-08 01:44:27 +00001860 // Itanium C++ ABI 3.3.2:
1861 // The following is pseudo-code showing how these functions can be used:
1862 // if (obj_guard.first_byte == 0) {
1863 // if ( __cxa_guard_acquire (&obj_guard) ) {
1864 // try {
1865 // ... initialize the object ...;
1866 // } catch (...) {
1867 // __cxa_guard_abort (&obj_guard);
1868 // throw;
1869 // }
1870 // ... queue object destructor with __cxa_atexit() ...;
1871 // __cxa_guard_release (&obj_guard);
1872 // }
1873 // }
Tim Northovera2ee4332014-03-29 15:09:45 +00001874
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001875 // Load the first byte of the guard variable.
1876 llvm::LoadInst *LI =
John McCallb88a5662012-03-30 21:00:39 +00001877 Builder.CreateLoad(Builder.CreateBitCast(guard, CGM.Int8PtrTy));
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001878 LI->setAlignment(1);
John McCall68ff0372010-09-08 01:44:27 +00001879
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001880 // Itanium ABI:
1881 // An implementation supporting thread-safety on multiprocessor
1882 // systems must also guarantee that references to the initialized
1883 // object do not occur before the load of the initialization flag.
1884 //
1885 // In LLVM, we do this by marking the load Acquire.
1886 if (threadsafe)
1887 LI->setAtomic(llvm::Acquire);
Eli Friedman84d28122011-09-13 22:21:56 +00001888
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001889 // For ARM, we should only check the first bit, rather than the entire byte:
1890 //
1891 // ARM C++ ABI 3.2.3.1:
1892 // To support the potential use of initialization guard variables
1893 // as semaphores that are the target of ARM SWP and LDREX/STREX
1894 // synchronizing instructions we define a static initialization
1895 // guard variable to be a 4-byte aligned, 4-byte word with the
1896 // following inline access protocol.
1897 // #define INITIALIZED 1
1898 // if ((obj_guard & INITIALIZED) != INITIALIZED) {
1899 // if (__cxa_guard_acquire(&obj_guard))
1900 // ...
1901 // }
1902 //
1903 // and similarly for ARM64:
1904 //
1905 // ARM64 C++ ABI 3.2.2:
1906 // This ABI instead only specifies the value bit 0 of the static guard
1907 // variable; all other bits are platform defined. Bit 0 shall be 0 when the
1908 // variable is not initialized and 1 when it is.
1909 llvm::Value *V =
1910 (UseARMGuardVarABI && !useInt8GuardVariable)
1911 ? Builder.CreateAnd(LI, llvm::ConstantInt::get(CGM.Int8Ty, 1))
1912 : LI;
1913 llvm::Value *isInitialized = Builder.CreateIsNull(V, "guard.uninitialized");
John McCall68ff0372010-09-08 01:44:27 +00001914
1915 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
1916 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
1917
1918 // Check if the first byte of the guard variable is zero.
John McCallb88a5662012-03-30 21:00:39 +00001919 Builder.CreateCondBr(isInitialized, InitCheckBlock, EndBlock);
John McCall68ff0372010-09-08 01:44:27 +00001920
1921 CGF.EmitBlock(InitCheckBlock);
1922
1923 // Variables used when coping with thread-safe statics and exceptions.
John McCall5aa52592011-06-17 07:33:57 +00001924 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00001925 // Call __cxa_guard_acquire.
1926 llvm::Value *V
John McCall882987f2013-02-28 19:01:20 +00001927 = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
John McCall68ff0372010-09-08 01:44:27 +00001928
1929 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
1930
1931 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
1932 InitBlock, EndBlock);
1933
1934 // Call __cxa_guard_abort along the exceptional edge.
John McCallb88a5662012-03-30 21:00:39 +00001935 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
John McCall68ff0372010-09-08 01:44:27 +00001936
1937 CGF.EmitBlock(InitBlock);
1938 }
1939
1940 // Emit the initializer and add a global destructor if appropriate.
John McCallb88a5662012-03-30 21:00:39 +00001941 CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
John McCall68ff0372010-09-08 01:44:27 +00001942
John McCall5aa52592011-06-17 07:33:57 +00001943 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00001944 // Pop the guard-abort cleanup if we pushed one.
1945 CGF.PopCleanupBlock();
1946
1947 // Call __cxa_guard_release. This cannot throw.
John McCall882987f2013-02-28 19:01:20 +00001948 CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy), guard);
John McCall68ff0372010-09-08 01:44:27 +00001949 } else {
John McCallb88a5662012-03-30 21:00:39 +00001950 Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guard);
John McCall68ff0372010-09-08 01:44:27 +00001951 }
1952
1953 CGF.EmitBlock(EndBlock);
1954}
John McCallc84ed6a2012-05-01 06:13:13 +00001955
1956/// Register a global destructor using __cxa_atexit.
1957static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
1958 llvm::Constant *dtor,
Richard Smithdbf74ba2013-04-14 23:01:42 +00001959 llvm::Constant *addr,
1960 bool TLS) {
Bill Wendling95cae882013-05-02 19:18:03 +00001961 const char *Name = "__cxa_atexit";
1962 if (TLS) {
1963 const llvm::Triple &T = CGF.getTarget().getTriple();
1964 Name = T.isMacOSX() ? "_tlv_atexit" : "__cxa_thread_atexit";
1965 }
Richard Smithdbf74ba2013-04-14 23:01:42 +00001966
John McCallc84ed6a2012-05-01 06:13:13 +00001967 // We're assuming that the destructor function is something we can
1968 // reasonably call with the default CC. Go ahead and cast it to the
1969 // right prototype.
1970 llvm::Type *dtorTy =
1971 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo();
1972
1973 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
1974 llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
1975 llvm::FunctionType *atexitTy =
1976 llvm::FunctionType::get(CGF.IntTy, paramTys, false);
1977
1978 // Fetch the actual function.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001979 llvm::Constant *atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name);
John McCallc84ed6a2012-05-01 06:13:13 +00001980 if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit))
1981 fn->setDoesNotThrow();
1982
1983 // Create a variable that binds the atexit to this shared object.
1984 llvm::Constant *handle =
1985 CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
1986
1987 llvm::Value *args[] = {
1988 llvm::ConstantExpr::getBitCast(dtor, dtorTy),
1989 llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy),
1990 handle
1991 };
John McCall882987f2013-02-28 19:01:20 +00001992 CGF.EmitNounwindRuntimeCall(atexit, args);
John McCallc84ed6a2012-05-01 06:13:13 +00001993}
1994
1995/// Register a global destructor as best as we know how.
1996void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF,
Richard Smithdbf74ba2013-04-14 23:01:42 +00001997 const VarDecl &D,
John McCallc84ed6a2012-05-01 06:13:13 +00001998 llvm::Constant *dtor,
1999 llvm::Constant *addr) {
2000 // Use __cxa_atexit if available.
Richard Smithdbf74ba2013-04-14 23:01:42 +00002001 if (CGM.getCodeGenOpts().CXAAtExit)
2002 return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind());
2003
2004 if (D.getTLSKind())
2005 CGM.ErrorUnsupported(&D, "non-trivial TLS destruction");
John McCallc84ed6a2012-05-01 06:13:13 +00002006
2007 // In Apple kexts, we want to add a global destructor entry.
2008 // FIXME: shouldn't this be guarded by some variable?
Richard Smith9c6890a2012-11-01 22:30:59 +00002009 if (CGM.getLangOpts().AppleKext) {
John McCallc84ed6a2012-05-01 06:13:13 +00002010 // Generate a global destructor entry.
2011 return CGM.AddCXXDtorEntry(dtor, addr);
2012 }
2013
David Blaikieebe87e12013-08-27 23:57:18 +00002014 CGF.registerGlobalDtorWithAtExit(D, dtor, addr);
John McCallc84ed6a2012-05-01 06:13:13 +00002015}
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002016
David Majnemer9b21c332014-07-11 20:28:10 +00002017static bool isThreadWrapperReplaceable(const VarDecl *VD,
2018 CodeGen::CodeGenModule &CGM) {
2019 assert(!VD->isStaticLocal() && "static local VarDecls don't need wrappers!");
2020 // OS X prefers to have references to thread local variables to go through
2021 // the thread wrapper instead of directly referencing the backing variable.
2022 return VD->getTLSKind() == VarDecl::TLS_Dynamic &&
2023 CGM.getTarget().getTriple().isMacOSX();
2024}
2025
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002026/// Get the appropriate linkage for the wrapper function. This is essentially
David Majnemer4632e1e2014-06-27 16:56:27 +00002027/// the weak form of the variable's linkage; every translation unit which needs
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002028/// the wrapper emits a copy, and we want the linker to merge them.
David Majnemer35ab3282014-06-11 04:08:55 +00002029static llvm::GlobalValue::LinkageTypes
2030getThreadLocalWrapperLinkage(const VarDecl *VD, CodeGen::CodeGenModule &CGM) {
2031 llvm::GlobalValue::LinkageTypes VarLinkage =
2032 CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false);
2033
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002034 // For internal linkage variables, we don't need an external or weak wrapper.
2035 if (llvm::GlobalValue::isLocalLinkage(VarLinkage))
2036 return VarLinkage;
David Majnemer35ab3282014-06-11 04:08:55 +00002037
David Majnemer9b21c332014-07-11 20:28:10 +00002038 // If the thread wrapper is replaceable, give it appropriate linkage.
2039 if (isThreadWrapperReplaceable(VD, CGM)) {
2040 if (llvm::GlobalVariable::isLinkOnceLinkage(VarLinkage) ||
2041 llvm::GlobalVariable::isWeakODRLinkage(VarLinkage))
2042 return llvm::GlobalVariable::WeakAnyLinkage;
2043 return VarLinkage;
2044 }
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002045 return llvm::GlobalValue::WeakODRLinkage;
2046}
2047
2048llvm::Function *
2049ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD,
Alexander Musmanf94c3182014-09-26 06:28:25 +00002050 llvm::Value *Val) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002051 // Mangle the name for the thread_local wrapper function.
2052 SmallString<256> WrapperName;
2053 {
2054 llvm::raw_svector_ostream Out(WrapperName);
2055 getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002056 }
2057
Alexander Musmanf94c3182014-09-26 06:28:25 +00002058 if (llvm::Value *V = CGM.getModule().getNamedValue(WrapperName))
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002059 return cast<llvm::Function>(V);
2060
Alexander Musmanf94c3182014-09-26 06:28:25 +00002061 llvm::Type *RetTy = Val->getType();
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002062 if (VD->getType()->isReferenceType())
2063 RetTy = RetTy->getPointerElementType();
2064
2065 llvm::FunctionType *FnTy = llvm::FunctionType::get(RetTy, false);
David Majnemer35ab3282014-06-11 04:08:55 +00002066 llvm::Function *Wrapper =
2067 llvm::Function::Create(FnTy, getThreadLocalWrapperLinkage(VD, CGM),
2068 WrapperName.str(), &CGM.getModule());
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002069 // Always resolve references to the wrapper at link time.
David Majnemer9b21c332014-07-11 20:28:10 +00002070 if (!Wrapper->hasLocalLinkage() && !isThreadWrapperReplaceable(VD, CGM))
Duncan P. N. Exon Smith4434d362014-05-07 22:36:11 +00002071 Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002072 return Wrapper;
2073}
2074
2075void ItaniumCXXABI::EmitThreadLocalInitFuncs(
David Majnemerb3341ea2014-10-05 05:05:40 +00002076 CodeGenModule &CGM,
2077 ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *>>
2078 CXXThreadLocals, ArrayRef<llvm::Function *> CXXThreadLocalInits,
2079 ArrayRef<llvm::GlobalVariable *> CXXThreadLocalInitVars) {
2080 llvm::Function *InitFunc = nullptr;
2081 if (!CXXThreadLocalInits.empty()) {
2082 // Generate a guarded initialization function.
2083 llvm::FunctionType *FTy =
2084 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
2085 InitFunc = CGM.CreateGlobalInitOrDestructFunction(FTy, "__tls_init",
Alexey Samsonov1444bb92014-10-17 00:20:19 +00002086 SourceLocation(),
David Majnemerb3341ea2014-10-05 05:05:40 +00002087 /*TLS=*/true);
2088 llvm::GlobalVariable *Guard = new llvm::GlobalVariable(
2089 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false,
2090 llvm::GlobalVariable::InternalLinkage,
2091 llvm::ConstantInt::get(CGM.Int8Ty, 0), "__tls_guard");
2092 Guard->setThreadLocal(true);
2093 CodeGenFunction(CGM)
2094 .GenerateCXXGlobalInitFunc(InitFunc, CXXThreadLocalInits, Guard);
2095 }
Yaron Kerenede60302015-08-01 19:11:36 +00002096 for (auto &I : CXXThreadLocals) {
2097 const VarDecl *VD = I.first;
2098 llvm::GlobalVariable *Var = I.second;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002099
David Majnemer9b21c332014-07-11 20:28:10 +00002100 // Some targets require that all access to thread local variables go through
2101 // the thread wrapper. This means that we cannot attempt to create a thread
2102 // wrapper or a thread helper.
2103 if (isThreadWrapperReplaceable(VD, CGM) && !VD->hasDefinition())
2104 continue;
2105
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002106 // Mangle the name for the thread_local initialization function.
2107 SmallString<256> InitFnName;
2108 {
2109 llvm::raw_svector_ostream Out(InitFnName);
2110 getMangleContext().mangleItaniumThreadLocalInit(VD, Out);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002111 }
2112
2113 // If we have a definition for the variable, emit the initialization
2114 // function as an alias to the global Init function (if any). Otherwise,
2115 // produce a declaration of the initialization function.
Craig Topper8a13c412014-05-21 05:09:00 +00002116 llvm::GlobalValue *Init = nullptr;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002117 bool InitIsInitFunc = false;
2118 if (VD->hasDefinition()) {
2119 InitIsInitFunc = true;
2120 if (InitFunc)
Rafael Espindola234405b2014-05-17 21:30:14 +00002121 Init = llvm::GlobalAlias::create(Var->getLinkage(), InitFnName.str(),
2122 InitFunc);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002123 } else {
2124 // Emit a weak global function referring to the initialization function.
2125 // This function will not exist if the TU defining the thread_local
2126 // variable in question does not need any dynamic initialization for
2127 // its thread_local variables.
2128 llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, false);
2129 Init = llvm::Function::Create(
2130 FnTy, llvm::GlobalVariable::ExternalWeakLinkage, InitFnName.str(),
2131 &CGM.getModule());
2132 }
2133
2134 if (Init)
2135 Init->setVisibility(Var->getVisibility());
2136
2137 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Var);
2138 llvm::LLVMContext &Context = CGM.getModule().getContext();
2139 llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper);
2140 CGBuilderTy Builder(Entry);
2141 if (InitIsInitFunc) {
2142 if (Init)
David Blaikie4ba525b2015-07-14 17:27:39 +00002143 Builder.CreateCall(Init);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002144 } else {
2145 // Don't know whether we have an init function. Call it if it exists.
2146 llvm::Value *Have = Builder.CreateIsNotNull(Init);
2147 llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2148 llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2149 Builder.CreateCondBr(Have, InitBB, ExitBB);
2150
2151 Builder.SetInsertPoint(InitBB);
David Blaikie4ba525b2015-07-14 17:27:39 +00002152 Builder.CreateCall(Init);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002153 Builder.CreateBr(ExitBB);
2154
2155 Builder.SetInsertPoint(ExitBB);
2156 }
2157
2158 // For a reference, the result of the wrapper function is a pointer to
2159 // the referenced object.
2160 llvm::Value *Val = Var;
2161 if (VD->getType()->isReferenceType()) {
2162 llvm::LoadInst *LI = Builder.CreateLoad(Val);
2163 LI->setAlignment(CGM.getContext().getDeclAlign(VD).getQuantity());
2164 Val = LI;
2165 }
Alexander Musmanf94c3182014-09-26 06:28:25 +00002166 if (Val->getType() != Wrapper->getReturnType())
2167 Val = Builder.CreatePointerBitCastOrAddrSpaceCast(
2168 Val, Wrapper->getReturnType(), "");
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002169 Builder.CreateRet(Val);
2170 }
2171}
2172
Richard Smith0f383742014-03-26 22:48:22 +00002173LValue ItaniumCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
2174 const VarDecl *VD,
2175 QualType LValType) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002176 QualType T = VD->getType();
2177 llvm::Type *Ty = CGF.getTypes().ConvertTypeForMem(T);
2178 llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD, Ty);
Alexander Musmanf94c3182014-09-26 06:28:25 +00002179 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Val);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002180
David Blaikie4ba525b2015-07-14 17:27:39 +00002181 Val = CGF.Builder.CreateCall(Wrapper);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002182
2183 LValue LV;
2184 if (VD->getType()->isReferenceType())
Richard Smith0f383742014-03-26 22:48:22 +00002185 LV = CGF.MakeNaturalAlignAddrLValue(Val, LValType);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002186 else
Richard Smith0f383742014-03-26 22:48:22 +00002187 LV = CGF.MakeAddrLValue(Val, LValType, CGF.getContext().getDeclAlign(VD));
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002188 // FIXME: need setObjCGCLValueClass?
2189 return LV;
2190}
Peter Collingbourne66f82e62013-06-28 20:45:28 +00002191
2192/// Return whether the given global decl needs a VTT parameter, which it does
2193/// if it's a base constructor or destructor with virtual bases.
2194bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) {
2195 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
2196
2197 // We don't have any virtual bases, just return early.
2198 if (!MD->getParent()->getNumVBases())
2199 return false;
2200
2201 // Check if we have a base constructor.
2202 if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base)
2203 return true;
2204
2205 // Check if we have a base destructor.
2206 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
2207 return true;
2208
2209 return false;
2210}
David Majnemere2cb8d12014-07-07 06:20:47 +00002211
2212namespace {
2213class ItaniumRTTIBuilder {
2214 CodeGenModule &CGM; // Per-module state.
2215 llvm::LLVMContext &VMContext;
2216 const ItaniumCXXABI &CXXABI; // Per-module state.
2217
2218 /// Fields - The fields of the RTTI descriptor currently being built.
2219 SmallVector<llvm::Constant *, 16> Fields;
2220
2221 /// GetAddrOfTypeName - Returns the mangled type name of the given type.
2222 llvm::GlobalVariable *
2223 GetAddrOfTypeName(QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage);
2224
2225 /// GetAddrOfExternalRTTIDescriptor - Returns the constant for the RTTI
2226 /// descriptor of the given type.
2227 llvm::Constant *GetAddrOfExternalRTTIDescriptor(QualType Ty);
2228
2229 /// BuildVTablePointer - Build the vtable pointer for the given type.
2230 void BuildVTablePointer(const Type *Ty);
2231
2232 /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
2233 /// inheritance, according to the Itanium C++ ABI, 2.9.5p6b.
2234 void BuildSIClassTypeInfo(const CXXRecordDecl *RD);
2235
2236 /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
2237 /// classes with bases that do not satisfy the abi::__si_class_type_info
2238 /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
2239 void BuildVMIClassTypeInfo(const CXXRecordDecl *RD);
2240
2241 /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct, used
2242 /// for pointer types.
2243 void BuildPointerTypeInfo(QualType PointeeTy);
2244
2245 /// BuildObjCObjectTypeInfo - Build the appropriate kind of
2246 /// type_info for an object type.
2247 void BuildObjCObjectTypeInfo(const ObjCObjectType *Ty);
2248
2249 /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
2250 /// struct, used for member pointer types.
2251 void BuildPointerToMemberTypeInfo(const MemberPointerType *Ty);
2252
2253public:
2254 ItaniumRTTIBuilder(const ItaniumCXXABI &ABI)
2255 : CGM(ABI.CGM), VMContext(CGM.getModule().getContext()), CXXABI(ABI) {}
2256
2257 // Pointer type info flags.
2258 enum {
2259 /// PTI_Const - Type has const qualifier.
2260 PTI_Const = 0x1,
2261
2262 /// PTI_Volatile - Type has volatile qualifier.
2263 PTI_Volatile = 0x2,
2264
2265 /// PTI_Restrict - Type has restrict qualifier.
2266 PTI_Restrict = 0x4,
2267
2268 /// PTI_Incomplete - Type is incomplete.
2269 PTI_Incomplete = 0x8,
2270
2271 /// PTI_ContainingClassIncomplete - Containing class is incomplete.
2272 /// (in pointer to member).
2273 PTI_ContainingClassIncomplete = 0x10
2274 };
2275
2276 // VMI type info flags.
2277 enum {
2278 /// VMI_NonDiamondRepeat - Class has non-diamond repeated inheritance.
2279 VMI_NonDiamondRepeat = 0x1,
2280
2281 /// VMI_DiamondShaped - Class is diamond shaped.
2282 VMI_DiamondShaped = 0x2
2283 };
2284
2285 // Base class type info flags.
2286 enum {
2287 /// BCTI_Virtual - Base class is virtual.
2288 BCTI_Virtual = 0x1,
2289
2290 /// BCTI_Public - Base class is public.
2291 BCTI_Public = 0x2
2292 };
2293
2294 /// BuildTypeInfo - Build the RTTI type info struct for the given type.
2295 ///
2296 /// \param Force - true to force the creation of this RTTI value
2297 llvm::Constant *BuildTypeInfo(QualType Ty, bool Force = false);
2298};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002299}
David Majnemere2cb8d12014-07-07 06:20:47 +00002300
2301llvm::GlobalVariable *ItaniumRTTIBuilder::GetAddrOfTypeName(
2302 QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage) {
Yaron Kerene46f7ed2015-07-29 14:21:47 +00002303 SmallString<256> Name;
2304 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00002305 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00002306
2307 // We know that the mangled name of the type starts at index 4 of the
2308 // mangled name of the typename, so we can just index into it in order to
2309 // get the mangled name of the type.
2310 llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,
2311 Name.substr(4));
2312
2313 llvm::GlobalVariable *GV =
2314 CGM.CreateOrReplaceCXXRuntimeVariable(Name, Init->getType(), Linkage);
2315
2316 GV->setInitializer(Init);
2317
2318 return GV;
2319}
2320
2321llvm::Constant *
2322ItaniumRTTIBuilder::GetAddrOfExternalRTTIDescriptor(QualType Ty) {
2323 // Mangle the RTTI name.
Yaron Kerene46f7ed2015-07-29 14:21:47 +00002324 SmallString<256> Name;
2325 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00002326 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00002327
2328 // Look for an existing global.
2329 llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name);
2330
2331 if (!GV) {
2332 // Create a new global variable.
2333 GV = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
2334 /*Constant=*/true,
2335 llvm::GlobalValue::ExternalLinkage, nullptr,
2336 Name);
David Majnemer1fb1a042014-11-07 07:26:38 +00002337 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2338 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
2339 if (RD->hasAttr<DLLImportAttr>())
2340 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
2341 }
David Majnemere2cb8d12014-07-07 06:20:47 +00002342 }
2343
2344 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
2345}
2346
2347/// TypeInfoIsInStandardLibrary - Given a builtin type, returns whether the type
2348/// info for that type is defined in the standard library.
2349static bool TypeInfoIsInStandardLibrary(const BuiltinType *Ty) {
2350 // Itanium C++ ABI 2.9.2:
2351 // Basic type information (e.g. for "int", "bool", etc.) will be kept in
2352 // the run-time support library. Specifically, the run-time support
2353 // library should contain type_info objects for the types X, X* and
2354 // X const*, for every X in: void, std::nullptr_t, bool, wchar_t, char,
2355 // unsigned char, signed char, short, unsigned short, int, unsigned int,
2356 // long, unsigned long, long long, unsigned long long, float, double,
2357 // long double, char16_t, char32_t, and the IEEE 754r decimal and
2358 // half-precision floating point types.
2359 switch (Ty->getKind()) {
2360 case BuiltinType::Void:
2361 case BuiltinType::NullPtr:
2362 case BuiltinType::Bool:
2363 case BuiltinType::WChar_S:
2364 case BuiltinType::WChar_U:
2365 case BuiltinType::Char_U:
2366 case BuiltinType::Char_S:
2367 case BuiltinType::UChar:
2368 case BuiltinType::SChar:
2369 case BuiltinType::Short:
2370 case BuiltinType::UShort:
2371 case BuiltinType::Int:
2372 case BuiltinType::UInt:
2373 case BuiltinType::Long:
2374 case BuiltinType::ULong:
2375 case BuiltinType::LongLong:
2376 case BuiltinType::ULongLong:
2377 case BuiltinType::Half:
2378 case BuiltinType::Float:
2379 case BuiltinType::Double:
2380 case BuiltinType::LongDouble:
2381 case BuiltinType::Char16:
2382 case BuiltinType::Char32:
2383 case BuiltinType::Int128:
2384 case BuiltinType::UInt128:
2385 case BuiltinType::OCLImage1d:
2386 case BuiltinType::OCLImage1dArray:
2387 case BuiltinType::OCLImage1dBuffer:
2388 case BuiltinType::OCLImage2d:
2389 case BuiltinType::OCLImage2dArray:
2390 case BuiltinType::OCLImage3d:
2391 case BuiltinType::OCLSampler:
2392 case BuiltinType::OCLEvent:
2393 return true;
2394
2395 case BuiltinType::Dependent:
2396#define BUILTIN_TYPE(Id, SingletonId)
2397#define PLACEHOLDER_TYPE(Id, SingletonId) \
2398 case BuiltinType::Id:
2399#include "clang/AST/BuiltinTypes.def"
2400 llvm_unreachable("asking for RRTI for a placeholder type!");
2401
2402 case BuiltinType::ObjCId:
2403 case BuiltinType::ObjCClass:
2404 case BuiltinType::ObjCSel:
2405 llvm_unreachable("FIXME: Objective-C types are unsupported!");
2406 }
2407
2408 llvm_unreachable("Invalid BuiltinType Kind!");
2409}
2410
2411static bool TypeInfoIsInStandardLibrary(const PointerType *PointerTy) {
2412 QualType PointeeTy = PointerTy->getPointeeType();
2413 const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(PointeeTy);
2414 if (!BuiltinTy)
2415 return false;
2416
2417 // Check the qualifiers.
2418 Qualifiers Quals = PointeeTy.getQualifiers();
2419 Quals.removeConst();
2420
2421 if (!Quals.empty())
2422 return false;
2423
2424 return TypeInfoIsInStandardLibrary(BuiltinTy);
2425}
2426
2427/// IsStandardLibraryRTTIDescriptor - Returns whether the type
2428/// information for the given type exists in the standard library.
2429static bool IsStandardLibraryRTTIDescriptor(QualType Ty) {
2430 // Type info for builtin types is defined in the standard library.
2431 if (const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(Ty))
2432 return TypeInfoIsInStandardLibrary(BuiltinTy);
2433
2434 // Type info for some pointer types to builtin types is defined in the
2435 // standard library.
2436 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2437 return TypeInfoIsInStandardLibrary(PointerTy);
2438
2439 return false;
2440}
2441
2442/// ShouldUseExternalRTTIDescriptor - Returns whether the type information for
2443/// the given type exists somewhere else, and that we should not emit the type
2444/// information in this translation unit. Assumes that it is not a
2445/// standard-library type.
2446static bool ShouldUseExternalRTTIDescriptor(CodeGenModule &CGM,
2447 QualType Ty) {
2448 ASTContext &Context = CGM.getContext();
2449
2450 // If RTTI is disabled, assume it might be disabled in the
2451 // translation unit that defines any potential key function, too.
2452 if (!Context.getLangOpts().RTTI) return false;
2453
2454 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2455 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
2456 if (!RD->hasDefinition())
2457 return false;
2458
2459 if (!RD->isDynamicClass())
2460 return false;
2461
2462 // FIXME: this may need to be reconsidered if the key function
2463 // changes.
David Majnemerbe9022c2015-08-06 20:56:55 +00002464 // N.B. We must always emit the RTTI data ourselves if there exists a key
2465 // function.
2466 bool IsDLLImport = RD->hasAttr<DLLImportAttr>();
David Majnemer1fb1a042014-11-07 07:26:38 +00002467 if (CGM.getVTables().isVTableExternal(RD))
David Majnemerbe9022c2015-08-06 20:56:55 +00002468 return IsDLLImport ? false : true;
David Majnemer1fb1a042014-11-07 07:26:38 +00002469
David Majnemerbe9022c2015-08-06 20:56:55 +00002470 if (IsDLLImport)
David Majnemer1fb1a042014-11-07 07:26:38 +00002471 return true;
David Majnemere2cb8d12014-07-07 06:20:47 +00002472 }
2473
2474 return false;
2475}
2476
2477/// IsIncompleteClassType - Returns whether the given record type is incomplete.
2478static bool IsIncompleteClassType(const RecordType *RecordTy) {
2479 return !RecordTy->getDecl()->isCompleteDefinition();
2480}
2481
2482/// ContainsIncompleteClassType - Returns whether the given type contains an
2483/// incomplete class type. This is true if
2484///
2485/// * The given type is an incomplete class type.
2486/// * The given type is a pointer type whose pointee type contains an
2487/// incomplete class type.
2488/// * The given type is a member pointer type whose class is an incomplete
2489/// class type.
2490/// * The given type is a member pointer type whoise pointee type contains an
2491/// incomplete class type.
2492/// is an indirect or direct pointer to an incomplete class type.
2493static bool ContainsIncompleteClassType(QualType Ty) {
2494 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2495 if (IsIncompleteClassType(RecordTy))
2496 return true;
2497 }
2498
2499 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2500 return ContainsIncompleteClassType(PointerTy->getPointeeType());
2501
2502 if (const MemberPointerType *MemberPointerTy =
2503 dyn_cast<MemberPointerType>(Ty)) {
2504 // Check if the class type is incomplete.
2505 const RecordType *ClassType = cast<RecordType>(MemberPointerTy->getClass());
2506 if (IsIncompleteClassType(ClassType))
2507 return true;
2508
2509 return ContainsIncompleteClassType(MemberPointerTy->getPointeeType());
2510 }
2511
2512 return false;
2513}
2514
2515// CanUseSingleInheritance - Return whether the given record decl has a "single,
2516// public, non-virtual base at offset zero (i.e. the derived class is dynamic
2517// iff the base is)", according to Itanium C++ ABI, 2.95p6b.
2518static bool CanUseSingleInheritance(const CXXRecordDecl *RD) {
2519 // Check the number of bases.
2520 if (RD->getNumBases() != 1)
2521 return false;
2522
2523 // Get the base.
2524 CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin();
2525
2526 // Check that the base is not virtual.
2527 if (Base->isVirtual())
2528 return false;
2529
2530 // Check that the base is public.
2531 if (Base->getAccessSpecifier() != AS_public)
2532 return false;
2533
2534 // Check that the class is dynamic iff the base is.
2535 const CXXRecordDecl *BaseDecl =
2536 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2537 if (!BaseDecl->isEmpty() &&
2538 BaseDecl->isDynamicClass() != RD->isDynamicClass())
2539 return false;
2540
2541 return true;
2542}
2543
2544void ItaniumRTTIBuilder::BuildVTablePointer(const Type *Ty) {
2545 // abi::__class_type_info.
2546 static const char * const ClassTypeInfo =
2547 "_ZTVN10__cxxabiv117__class_type_infoE";
2548 // abi::__si_class_type_info.
2549 static const char * const SIClassTypeInfo =
2550 "_ZTVN10__cxxabiv120__si_class_type_infoE";
2551 // abi::__vmi_class_type_info.
2552 static const char * const VMIClassTypeInfo =
2553 "_ZTVN10__cxxabiv121__vmi_class_type_infoE";
2554
2555 const char *VTableName = nullptr;
2556
2557 switch (Ty->getTypeClass()) {
2558#define TYPE(Class, Base)
2559#define ABSTRACT_TYPE(Class, Base)
2560#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2561#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2562#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2563#include "clang/AST/TypeNodes.def"
2564 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
2565
2566 case Type::LValueReference:
2567 case Type::RValueReference:
2568 llvm_unreachable("References shouldn't get here");
2569
2570 case Type::Auto:
2571 llvm_unreachable("Undeduced auto type shouldn't get here");
2572
2573 case Type::Builtin:
2574 // GCC treats vector and complex types as fundamental types.
2575 case Type::Vector:
2576 case Type::ExtVector:
2577 case Type::Complex:
2578 case Type::Atomic:
2579 // FIXME: GCC treats block pointers as fundamental types?!
2580 case Type::BlockPointer:
2581 // abi::__fundamental_type_info.
2582 VTableName = "_ZTVN10__cxxabiv123__fundamental_type_infoE";
2583 break;
2584
2585 case Type::ConstantArray:
2586 case Type::IncompleteArray:
2587 case Type::VariableArray:
2588 // abi::__array_type_info.
2589 VTableName = "_ZTVN10__cxxabiv117__array_type_infoE";
2590 break;
2591
2592 case Type::FunctionNoProto:
2593 case Type::FunctionProto:
2594 // abi::__function_type_info.
2595 VTableName = "_ZTVN10__cxxabiv120__function_type_infoE";
2596 break;
2597
2598 case Type::Enum:
2599 // abi::__enum_type_info.
2600 VTableName = "_ZTVN10__cxxabiv116__enum_type_infoE";
2601 break;
2602
2603 case Type::Record: {
2604 const CXXRecordDecl *RD =
2605 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
2606
2607 if (!RD->hasDefinition() || !RD->getNumBases()) {
2608 VTableName = ClassTypeInfo;
2609 } else if (CanUseSingleInheritance(RD)) {
2610 VTableName = SIClassTypeInfo;
2611 } else {
2612 VTableName = VMIClassTypeInfo;
2613 }
2614
2615 break;
2616 }
2617
2618 case Type::ObjCObject:
2619 // Ignore protocol qualifiers.
2620 Ty = cast<ObjCObjectType>(Ty)->getBaseType().getTypePtr();
2621
2622 // Handle id and Class.
2623 if (isa<BuiltinType>(Ty)) {
2624 VTableName = ClassTypeInfo;
2625 break;
2626 }
2627
2628 assert(isa<ObjCInterfaceType>(Ty));
2629 // Fall through.
2630
2631 case Type::ObjCInterface:
2632 if (cast<ObjCInterfaceType>(Ty)->getDecl()->getSuperClass()) {
2633 VTableName = SIClassTypeInfo;
2634 } else {
2635 VTableName = ClassTypeInfo;
2636 }
2637 break;
2638
2639 case Type::ObjCObjectPointer:
2640 case Type::Pointer:
2641 // abi::__pointer_type_info.
2642 VTableName = "_ZTVN10__cxxabiv119__pointer_type_infoE";
2643 break;
2644
2645 case Type::MemberPointer:
2646 // abi::__pointer_to_member_type_info.
2647 VTableName = "_ZTVN10__cxxabiv129__pointer_to_member_type_infoE";
2648 break;
2649 }
2650
2651 llvm::Constant *VTable =
2652 CGM.getModule().getOrInsertGlobal(VTableName, CGM.Int8PtrTy);
2653
2654 llvm::Type *PtrDiffTy =
2655 CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
2656
2657 // The vtable address point is 2.
2658 llvm::Constant *Two = llvm::ConstantInt::get(PtrDiffTy, 2);
David Blaikiee3b172a2015-04-02 18:55:21 +00002659 VTable =
2660 llvm::ConstantExpr::getInBoundsGetElementPtr(CGM.Int8PtrTy, VTable, Two);
David Majnemere2cb8d12014-07-07 06:20:47 +00002661 VTable = llvm::ConstantExpr::getBitCast(VTable, CGM.Int8PtrTy);
2662
2663 Fields.push_back(VTable);
2664}
2665
2666/// \brief Return the linkage that the type info and type info name constants
2667/// should have for the given type.
2668static llvm::GlobalVariable::LinkageTypes getTypeInfoLinkage(CodeGenModule &CGM,
2669 QualType Ty) {
2670 // Itanium C++ ABI 2.9.5p7:
2671 // In addition, it and all of the intermediate abi::__pointer_type_info
2672 // structs in the chain down to the abi::__class_type_info for the
2673 // incomplete class type must be prevented from resolving to the
2674 // corresponding type_info structs for the complete class type, possibly
2675 // by making them local static objects. Finally, a dummy class RTTI is
2676 // generated for the incomplete type that will not resolve to the final
2677 // complete class RTTI (because the latter need not exist), possibly by
2678 // making it a local static object.
2679 if (ContainsIncompleteClassType(Ty))
2680 return llvm::GlobalValue::InternalLinkage;
2681
2682 switch (Ty->getLinkage()) {
2683 case NoLinkage:
2684 case InternalLinkage:
2685 case UniqueExternalLinkage:
2686 return llvm::GlobalValue::InternalLinkage;
2687
2688 case VisibleNoLinkage:
2689 case ExternalLinkage:
2690 if (!CGM.getLangOpts().RTTI) {
2691 // RTTI is not enabled, which means that this type info struct is going
2692 // to be used for exception handling. Give it linkonce_odr linkage.
2693 return llvm::GlobalValue::LinkOnceODRLinkage;
2694 }
2695
2696 if (const RecordType *Record = dyn_cast<RecordType>(Ty)) {
2697 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2698 if (RD->hasAttr<WeakAttr>())
2699 return llvm::GlobalValue::WeakODRLinkage;
David Majnemerbe9022c2015-08-06 20:56:55 +00002700 if (RD->isDynamicClass()) {
2701 llvm::GlobalValue::LinkageTypes LT = CGM.getVTableLinkage(RD);
2702 // MinGW won't export the RTTI information when there is a key function.
2703 // Make sure we emit our own copy instead of attempting to dllimport it.
2704 if (RD->hasAttr<DLLImportAttr>() &&
2705 llvm::GlobalValue::isAvailableExternallyLinkage(LT))
2706 LT = llvm::GlobalValue::LinkOnceODRLinkage;
2707 return LT;
2708 }
David Majnemere2cb8d12014-07-07 06:20:47 +00002709 }
2710
2711 return llvm::GlobalValue::LinkOnceODRLinkage;
2712 }
2713
2714 llvm_unreachable("Invalid linkage!");
2715}
2716
2717llvm::Constant *ItaniumRTTIBuilder::BuildTypeInfo(QualType Ty, bool Force) {
2718 // We want to operate on the canonical type.
2719 Ty = CGM.getContext().getCanonicalType(Ty);
2720
2721 // Check if we've already emitted an RTTI descriptor for this type.
Yaron Kerene46f7ed2015-07-29 14:21:47 +00002722 SmallString<256> Name;
2723 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00002724 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00002725
2726 llvm::GlobalVariable *OldGV = CGM.getModule().getNamedGlobal(Name);
2727 if (OldGV && !OldGV->isDeclaration()) {
2728 assert(!OldGV->hasAvailableExternallyLinkage() &&
2729 "available_externally typeinfos not yet implemented");
2730
2731 return llvm::ConstantExpr::getBitCast(OldGV, CGM.Int8PtrTy);
2732 }
2733
2734 // Check if there is already an external RTTI descriptor for this type.
2735 bool IsStdLib = IsStandardLibraryRTTIDescriptor(Ty);
2736 if (!Force && (IsStdLib || ShouldUseExternalRTTIDescriptor(CGM, Ty)))
2737 return GetAddrOfExternalRTTIDescriptor(Ty);
2738
2739 // Emit the standard library with external linkage.
2740 llvm::GlobalVariable::LinkageTypes Linkage;
2741 if (IsStdLib)
2742 Linkage = llvm::GlobalValue::ExternalLinkage;
2743 else
2744 Linkage = getTypeInfoLinkage(CGM, Ty);
2745
2746 // Add the vtable pointer.
2747 BuildVTablePointer(cast<Type>(Ty));
2748
2749 // And the name.
2750 llvm::GlobalVariable *TypeName = GetAddrOfTypeName(Ty, Linkage);
2751 llvm::Constant *TypeNameField;
2752
2753 // If we're supposed to demote the visibility, be sure to set a flag
2754 // to use a string comparison for type_info comparisons.
2755 ItaniumCXXABI::RTTIUniquenessKind RTTIUniqueness =
2756 CXXABI.classifyRTTIUniqueness(Ty, Linkage);
2757 if (RTTIUniqueness != ItaniumCXXABI::RUK_Unique) {
2758 // The flag is the sign bit, which on ARM64 is defined to be clear
2759 // for global pointers. This is very ARM64-specific.
2760 TypeNameField = llvm::ConstantExpr::getPtrToInt(TypeName, CGM.Int64Ty);
2761 llvm::Constant *flag =
2762 llvm::ConstantInt::get(CGM.Int64Ty, ((uint64_t)1) << 63);
2763 TypeNameField = llvm::ConstantExpr::getAdd(TypeNameField, flag);
2764 TypeNameField =
2765 llvm::ConstantExpr::getIntToPtr(TypeNameField, CGM.Int8PtrTy);
2766 } else {
2767 TypeNameField = llvm::ConstantExpr::getBitCast(TypeName, CGM.Int8PtrTy);
2768 }
2769 Fields.push_back(TypeNameField);
2770
2771 switch (Ty->getTypeClass()) {
2772#define TYPE(Class, Base)
2773#define ABSTRACT_TYPE(Class, Base)
2774#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2775#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2776#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2777#include "clang/AST/TypeNodes.def"
2778 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
2779
2780 // GCC treats vector types as fundamental types.
2781 case Type::Builtin:
2782 case Type::Vector:
2783 case Type::ExtVector:
2784 case Type::Complex:
2785 case Type::BlockPointer:
2786 // Itanium C++ ABI 2.9.5p4:
2787 // abi::__fundamental_type_info adds no data members to std::type_info.
2788 break;
2789
2790 case Type::LValueReference:
2791 case Type::RValueReference:
2792 llvm_unreachable("References shouldn't get here");
2793
2794 case Type::Auto:
2795 llvm_unreachable("Undeduced auto type shouldn't get here");
2796
2797 case Type::ConstantArray:
2798 case Type::IncompleteArray:
2799 case Type::VariableArray:
2800 // Itanium C++ ABI 2.9.5p5:
2801 // abi::__array_type_info adds no data members to std::type_info.
2802 break;
2803
2804 case Type::FunctionNoProto:
2805 case Type::FunctionProto:
2806 // Itanium C++ ABI 2.9.5p5:
2807 // abi::__function_type_info adds no data members to std::type_info.
2808 break;
2809
2810 case Type::Enum:
2811 // Itanium C++ ABI 2.9.5p5:
2812 // abi::__enum_type_info adds no data members to std::type_info.
2813 break;
2814
2815 case Type::Record: {
2816 const CXXRecordDecl *RD =
2817 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
2818 if (!RD->hasDefinition() || !RD->getNumBases()) {
2819 // We don't need to emit any fields.
2820 break;
2821 }
2822
2823 if (CanUseSingleInheritance(RD))
2824 BuildSIClassTypeInfo(RD);
2825 else
2826 BuildVMIClassTypeInfo(RD);
2827
2828 break;
2829 }
2830
2831 case Type::ObjCObject:
2832 case Type::ObjCInterface:
2833 BuildObjCObjectTypeInfo(cast<ObjCObjectType>(Ty));
2834 break;
2835
2836 case Type::ObjCObjectPointer:
2837 BuildPointerTypeInfo(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
2838 break;
2839
2840 case Type::Pointer:
2841 BuildPointerTypeInfo(cast<PointerType>(Ty)->getPointeeType());
2842 break;
2843
2844 case Type::MemberPointer:
2845 BuildPointerToMemberTypeInfo(cast<MemberPointerType>(Ty));
2846 break;
2847
2848 case Type::Atomic:
2849 // No fields, at least for the moment.
2850 break;
2851 }
2852
2853 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Fields);
2854
Rafael Espindolacb92c192015-01-15 23:18:01 +00002855 llvm::Module &M = CGM.getModule();
David Majnemere2cb8d12014-07-07 06:20:47 +00002856 llvm::GlobalVariable *GV =
Rafael Espindolacb92c192015-01-15 23:18:01 +00002857 new llvm::GlobalVariable(M, Init->getType(),
2858 /*Constant=*/true, Linkage, Init, Name);
2859
David Majnemere2cb8d12014-07-07 06:20:47 +00002860 // If there's already an old global variable, replace it with the new one.
2861 if (OldGV) {
2862 GV->takeName(OldGV);
2863 llvm::Constant *NewPtr =
2864 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
2865 OldGV->replaceAllUsesWith(NewPtr);
2866 OldGV->eraseFromParent();
2867 }
2868
Yaron Keren04da2382015-07-29 15:42:28 +00002869 if (CGM.supportsCOMDAT() && GV->isWeakForLinker())
2870 GV->setComdat(M.getOrInsertComdat(GV->getName()));
2871
David Majnemere2cb8d12014-07-07 06:20:47 +00002872 // The Itanium ABI specifies that type_info objects must be globally
2873 // unique, with one exception: if the type is an incomplete class
2874 // type or a (possibly indirect) pointer to one. That exception
2875 // affects the general case of comparing type_info objects produced
2876 // by the typeid operator, which is why the comparison operators on
2877 // std::type_info generally use the type_info name pointers instead
2878 // of the object addresses. However, the language's built-in uses
2879 // of RTTI generally require class types to be complete, even when
2880 // manipulating pointers to those class types. This allows the
2881 // implementation of dynamic_cast to rely on address equality tests,
2882 // which is much faster.
2883
2884 // All of this is to say that it's important that both the type_info
2885 // object and the type_info name be uniqued when weakly emitted.
2886
2887 // Give the type_info object and name the formal visibility of the
2888 // type itself.
2889 llvm::GlobalValue::VisibilityTypes llvmVisibility;
2890 if (llvm::GlobalValue::isLocalLinkage(Linkage))
2891 // If the linkage is local, only default visibility makes sense.
2892 llvmVisibility = llvm::GlobalValue::DefaultVisibility;
2893 else if (RTTIUniqueness == ItaniumCXXABI::RUK_NonUniqueHidden)
2894 llvmVisibility = llvm::GlobalValue::HiddenVisibility;
2895 else
2896 llvmVisibility = CodeGenModule::GetLLVMVisibility(Ty->getVisibility());
2897 TypeName->setVisibility(llvmVisibility);
2898 GV->setVisibility(llvmVisibility);
2899
2900 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
2901}
2902
2903/// ComputeQualifierFlags - Compute the pointer type info flags from the
2904/// given qualifier.
2905static unsigned ComputeQualifierFlags(Qualifiers Quals) {
2906 unsigned Flags = 0;
2907
2908 if (Quals.hasConst())
2909 Flags |= ItaniumRTTIBuilder::PTI_Const;
2910 if (Quals.hasVolatile())
2911 Flags |= ItaniumRTTIBuilder::PTI_Volatile;
2912 if (Quals.hasRestrict())
2913 Flags |= ItaniumRTTIBuilder::PTI_Restrict;
2914
2915 return Flags;
2916}
2917
2918/// BuildObjCObjectTypeInfo - Build the appropriate kind of type_info
2919/// for the given Objective-C object type.
2920void ItaniumRTTIBuilder::BuildObjCObjectTypeInfo(const ObjCObjectType *OT) {
2921 // Drop qualifiers.
2922 const Type *T = OT->getBaseType().getTypePtr();
2923 assert(isa<BuiltinType>(T) || isa<ObjCInterfaceType>(T));
2924
2925 // The builtin types are abi::__class_type_infos and don't require
2926 // extra fields.
2927 if (isa<BuiltinType>(T)) return;
2928
2929 ObjCInterfaceDecl *Class = cast<ObjCInterfaceType>(T)->getDecl();
2930 ObjCInterfaceDecl *Super = Class->getSuperClass();
2931
2932 // Root classes are also __class_type_info.
2933 if (!Super) return;
2934
2935 QualType SuperTy = CGM.getContext().getObjCInterfaceType(Super);
2936
2937 // Everything else is single inheritance.
2938 llvm::Constant *BaseTypeInfo =
2939 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(SuperTy);
2940 Fields.push_back(BaseTypeInfo);
2941}
2942
2943/// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
2944/// inheritance, according to the Itanium C++ ABI, 2.95p6b.
2945void ItaniumRTTIBuilder::BuildSIClassTypeInfo(const CXXRecordDecl *RD) {
2946 // Itanium C++ ABI 2.9.5p6b:
2947 // It adds to abi::__class_type_info a single member pointing to the
2948 // type_info structure for the base type,
2949 llvm::Constant *BaseTypeInfo =
2950 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(RD->bases_begin()->getType());
2951 Fields.push_back(BaseTypeInfo);
2952}
2953
2954namespace {
2955 /// SeenBases - Contains virtual and non-virtual bases seen when traversing
2956 /// a class hierarchy.
2957 struct SeenBases {
2958 llvm::SmallPtrSet<const CXXRecordDecl *, 16> NonVirtualBases;
2959 llvm::SmallPtrSet<const CXXRecordDecl *, 16> VirtualBases;
2960 };
2961}
2962
2963/// ComputeVMIClassTypeInfoFlags - Compute the value of the flags member in
2964/// abi::__vmi_class_type_info.
2965///
2966static unsigned ComputeVMIClassTypeInfoFlags(const CXXBaseSpecifier *Base,
2967 SeenBases &Bases) {
2968
2969 unsigned Flags = 0;
2970
2971 const CXXRecordDecl *BaseDecl =
2972 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2973
2974 if (Base->isVirtual()) {
2975 // Mark the virtual base as seen.
David Blaikie82e95a32014-11-19 07:49:47 +00002976 if (!Bases.VirtualBases.insert(BaseDecl).second) {
David Majnemere2cb8d12014-07-07 06:20:47 +00002977 // If this virtual base has been seen before, then the class is diamond
2978 // shaped.
2979 Flags |= ItaniumRTTIBuilder::VMI_DiamondShaped;
2980 } else {
2981 if (Bases.NonVirtualBases.count(BaseDecl))
2982 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
2983 }
2984 } else {
2985 // Mark the non-virtual base as seen.
David Blaikie82e95a32014-11-19 07:49:47 +00002986 if (!Bases.NonVirtualBases.insert(BaseDecl).second) {
David Majnemere2cb8d12014-07-07 06:20:47 +00002987 // If this non-virtual base has been seen before, then the class has non-
2988 // diamond shaped repeated inheritance.
2989 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
2990 } else {
2991 if (Bases.VirtualBases.count(BaseDecl))
2992 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
2993 }
2994 }
2995
2996 // Walk all bases.
2997 for (const auto &I : BaseDecl->bases())
2998 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
2999
3000 return Flags;
3001}
3002
3003static unsigned ComputeVMIClassTypeInfoFlags(const CXXRecordDecl *RD) {
3004 unsigned Flags = 0;
3005 SeenBases Bases;
3006
3007 // Walk all bases.
3008 for (const auto &I : RD->bases())
3009 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
3010
3011 return Flags;
3012}
3013
3014/// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
3015/// classes with bases that do not satisfy the abi::__si_class_type_info
3016/// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
3017void ItaniumRTTIBuilder::BuildVMIClassTypeInfo(const CXXRecordDecl *RD) {
3018 llvm::Type *UnsignedIntLTy =
3019 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3020
3021 // Itanium C++ ABI 2.9.5p6c:
3022 // __flags is a word with flags describing details about the class
3023 // structure, which may be referenced by using the __flags_masks
3024 // enumeration. These flags refer to both direct and indirect bases.
3025 unsigned Flags = ComputeVMIClassTypeInfoFlags(RD);
3026 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3027
3028 // Itanium C++ ABI 2.9.5p6c:
3029 // __base_count is a word with the number of direct proper base class
3030 // descriptions that follow.
3031 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, RD->getNumBases()));
3032
3033 if (!RD->getNumBases())
3034 return;
3035
3036 llvm::Type *LongLTy =
3037 CGM.getTypes().ConvertType(CGM.getContext().LongTy);
3038
3039 // Now add the base class descriptions.
3040
3041 // Itanium C++ ABI 2.9.5p6c:
3042 // __base_info[] is an array of base class descriptions -- one for every
3043 // direct proper base. Each description is of the type:
3044 //
3045 // struct abi::__base_class_type_info {
3046 // public:
3047 // const __class_type_info *__base_type;
3048 // long __offset_flags;
3049 //
3050 // enum __offset_flags_masks {
3051 // __virtual_mask = 0x1,
3052 // __public_mask = 0x2,
3053 // __offset_shift = 8
3054 // };
3055 // };
3056 for (const auto &Base : RD->bases()) {
3057 // The __base_type member points to the RTTI for the base type.
3058 Fields.push_back(ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(Base.getType()));
3059
3060 const CXXRecordDecl *BaseDecl =
3061 cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
3062
3063 int64_t OffsetFlags = 0;
3064
3065 // All but the lower 8 bits of __offset_flags are a signed offset.
3066 // For a non-virtual base, this is the offset in the object of the base
3067 // subobject. For a virtual base, this is the offset in the virtual table of
3068 // the virtual base offset for the virtual base referenced (negative).
3069 CharUnits Offset;
3070 if (Base.isVirtual())
3071 Offset =
3072 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(RD, BaseDecl);
3073 else {
3074 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
3075 Offset = Layout.getBaseClassOffset(BaseDecl);
3076 };
3077
3078 OffsetFlags = uint64_t(Offset.getQuantity()) << 8;
3079
3080 // The low-order byte of __offset_flags contains flags, as given by the
3081 // masks from the enumeration __offset_flags_masks.
3082 if (Base.isVirtual())
3083 OffsetFlags |= BCTI_Virtual;
3084 if (Base.getAccessSpecifier() == AS_public)
3085 OffsetFlags |= BCTI_Public;
3086
3087 Fields.push_back(llvm::ConstantInt::get(LongLTy, OffsetFlags));
3088 }
3089}
3090
3091/// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct,
3092/// used for pointer types.
3093void ItaniumRTTIBuilder::BuildPointerTypeInfo(QualType PointeeTy) {
3094 Qualifiers Quals;
3095 QualType UnqualifiedPointeeTy =
3096 CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals);
3097
3098 // Itanium C++ ABI 2.9.5p7:
3099 // __flags is a flag word describing the cv-qualification and other
3100 // attributes of the type pointed to
3101 unsigned Flags = ComputeQualifierFlags(Quals);
3102
3103 // Itanium C++ ABI 2.9.5p7:
3104 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
3105 // incomplete class type, the incomplete target type flag is set.
3106 if (ContainsIncompleteClassType(UnqualifiedPointeeTy))
3107 Flags |= PTI_Incomplete;
3108
3109 llvm::Type *UnsignedIntLTy =
3110 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3111 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3112
3113 // Itanium C++ ABI 2.9.5p7:
3114 // __pointee is a pointer to the std::type_info derivation for the
3115 // unqualified type being pointed to.
3116 llvm::Constant *PointeeTypeInfo =
3117 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(UnqualifiedPointeeTy);
3118 Fields.push_back(PointeeTypeInfo);
3119}
3120
3121/// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
3122/// struct, used for member pointer types.
3123void
3124ItaniumRTTIBuilder::BuildPointerToMemberTypeInfo(const MemberPointerType *Ty) {
3125 QualType PointeeTy = Ty->getPointeeType();
3126
3127 Qualifiers Quals;
3128 QualType UnqualifiedPointeeTy =
3129 CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals);
3130
3131 // Itanium C++ ABI 2.9.5p7:
3132 // __flags is a flag word describing the cv-qualification and other
3133 // attributes of the type pointed to.
3134 unsigned Flags = ComputeQualifierFlags(Quals);
3135
3136 const RecordType *ClassType = cast<RecordType>(Ty->getClass());
3137
3138 // Itanium C++ ABI 2.9.5p7:
3139 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
3140 // incomplete class type, the incomplete target type flag is set.
3141 if (ContainsIncompleteClassType(UnqualifiedPointeeTy))
3142 Flags |= PTI_Incomplete;
3143
3144 if (IsIncompleteClassType(ClassType))
3145 Flags |= PTI_ContainingClassIncomplete;
3146
3147 llvm::Type *UnsignedIntLTy =
3148 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3149 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3150
3151 // Itanium C++ ABI 2.9.5p7:
3152 // __pointee is a pointer to the std::type_info derivation for the
3153 // unqualified type being pointed to.
3154 llvm::Constant *PointeeTypeInfo =
3155 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(UnqualifiedPointeeTy);
3156 Fields.push_back(PointeeTypeInfo);
3157
3158 // Itanium C++ ABI 2.9.5p9:
3159 // __context is a pointer to an abi::__class_type_info corresponding to the
3160 // class type containing the member pointed to
3161 // (e.g., the "A" in "int A::*").
3162 Fields.push_back(
3163 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(QualType(ClassType, 0)));
3164}
3165
David Majnemer443250f2015-03-17 20:35:00 +00003166llvm::Constant *ItaniumCXXABI::getAddrOfRTTIDescriptor(QualType Ty) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003167 return ItaniumRTTIBuilder(*this).BuildTypeInfo(Ty);
3168}
3169
3170void ItaniumCXXABI::EmitFundamentalRTTIDescriptor(QualType Type) {
3171 QualType PointerType = getContext().getPointerType(Type);
3172 QualType PointerTypeConst = getContext().getPointerType(Type.withConst());
3173 ItaniumRTTIBuilder(*this).BuildTypeInfo(Type, true);
3174 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerType, true);
3175 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerTypeConst, true);
3176}
3177
3178void ItaniumCXXABI::EmitFundamentalRTTIDescriptors() {
3179 QualType FundamentalTypes[] = {
3180 getContext().VoidTy, getContext().NullPtrTy,
3181 getContext().BoolTy, getContext().WCharTy,
3182 getContext().CharTy, getContext().UnsignedCharTy,
3183 getContext().SignedCharTy, getContext().ShortTy,
3184 getContext().UnsignedShortTy, getContext().IntTy,
3185 getContext().UnsignedIntTy, getContext().LongTy,
3186 getContext().UnsignedLongTy, getContext().LongLongTy,
3187 getContext().UnsignedLongLongTy, getContext().HalfTy,
3188 getContext().FloatTy, getContext().DoubleTy,
3189 getContext().LongDoubleTy, getContext().Char16Ty,
3190 getContext().Char32Ty,
3191 };
3192 for (const QualType &FundamentalType : FundamentalTypes)
3193 EmitFundamentalRTTIDescriptor(FundamentalType);
3194}
3195
3196/// What sort of uniqueness rules should we use for the RTTI for the
3197/// given type?
3198ItaniumCXXABI::RTTIUniquenessKind ItaniumCXXABI::classifyRTTIUniqueness(
3199 QualType CanTy, llvm::GlobalValue::LinkageTypes Linkage) const {
3200 if (shouldRTTIBeUnique())
3201 return RUK_Unique;
3202
3203 // It's only necessary for linkonce_odr or weak_odr linkage.
3204 if (Linkage != llvm::GlobalValue::LinkOnceODRLinkage &&
3205 Linkage != llvm::GlobalValue::WeakODRLinkage)
3206 return RUK_Unique;
3207
3208 // It's only necessary with default visibility.
3209 if (CanTy->getVisibility() != DefaultVisibility)
3210 return RUK_Unique;
3211
3212 // If we're not required to publish this symbol, hide it.
3213 if (Linkage == llvm::GlobalValue::LinkOnceODRLinkage)
3214 return RUK_NonUniqueHidden;
3215
3216 // If we're required to publish this symbol, as we might be under an
3217 // explicit instantiation, leave it with default visibility but
3218 // enable string-comparisons.
3219 assert(Linkage == llvm::GlobalValue::WeakODRLinkage);
3220 return RUK_NonUniqueVisible;
3221}
Rafael Espindola91f68b42014-09-15 19:20:10 +00003222
Rafael Espindola1e4df922014-09-16 15:18:21 +00003223// Find out how to codegen the complete destructor and constructor
3224namespace {
3225enum class StructorCodegen { Emit, RAUW, Alias, COMDAT };
3226}
3227static StructorCodegen getCodegenToUse(CodeGenModule &CGM,
3228 const CXXMethodDecl *MD) {
3229 if (!CGM.getCodeGenOpts().CXXCtorDtorAliases)
3230 return StructorCodegen::Emit;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003231
Rafael Espindola1e4df922014-09-16 15:18:21 +00003232 // The complete and base structors are not equivalent if there are any virtual
3233 // bases, so emit separate functions.
3234 if (MD->getParent()->getNumVBases())
3235 return StructorCodegen::Emit;
3236
3237 GlobalDecl AliasDecl;
3238 if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) {
3239 AliasDecl = GlobalDecl(DD, Dtor_Complete);
3240 } else {
3241 const auto *CD = cast<CXXConstructorDecl>(MD);
3242 AliasDecl = GlobalDecl(CD, Ctor_Complete);
3243 }
3244 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3245
3246 if (llvm::GlobalValue::isDiscardableIfUnused(Linkage))
3247 return StructorCodegen::RAUW;
3248
3249 // FIXME: Should we allow available_externally aliases?
3250 if (!llvm::GlobalAlias::isValidLinkage(Linkage))
3251 return StructorCodegen::RAUW;
3252
Rafael Espindola0806f982014-09-16 20:19:43 +00003253 if (llvm::GlobalValue::isWeakForLinker(Linkage)) {
3254 // Only ELF supports COMDATs with arbitrary names (C5/D5).
3255 if (CGM.getTarget().getTriple().isOSBinFormatELF())
3256 return StructorCodegen::COMDAT;
3257 return StructorCodegen::Emit;
3258 }
Rafael Espindola1e4df922014-09-16 15:18:21 +00003259
3260 return StructorCodegen::Alias;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003261}
3262
Rafael Espindola1e4df922014-09-16 15:18:21 +00003263static void emitConstructorDestructorAlias(CodeGenModule &CGM,
3264 GlobalDecl AliasDecl,
3265 GlobalDecl TargetDecl) {
3266 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3267
3268 StringRef MangledName = CGM.getMangledName(AliasDecl);
3269 llvm::GlobalValue *Entry = CGM.GetGlobalValue(MangledName);
3270 if (Entry && !Entry->isDeclaration())
3271 return;
3272
3273 auto *Aliasee = cast<llvm::GlobalValue>(CGM.GetAddrOfGlobal(TargetDecl));
3274 llvm::PointerType *AliasType = Aliasee->getType();
3275
3276 // Create the alias with no name.
David Blaikie881b2342015-04-29 21:22:47 +00003277 auto *Alias = llvm::GlobalAlias::create(AliasType, Linkage, "", Aliasee,
3278 &CGM.getModule());
Rafael Espindola1e4df922014-09-16 15:18:21 +00003279
3280 // Switch any previous uses to the alias.
3281 if (Entry) {
3282 assert(Entry->getType() == AliasType &&
3283 "declaration exists with different type");
3284 Alias->takeName(Entry);
3285 Entry->replaceAllUsesWith(Alias);
3286 Entry->eraseFromParent();
3287 } else {
3288 Alias->setName(MangledName);
3289 }
3290
3291 // Finally, set up the alias with its proper name and attributes.
Dario Domiziolic4fb8ca72014-09-19 22:06:24 +00003292 CGM.setAliasAttributes(cast<NamedDecl>(AliasDecl.getDecl()), Alias);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003293}
3294
3295void ItaniumCXXABI::emitCXXStructor(const CXXMethodDecl *MD,
3296 StructorType Type) {
3297 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
3298 const CXXDestructorDecl *DD = CD ? nullptr : cast<CXXDestructorDecl>(MD);
3299
3300 StructorCodegen CGType = getCodegenToUse(CGM, MD);
3301
3302 if (Type == StructorType::Complete) {
3303 GlobalDecl CompleteDecl;
3304 GlobalDecl BaseDecl;
3305 if (CD) {
3306 CompleteDecl = GlobalDecl(CD, Ctor_Complete);
3307 BaseDecl = GlobalDecl(CD, Ctor_Base);
3308 } else {
3309 CompleteDecl = GlobalDecl(DD, Dtor_Complete);
3310 BaseDecl = GlobalDecl(DD, Dtor_Base);
3311 }
3312
3313 if (CGType == StructorCodegen::Alias || CGType == StructorCodegen::COMDAT) {
3314 emitConstructorDestructorAlias(CGM, CompleteDecl, BaseDecl);
3315 return;
3316 }
3317
3318 if (CGType == StructorCodegen::RAUW) {
3319 StringRef MangledName = CGM.getMangledName(CompleteDecl);
Andrey Bokhankocab58582015-08-31 13:20:44 +00003320 auto *Aliasee = CGM.GetAddrOfGlobal(BaseDecl);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003321 CGM.addReplacement(MangledName, Aliasee);
3322 return;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003323 }
3324 }
3325
3326 // The base destructor is equivalent to the base destructor of its
3327 // base class if there is exactly one non-virtual base class with a
3328 // non-trivial destructor, there are no fields with a non-trivial
3329 // destructor, and the body of the destructor is trivial.
Rafael Espindola1e4df922014-09-16 15:18:21 +00003330 if (DD && Type == StructorType::Base && CGType != StructorCodegen::COMDAT &&
3331 !CGM.TryEmitBaseDestructorAsAlias(DD))
Rafael Espindola91f68b42014-09-15 19:20:10 +00003332 return;
3333
Rafael Espindola1e4df922014-09-16 15:18:21 +00003334 llvm::Function *Fn = CGM.codegenCXXStructor(MD, Type);
Rafael Espindola91f68b42014-09-15 19:20:10 +00003335
Rafael Espindola1e4df922014-09-16 15:18:21 +00003336 if (CGType == StructorCodegen::COMDAT) {
3337 SmallString<256> Buffer;
3338 llvm::raw_svector_ostream Out(Buffer);
3339 if (DD)
3340 getMangleContext().mangleCXXDtorComdat(DD, Out);
3341 else
3342 getMangleContext().mangleCXXCtorComdat(CD, Out);
3343 llvm::Comdat *C = CGM.getModule().getOrInsertComdat(Out.str());
3344 Fn->setComdat(C);
Rafael Espindoladbee8a72015-01-15 21:36:08 +00003345 } else {
3346 CGM.maybeSetTrivialComdat(*MD, *Fn);
Rafael Espindola91f68b42014-09-15 19:20:10 +00003347 }
Rafael Espindola91f68b42014-09-15 19:20:10 +00003348}
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003349
3350static llvm::Constant *getBeginCatchFn(CodeGenModule &CGM) {
3351 // void *__cxa_begin_catch(void*);
3352 llvm::FunctionType *FTy = llvm::FunctionType::get(
3353 CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3354
3355 return CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
3356}
3357
3358static llvm::Constant *getEndCatchFn(CodeGenModule &CGM) {
3359 // void __cxa_end_catch();
3360 llvm::FunctionType *FTy =
3361 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
3362
3363 return CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
3364}
3365
3366static llvm::Constant *getGetExceptionPtrFn(CodeGenModule &CGM) {
3367 // void *__cxa_get_exception_ptr(void*);
3368 llvm::FunctionType *FTy = llvm::FunctionType::get(
3369 CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3370
3371 return CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
3372}
3373
3374namespace {
3375 /// A cleanup to call __cxa_end_catch. In many cases, the caught
3376 /// exception type lets us state definitively that the thrown exception
3377 /// type does not have a destructor. In particular:
3378 /// - Catch-alls tell us nothing, so we have to conservatively
3379 /// assume that the thrown exception might have a destructor.
3380 /// - Catches by reference behave according to their base types.
3381 /// - Catches of non-record types will only trigger for exceptions
3382 /// of non-record types, which never have destructors.
3383 /// - Catches of record types can trigger for arbitrary subclasses
3384 /// of the caught type, so we have to assume the actual thrown
3385 /// exception type might have a throwing destructor, even if the
3386 /// caught type's destructor is trivial or nothrow.
David Blaikie7e70d682015-08-18 22:40:54 +00003387 struct CallEndCatch final : EHScopeStack::Cleanup {
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003388 CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
3389 bool MightThrow;
3390
3391 void Emit(CodeGenFunction &CGF, Flags flags) override {
3392 if (!MightThrow) {
3393 CGF.EmitNounwindRuntimeCall(getEndCatchFn(CGF.CGM));
3394 return;
3395 }
3396
3397 CGF.EmitRuntimeCallOrInvoke(getEndCatchFn(CGF.CGM));
3398 }
3399 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003400}
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003401
3402/// Emits a call to __cxa_begin_catch and enters a cleanup to call
3403/// __cxa_end_catch.
3404///
3405/// \param EndMightThrow - true if __cxa_end_catch might throw
3406static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
3407 llvm::Value *Exn,
3408 bool EndMightThrow) {
3409 llvm::CallInst *call =
3410 CGF.EmitNounwindRuntimeCall(getBeginCatchFn(CGF.CGM), Exn);
3411
3412 CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
3413
3414 return call;
3415}
3416
3417/// A "special initializer" callback for initializing a catch
3418/// parameter during catch initialization.
3419static void InitCatchParam(CodeGenFunction &CGF,
3420 const VarDecl &CatchParam,
3421 llvm::Value *ParamAddr,
3422 SourceLocation Loc) {
3423 // Load the exception from where the landing pad saved it.
3424 llvm::Value *Exn = CGF.getExceptionFromSlot();
3425
3426 CanQualType CatchType =
3427 CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
3428 llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
3429
3430 // If we're catching by reference, we can just cast the object
3431 // pointer to the appropriate pointer.
3432 if (isa<ReferenceType>(CatchType)) {
3433 QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
3434 bool EndCatchMightThrow = CaughtType->isRecordType();
3435
3436 // __cxa_begin_catch returns the adjusted object pointer.
3437 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
3438
3439 // We have no way to tell the personality function that we're
3440 // catching by reference, so if we're catching a pointer,
3441 // __cxa_begin_catch will actually return that pointer by value.
3442 if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
3443 QualType PointeeType = PT->getPointeeType();
3444
3445 // When catching by reference, generally we should just ignore
3446 // this by-value pointer and use the exception object instead.
3447 if (!PointeeType->isRecordType()) {
3448
3449 // Exn points to the struct _Unwind_Exception header, which
3450 // we have to skip past in order to reach the exception data.
3451 unsigned HeaderSize =
3452 CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
3453 AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
3454
3455 // However, if we're catching a pointer-to-record type that won't
3456 // work, because the personality function might have adjusted
3457 // the pointer. There's actually no way for us to fully satisfy
3458 // the language/ABI contract here: we can't use Exn because it
3459 // might have the wrong adjustment, but we can't use the by-value
3460 // pointer because it's off by a level of abstraction.
3461 //
3462 // The current solution is to dump the adjusted pointer into an
3463 // alloca, which breaks language semantics (because changing the
3464 // pointer doesn't change the exception) but at least works.
3465 // The better solution would be to filter out non-exact matches
3466 // and rethrow them, but this is tricky because the rethrow
3467 // really needs to be catchable by other sites at this landing
3468 // pad. The best solution is to fix the personality function.
3469 } else {
3470 // Pull the pointer for the reference type off.
3471 llvm::Type *PtrTy =
3472 cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
3473
3474 // Create the temporary and write the adjusted pointer into it.
3475 llvm::Value *ExnPtrTmp = CGF.CreateTempAlloca(PtrTy, "exn.byref.tmp");
3476 llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
3477 CGF.Builder.CreateStore(Casted, ExnPtrTmp);
3478
3479 // Bind the reference to the temporary.
3480 AdjustedExn = ExnPtrTmp;
3481 }
3482 }
3483
3484 llvm::Value *ExnCast =
3485 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
3486 CGF.Builder.CreateStore(ExnCast, ParamAddr);
3487 return;
3488 }
3489
3490 // Scalars and complexes.
3491 TypeEvaluationKind TEK = CGF.getEvaluationKind(CatchType);
3492 if (TEK != TEK_Aggregate) {
3493 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
3494
3495 // If the catch type is a pointer type, __cxa_begin_catch returns
3496 // the pointer by value.
3497 if (CatchType->hasPointerRepresentation()) {
3498 llvm::Value *CastExn =
3499 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
3500
3501 switch (CatchType.getQualifiers().getObjCLifetime()) {
3502 case Qualifiers::OCL_Strong:
3503 CastExn = CGF.EmitARCRetainNonBlock(CastExn);
3504 // fallthrough
3505
3506 case Qualifiers::OCL_None:
3507 case Qualifiers::OCL_ExplicitNone:
3508 case Qualifiers::OCL_Autoreleasing:
3509 CGF.Builder.CreateStore(CastExn, ParamAddr);
3510 return;
3511
3512 case Qualifiers::OCL_Weak:
3513 CGF.EmitARCInitWeak(ParamAddr, CastExn);
3514 return;
3515 }
3516 llvm_unreachable("bad ownership qualifier!");
3517 }
3518
3519 // Otherwise, it returns a pointer into the exception object.
3520
3521 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
3522 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
3523
3524 LValue srcLV = CGF.MakeNaturalAlignAddrLValue(Cast, CatchType);
3525 LValue destLV = CGF.MakeAddrLValue(ParamAddr, CatchType,
3526 CGF.getContext().getDeclAlign(&CatchParam));
3527 switch (TEK) {
3528 case TEK_Complex:
3529 CGF.EmitStoreOfComplex(CGF.EmitLoadOfComplex(srcLV, Loc), destLV,
3530 /*init*/ true);
3531 return;
3532 case TEK_Scalar: {
3533 llvm::Value *ExnLoad = CGF.EmitLoadOfScalar(srcLV, Loc);
3534 CGF.EmitStoreOfScalar(ExnLoad, destLV, /*init*/ true);
3535 return;
3536 }
3537 case TEK_Aggregate:
3538 llvm_unreachable("evaluation kind filtered out!");
3539 }
3540 llvm_unreachable("bad evaluation kind");
3541 }
3542
3543 assert(isa<RecordType>(CatchType) && "unexpected catch type!");
3544
3545 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
3546
3547 // Check for a copy expression. If we don't have a copy expression,
3548 // that means a trivial copy is okay.
3549 const Expr *copyExpr = CatchParam.getInit();
3550 if (!copyExpr) {
3551 llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true);
3552 llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
3553 CGF.EmitAggregateCopy(ParamAddr, adjustedExn, CatchType);
3554 return;
3555 }
3556
3557 // We have to call __cxa_get_exception_ptr to get the adjusted
3558 // pointer before copying.
3559 llvm::CallInst *rawAdjustedExn =
3560 CGF.EmitNounwindRuntimeCall(getGetExceptionPtrFn(CGF.CGM), Exn);
3561
3562 // Cast that to the appropriate type.
3563 llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
3564
3565 // The copy expression is defined in terms of an OpaqueValueExpr.
3566 // Find it and map it to the adjusted expression.
3567 CodeGenFunction::OpaqueValueMapping
3568 opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr),
3569 CGF.MakeAddrLValue(adjustedExn, CatchParam.getType()));
3570
3571 // Call the copy ctor in a terminate scope.
3572 CGF.EHStack.pushTerminate();
3573
3574 // Perform the copy construction.
3575 CharUnits Alignment = CGF.getContext().getDeclAlign(&CatchParam);
3576 CGF.EmitAggExpr(copyExpr,
3577 AggValueSlot::forAddr(ParamAddr, Alignment, Qualifiers(),
3578 AggValueSlot::IsNotDestructed,
3579 AggValueSlot::DoesNotNeedGCBarriers,
3580 AggValueSlot::IsNotAliased));
3581
3582 // Leave the terminate scope.
3583 CGF.EHStack.popTerminate();
3584
3585 // Undo the opaque value mapping.
3586 opaque.pop();
3587
3588 // Finally we can call __cxa_begin_catch.
3589 CallBeginCatch(CGF, Exn, true);
3590}
3591
3592/// Begins a catch statement by initializing the catch variable and
3593/// calling __cxa_begin_catch.
3594void ItaniumCXXABI::emitBeginCatch(CodeGenFunction &CGF,
3595 const CXXCatchStmt *S) {
3596 // We have to be very careful with the ordering of cleanups here:
3597 // C++ [except.throw]p4:
3598 // The destruction [of the exception temporary] occurs
3599 // immediately after the destruction of the object declared in
3600 // the exception-declaration in the handler.
3601 //
3602 // So the precise ordering is:
3603 // 1. Construct catch variable.
3604 // 2. __cxa_begin_catch
3605 // 3. Enter __cxa_end_catch cleanup
3606 // 4. Enter dtor cleanup
3607 //
3608 // We do this by using a slightly abnormal initialization process.
3609 // Delegation sequence:
3610 // - ExitCXXTryStmt opens a RunCleanupsScope
3611 // - EmitAutoVarAlloca creates the variable and debug info
3612 // - InitCatchParam initializes the variable from the exception
3613 // - CallBeginCatch calls __cxa_begin_catch
3614 // - CallBeginCatch enters the __cxa_end_catch cleanup
3615 // - EmitAutoVarCleanups enters the variable destructor cleanup
3616 // - EmitCXXTryStmt emits the code for the catch body
3617 // - EmitCXXTryStmt close the RunCleanupsScope
3618
3619 VarDecl *CatchParam = S->getExceptionDecl();
3620 if (!CatchParam) {
3621 llvm::Value *Exn = CGF.getExceptionFromSlot();
3622 CallBeginCatch(CGF, Exn, true);
3623 return;
3624 }
3625
3626 // Emit the local.
3627 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
3628 InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF), S->getLocStart());
3629 CGF.EmitAutoVarCleanups(var);
3630}
3631
3632/// Get or define the following function:
3633/// void @__clang_call_terminate(i8* %exn) nounwind noreturn
3634/// This code is used only in C++.
3635static llvm::Constant *getClangCallTerminateFn(CodeGenModule &CGM) {
3636 llvm::FunctionType *fnTy =
3637 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3638 llvm::Constant *fnRef =
3639 CGM.CreateRuntimeFunction(fnTy, "__clang_call_terminate");
3640
3641 llvm::Function *fn = dyn_cast<llvm::Function>(fnRef);
3642 if (fn && fn->empty()) {
3643 fn->setDoesNotThrow();
3644 fn->setDoesNotReturn();
3645
3646 // What we really want is to massively penalize inlining without
3647 // forbidding it completely. The difference between that and
3648 // 'noinline' is negligible.
3649 fn->addFnAttr(llvm::Attribute::NoInline);
3650
3651 // Allow this function to be shared across translation units, but
3652 // we don't want it to turn into an exported symbol.
3653 fn->setLinkage(llvm::Function::LinkOnceODRLinkage);
3654 fn->setVisibility(llvm::Function::HiddenVisibility);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00003655 if (CGM.supportsCOMDAT())
3656 fn->setComdat(CGM.getModule().getOrInsertComdat(fn->getName()));
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003657
3658 // Set up the function.
3659 llvm::BasicBlock *entry =
3660 llvm::BasicBlock::Create(CGM.getLLVMContext(), "", fn);
3661 CGBuilderTy builder(entry);
3662
3663 // Pull the exception pointer out of the parameter list.
3664 llvm::Value *exn = &*fn->arg_begin();
3665
3666 // Call __cxa_begin_catch(exn).
3667 llvm::CallInst *catchCall = builder.CreateCall(getBeginCatchFn(CGM), exn);
3668 catchCall->setDoesNotThrow();
3669 catchCall->setCallingConv(CGM.getRuntimeCC());
3670
3671 // Call std::terminate().
David Blaikie4ba525b2015-07-14 17:27:39 +00003672 llvm::CallInst *termCall = builder.CreateCall(CGM.getTerminateFn());
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003673 termCall->setDoesNotThrow();
3674 termCall->setDoesNotReturn();
3675 termCall->setCallingConv(CGM.getRuntimeCC());
3676
3677 // std::terminate cannot return.
3678 builder.CreateUnreachable();
3679 }
3680
3681 return fnRef;
3682}
3683
3684llvm::CallInst *
3685ItaniumCXXABI::emitTerminateForUnexpectedException(CodeGenFunction &CGF,
3686 llvm::Value *Exn) {
3687 // In C++, we want to call __cxa_begin_catch() before terminating.
3688 if (Exn) {
3689 assert(CGF.CGM.getLangOpts().CPlusPlus);
3690 return CGF.EmitNounwindRuntimeCall(getClangCallTerminateFn(CGF.CGM), Exn);
3691 }
3692 return CGF.EmitNounwindRuntimeCall(CGF.CGM.getTerminateFn());
3693}