blob: 0b65088e619634ff43c4dbe6c14dc703ebd68088 [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,
195 BaseSubobject Base, const CXXRecordDecl *NearestVBase,
Craig Topper4f12f102014-03-12 06:41:41 +0000196 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
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000218 bool canEmitAvailableExternallyVTable(const CXXRecordDecl *RD) const override;
219
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:
309 /// Checks if function has any virtual inline function.
310 bool hasAnyVirtualInlineFunction(const CXXRecordDecl *RD) const {
311 const auto &VtableLayout =
312 CGM.getItaniumVTableContext().getVTableLayout(RD);
313
314 for (const auto &VtableComponent : VtableLayout.vtable_components()) {
315 if (VtableComponent.getKind() !=
316 VTableComponent::Kind::CK_FunctionPointer)
317 continue;
318
319 const auto &Method = VtableComponent.getFunctionDecl();
320 if (Method->getCanonicalDecl()->isInlined())
321 return true;
322 }
323 return false;
324 }
Charles Davis4e786dd2010-05-25 19:52:27 +0000325};
John McCall86353412010-08-21 22:46:04 +0000326
327class ARMCXXABI : public ItaniumCXXABI {
328public:
Mark Seabornedf0d382013-07-24 16:25:13 +0000329 ARMCXXABI(CodeGen::CodeGenModule &CGM) :
330 ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
331 /* UseARMGuardVarABI = */ true) {}
John McCall5d865c322010-08-31 07:33:07 +0000332
Craig Topper4f12f102014-03-12 06:41:41 +0000333 bool HasThisReturn(GlobalDecl GD) const override {
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000334 return (isa<CXXConstructorDecl>(GD.getDecl()) || (
335 isa<CXXDestructorDecl>(GD.getDecl()) &&
336 GD.getDtorType() != Dtor_Deleting));
337 }
John McCall5d865c322010-08-31 07:33:07 +0000338
Craig Topper4f12f102014-03-12 06:41:41 +0000339 void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV,
340 QualType ResTy) override;
John McCall5d865c322010-08-31 07:33:07 +0000341
Craig Topper4f12f102014-03-12 06:41:41 +0000342 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
John McCall8ed55a52010-09-02 09:58:18 +0000343 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
344 llvm::Value *NewPtr,
345 llvm::Value *NumElements,
John McCall284c48f2011-01-27 09:37:56 +0000346 const CXXNewExpr *expr,
Craig Topper4f12f102014-03-12 06:41:41 +0000347 QualType ElementType) override;
John McCallb91cd662012-05-01 05:23:51 +0000348 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, llvm::Value *allocPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000349 CharUnits cookieSize) override;
John McCall86353412010-08-21 22:46:04 +0000350};
Tim Northovera2ee4332014-03-29 15:09:45 +0000351
352class iOS64CXXABI : public ARMCXXABI {
353public:
354 iOS64CXXABI(CodeGen::CodeGenModule &CGM) : ARMCXXABI(CGM) {}
Tim Northover65f582f2014-03-30 17:32:48 +0000355
356 // ARM64 libraries are prepared for non-unique RTTI.
David Majnemere2cb8d12014-07-07 06:20:47 +0000357 bool shouldRTTIBeUnique() const override { return false; }
Tim Northovera2ee4332014-03-29 15:09:45 +0000358};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000359}
Charles Davis4e786dd2010-05-25 19:52:27 +0000360
Charles Davis53c59df2010-08-16 03:33:14 +0000361CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
John McCallc8e01702013-04-16 22:48:15 +0000362 switch (CGM.getTarget().getCXXABI().getKind()) {
John McCall57625922013-01-25 23:36:14 +0000363 // For IR-generation purposes, there's no significant difference
364 // between the ARM and iOS ABIs.
365 case TargetCXXABI::GenericARM:
366 case TargetCXXABI::iOS:
367 return new ARMCXXABI(CGM);
Charles Davis4e786dd2010-05-25 19:52:27 +0000368
Tim Northovera2ee4332014-03-29 15:09:45 +0000369 case TargetCXXABI::iOS64:
370 return new iOS64CXXABI(CGM);
371
Tim Northover9bb857a2013-01-31 12:13:10 +0000372 // Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't
373 // include the other 32-bit ARM oddities: constructor/destructor return values
374 // and array cookies.
375 case TargetCXXABI::GenericAArch64:
Mark Seabornedf0d382013-07-24 16:25:13 +0000376 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
377 /* UseARMGuardVarABI = */ true);
Tim Northover9bb857a2013-01-31 12:13:10 +0000378
Zoran Jovanovic26a12162015-02-18 15:21:35 +0000379 case TargetCXXABI::GenericMIPS:
380 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true);
381
John McCall57625922013-01-25 23:36:14 +0000382 case TargetCXXABI::GenericItanium:
Mark Seabornedf0d382013-07-24 16:25:13 +0000383 if (CGM.getContext().getTargetInfo().getTriple().getArch()
384 == llvm::Triple::le32) {
385 // For PNaCl, use ARM-style method pointers so that PNaCl code
386 // does not assume anything about the alignment of function
387 // pointers.
388 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
389 /* UseARMGuardVarABI = */ false);
390 }
John McCall57625922013-01-25 23:36:14 +0000391 return new ItaniumCXXABI(CGM);
392
393 case TargetCXXABI::Microsoft:
394 llvm_unreachable("Microsoft ABI is not Itanium-based");
395 }
396 llvm_unreachable("bad ABI kind");
John McCall86353412010-08-21 22:46:04 +0000397}
398
Chris Lattnera5f58b02011-07-09 17:41:47 +0000399llvm::Type *
John McCall7a9aac22010-08-23 01:21:21 +0000400ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
401 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000402 return CGM.PtrDiffTy;
Reid Kleckneree7cf842014-12-01 22:02:27 +0000403 return llvm::StructType::get(CGM.PtrDiffTy, CGM.PtrDiffTy, nullptr);
John McCall1c456c82010-08-22 06:43:33 +0000404}
405
John McCalld9c6c0b2010-08-22 00:59:17 +0000406/// In the Itanium and ARM ABIs, method pointers have the form:
407/// struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
408///
409/// In the Itanium ABI:
410/// - method pointers are virtual if (memptr.ptr & 1) is nonzero
411/// - the this-adjustment is (memptr.adj)
412/// - the virtual offset is (memptr.ptr - 1)
413///
414/// In the ARM ABI:
415/// - method pointers are virtual if (memptr.adj & 1) is nonzero
416/// - the this-adjustment is (memptr.adj >> 1)
417/// - the virtual offset is (memptr.ptr)
418/// ARM uses 'adj' for the virtual flag because Thumb functions
419/// may be only single-byte aligned.
420///
421/// If the member is virtual, the adjusted 'this' pointer points
422/// to a vtable pointer from which the virtual offset is applied.
423///
424/// If the member is non-virtual, memptr.ptr is the address of
425/// the function to call.
David Majnemer2b0d66d2014-02-20 23:22:07 +0000426llvm::Value *ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(
427 CodeGenFunction &CGF, const Expr *E, llvm::Value *&This,
428 llvm::Value *MemFnPtr, const MemberPointerType *MPT) {
John McCall475999d2010-08-22 00:05:51 +0000429 CGBuilderTy &Builder = CGF.Builder;
430
431 const FunctionProtoType *FPT =
432 MPT->getPointeeType()->getAs<FunctionProtoType>();
433 const CXXRecordDecl *RD =
434 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
435
Chris Lattner2192fe52011-07-18 04:24:23 +0000436 llvm::FunctionType *FTy =
John McCalla729c622012-02-17 03:33:10 +0000437 CGM.getTypes().GetFunctionType(
438 CGM.getTypes().arrangeCXXMethodType(RD, FPT));
John McCall475999d2010-08-22 00:05:51 +0000439
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000440 llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(CGM.PtrDiffTy, 1);
John McCall475999d2010-08-22 00:05:51 +0000441
John McCalld9c6c0b2010-08-22 00:59:17 +0000442 llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
443 llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
444 llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
445
John McCalla1dee5302010-08-22 10:59:02 +0000446 // Extract memptr.adj, which is in the second field.
447 llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
John McCalld9c6c0b2010-08-22 00:59:17 +0000448
449 // Compute the true adjustment.
450 llvm::Value *Adj = RawAdj;
Mark Seabornedf0d382013-07-24 16:25:13 +0000451 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000452 Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
John McCall475999d2010-08-22 00:05:51 +0000453
454 // Apply the adjustment and cast back to the original struct type
455 // for consistency.
John McCalld9c6c0b2010-08-22 00:59:17 +0000456 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
457 Ptr = Builder.CreateInBoundsGEP(Ptr, Adj);
458 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
John McCall475999d2010-08-22 00:05:51 +0000459
460 // Load the function pointer.
John McCalla1dee5302010-08-22 10:59:02 +0000461 llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
John McCall475999d2010-08-22 00:05:51 +0000462
463 // If the LSB in the function pointer is 1, the function pointer points to
464 // a virtual function.
John McCalld9c6c0b2010-08-22 00:59:17 +0000465 llvm::Value *IsVirtual;
Mark Seabornedf0d382013-07-24 16:25:13 +0000466 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000467 IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
468 else
469 IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
470 IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
John McCall475999d2010-08-22 00:05:51 +0000471 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
472
473 // In the virtual path, the adjustment left 'This' pointing to the
474 // vtable of the correct base subobject. The "function pointer" is an
John McCalld9c6c0b2010-08-22 00:59:17 +0000475 // offset within the vtable (+1 for the virtual flag on non-ARM).
John McCall475999d2010-08-22 00:05:51 +0000476 CGF.EmitBlock(FnVirtual);
477
478 // Cast the adjusted this to a pointer to vtable pointer and load.
Chris Lattner2192fe52011-07-18 04:24:23 +0000479 llvm::Type *VTableTy = Builder.getInt8PtrTy();
Richard Smith0fc7bdc2014-03-12 18:26:14 +0000480 llvm::Value *VTable = CGF.GetVTablePtr(This, VTableTy);
John McCall475999d2010-08-22 00:05:51 +0000481
482 // Apply the offset.
John McCalld9c6c0b2010-08-22 00:59:17 +0000483 llvm::Value *VTableOffset = FnAsInt;
Mark Seabornedf0d382013-07-24 16:25:13 +0000484 if (!UseARMMethodPtrABI)
485 VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
John McCalld9c6c0b2010-08-22 00:59:17 +0000486 VTable = Builder.CreateGEP(VTable, VTableOffset);
John McCall475999d2010-08-22 00:05:51 +0000487
488 // Load the virtual function to call.
489 VTable = Builder.CreateBitCast(VTable, FTy->getPointerTo()->getPointerTo());
John McCalld9c6c0b2010-08-22 00:59:17 +0000490 llvm::Value *VirtualFn = Builder.CreateLoad(VTable, "memptr.virtualfn");
John McCall475999d2010-08-22 00:05:51 +0000491 CGF.EmitBranch(FnEnd);
492
493 // In the non-virtual path, the function pointer is actually a
494 // function pointer.
495 CGF.EmitBlock(FnNonVirtual);
496 llvm::Value *NonVirtualFn =
John McCalld9c6c0b2010-08-22 00:59:17 +0000497 Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn");
John McCall475999d2010-08-22 00:05:51 +0000498
499 // We're done.
500 CGF.EmitBlock(FnEnd);
Jay Foad20c0f022011-03-30 11:28:58 +0000501 llvm::PHINode *Callee = Builder.CreatePHI(FTy->getPointerTo(), 2);
John McCall475999d2010-08-22 00:05:51 +0000502 Callee->addIncoming(VirtualFn, FnVirtual);
503 Callee->addIncoming(NonVirtualFn, FnNonVirtual);
504 return Callee;
505}
John McCalla8bbb822010-08-22 03:04:22 +0000506
John McCallc134eb52010-08-31 21:07:20 +0000507/// Compute an l-value by applying the given pointer-to-member to a
508/// base object.
David Majnemer2b0d66d2014-02-20 23:22:07 +0000509llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(
510 CodeGenFunction &CGF, const Expr *E, llvm::Value *Base, llvm::Value *MemPtr,
511 const MemberPointerType *MPT) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000512 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCallc134eb52010-08-31 21:07:20 +0000513
514 CGBuilderTy &Builder = CGF.Builder;
515
Micah Villmowea2fea22012-10-25 15:39:14 +0000516 unsigned AS = Base->getType()->getPointerAddressSpace();
John McCallc134eb52010-08-31 21:07:20 +0000517
518 // Cast to char*.
519 Base = Builder.CreateBitCast(Base, Builder.getInt8Ty()->getPointerTo(AS));
520
521 // Apply the offset, which we assume is non-null.
522 llvm::Value *Addr = Builder.CreateInBoundsGEP(Base, MemPtr, "memptr.offset");
523
524 // Cast the address to the appropriate pointer type, adopting the
525 // address space of the base pointer.
Chris Lattner2192fe52011-07-18 04:24:23 +0000526 llvm::Type *PType
Douglas Gregor04f36212010-09-02 17:38:50 +0000527 = CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
John McCallc134eb52010-08-31 21:07:20 +0000528 return Builder.CreateBitCast(Addr, PType);
529}
530
John McCallc62bb392012-02-15 01:22:51 +0000531/// Perform a bitcast, derived-to-base, or base-to-derived member pointer
532/// conversion.
533///
534/// Bitcast conversions are always a no-op under Itanium.
John McCall7a9aac22010-08-23 01:21:21 +0000535///
536/// Obligatory offset/adjustment diagram:
537/// <-- offset --> <-- adjustment -->
538/// |--------------------------|----------------------|--------------------|
539/// ^Derived address point ^Base address point ^Member address point
540///
541/// So when converting a base member pointer to a derived member pointer,
542/// we add the offset to the adjustment because the address point has
543/// decreased; and conversely, when converting a derived MP to a base MP
544/// we subtract the offset from the adjustment because the address point
545/// has increased.
546///
547/// The standard forbids (at compile time) conversion to and from
548/// virtual bases, which is why we don't have to consider them here.
549///
550/// The standard forbids (at run time) casting a derived MP to a base
551/// MP when the derived MP does not point to a member of the base.
552/// This is why -1 is a reasonable choice for null data member
553/// pointers.
John McCalla1dee5302010-08-22 10:59:02 +0000554llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000555ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
556 const CastExpr *E,
John McCallc62bb392012-02-15 01:22:51 +0000557 llvm::Value *src) {
John McCalle3027922010-08-25 11:45:40 +0000558 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
John McCallc62bb392012-02-15 01:22:51 +0000559 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
560 E->getCastKind() == CK_ReinterpretMemberPointer);
561
562 // Under Itanium, reinterprets don't require any additional processing.
563 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
564
565 // Use constant emission if we can.
566 if (isa<llvm::Constant>(src))
567 return EmitMemberPointerConversion(E, cast<llvm::Constant>(src));
568
569 llvm::Constant *adj = getMemberPointerAdjustment(E);
570 if (!adj) return src;
John McCalla8bbb822010-08-22 03:04:22 +0000571
572 CGBuilderTy &Builder = CGF.Builder;
John McCallc62bb392012-02-15 01:22:51 +0000573 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
John McCalla8bbb822010-08-22 03:04:22 +0000574
John McCallc62bb392012-02-15 01:22:51 +0000575 const MemberPointerType *destTy =
576 E->getType()->castAs<MemberPointerType>();
John McCall1c456c82010-08-22 06:43:33 +0000577
John McCall7a9aac22010-08-23 01:21:21 +0000578 // For member data pointers, this is just a matter of adding the
579 // offset if the source is non-null.
John McCallc62bb392012-02-15 01:22:51 +0000580 if (destTy->isMemberDataPointer()) {
581 llvm::Value *dst;
582 if (isDerivedToBase)
583 dst = Builder.CreateNSWSub(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000584 else
John McCallc62bb392012-02-15 01:22:51 +0000585 dst = Builder.CreateNSWAdd(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000586
587 // Null check.
John McCallc62bb392012-02-15 01:22:51 +0000588 llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType());
589 llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull");
590 return Builder.CreateSelect(isNull, src, dst);
John McCall7a9aac22010-08-23 01:21:21 +0000591 }
592
John McCalla1dee5302010-08-22 10:59:02 +0000593 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000594 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000595 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
596 offset <<= 1;
597 adj = llvm::ConstantInt::get(adj->getType(), offset);
John McCalla1dee5302010-08-22 10:59:02 +0000598 }
599
John McCallc62bb392012-02-15 01:22:51 +0000600 llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj");
601 llvm::Value *dstAdj;
602 if (isDerivedToBase)
603 dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000604 else
John McCallc62bb392012-02-15 01:22:51 +0000605 dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000606
John McCallc62bb392012-02-15 01:22:51 +0000607 return Builder.CreateInsertValue(src, dstAdj, 1);
608}
609
610llvm::Constant *
611ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E,
612 llvm::Constant *src) {
613 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
614 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
615 E->getCastKind() == CK_ReinterpretMemberPointer);
616
617 // Under Itanium, reinterprets don't require any additional processing.
618 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
619
620 // If the adjustment is trivial, we don't need to do anything.
621 llvm::Constant *adj = getMemberPointerAdjustment(E);
622 if (!adj) return src;
623
624 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
625
626 const MemberPointerType *destTy =
627 E->getType()->castAs<MemberPointerType>();
628
629 // For member data pointers, this is just a matter of adding the
630 // offset if the source is non-null.
631 if (destTy->isMemberDataPointer()) {
632 // null maps to null.
633 if (src->isAllOnesValue()) return src;
634
635 if (isDerivedToBase)
636 return llvm::ConstantExpr::getNSWSub(src, adj);
637 else
638 return llvm::ConstantExpr::getNSWAdd(src, adj);
639 }
640
641 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000642 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000643 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
644 offset <<= 1;
645 adj = llvm::ConstantInt::get(adj->getType(), offset);
646 }
647
648 llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1);
649 llvm::Constant *dstAdj;
650 if (isDerivedToBase)
651 dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj);
652 else
653 dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj);
654
655 return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1);
John McCalla8bbb822010-08-22 03:04:22 +0000656}
John McCall84fa5102010-08-22 04:16:24 +0000657
658llvm::Constant *
John McCall7a9aac22010-08-23 01:21:21 +0000659ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
John McCall7a9aac22010-08-23 01:21:21 +0000660 // Itanium C++ ABI 2.3:
661 // A NULL pointer is represented as -1.
662 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000663 return llvm::ConstantInt::get(CGM.PtrDiffTy, -1ULL, /*isSigned=*/true);
John McCalla1dee5302010-08-22 10:59:02 +0000664
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000665 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.PtrDiffTy, 0);
John McCalla1dee5302010-08-22 10:59:02 +0000666 llvm::Constant *Values[2] = { Zero, Zero };
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000667 return llvm::ConstantStruct::getAnon(Values);
John McCall84fa5102010-08-22 04:16:24 +0000668}
669
John McCallf3a88602011-02-03 08:15:49 +0000670llvm::Constant *
671ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
672 CharUnits offset) {
John McCall7a9aac22010-08-23 01:21:21 +0000673 // Itanium C++ ABI 2.3:
674 // A pointer to data member is an offset from the base address of
675 // the class object containing it, represented as a ptrdiff_t
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000676 return llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity());
John McCall7a9aac22010-08-23 01:21:21 +0000677}
678
David Majnemere2be95b2015-06-23 07:31:01 +0000679llvm::Constant *
680ItaniumCXXABI::EmitMemberFunctionPointer(const CXXMethodDecl *MD) {
Richard Smithdafff942012-01-14 04:30:29 +0000681 return BuildMemberPointer(MD, CharUnits::Zero());
682}
683
684llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD,
685 CharUnits ThisAdjustment) {
John McCalla1dee5302010-08-22 10:59:02 +0000686 assert(MD->isInstance() && "Member function must not be static!");
687 MD = MD->getCanonicalDecl();
688
689 CodeGenTypes &Types = CGM.getTypes();
John McCalla1dee5302010-08-22 10:59:02 +0000690
691 // Get the function pointer (or index if this is a virtual function).
692 llvm::Constant *MemPtr[2];
693 if (MD->isVirtual()) {
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000694 uint64_t Index = CGM.getItaniumVTableContext().getMethodVTableIndex(MD);
John McCalla1dee5302010-08-22 10:59:02 +0000695
Ken Dyckdf016282011-04-09 01:30:02 +0000696 const ASTContext &Context = getContext();
697 CharUnits PointerWidth =
Douglas Gregore8bbc122011-09-02 00:18:52 +0000698 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Ken Dyckdf016282011-04-09 01:30:02 +0000699 uint64_t VTableOffset = (Index * PointerWidth.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000700
Mark Seabornedf0d382013-07-24 16:25:13 +0000701 if (UseARMMethodPtrABI) {
John McCalla1dee5302010-08-22 10:59:02 +0000702 // ARM C++ ABI 3.2.1:
703 // This ABI specifies that adj contains twice the this
704 // adjustment, plus 1 if the member function is virtual. The
705 // least significant bit of adj then makes exactly the same
706 // discrimination as the least significant bit of ptr does for
707 // Itanium.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000708 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset);
709 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000710 2 * ThisAdjustment.getQuantity() + 1);
John McCalla1dee5302010-08-22 10:59:02 +0000711 } else {
712 // Itanium C++ ABI 2.3:
713 // For a virtual function, [the pointer field] is 1 plus the
714 // virtual table offset (in bytes) of the function,
715 // represented as a ptrdiff_t.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000716 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset + 1);
717 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000718 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000719 }
720 } else {
John McCall2979fe02011-04-12 00:42:48 +0000721 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
Chris Lattner2192fe52011-07-18 04:24:23 +0000722 llvm::Type *Ty;
John McCall2979fe02011-04-12 00:42:48 +0000723 // Check whether the function has a computable LLVM signature.
Chris Lattner8806e322011-07-10 00:18:59 +0000724 if (Types.isFuncTypeConvertible(FPT)) {
John McCall2979fe02011-04-12 00:42:48 +0000725 // The function has a computable LLVM signature; use the correct type.
John McCalla729c622012-02-17 03:33:10 +0000726 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
John McCalla1dee5302010-08-22 10:59:02 +0000727 } else {
John McCall2979fe02011-04-12 00:42:48 +0000728 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
729 // function type is incomplete.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000730 Ty = CGM.PtrDiffTy;
John McCalla1dee5302010-08-22 10:59:02 +0000731 }
John McCall2979fe02011-04-12 00:42:48 +0000732 llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty);
John McCalla1dee5302010-08-22 10:59:02 +0000733
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000734 MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, CGM.PtrDiffTy);
Mark Seabornedf0d382013-07-24 16:25:13 +0000735 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
736 (UseARMMethodPtrABI ? 2 : 1) *
Richard Smithdafff942012-01-14 04:30:29 +0000737 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000738 }
John McCall1c456c82010-08-22 06:43:33 +0000739
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000740 return llvm::ConstantStruct::getAnon(MemPtr);
John McCall1c456c82010-08-22 06:43:33 +0000741}
742
Richard Smithdafff942012-01-14 04:30:29 +0000743llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP,
744 QualType MPType) {
745 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
746 const ValueDecl *MPD = MP.getMemberPointerDecl();
747 if (!MPD)
748 return EmitNullMemberPointer(MPT);
749
Reid Kleckner452abac2013-05-09 21:01:17 +0000750 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
Richard Smithdafff942012-01-14 04:30:29 +0000751
752 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
753 return BuildMemberPointer(MD, ThisAdjustment);
754
755 CharUnits FieldOffset =
756 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
757 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
758}
759
John McCall131d97d2010-08-22 08:30:07 +0000760/// The comparison algorithm is pretty easy: the member pointers are
761/// the same if they're either bitwise identical *or* both null.
762///
763/// ARM is different here only because null-ness is more complicated.
764llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000765ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
766 llvm::Value *L,
767 llvm::Value *R,
768 const MemberPointerType *MPT,
769 bool Inequality) {
John McCall131d97d2010-08-22 08:30:07 +0000770 CGBuilderTy &Builder = CGF.Builder;
771
John McCall131d97d2010-08-22 08:30:07 +0000772 llvm::ICmpInst::Predicate Eq;
773 llvm::Instruction::BinaryOps And, Or;
774 if (Inequality) {
775 Eq = llvm::ICmpInst::ICMP_NE;
776 And = llvm::Instruction::Or;
777 Or = llvm::Instruction::And;
778 } else {
779 Eq = llvm::ICmpInst::ICMP_EQ;
780 And = llvm::Instruction::And;
781 Or = llvm::Instruction::Or;
782 }
783
John McCall7a9aac22010-08-23 01:21:21 +0000784 // Member data pointers are easy because there's a unique null
785 // value, so it just comes down to bitwise equality.
786 if (MPT->isMemberDataPointer())
787 return Builder.CreateICmp(Eq, L, R);
788
789 // For member function pointers, the tautologies are more complex.
790 // The Itanium tautology is:
John McCall61a14882010-08-23 06:56:36 +0000791 // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
John McCall7a9aac22010-08-23 01:21:21 +0000792 // The ARM tautology is:
John McCall61a14882010-08-23 06:56:36 +0000793 // (L == R) <==> (L.ptr == R.ptr &&
794 // (L.adj == R.adj ||
795 // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
John McCall7a9aac22010-08-23 01:21:21 +0000796 // The inequality tautologies have exactly the same structure, except
797 // applying De Morgan's laws.
798
799 llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
800 llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
801
John McCall131d97d2010-08-22 08:30:07 +0000802 // This condition tests whether L.ptr == R.ptr. This must always be
803 // true for equality to hold.
804 llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
805
806 // This condition, together with the assumption that L.ptr == R.ptr,
807 // tests whether the pointers are both null. ARM imposes an extra
808 // condition.
809 llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
810 llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
811
812 // This condition tests whether L.adj == R.adj. If this isn't
813 // true, the pointers are unequal unless they're both null.
John McCalla1dee5302010-08-22 10:59:02 +0000814 llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
815 llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000816 llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
817
818 // Null member function pointers on ARM clear the low bit of Adj,
819 // so the zero condition has to check that neither low bit is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000820 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000821 llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
822
823 // Compute (l.adj | r.adj) & 1 and test it against zero.
824 llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
825 llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
826 llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
827 "cmp.or.adj");
828 EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
829 }
830
831 // Tie together all our conditions.
832 llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
833 Result = Builder.CreateBinOp(And, PtrEq, Result,
834 Inequality ? "memptr.ne" : "memptr.eq");
835 return Result;
836}
837
838llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000839ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
840 llvm::Value *MemPtr,
841 const MemberPointerType *MPT) {
John McCall131d97d2010-08-22 08:30:07 +0000842 CGBuilderTy &Builder = CGF.Builder;
John McCall7a9aac22010-08-23 01:21:21 +0000843
844 /// For member data pointers, this is just a check against -1.
845 if (MPT->isMemberDataPointer()) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000846 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCall7a9aac22010-08-23 01:21:21 +0000847 llvm::Value *NegativeOne =
848 llvm::Constant::getAllOnesValue(MemPtr->getType());
849 return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
850 }
John McCall131d97d2010-08-22 08:30:07 +0000851
Daniel Dunbar914bc412011-04-19 23:10:47 +0000852 // In Itanium, a member function pointer is not null if 'ptr' is not null.
John McCalla1dee5302010-08-22 10:59:02 +0000853 llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
John McCall131d97d2010-08-22 08:30:07 +0000854
855 llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
856 llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
857
Daniel Dunbar914bc412011-04-19 23:10:47 +0000858 // On ARM, a member function pointer is also non-null if the low bit of 'adj'
859 // (the virtual bit) is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000860 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000861 llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
John McCalla1dee5302010-08-22 10:59:02 +0000862 llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000863 llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
Daniel Dunbar914bc412011-04-19 23:10:47 +0000864 llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero,
865 "memptr.isvirtual");
866 Result = Builder.CreateOr(Result, IsVirtual);
John McCall131d97d2010-08-22 08:30:07 +0000867 }
868
869 return Result;
870}
John McCall1c456c82010-08-22 06:43:33 +0000871
Reid Kleckner40ca9132014-05-13 22:05:45 +0000872bool ItaniumCXXABI::classifyReturnType(CGFunctionInfo &FI) const {
873 const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl();
874 if (!RD)
875 return false;
876
Reid Klecknerd355ca72014-05-15 01:26:32 +0000877 // Return indirectly if we have a non-trivial copy ctor or non-trivial dtor.
878 // FIXME: Use canCopyArgument() when it is fixed to handle lazily declared
879 // special members.
880 if (RD->hasNonTrivialDestructor() || RD->hasNonTrivialCopyConstructor()) {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000881 FI.getReturnInfo() = ABIArgInfo::getIndirect(0, /*ByVal=*/false);
882 return true;
883 }
Reid Kleckner40ca9132014-05-13 22:05:45 +0000884 return false;
885}
886
John McCall614dbdc2010-08-22 21:01:12 +0000887/// The Itanium ABI requires non-zero initialization only for data
888/// member pointers, for which '0' is a valid offset.
889bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
David Majnemer5fd33e02015-04-24 01:25:08 +0000890 return MPT->isMemberFunctionPointer();
John McCall84fa5102010-08-22 04:16:24 +0000891}
John McCall5d865c322010-08-31 07:33:07 +0000892
John McCall82fb8922012-09-25 10:10:39 +0000893/// The Itanium ABI always places an offset to the complete object
894/// at entry -2 in the vtable.
David Majnemer08681372014-11-01 07:37:17 +0000895void ItaniumCXXABI::emitVirtualObjectDelete(CodeGenFunction &CGF,
896 const CXXDeleteExpr *DE,
897 llvm::Value *Ptr,
898 QualType ElementType,
899 const CXXDestructorDecl *Dtor) {
900 bool UseGlobalDelete = DE->isGlobalDelete();
David Majnemer0c0b6d92014-10-31 20:09:12 +0000901 if (UseGlobalDelete) {
902 // Derive the complete-object pointer, which is what we need
903 // to pass to the deallocation function.
John McCall82fb8922012-09-25 10:10:39 +0000904
David Majnemer0c0b6d92014-10-31 20:09:12 +0000905 // Grab the vtable pointer as an intptr_t*.
906 llvm::Value *VTable = CGF.GetVTablePtr(Ptr, CGF.IntPtrTy->getPointerTo());
John McCall82fb8922012-09-25 10:10:39 +0000907
David Majnemer0c0b6d92014-10-31 20:09:12 +0000908 // Track back to entry -2 and pull out the offset there.
909 llvm::Value *OffsetPtr = CGF.Builder.CreateConstInBoundsGEP1_64(
910 VTable, -2, "complete-offset.ptr");
911 llvm::LoadInst *Offset = CGF.Builder.CreateLoad(OffsetPtr);
912 Offset->setAlignment(CGF.PointerAlignInBytes);
913
914 // Apply the offset.
915 llvm::Value *CompletePtr = CGF.Builder.CreateBitCast(Ptr, CGF.Int8PtrTy);
916 CompletePtr = CGF.Builder.CreateInBoundsGEP(CompletePtr, Offset);
917
918 // If we're supposed to call the global delete, make sure we do so
919 // even if the destructor throws.
David Majnemer08681372014-11-01 07:37:17 +0000920 CGF.pushCallObjectDeleteCleanup(DE->getOperatorDelete(), CompletePtr,
921 ElementType);
David Majnemer0c0b6d92014-10-31 20:09:12 +0000922 }
923
924 // FIXME: Provide a source location here even though there's no
925 // CXXMemberCallExpr for dtor call.
926 CXXDtorType DtorType = UseGlobalDelete ? Dtor_Complete : Dtor_Deleting;
927 EmitVirtualDestructorCall(CGF, Dtor, DtorType, Ptr, /*CE=*/nullptr);
928
929 if (UseGlobalDelete)
930 CGF.PopCleanupBlock();
John McCall82fb8922012-09-25 10:10:39 +0000931}
932
David Majnemer442d0a22014-11-25 07:20:20 +0000933void ItaniumCXXABI::emitRethrow(CodeGenFunction &CGF, bool isNoReturn) {
934 // void __cxa_rethrow();
935
936 llvm::FunctionType *FTy =
937 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
938
939 llvm::Constant *Fn = CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow");
940
941 if (isNoReturn)
942 CGF.EmitNoreturnRuntimeCallOrInvoke(Fn, None);
943 else
944 CGF.EmitRuntimeCallOrInvoke(Fn);
945}
946
David Majnemer7c237072015-03-05 00:46:22 +0000947static llvm::Constant *getAllocateExceptionFn(CodeGenModule &CGM) {
948 // void *__cxa_allocate_exception(size_t thrown_size);
949
950 llvm::FunctionType *FTy =
951 llvm::FunctionType::get(CGM.Int8PtrTy, CGM.SizeTy, /*IsVarArgs=*/false);
952
953 return CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
954}
955
956static llvm::Constant *getThrowFn(CodeGenModule &CGM) {
957 // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
958 // void (*dest) (void *));
959
960 llvm::Type *Args[3] = { CGM.Int8PtrTy, CGM.Int8PtrTy, CGM.Int8PtrTy };
961 llvm::FunctionType *FTy =
962 llvm::FunctionType::get(CGM.VoidTy, Args, /*IsVarArgs=*/false);
963
964 return CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
965}
966
967void ItaniumCXXABI::emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) {
968 QualType ThrowType = E->getSubExpr()->getType();
969 // Now allocate the exception object.
970 llvm::Type *SizeTy = CGF.ConvertType(getContext().getSizeType());
971 uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
972
973 llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(CGM);
974 llvm::CallInst *ExceptionPtr = CGF.EmitNounwindRuntimeCall(
975 AllocExceptionFn, llvm::ConstantInt::get(SizeTy, TypeSize), "exception");
976
977 CGF.EmitAnyExprToExn(E->getSubExpr(), ExceptionPtr);
978
979 // Now throw the exception.
980 llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType,
981 /*ForEH=*/true);
982
983 // The address of the destructor. If the exception type has a
984 // trivial destructor (or isn't a record), we just pass null.
985 llvm::Constant *Dtor = nullptr;
986 if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
987 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
988 if (!Record->hasTrivialDestructor()) {
989 CXXDestructorDecl *DtorD = Record->getDestructor();
990 Dtor = CGM.getAddrOfCXXStructor(DtorD, StructorType::Complete);
991 Dtor = llvm::ConstantExpr::getBitCast(Dtor, CGM.Int8PtrTy);
992 }
993 }
994 if (!Dtor) Dtor = llvm::Constant::getNullValue(CGM.Int8PtrTy);
995
996 llvm::Value *args[] = { ExceptionPtr, TypeInfo, Dtor };
997 CGF.EmitNoreturnRuntimeCallOrInvoke(getThrowFn(CGM), args);
998}
999
David Majnemer1162d252014-06-22 19:05:33 +00001000static llvm::Constant *getItaniumDynamicCastFn(CodeGenFunction &CGF) {
1001 // void *__dynamic_cast(const void *sub,
1002 // const abi::__class_type_info *src,
1003 // const abi::__class_type_info *dst,
1004 // std::ptrdiff_t src2dst_offset);
1005
1006 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
1007 llvm::Type *PtrDiffTy =
1008 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1009
1010 llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
1011
1012 llvm::FunctionType *FTy = llvm::FunctionType::get(Int8PtrTy, Args, false);
1013
1014 // Mark the function as nounwind readonly.
1015 llvm::Attribute::AttrKind FuncAttrs[] = { llvm::Attribute::NoUnwind,
1016 llvm::Attribute::ReadOnly };
1017 llvm::AttributeSet Attrs = llvm::AttributeSet::get(
1018 CGF.getLLVMContext(), llvm::AttributeSet::FunctionIndex, FuncAttrs);
1019
1020 return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast", Attrs);
1021}
1022
1023static llvm::Constant *getBadCastFn(CodeGenFunction &CGF) {
1024 // void __cxa_bad_cast();
1025 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1026 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
1027}
1028
1029/// \brief Compute the src2dst_offset hint as described in the
1030/// Itanium C++ ABI [2.9.7]
1031static CharUnits computeOffsetHint(ASTContext &Context,
1032 const CXXRecordDecl *Src,
1033 const CXXRecordDecl *Dst) {
1034 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1035 /*DetectVirtual=*/false);
1036
1037 // If Dst is not derived from Src we can skip the whole computation below and
1038 // return that Src is not a public base of Dst. Record all inheritance paths.
1039 if (!Dst->isDerivedFrom(Src, Paths))
1040 return CharUnits::fromQuantity(-2ULL);
1041
1042 unsigned NumPublicPaths = 0;
1043 CharUnits Offset;
1044
1045 // Now walk all possible inheritance paths.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001046 for (const CXXBasePath &Path : Paths) {
1047 if (Path.Access != AS_public) // Ignore non-public inheritance.
David Majnemer1162d252014-06-22 19:05:33 +00001048 continue;
1049
1050 ++NumPublicPaths;
1051
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001052 for (const CXXBasePathElement &PathElement : Path) {
David Majnemer1162d252014-06-22 19:05:33 +00001053 // If the path contains a virtual base class we can't give any hint.
1054 // -1: no hint.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001055 if (PathElement.Base->isVirtual())
David Majnemer1162d252014-06-22 19:05:33 +00001056 return CharUnits::fromQuantity(-1ULL);
1057
1058 if (NumPublicPaths > 1) // Won't use offsets, skip computation.
1059 continue;
1060
1061 // Accumulate the base class offsets.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001062 const ASTRecordLayout &L = Context.getASTRecordLayout(PathElement.Class);
1063 Offset += L.getBaseClassOffset(
1064 PathElement.Base->getType()->getAsCXXRecordDecl());
David Majnemer1162d252014-06-22 19:05:33 +00001065 }
1066 }
1067
1068 // -2: Src is not a public base of Dst.
1069 if (NumPublicPaths == 0)
1070 return CharUnits::fromQuantity(-2ULL);
1071
1072 // -3: Src is a multiple public base type but never a virtual base type.
1073 if (NumPublicPaths > 1)
1074 return CharUnits::fromQuantity(-3ULL);
1075
1076 // Otherwise, the Src type is a unique public nonvirtual base type of Dst.
1077 // Return the offset of Src from the origin of Dst.
1078 return Offset;
1079}
1080
1081static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) {
1082 // void __cxa_bad_typeid();
1083 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1084
1085 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
1086}
1087
1088bool ItaniumCXXABI::shouldTypeidBeNullChecked(bool IsDeref,
1089 QualType SrcRecordTy) {
1090 return IsDeref;
1091}
1092
1093void ItaniumCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) {
1094 llvm::Value *Fn = getBadTypeidFn(CGF);
1095 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
1096 CGF.Builder.CreateUnreachable();
1097}
1098
1099llvm::Value *ItaniumCXXABI::EmitTypeid(CodeGenFunction &CGF,
1100 QualType SrcRecordTy,
1101 llvm::Value *ThisPtr,
1102 llvm::Type *StdTypeInfoPtrTy) {
1103 llvm::Value *Value =
1104 CGF.GetVTablePtr(ThisPtr, StdTypeInfoPtrTy->getPointerTo());
1105
1106 // Load the type info.
1107 Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL);
1108 return CGF.Builder.CreateLoad(Value);
1109}
1110
1111bool ItaniumCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
1112 QualType SrcRecordTy) {
1113 return SrcIsPtr;
1114}
1115
1116llvm::Value *ItaniumCXXABI::EmitDynamicCastCall(
1117 CodeGenFunction &CGF, llvm::Value *Value, QualType SrcRecordTy,
1118 QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) {
1119 llvm::Type *PtrDiffLTy =
1120 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1121 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1122
1123 llvm::Value *SrcRTTI =
1124 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
1125 llvm::Value *DestRTTI =
1126 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
1127
1128 // Compute the offset hint.
1129 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
1130 const CXXRecordDecl *DestDecl = DestRecordTy->getAsCXXRecordDecl();
1131 llvm::Value *OffsetHint = llvm::ConstantInt::get(
1132 PtrDiffLTy,
1133 computeOffsetHint(CGF.getContext(), SrcDecl, DestDecl).getQuantity());
1134
1135 // Emit the call to __dynamic_cast.
1136 Value = CGF.EmitCastToVoidPtr(Value);
1137
1138 llvm::Value *args[] = {Value, SrcRTTI, DestRTTI, OffsetHint};
1139 Value = CGF.EmitNounwindRuntimeCall(getItaniumDynamicCastFn(CGF), args);
1140 Value = CGF.Builder.CreateBitCast(Value, DestLTy);
1141
1142 /// C++ [expr.dynamic.cast]p9:
1143 /// A failed cast to reference type throws std::bad_cast
1144 if (DestTy->isReferenceType()) {
1145 llvm::BasicBlock *BadCastBlock =
1146 CGF.createBasicBlock("dynamic_cast.bad_cast");
1147
1148 llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
1149 CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
1150
1151 CGF.EmitBlock(BadCastBlock);
1152 EmitBadCastCall(CGF);
1153 }
1154
1155 return Value;
1156}
1157
1158llvm::Value *ItaniumCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF,
1159 llvm::Value *Value,
1160 QualType SrcRecordTy,
1161 QualType DestTy) {
1162 llvm::Type *PtrDiffLTy =
1163 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1164 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1165
1166 // Get the vtable pointer.
1167 llvm::Value *VTable = CGF.GetVTablePtr(Value, PtrDiffLTy->getPointerTo());
1168
1169 // Get the offset-to-top from the vtable.
1170 llvm::Value *OffsetToTop =
1171 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL);
1172 OffsetToTop = CGF.Builder.CreateLoad(OffsetToTop, "offset.to.top");
1173
1174 // Finally, add the offset to the pointer.
1175 Value = CGF.EmitCastToVoidPtr(Value);
1176 Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop);
1177
1178 return CGF.Builder.CreateBitCast(Value, DestLTy);
1179}
1180
1181bool ItaniumCXXABI::EmitBadCastCall(CodeGenFunction &CGF) {
1182 llvm::Value *Fn = getBadCastFn(CGF);
1183 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
1184 CGF.Builder.CreateUnreachable();
1185 return true;
1186}
1187
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001188llvm::Value *
1189ItaniumCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
1190 llvm::Value *This,
1191 const CXXRecordDecl *ClassDecl,
1192 const CXXRecordDecl *BaseClassDecl) {
1193 llvm::Value *VTablePtr = CGF.GetVTablePtr(This, CGM.Int8PtrTy);
1194 CharUnits VBaseOffsetOffset =
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001195 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(ClassDecl,
1196 BaseClassDecl);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001197
1198 llvm::Value *VBaseOffsetPtr =
1199 CGF.Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
1200 "vbase.offset.ptr");
1201 VBaseOffsetPtr = CGF.Builder.CreateBitCast(VBaseOffsetPtr,
1202 CGM.PtrDiffTy->getPointerTo());
1203
1204 llvm::Value *VBaseOffset =
1205 CGF.Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
1206
1207 return VBaseOffset;
1208}
1209
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001210void ItaniumCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
1211 // Just make sure we're in sync with TargetCXXABI.
1212 assert(CGM.getTarget().getCXXABI().hasConstructorVariants());
1213
Rafael Espindolac3cde362013-12-09 14:51:17 +00001214 // The constructor used for constructing this as a base class;
1215 // ignores virtual bases.
1216 CGM.EmitGlobal(GlobalDecl(D, Ctor_Base));
1217
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001218 // The constructor used for constructing this as a complete class;
Nico Weber4c2ffb22015-01-07 05:25:05 +00001219 // constructs the virtual bases, then calls the base constructor.
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001220 if (!D->getParent()->isAbstract()) {
1221 // We don't need to emit the complete ctor if the class is abstract.
1222 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
1223 }
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001224}
1225
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001226void
1227ItaniumCXXABI::buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
1228 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9bca9232010-09-02 10:25:57 +00001229 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001230
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001231 // All parameters are already in place except VTT, which goes after 'this'.
1232 // These are Clang types, so we don't need to worry about sret yet.
John McCall5d865c322010-08-31 07:33:07 +00001233
1234 // Check if we need to add a VTT parameter (which has type void **).
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001235 if (T == StructorType::Base && MD->getParent()->getNumVBases() != 0)
1236 ArgTys.insert(ArgTys.begin() + 1,
1237 Context.getPointerType(Context.VoidPtrTy));
John McCall5d865c322010-08-31 07:33:07 +00001238}
1239
Reid Klecknere7de47e2013-07-22 13:51:44 +00001240void ItaniumCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
Rafael Espindolac3cde362013-12-09 14:51:17 +00001241 // The destructor used for destructing this as a base class; ignores
1242 // virtual bases.
1243 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001244
1245 // The destructor used for destructing this as a most-derived class;
1246 // call the base destructor and then destructs any virtual bases.
1247 CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));
1248
Rafael Espindolac3cde362013-12-09 14:51:17 +00001249 // The destructor in a virtual table is always a 'deleting'
1250 // destructor, which calls the complete destructor and then uses the
1251 // appropriate operator delete.
1252 if (D->isVirtual())
1253 CGM.EmitGlobal(GlobalDecl(D, Dtor_Deleting));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001254}
1255
Reid Kleckner89077a12013-12-17 19:46:40 +00001256void ItaniumCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
1257 QualType &ResTy,
1258 FunctionArgList &Params) {
John McCall5d865c322010-08-31 07:33:07 +00001259 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
Reid Kleckner89077a12013-12-17 19:46:40 +00001260 assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
John McCall5d865c322010-08-31 07:33:07 +00001261
1262 // Check if we need a VTT parameter as well.
Peter Collingbourne66f82e62013-06-28 20:45:28 +00001263 if (NeedsVTTParameter(CGF.CurGD)) {
John McCall9bca9232010-09-02 10:25:57 +00001264 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001265
1266 // FIXME: avoid the fake decl
1267 QualType T = Context.getPointerType(Context.VoidPtrTy);
1268 ImplicitParamDecl *VTTDecl
Craig Topper8a13c412014-05-21 05:09:00 +00001269 = ImplicitParamDecl::Create(Context, nullptr, MD->getLocation(),
John McCall5d865c322010-08-31 07:33:07 +00001270 &Context.Idents.get("vtt"), T);
Reid Kleckner89077a12013-12-17 19:46:40 +00001271 Params.insert(Params.begin() + 1, VTTDecl);
Reid Kleckner2af6d732013-12-13 00:09:59 +00001272 getStructorImplicitParamDecl(CGF) = VTTDecl;
John McCall5d865c322010-08-31 07:33:07 +00001273 }
1274}
1275
John McCall5d865c322010-08-31 07:33:07 +00001276void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
1277 /// Initialize the 'this' slot.
1278 EmitThisParam(CGF);
1279
1280 /// Initialize the 'vtt' slot if needed.
Reid Kleckner2af6d732013-12-13 00:09:59 +00001281 if (getStructorImplicitParamDecl(CGF)) {
1282 getStructorImplicitParamValue(CGF) = CGF.Builder.CreateLoad(
1283 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), "vtt");
John McCall5d865c322010-08-31 07:33:07 +00001284 }
John McCall5d865c322010-08-31 07:33:07 +00001285
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001286 /// If this is a function that the ABI specifies returns 'this', initialize
1287 /// the return slot to 'this' at the start of the function.
1288 ///
1289 /// Unlike the setting of return types, this is done within the ABI
1290 /// implementation instead of by clients of CGCXXABI because:
1291 /// 1) getThisValue is currently protected
1292 /// 2) in theory, an ABI could implement 'this' returns some other way;
1293 /// HasThisReturn only specifies a contract, not the implementation
John McCall5d865c322010-08-31 07:33:07 +00001294 if (HasThisReturn(CGF.CurGD))
Eli Friedman9fbeba02012-02-11 02:57:39 +00001295 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
John McCall5d865c322010-08-31 07:33:07 +00001296}
1297
Reid Kleckner89077a12013-12-17 19:46:40 +00001298unsigned ItaniumCXXABI::addImplicitConstructorArgs(
1299 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
1300 bool ForVirtualBase, bool Delegating, CallArgList &Args) {
1301 if (!NeedsVTTParameter(GlobalDecl(D, Type)))
1302 return 0;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001303
Reid Kleckner89077a12013-12-17 19:46:40 +00001304 // Insert the implicit 'vtt' argument as the second argument.
1305 llvm::Value *VTT =
1306 CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase, Delegating);
1307 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1308 Args.insert(Args.begin() + 1,
1309 CallArg(RValue::get(VTT), VTTTy, /*needscopy=*/false));
1310 return 1; // Added one arg.
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001311}
1312
1313void ItaniumCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
1314 const CXXDestructorDecl *DD,
1315 CXXDtorType Type, bool ForVirtualBase,
1316 bool Delegating, llvm::Value *This) {
1317 GlobalDecl GD(DD, Type);
1318 llvm::Value *VTT = CGF.GetVTTParameter(GD, ForVirtualBase, Delegating);
1319 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1320
Craig Topper8a13c412014-05-21 05:09:00 +00001321 llvm::Value *Callee = nullptr;
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001322 if (getContext().getLangOpts().AppleKext)
1323 Callee = CGF.BuildAppleKextVirtualDestructorCall(DD, Type, DD->getParent());
1324
1325 if (!Callee)
Rafael Espindola1ac0ec82014-09-11 15:42:06 +00001326 Callee = CGM.getAddrOfCXXStructor(DD, getFromDtorType(Type));
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001327
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001328 CGF.EmitCXXMemberOrOperatorCall(DD, Callee, ReturnValueSlot(), This, VTT,
1329 VTTTy, nullptr);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001330}
1331
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001332void ItaniumCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
1333 const CXXRecordDecl *RD) {
1334 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, CharUnits());
1335 if (VTable->hasInitializer())
1336 return;
1337
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001338 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001339 const VTableLayout &VTLayout = VTContext.getVTableLayout(RD);
1340 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
David Majnemerd905da42014-07-01 20:30:31 +00001341 llvm::Constant *RTTI =
1342 CGM.GetAddrOfRTTIDescriptor(CGM.getContext().getTagDeclType(RD));
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001343
1344 // Create and set the initializer.
1345 llvm::Constant *Init = CGVT.CreateVTableInitializer(
1346 RD, VTLayout.vtable_component_begin(), VTLayout.getNumVTableComponents(),
David Majnemerd905da42014-07-01 20:30:31 +00001347 VTLayout.vtable_thunk_begin(), VTLayout.getNumVTableThunks(), RTTI);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001348 VTable->setInitializer(Init);
1349
1350 // Set the correct linkage.
1351 VTable->setLinkage(Linkage);
1352
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00001353 if (CGM.supportsCOMDAT() && VTable->isWeakForLinker())
1354 VTable->setComdat(CGM.getModule().getOrInsertComdat(VTable->getName()));
Rafael Espindolacb92c192015-01-15 23:18:01 +00001355
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001356 // Set the right visibility.
John McCall8f80a612014-02-08 00:41:16 +00001357 CGM.setGlobalVisibility(VTable, RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001358
Benjamin Kramer5d34a2b2014-09-10 12:50:59 +00001359 // Use pointer alignment for the vtable. Otherwise we would align them based
1360 // on the size of the initializer which doesn't make sense as only single
1361 // values are read.
1362 unsigned PAlign = CGM.getTarget().getPointerAlign(0);
1363 VTable->setAlignment(getContext().toCharUnitsFromBits(PAlign).getQuantity());
1364
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001365 // If this is the magic class __cxxabiv1::__fundamental_type_info,
1366 // we will emit the typeinfo for the fundamental types. This is the
1367 // same behaviour as GCC.
1368 const DeclContext *DC = RD->getDeclContext();
1369 if (RD->getIdentifier() &&
1370 RD->getIdentifier()->isStr("__fundamental_type_info") &&
1371 isa<NamespaceDecl>(DC) && cast<NamespaceDecl>(DC)->getIdentifier() &&
1372 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
1373 DC->getParent()->isTranslationUnit())
David Majnemere2cb8d12014-07-07 06:20:47 +00001374 EmitFundamentalRTTIDescriptors();
Peter Collingbournea4ccff32015-02-20 20:30:56 +00001375
1376 CGM.EmitVTableBitSetEntries(VTable, VTLayout);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001377}
1378
1379llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructor(
1380 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1381 const CXXRecordDecl *NearestVBase, bool &NeedsVirtualOffset) {
1382 bool NeedsVTTParam = CGM.getCXXABI().NeedsVTTParameter(CGF.CurGD);
1383 NeedsVirtualOffset = (NeedsVTTParam && NearestVBase);
1384
1385 llvm::Value *VTableAddressPoint;
1386 if (NeedsVTTParam && (Base.getBase()->getNumVBases() || NearestVBase)) {
1387 // Get the secondary vpointer index.
1388 uint64_t VirtualPointerIndex =
1389 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1390
1391 /// Load the VTT.
1392 llvm::Value *VTT = CGF.LoadCXXVTT();
1393 if (VirtualPointerIndex)
1394 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1395
1396 // And load the address point from the VTT.
1397 VTableAddressPoint = CGF.Builder.CreateLoad(VTT);
1398 } else {
1399 llvm::Constant *VTable =
1400 CGM.getCXXABI().getAddrOfVTable(VTableClass, CharUnits());
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001401 uint64_t AddressPoint = CGM.getItaniumVTableContext()
1402 .getVTableLayout(VTableClass)
1403 .getAddressPoint(Base);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001404 VTableAddressPoint =
1405 CGF.Builder.CreateConstInBoundsGEP2_64(VTable, 0, AddressPoint);
1406 }
1407
1408 return VTableAddressPoint;
1409}
1410
1411llvm::Constant *ItaniumCXXABI::getVTableAddressPointForConstExpr(
1412 BaseSubobject Base, const CXXRecordDecl *VTableClass) {
David Blaikiee3b172a2015-04-02 18:55:21 +00001413 auto *VTable = getAddrOfVTable(VTableClass, CharUnits());
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001414
1415 // Find the appropriate vtable within the vtable group.
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001416 uint64_t AddressPoint = CGM.getItaniumVTableContext()
1417 .getVTableLayout(VTableClass)
1418 .getAddressPoint(Base);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001419 llvm::Value *Indices[] = {
1420 llvm::ConstantInt::get(CGM.Int64Ty, 0),
1421 llvm::ConstantInt::get(CGM.Int64Ty, AddressPoint)
1422 };
1423
David Blaikiee3b172a2015-04-02 18:55:21 +00001424 return llvm::ConstantExpr::getInBoundsGetElementPtr(VTable->getValueType(),
1425 VTable, Indices);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001426}
1427
1428llvm::GlobalVariable *ItaniumCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
1429 CharUnits VPtrOffset) {
1430 assert(VPtrOffset.isZero() && "Itanium ABI only supports zero vptr offsets");
1431
1432 llvm::GlobalVariable *&VTable = VTables[RD];
1433 if (VTable)
1434 return VTable;
1435
1436 // Queue up this v-table for possible deferred emission.
1437 CGM.addDeferredVTable(RD);
1438
Yaron Kerene46f7ed2015-07-29 14:21:47 +00001439 SmallString<256> Name;
1440 llvm::raw_svector_ostream Out(Name);
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00001441 getMangleContext().mangleCXXVTable(RD, Out);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001442 Out.flush();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001443
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001444 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001445 llvm::ArrayType *ArrayType = llvm::ArrayType::get(
1446 CGM.Int8PtrTy, VTContext.getVTableLayout(RD).getNumVTableComponents());
1447
1448 VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
1449 Name, ArrayType, llvm::GlobalValue::ExternalLinkage);
1450 VTable->setUnnamedAddr(true);
Hans Wennborgda24e9c2014-06-02 23:13:03 +00001451
1452 if (RD->hasAttr<DLLImportAttr>())
1453 VTable->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1454 else if (RD->hasAttr<DLLExportAttr>())
1455 VTable->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1456
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001457 return VTable;
1458}
1459
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001460llvm::Value *ItaniumCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
1461 GlobalDecl GD,
1462 llvm::Value *This,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00001463 llvm::Type *Ty,
1464 SourceLocation Loc) {
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001465 GD = GD.getCanonicalDecl();
1466 Ty = Ty->getPointerTo()->getPointerTo();
1467 llvm::Value *VTable = CGF.GetVTablePtr(This, Ty);
1468
Peter Collingbourne1a7488a2015-04-02 00:23:30 +00001469 if (CGF.SanOpts.has(SanitizerKind::CFIVCall))
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00001470 CGF.EmitVTablePtrCheckForCall(cast<CXXMethodDecl>(GD.getDecl()), VTable,
1471 CodeGenFunction::CFITCK_VCall, Loc);
Peter Collingbournea4ccff32015-02-20 20:30:56 +00001472
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001473 uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001474 llvm::Value *VFuncPtr =
1475 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfn");
1476 return CGF.Builder.CreateLoad(VFuncPtr);
1477}
1478
David Majnemer0c0b6d92014-10-31 20:09:12 +00001479llvm::Value *ItaniumCXXABI::EmitVirtualDestructorCall(
1480 CodeGenFunction &CGF, const CXXDestructorDecl *Dtor, CXXDtorType DtorType,
1481 llvm::Value *This, const CXXMemberCallExpr *CE) {
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001482 assert(CE == nullptr || CE->arg_begin() == CE->arg_end());
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001483 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
1484
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001485 const CGFunctionInfo *FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
1486 Dtor, getFromDtorType(DtorType));
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001487 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001488 llvm::Value *Callee =
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00001489 getVirtualFunctionPointer(CGF, GlobalDecl(Dtor, DtorType), This, Ty,
1490 CE ? CE->getLocStart() : SourceLocation());
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001491
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001492 CGF.EmitCXXMemberOrOperatorCall(Dtor, Callee, ReturnValueSlot(), This,
1493 /*ImplicitParam=*/nullptr, QualType(), CE);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001494 return nullptr;
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001495}
1496
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001497void ItaniumCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
Reid Kleckner7810af02013-06-19 15:20:38 +00001498 CodeGenVTables &VTables = CGM.getVTables();
1499 llvm::GlobalVariable *VTT = VTables.GetAddrOfVTT(RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001500 VTables.EmitVTTDefinition(VTT, CGM.getVTableLinkage(RD), RD);
Reid Kleckner7810af02013-06-19 15:20:38 +00001501}
1502
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001503bool ItaniumCXXABI::canEmitAvailableExternallyVTable(
1504 const CXXRecordDecl *RD) const {
1505 // We don't emit available_externally vtables if we are in -fapple-kext mode
1506 // because kext mode does not permit devirtualization.
1507 if (CGM.getLangOpts().AppleKext)
1508 return false;
1509
1510 // If we don't have any inline virtual functions,
1511 // then we are safe to emit available_externally copy of vtable.
1512 // FIXME we can still emit a copy of the vtable if we
1513 // can emit definition of the inline functions.
1514 return !hasAnyVirtualInlineFunction(RD);
1515}
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001516static llvm::Value *performTypeAdjustment(CodeGenFunction &CGF,
1517 llvm::Value *Ptr,
1518 int64_t NonVirtualAdjustment,
1519 int64_t VirtualAdjustment,
1520 bool IsReturnAdjustment) {
1521 if (!NonVirtualAdjustment && !VirtualAdjustment)
1522 return Ptr;
1523
1524 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
1525 llvm::Value *V = CGF.Builder.CreateBitCast(Ptr, Int8PtrTy);
1526
1527 if (NonVirtualAdjustment && !IsReturnAdjustment) {
1528 // Perform the non-virtual adjustment for a base-to-derived cast.
1529 V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
1530 }
1531
1532 if (VirtualAdjustment) {
1533 llvm::Type *PtrDiffTy =
1534 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1535
1536 // Perform the virtual adjustment.
1537 llvm::Value *VTablePtrPtr =
1538 CGF.Builder.CreateBitCast(V, Int8PtrTy->getPointerTo());
1539
1540 llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr);
1541
1542 llvm::Value *OffsetPtr =
1543 CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
1544
1545 OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo());
1546
1547 // Load the adjustment offset from the vtable.
1548 llvm::Value *Offset = CGF.Builder.CreateLoad(OffsetPtr);
1549
1550 // Adjust our pointer.
1551 V = CGF.Builder.CreateInBoundsGEP(V, Offset);
1552 }
1553
1554 if (NonVirtualAdjustment && IsReturnAdjustment) {
1555 // Perform the non-virtual adjustment for a derived-to-base cast.
1556 V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
1557 }
1558
1559 // Cast back to the original type.
1560 return CGF.Builder.CreateBitCast(V, Ptr->getType());
1561}
1562
1563llvm::Value *ItaniumCXXABI::performThisAdjustment(CodeGenFunction &CGF,
1564 llvm::Value *This,
1565 const ThisAdjustment &TA) {
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00001566 return performTypeAdjustment(CGF, This, TA.NonVirtual,
1567 TA.Virtual.Itanium.VCallOffsetOffset,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001568 /*IsReturnAdjustment=*/false);
1569}
1570
1571llvm::Value *
1572ItaniumCXXABI::performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
1573 const ReturnAdjustment &RA) {
1574 return performTypeAdjustment(CGF, Ret, RA.NonVirtual,
1575 RA.Virtual.Itanium.VBaseOffsetOffset,
1576 /*IsReturnAdjustment=*/true);
1577}
1578
John McCall5d865c322010-08-31 07:33:07 +00001579void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
1580 RValue RV, QualType ResultType) {
1581 if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
1582 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
1583
1584 // Destructor thunks in the ARM ABI have indeterminate results.
Chris Lattner2192fe52011-07-18 04:24:23 +00001585 llvm::Type *T =
John McCall5d865c322010-08-31 07:33:07 +00001586 cast<llvm::PointerType>(CGF.ReturnValue->getType())->getElementType();
1587 RValue Undef = RValue::get(llvm::UndefValue::get(T));
1588 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
1589}
John McCall8ed55a52010-09-02 09:58:18 +00001590
1591/************************** Array allocation cookies **************************/
1592
John McCallb91cd662012-05-01 05:23:51 +00001593CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
1594 // The array cookie is a size_t; pad that up to the element alignment.
1595 // The cookie is actually right-justified in that space.
1596 return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
1597 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001598}
1599
1600llvm::Value *ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1601 llvm::Value *NewPtr,
1602 llvm::Value *NumElements,
John McCall284c48f2011-01-27 09:37:56 +00001603 const CXXNewExpr *expr,
John McCall8ed55a52010-09-02 09:58:18 +00001604 QualType ElementType) {
John McCallb91cd662012-05-01 05:23:51 +00001605 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001606
Micah Villmowea2fea22012-10-25 15:39:14 +00001607 unsigned AS = NewPtr->getType()->getPointerAddressSpace();
John McCall8ed55a52010-09-02 09:58:18 +00001608
John McCall9bca9232010-09-02 10:25:57 +00001609 ASTContext &Ctx = getContext();
John McCall8ed55a52010-09-02 09:58:18 +00001610 QualType SizeTy = Ctx.getSizeType();
1611 CharUnits SizeSize = Ctx.getTypeSizeInChars(SizeTy);
1612
1613 // The size of the cookie.
1614 CharUnits CookieSize =
1615 std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
John McCallb91cd662012-05-01 05:23:51 +00001616 assert(CookieSize == getArrayCookieSizeImpl(ElementType));
John McCall8ed55a52010-09-02 09:58:18 +00001617
1618 // Compute an offset to the cookie.
1619 llvm::Value *CookiePtr = NewPtr;
1620 CharUnits CookieOffset = CookieSize - SizeSize;
1621 if (!CookieOffset.isZero())
1622 CookiePtr = CGF.Builder.CreateConstInBoundsGEP1_64(CookiePtr,
1623 CookieOffset.getQuantity());
1624
1625 // Write the number of elements into the appropriate slot.
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001626 llvm::Type *NumElementsTy = CGF.ConvertType(SizeTy)->getPointerTo(AS);
1627 llvm::Value *NumElementsPtr =
1628 CGF.Builder.CreateBitCast(CookiePtr, NumElementsTy);
1629 llvm::Instruction *SI = CGF.Builder.CreateStore(NumElements, NumElementsPtr);
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001630 if (CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) && AS == 0 &&
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001631 expr->getOperatorNew()->isReplaceableGlobalAllocationFunction()) {
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001632 // The store to the CookiePtr does not need to be instrumented.
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001633 CGM.getSanitizerMetadata()->disableSanitizerForInstruction(SI);
1634 llvm::FunctionType *FTy =
1635 llvm::FunctionType::get(CGM.VoidTy, NumElementsTy, false);
1636 llvm::Constant *F =
1637 CGM.CreateRuntimeFunction(FTy, "__asan_poison_cxx_array_cookie");
1638 CGF.Builder.CreateCall(F, NumElementsPtr);
1639 }
John McCall8ed55a52010-09-02 09:58:18 +00001640
1641 // Finally, compute a pointer to the actual data buffer by skipping
1642 // over the cookie completely.
1643 return CGF.Builder.CreateConstInBoundsGEP1_64(NewPtr,
1644 CookieSize.getQuantity());
1645}
1646
John McCallb91cd662012-05-01 05:23:51 +00001647llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1648 llvm::Value *allocPtr,
1649 CharUnits cookieSize) {
1650 // The element size is right-justified in the cookie.
1651 llvm::Value *numElementsPtr = allocPtr;
1652 CharUnits numElementsOffset =
1653 cookieSize - CharUnits::fromQuantity(CGF.SizeSizeInBytes);
1654 if (!numElementsOffset.isZero())
1655 numElementsPtr =
1656 CGF.Builder.CreateConstInBoundsGEP1_64(numElementsPtr,
1657 numElementsOffset.getQuantity());
John McCall8ed55a52010-09-02 09:58:18 +00001658
Micah Villmowea2fea22012-10-25 15:39:14 +00001659 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCallb91cd662012-05-01 05:23:51 +00001660 numElementsPtr =
1661 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001662 if (!CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) || AS != 0)
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001663 return CGF.Builder.CreateLoad(numElementsPtr);
1664 // In asan mode emit a function call instead of a regular load and let the
1665 // run-time deal with it: if the shadow is properly poisoned return the
1666 // cookie, otherwise return 0 to avoid an infinite loop calling DTORs.
1667 // We can't simply ignore this load using nosanitize metadata because
1668 // the metadata may be lost.
1669 llvm::FunctionType *FTy =
1670 llvm::FunctionType::get(CGF.SizeTy, CGF.SizeTy->getPointerTo(0), false);
1671 llvm::Constant *F =
1672 CGM.CreateRuntimeFunction(FTy, "__asan_load_cxx_array_cookie");
1673 return CGF.Builder.CreateCall(F, numElementsPtr);
John McCall8ed55a52010-09-02 09:58:18 +00001674}
1675
John McCallb91cd662012-05-01 05:23:51 +00001676CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
John McCallc19c7062013-01-25 23:36:19 +00001677 // ARM says that the cookie is always:
John McCall8ed55a52010-09-02 09:58:18 +00001678 // struct array_cookie {
1679 // std::size_t element_size; // element_size != 0
1680 // std::size_t element_count;
1681 // };
John McCallc19c7062013-01-25 23:36:19 +00001682 // But the base ABI doesn't give anything an alignment greater than
1683 // 8, so we can dismiss this as typical ABI-author blindness to
1684 // actual language complexity and round up to the element alignment.
1685 return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes),
1686 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001687}
1688
1689llvm::Value *ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
John McCallc19c7062013-01-25 23:36:19 +00001690 llvm::Value *newPtr,
1691 llvm::Value *numElements,
John McCall284c48f2011-01-27 09:37:56 +00001692 const CXXNewExpr *expr,
John McCallc19c7062013-01-25 23:36:19 +00001693 QualType elementType) {
John McCallb91cd662012-05-01 05:23:51 +00001694 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001695
John McCallc19c7062013-01-25 23:36:19 +00001696 // NewPtr is a char*, but we generalize to arbitrary addrspaces.
1697 unsigned AS = newPtr->getType()->getPointerAddressSpace();
John McCall8ed55a52010-09-02 09:58:18 +00001698
1699 // The cookie is always at the start of the buffer.
John McCallc19c7062013-01-25 23:36:19 +00001700 llvm::Value *cookie = newPtr;
John McCall8ed55a52010-09-02 09:58:18 +00001701
1702 // The first element is the element size.
John McCallc19c7062013-01-25 23:36:19 +00001703 cookie = CGF.Builder.CreateBitCast(cookie, CGF.SizeTy->getPointerTo(AS));
1704 llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy,
1705 getContext().getTypeSizeInChars(elementType).getQuantity());
1706 CGF.Builder.CreateStore(elementSize, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001707
1708 // The second element is the element count.
David Blaikiefb901c7a2015-04-04 15:12:29 +00001709 cookie = CGF.Builder.CreateConstInBoundsGEP1_32(CGF.SizeTy, cookie, 1);
John McCallc19c7062013-01-25 23:36:19 +00001710 CGF.Builder.CreateStore(numElements, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001711
1712 // Finally, compute a pointer to the actual data buffer by skipping
1713 // over the cookie completely.
John McCallc19c7062013-01-25 23:36:19 +00001714 CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType);
1715 return CGF.Builder.CreateConstInBoundsGEP1_64(newPtr,
1716 cookieSize.getQuantity());
John McCall8ed55a52010-09-02 09:58:18 +00001717}
1718
John McCallb91cd662012-05-01 05:23:51 +00001719llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1720 llvm::Value *allocPtr,
1721 CharUnits cookieSize) {
1722 // The number of elements is at offset sizeof(size_t) relative to
1723 // the allocated pointer.
1724 llvm::Value *numElementsPtr
1725 = CGF.Builder.CreateConstInBoundsGEP1_64(allocPtr, CGF.SizeSizeInBytes);
John McCall8ed55a52010-09-02 09:58:18 +00001726
Micah Villmowea2fea22012-10-25 15:39:14 +00001727 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCallb91cd662012-05-01 05:23:51 +00001728 numElementsPtr =
1729 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
1730 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall8ed55a52010-09-02 09:58:18 +00001731}
1732
John McCall68ff0372010-09-08 01:44:27 +00001733/*********************** Static local initialization **************************/
1734
1735static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001736 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001737 // int __cxa_guard_acquire(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001738 llvm::FunctionType *FTy =
John McCall68ff0372010-09-08 01:44:27 +00001739 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
Jay Foad5709f7c2011-07-29 13:56:53 +00001740 GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001741 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_acquire",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001742 llvm::AttributeSet::get(CGM.getLLVMContext(),
1743 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001744 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001745}
1746
1747static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001748 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001749 // void __cxa_guard_release(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001750 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001751 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001752 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_release",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001753 llvm::AttributeSet::get(CGM.getLLVMContext(),
1754 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001755 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001756}
1757
1758static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001759 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001760 // void __cxa_guard_abort(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001761 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001762 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001763 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_abort",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001764 llvm::AttributeSet::get(CGM.getLLVMContext(),
1765 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001766 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001767}
1768
1769namespace {
1770 struct CallGuardAbort : EHScopeStack::Cleanup {
1771 llvm::GlobalVariable *Guard;
Chandler Carruth84537952012-03-30 19:44:53 +00001772 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
John McCall68ff0372010-09-08 01:44:27 +00001773
Craig Topper4f12f102014-03-12 06:41:41 +00001774 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall882987f2013-02-28 19:01:20 +00001775 CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()),
1776 Guard);
John McCall68ff0372010-09-08 01:44:27 +00001777 }
1778 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001779}
John McCall68ff0372010-09-08 01:44:27 +00001780
1781/// The ARM code here follows the Itanium code closely enough that we
1782/// just special-case it at particular places.
John McCallcdf7ef52010-11-06 09:44:32 +00001783void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
1784 const VarDecl &D,
John McCallb88a5662012-03-30 21:00:39 +00001785 llvm::GlobalVariable *var,
1786 bool shouldPerformInit) {
John McCall68ff0372010-09-08 01:44:27 +00001787 CGBuilderTy &Builder = CGF.Builder;
John McCallcdf7ef52010-11-06 09:44:32 +00001788
Richard Smithdbf74ba2013-04-14 23:01:42 +00001789 // We only need to use thread-safe statics for local non-TLS variables;
John McCallcdf7ef52010-11-06 09:44:32 +00001790 // global initialization is always single-threaded.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001791 bool threadsafe = getContext().getLangOpts().ThreadsafeStatics &&
1792 D.isLocalVarDecl() && !D.getTLSKind();
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001793
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001794 // If we have a global variable with internal linkage and thread-safe statics
1795 // are disabled, we can just let the guard variable be of type i8.
John McCallb88a5662012-03-30 21:00:39 +00001796 bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
1797
1798 llvm::IntegerType *guardTy;
John McCall5aa52592011-06-17 07:33:57 +00001799 if (useInt8GuardVariable) {
John McCallb88a5662012-03-30 21:00:39 +00001800 guardTy = CGF.Int8Ty;
John McCall5aa52592011-06-17 07:33:57 +00001801 } else {
Tim Northover9bb857a2013-01-31 12:13:10 +00001802 // Guard variables are 64 bits in the generic ABI and size width on ARM
1803 // (i.e. 32-bit on AArch32, 64-bit on AArch64).
Mark Seabornedf0d382013-07-24 16:25:13 +00001804 guardTy = (UseARMGuardVarABI ? CGF.SizeTy : CGF.Int64Ty);
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001805 }
John McCallb88a5662012-03-30 21:00:39 +00001806 llvm::PointerType *guardPtrTy = guardTy->getPointerTo();
John McCall68ff0372010-09-08 01:44:27 +00001807
John McCallb88a5662012-03-30 21:00:39 +00001808 // Create the guard variable if we don't already have it (as we
1809 // might if we're double-emitting this function body).
1810 llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
1811 if (!guard) {
1812 // Mangle the name for the guard.
1813 SmallString<256> guardName;
1814 {
1815 llvm::raw_svector_ostream out(guardName);
Reid Klecknerd8110b62013-09-10 20:14:30 +00001816 getMangleContext().mangleStaticGuardVariable(&D, out);
John McCallb88a5662012-03-30 21:00:39 +00001817 out.flush();
1818 }
John McCall8e7cb6d2010-11-02 21:04:24 +00001819
John McCallb88a5662012-03-30 21:00:39 +00001820 // Create the guard variable with a zero-initializer.
1821 // Just absorb linkage and visibility from the guarded variable.
1822 guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
1823 false, var->getLinkage(),
1824 llvm::ConstantInt::get(guardTy, 0),
1825 guardName.str());
1826 guard->setVisibility(var->getVisibility());
Richard Smithdbf74ba2013-04-14 23:01:42 +00001827 // If the variable is thread-local, so is its guard variable.
1828 guard->setThreadLocalMode(var->getThreadLocalMode());
John McCallb88a5662012-03-30 21:00:39 +00001829
Rafael Espindola2ae4b632014-09-19 19:43:18 +00001830 // The ABI says: It is suggested that it be emitted in the same COMDAT group
1831 // as the associated data object
Rafael Espindola0d4fb982015-01-12 22:13:53 +00001832 llvm::Comdat *C = var->getComdat();
1833 if (!D.isLocalVarDecl() && C) {
Rafael Espindola2ae4b632014-09-19 19:43:18 +00001834 guard->setComdat(C);
Rafael Espindola2ae4b632014-09-19 19:43:18 +00001835 CGF.CurFn->setComdat(C);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00001836 } else if (CGM.supportsCOMDAT() && guard->isWeakForLinker()) {
1837 guard->setComdat(CGM.getModule().getOrInsertComdat(guard->getName()));
Rafael Espindola2ae4b632014-09-19 19:43:18 +00001838 }
1839
John McCallb88a5662012-03-30 21:00:39 +00001840 CGM.setStaticLocalDeclGuardAddress(&D, guard);
1841 }
John McCall87590e62012-03-30 07:09:50 +00001842
John McCall68ff0372010-09-08 01:44:27 +00001843 // Test whether the variable has completed initialization.
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001844 //
John McCall68ff0372010-09-08 01:44:27 +00001845 // Itanium C++ ABI 3.3.2:
1846 // The following is pseudo-code showing how these functions can be used:
1847 // if (obj_guard.first_byte == 0) {
1848 // if ( __cxa_guard_acquire (&obj_guard) ) {
1849 // try {
1850 // ... initialize the object ...;
1851 // } catch (...) {
1852 // __cxa_guard_abort (&obj_guard);
1853 // throw;
1854 // }
1855 // ... queue object destructor with __cxa_atexit() ...;
1856 // __cxa_guard_release (&obj_guard);
1857 // }
1858 // }
Tim Northovera2ee4332014-03-29 15:09:45 +00001859
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001860 // Load the first byte of the guard variable.
1861 llvm::LoadInst *LI =
John McCallb88a5662012-03-30 21:00:39 +00001862 Builder.CreateLoad(Builder.CreateBitCast(guard, CGM.Int8PtrTy));
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001863 LI->setAlignment(1);
John McCall68ff0372010-09-08 01:44:27 +00001864
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001865 // Itanium ABI:
1866 // An implementation supporting thread-safety on multiprocessor
1867 // systems must also guarantee that references to the initialized
1868 // object do not occur before the load of the initialization flag.
1869 //
1870 // In LLVM, we do this by marking the load Acquire.
1871 if (threadsafe)
1872 LI->setAtomic(llvm::Acquire);
Eli Friedman84d28122011-09-13 22:21:56 +00001873
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001874 // For ARM, we should only check the first bit, rather than the entire byte:
1875 //
1876 // ARM C++ ABI 3.2.3.1:
1877 // To support the potential use of initialization guard variables
1878 // as semaphores that are the target of ARM SWP and LDREX/STREX
1879 // synchronizing instructions we define a static initialization
1880 // guard variable to be a 4-byte aligned, 4-byte word with the
1881 // following inline access protocol.
1882 // #define INITIALIZED 1
1883 // if ((obj_guard & INITIALIZED) != INITIALIZED) {
1884 // if (__cxa_guard_acquire(&obj_guard))
1885 // ...
1886 // }
1887 //
1888 // and similarly for ARM64:
1889 //
1890 // ARM64 C++ ABI 3.2.2:
1891 // This ABI instead only specifies the value bit 0 of the static guard
1892 // variable; all other bits are platform defined. Bit 0 shall be 0 when the
1893 // variable is not initialized and 1 when it is.
1894 llvm::Value *V =
1895 (UseARMGuardVarABI && !useInt8GuardVariable)
1896 ? Builder.CreateAnd(LI, llvm::ConstantInt::get(CGM.Int8Ty, 1))
1897 : LI;
1898 llvm::Value *isInitialized = Builder.CreateIsNull(V, "guard.uninitialized");
John McCall68ff0372010-09-08 01:44:27 +00001899
1900 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
1901 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
1902
1903 // Check if the first byte of the guard variable is zero.
John McCallb88a5662012-03-30 21:00:39 +00001904 Builder.CreateCondBr(isInitialized, InitCheckBlock, EndBlock);
John McCall68ff0372010-09-08 01:44:27 +00001905
1906 CGF.EmitBlock(InitCheckBlock);
1907
1908 // Variables used when coping with thread-safe statics and exceptions.
John McCall5aa52592011-06-17 07:33:57 +00001909 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00001910 // Call __cxa_guard_acquire.
1911 llvm::Value *V
John McCall882987f2013-02-28 19:01:20 +00001912 = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
John McCall68ff0372010-09-08 01:44:27 +00001913
1914 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
1915
1916 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
1917 InitBlock, EndBlock);
1918
1919 // Call __cxa_guard_abort along the exceptional edge.
John McCallb88a5662012-03-30 21:00:39 +00001920 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
John McCall68ff0372010-09-08 01:44:27 +00001921
1922 CGF.EmitBlock(InitBlock);
1923 }
1924
1925 // Emit the initializer and add a global destructor if appropriate.
John McCallb88a5662012-03-30 21:00:39 +00001926 CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
John McCall68ff0372010-09-08 01:44:27 +00001927
John McCall5aa52592011-06-17 07:33:57 +00001928 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00001929 // Pop the guard-abort cleanup if we pushed one.
1930 CGF.PopCleanupBlock();
1931
1932 // Call __cxa_guard_release. This cannot throw.
John McCall882987f2013-02-28 19:01:20 +00001933 CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy), guard);
John McCall68ff0372010-09-08 01:44:27 +00001934 } else {
John McCallb88a5662012-03-30 21:00:39 +00001935 Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guard);
John McCall68ff0372010-09-08 01:44:27 +00001936 }
1937
1938 CGF.EmitBlock(EndBlock);
1939}
John McCallc84ed6a2012-05-01 06:13:13 +00001940
1941/// Register a global destructor using __cxa_atexit.
1942static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
1943 llvm::Constant *dtor,
Richard Smithdbf74ba2013-04-14 23:01:42 +00001944 llvm::Constant *addr,
1945 bool TLS) {
Bill Wendling95cae882013-05-02 19:18:03 +00001946 const char *Name = "__cxa_atexit";
1947 if (TLS) {
1948 const llvm::Triple &T = CGF.getTarget().getTriple();
1949 Name = T.isMacOSX() ? "_tlv_atexit" : "__cxa_thread_atexit";
1950 }
Richard Smithdbf74ba2013-04-14 23:01:42 +00001951
John McCallc84ed6a2012-05-01 06:13:13 +00001952 // We're assuming that the destructor function is something we can
1953 // reasonably call with the default CC. Go ahead and cast it to the
1954 // right prototype.
1955 llvm::Type *dtorTy =
1956 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo();
1957
1958 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
1959 llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
1960 llvm::FunctionType *atexitTy =
1961 llvm::FunctionType::get(CGF.IntTy, paramTys, false);
1962
1963 // Fetch the actual function.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001964 llvm::Constant *atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name);
John McCallc84ed6a2012-05-01 06:13:13 +00001965 if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit))
1966 fn->setDoesNotThrow();
1967
1968 // Create a variable that binds the atexit to this shared object.
1969 llvm::Constant *handle =
1970 CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
1971
1972 llvm::Value *args[] = {
1973 llvm::ConstantExpr::getBitCast(dtor, dtorTy),
1974 llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy),
1975 handle
1976 };
John McCall882987f2013-02-28 19:01:20 +00001977 CGF.EmitNounwindRuntimeCall(atexit, args);
John McCallc84ed6a2012-05-01 06:13:13 +00001978}
1979
1980/// Register a global destructor as best as we know how.
1981void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF,
Richard Smithdbf74ba2013-04-14 23:01:42 +00001982 const VarDecl &D,
John McCallc84ed6a2012-05-01 06:13:13 +00001983 llvm::Constant *dtor,
1984 llvm::Constant *addr) {
1985 // Use __cxa_atexit if available.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001986 if (CGM.getCodeGenOpts().CXAAtExit)
1987 return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind());
1988
1989 if (D.getTLSKind())
1990 CGM.ErrorUnsupported(&D, "non-trivial TLS destruction");
John McCallc84ed6a2012-05-01 06:13:13 +00001991
1992 // In Apple kexts, we want to add a global destructor entry.
1993 // FIXME: shouldn't this be guarded by some variable?
Richard Smith9c6890a2012-11-01 22:30:59 +00001994 if (CGM.getLangOpts().AppleKext) {
John McCallc84ed6a2012-05-01 06:13:13 +00001995 // Generate a global destructor entry.
1996 return CGM.AddCXXDtorEntry(dtor, addr);
1997 }
1998
David Blaikieebe87e12013-08-27 23:57:18 +00001999 CGF.registerGlobalDtorWithAtExit(D, dtor, addr);
John McCallc84ed6a2012-05-01 06:13:13 +00002000}
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002001
David Majnemer9b21c332014-07-11 20:28:10 +00002002static bool isThreadWrapperReplaceable(const VarDecl *VD,
2003 CodeGen::CodeGenModule &CGM) {
2004 assert(!VD->isStaticLocal() && "static local VarDecls don't need wrappers!");
2005 // OS X prefers to have references to thread local variables to go through
2006 // the thread wrapper instead of directly referencing the backing variable.
2007 return VD->getTLSKind() == VarDecl::TLS_Dynamic &&
2008 CGM.getTarget().getTriple().isMacOSX();
2009}
2010
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002011/// Get the appropriate linkage for the wrapper function. This is essentially
David Majnemer4632e1e2014-06-27 16:56:27 +00002012/// the weak form of the variable's linkage; every translation unit which needs
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002013/// the wrapper emits a copy, and we want the linker to merge them.
David Majnemer35ab3282014-06-11 04:08:55 +00002014static llvm::GlobalValue::LinkageTypes
2015getThreadLocalWrapperLinkage(const VarDecl *VD, CodeGen::CodeGenModule &CGM) {
2016 llvm::GlobalValue::LinkageTypes VarLinkage =
2017 CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false);
2018
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002019 // For internal linkage variables, we don't need an external or weak wrapper.
2020 if (llvm::GlobalValue::isLocalLinkage(VarLinkage))
2021 return VarLinkage;
David Majnemer35ab3282014-06-11 04:08:55 +00002022
David Majnemer9b21c332014-07-11 20:28:10 +00002023 // If the thread wrapper is replaceable, give it appropriate linkage.
2024 if (isThreadWrapperReplaceable(VD, CGM)) {
2025 if (llvm::GlobalVariable::isLinkOnceLinkage(VarLinkage) ||
2026 llvm::GlobalVariable::isWeakODRLinkage(VarLinkage))
2027 return llvm::GlobalVariable::WeakAnyLinkage;
2028 return VarLinkage;
2029 }
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002030 return llvm::GlobalValue::WeakODRLinkage;
2031}
2032
2033llvm::Function *
2034ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD,
Alexander Musmanf94c3182014-09-26 06:28:25 +00002035 llvm::Value *Val) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002036 // Mangle the name for the thread_local wrapper function.
2037 SmallString<256> WrapperName;
2038 {
2039 llvm::raw_svector_ostream Out(WrapperName);
2040 getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out);
2041 Out.flush();
2042 }
2043
Alexander Musmanf94c3182014-09-26 06:28:25 +00002044 if (llvm::Value *V = CGM.getModule().getNamedValue(WrapperName))
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002045 return cast<llvm::Function>(V);
2046
Alexander Musmanf94c3182014-09-26 06:28:25 +00002047 llvm::Type *RetTy = Val->getType();
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002048 if (VD->getType()->isReferenceType())
2049 RetTy = RetTy->getPointerElementType();
2050
2051 llvm::FunctionType *FnTy = llvm::FunctionType::get(RetTy, false);
David Majnemer35ab3282014-06-11 04:08:55 +00002052 llvm::Function *Wrapper =
2053 llvm::Function::Create(FnTy, getThreadLocalWrapperLinkage(VD, CGM),
2054 WrapperName.str(), &CGM.getModule());
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002055 // Always resolve references to the wrapper at link time.
David Majnemer9b21c332014-07-11 20:28:10 +00002056 if (!Wrapper->hasLocalLinkage() && !isThreadWrapperReplaceable(VD, CGM))
Duncan P. N. Exon Smith4434d362014-05-07 22:36:11 +00002057 Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002058 return Wrapper;
2059}
2060
2061void ItaniumCXXABI::EmitThreadLocalInitFuncs(
David Majnemerb3341ea2014-10-05 05:05:40 +00002062 CodeGenModule &CGM,
2063 ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *>>
2064 CXXThreadLocals, ArrayRef<llvm::Function *> CXXThreadLocalInits,
2065 ArrayRef<llvm::GlobalVariable *> CXXThreadLocalInitVars) {
2066 llvm::Function *InitFunc = nullptr;
2067 if (!CXXThreadLocalInits.empty()) {
2068 // Generate a guarded initialization function.
2069 llvm::FunctionType *FTy =
2070 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
2071 InitFunc = CGM.CreateGlobalInitOrDestructFunction(FTy, "__tls_init",
Alexey Samsonov1444bb92014-10-17 00:20:19 +00002072 SourceLocation(),
David Majnemerb3341ea2014-10-05 05:05:40 +00002073 /*TLS=*/true);
2074 llvm::GlobalVariable *Guard = new llvm::GlobalVariable(
2075 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false,
2076 llvm::GlobalVariable::InternalLinkage,
2077 llvm::ConstantInt::get(CGM.Int8Ty, 0), "__tls_guard");
2078 Guard->setThreadLocal(true);
2079 CodeGenFunction(CGM)
2080 .GenerateCXXGlobalInitFunc(InitFunc, CXXThreadLocalInits, Guard);
2081 }
2082 for (unsigned I = 0, N = CXXThreadLocals.size(); I != N; ++I) {
2083 const VarDecl *VD = CXXThreadLocals[I].first;
2084 llvm::GlobalVariable *Var = CXXThreadLocals[I].second;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002085
David Majnemer9b21c332014-07-11 20:28:10 +00002086 // Some targets require that all access to thread local variables go through
2087 // the thread wrapper. This means that we cannot attempt to create a thread
2088 // wrapper or a thread helper.
2089 if (isThreadWrapperReplaceable(VD, CGM) && !VD->hasDefinition())
2090 continue;
2091
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002092 // Mangle the name for the thread_local initialization function.
2093 SmallString<256> InitFnName;
2094 {
2095 llvm::raw_svector_ostream Out(InitFnName);
2096 getMangleContext().mangleItaniumThreadLocalInit(VD, Out);
2097 Out.flush();
2098 }
2099
2100 // If we have a definition for the variable, emit the initialization
2101 // function as an alias to the global Init function (if any). Otherwise,
2102 // produce a declaration of the initialization function.
Craig Topper8a13c412014-05-21 05:09:00 +00002103 llvm::GlobalValue *Init = nullptr;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002104 bool InitIsInitFunc = false;
2105 if (VD->hasDefinition()) {
2106 InitIsInitFunc = true;
2107 if (InitFunc)
Rafael Espindola234405b2014-05-17 21:30:14 +00002108 Init = llvm::GlobalAlias::create(Var->getLinkage(), InitFnName.str(),
2109 InitFunc);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002110 } else {
2111 // Emit a weak global function referring to the initialization function.
2112 // This function will not exist if the TU defining the thread_local
2113 // variable in question does not need any dynamic initialization for
2114 // its thread_local variables.
2115 llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, false);
2116 Init = llvm::Function::Create(
2117 FnTy, llvm::GlobalVariable::ExternalWeakLinkage, InitFnName.str(),
2118 &CGM.getModule());
2119 }
2120
2121 if (Init)
2122 Init->setVisibility(Var->getVisibility());
2123
2124 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Var);
2125 llvm::LLVMContext &Context = CGM.getModule().getContext();
2126 llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper);
2127 CGBuilderTy Builder(Entry);
2128 if (InitIsInitFunc) {
2129 if (Init)
David Blaikie4ba525b2015-07-14 17:27:39 +00002130 Builder.CreateCall(Init);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002131 } else {
2132 // Don't know whether we have an init function. Call it if it exists.
2133 llvm::Value *Have = Builder.CreateIsNotNull(Init);
2134 llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2135 llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2136 Builder.CreateCondBr(Have, InitBB, ExitBB);
2137
2138 Builder.SetInsertPoint(InitBB);
David Blaikie4ba525b2015-07-14 17:27:39 +00002139 Builder.CreateCall(Init);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002140 Builder.CreateBr(ExitBB);
2141
2142 Builder.SetInsertPoint(ExitBB);
2143 }
2144
2145 // For a reference, the result of the wrapper function is a pointer to
2146 // the referenced object.
2147 llvm::Value *Val = Var;
2148 if (VD->getType()->isReferenceType()) {
2149 llvm::LoadInst *LI = Builder.CreateLoad(Val);
2150 LI->setAlignment(CGM.getContext().getDeclAlign(VD).getQuantity());
2151 Val = LI;
2152 }
Alexander Musmanf94c3182014-09-26 06:28:25 +00002153 if (Val->getType() != Wrapper->getReturnType())
2154 Val = Builder.CreatePointerBitCastOrAddrSpaceCast(
2155 Val, Wrapper->getReturnType(), "");
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002156 Builder.CreateRet(Val);
2157 }
2158}
2159
Richard Smith0f383742014-03-26 22:48:22 +00002160LValue ItaniumCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
2161 const VarDecl *VD,
2162 QualType LValType) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002163 QualType T = VD->getType();
2164 llvm::Type *Ty = CGF.getTypes().ConvertTypeForMem(T);
2165 llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD, Ty);
Alexander Musmanf94c3182014-09-26 06:28:25 +00002166 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Val);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002167
David Blaikie4ba525b2015-07-14 17:27:39 +00002168 Val = CGF.Builder.CreateCall(Wrapper);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002169
2170 LValue LV;
2171 if (VD->getType()->isReferenceType())
Richard Smith0f383742014-03-26 22:48:22 +00002172 LV = CGF.MakeNaturalAlignAddrLValue(Val, LValType);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002173 else
Richard Smith0f383742014-03-26 22:48:22 +00002174 LV = CGF.MakeAddrLValue(Val, LValType, CGF.getContext().getDeclAlign(VD));
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002175 // FIXME: need setObjCGCLValueClass?
2176 return LV;
2177}
Peter Collingbourne66f82e62013-06-28 20:45:28 +00002178
2179/// Return whether the given global decl needs a VTT parameter, which it does
2180/// if it's a base constructor or destructor with virtual bases.
2181bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) {
2182 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
2183
2184 // We don't have any virtual bases, just return early.
2185 if (!MD->getParent()->getNumVBases())
2186 return false;
2187
2188 // Check if we have a base constructor.
2189 if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base)
2190 return true;
2191
2192 // Check if we have a base destructor.
2193 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
2194 return true;
2195
2196 return false;
2197}
David Majnemere2cb8d12014-07-07 06:20:47 +00002198
2199namespace {
2200class ItaniumRTTIBuilder {
2201 CodeGenModule &CGM; // Per-module state.
2202 llvm::LLVMContext &VMContext;
2203 const ItaniumCXXABI &CXXABI; // Per-module state.
2204
2205 /// Fields - The fields of the RTTI descriptor currently being built.
2206 SmallVector<llvm::Constant *, 16> Fields;
2207
2208 /// GetAddrOfTypeName - Returns the mangled type name of the given type.
2209 llvm::GlobalVariable *
2210 GetAddrOfTypeName(QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage);
2211
2212 /// GetAddrOfExternalRTTIDescriptor - Returns the constant for the RTTI
2213 /// descriptor of the given type.
2214 llvm::Constant *GetAddrOfExternalRTTIDescriptor(QualType Ty);
2215
2216 /// BuildVTablePointer - Build the vtable pointer for the given type.
2217 void BuildVTablePointer(const Type *Ty);
2218
2219 /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
2220 /// inheritance, according to the Itanium C++ ABI, 2.9.5p6b.
2221 void BuildSIClassTypeInfo(const CXXRecordDecl *RD);
2222
2223 /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
2224 /// classes with bases that do not satisfy the abi::__si_class_type_info
2225 /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
2226 void BuildVMIClassTypeInfo(const CXXRecordDecl *RD);
2227
2228 /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct, used
2229 /// for pointer types.
2230 void BuildPointerTypeInfo(QualType PointeeTy);
2231
2232 /// BuildObjCObjectTypeInfo - Build the appropriate kind of
2233 /// type_info for an object type.
2234 void BuildObjCObjectTypeInfo(const ObjCObjectType *Ty);
2235
2236 /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
2237 /// struct, used for member pointer types.
2238 void BuildPointerToMemberTypeInfo(const MemberPointerType *Ty);
2239
2240public:
2241 ItaniumRTTIBuilder(const ItaniumCXXABI &ABI)
2242 : CGM(ABI.CGM), VMContext(CGM.getModule().getContext()), CXXABI(ABI) {}
2243
2244 // Pointer type info flags.
2245 enum {
2246 /// PTI_Const - Type has const qualifier.
2247 PTI_Const = 0x1,
2248
2249 /// PTI_Volatile - Type has volatile qualifier.
2250 PTI_Volatile = 0x2,
2251
2252 /// PTI_Restrict - Type has restrict qualifier.
2253 PTI_Restrict = 0x4,
2254
2255 /// PTI_Incomplete - Type is incomplete.
2256 PTI_Incomplete = 0x8,
2257
2258 /// PTI_ContainingClassIncomplete - Containing class is incomplete.
2259 /// (in pointer to member).
2260 PTI_ContainingClassIncomplete = 0x10
2261 };
2262
2263 // VMI type info flags.
2264 enum {
2265 /// VMI_NonDiamondRepeat - Class has non-diamond repeated inheritance.
2266 VMI_NonDiamondRepeat = 0x1,
2267
2268 /// VMI_DiamondShaped - Class is diamond shaped.
2269 VMI_DiamondShaped = 0x2
2270 };
2271
2272 // Base class type info flags.
2273 enum {
2274 /// BCTI_Virtual - Base class is virtual.
2275 BCTI_Virtual = 0x1,
2276
2277 /// BCTI_Public - Base class is public.
2278 BCTI_Public = 0x2
2279 };
2280
2281 /// BuildTypeInfo - Build the RTTI type info struct for the given type.
2282 ///
2283 /// \param Force - true to force the creation of this RTTI value
2284 llvm::Constant *BuildTypeInfo(QualType Ty, bool Force = false);
2285};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002286}
David Majnemere2cb8d12014-07-07 06:20:47 +00002287
2288llvm::GlobalVariable *ItaniumRTTIBuilder::GetAddrOfTypeName(
2289 QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage) {
Yaron Kerene46f7ed2015-07-29 14:21:47 +00002290 SmallString<256> Name;
2291 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00002292 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(Ty, Out);
2293 Out.flush();
David Majnemere2cb8d12014-07-07 06:20:47 +00002294
2295 // We know that the mangled name of the type starts at index 4 of the
2296 // mangled name of the typename, so we can just index into it in order to
2297 // get the mangled name of the type.
2298 llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,
2299 Name.substr(4));
2300
2301 llvm::GlobalVariable *GV =
2302 CGM.CreateOrReplaceCXXRuntimeVariable(Name, Init->getType(), Linkage);
2303
2304 GV->setInitializer(Init);
2305
2306 return GV;
2307}
2308
2309llvm::Constant *
2310ItaniumRTTIBuilder::GetAddrOfExternalRTTIDescriptor(QualType Ty) {
2311 // Mangle the RTTI name.
Yaron Kerene46f7ed2015-07-29 14:21:47 +00002312 SmallString<256> Name;
2313 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00002314 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
2315 Out.flush();
David Majnemere2cb8d12014-07-07 06:20:47 +00002316
2317 // Look for an existing global.
2318 llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name);
2319
2320 if (!GV) {
2321 // Create a new global variable.
2322 GV = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
2323 /*Constant=*/true,
2324 llvm::GlobalValue::ExternalLinkage, nullptr,
2325 Name);
David Majnemer1fb1a042014-11-07 07:26:38 +00002326 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2327 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
2328 if (RD->hasAttr<DLLImportAttr>())
2329 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
2330 }
David Majnemere2cb8d12014-07-07 06:20:47 +00002331 }
2332
2333 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
2334}
2335
2336/// TypeInfoIsInStandardLibrary - Given a builtin type, returns whether the type
2337/// info for that type is defined in the standard library.
2338static bool TypeInfoIsInStandardLibrary(const BuiltinType *Ty) {
2339 // Itanium C++ ABI 2.9.2:
2340 // Basic type information (e.g. for "int", "bool", etc.) will be kept in
2341 // the run-time support library. Specifically, the run-time support
2342 // library should contain type_info objects for the types X, X* and
2343 // X const*, for every X in: void, std::nullptr_t, bool, wchar_t, char,
2344 // unsigned char, signed char, short, unsigned short, int, unsigned int,
2345 // long, unsigned long, long long, unsigned long long, float, double,
2346 // long double, char16_t, char32_t, and the IEEE 754r decimal and
2347 // half-precision floating point types.
2348 switch (Ty->getKind()) {
2349 case BuiltinType::Void:
2350 case BuiltinType::NullPtr:
2351 case BuiltinType::Bool:
2352 case BuiltinType::WChar_S:
2353 case BuiltinType::WChar_U:
2354 case BuiltinType::Char_U:
2355 case BuiltinType::Char_S:
2356 case BuiltinType::UChar:
2357 case BuiltinType::SChar:
2358 case BuiltinType::Short:
2359 case BuiltinType::UShort:
2360 case BuiltinType::Int:
2361 case BuiltinType::UInt:
2362 case BuiltinType::Long:
2363 case BuiltinType::ULong:
2364 case BuiltinType::LongLong:
2365 case BuiltinType::ULongLong:
2366 case BuiltinType::Half:
2367 case BuiltinType::Float:
2368 case BuiltinType::Double:
2369 case BuiltinType::LongDouble:
2370 case BuiltinType::Char16:
2371 case BuiltinType::Char32:
2372 case BuiltinType::Int128:
2373 case BuiltinType::UInt128:
2374 case BuiltinType::OCLImage1d:
2375 case BuiltinType::OCLImage1dArray:
2376 case BuiltinType::OCLImage1dBuffer:
2377 case BuiltinType::OCLImage2d:
2378 case BuiltinType::OCLImage2dArray:
2379 case BuiltinType::OCLImage3d:
2380 case BuiltinType::OCLSampler:
2381 case BuiltinType::OCLEvent:
2382 return true;
2383
2384 case BuiltinType::Dependent:
2385#define BUILTIN_TYPE(Id, SingletonId)
2386#define PLACEHOLDER_TYPE(Id, SingletonId) \
2387 case BuiltinType::Id:
2388#include "clang/AST/BuiltinTypes.def"
2389 llvm_unreachable("asking for RRTI for a placeholder type!");
2390
2391 case BuiltinType::ObjCId:
2392 case BuiltinType::ObjCClass:
2393 case BuiltinType::ObjCSel:
2394 llvm_unreachable("FIXME: Objective-C types are unsupported!");
2395 }
2396
2397 llvm_unreachable("Invalid BuiltinType Kind!");
2398}
2399
2400static bool TypeInfoIsInStandardLibrary(const PointerType *PointerTy) {
2401 QualType PointeeTy = PointerTy->getPointeeType();
2402 const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(PointeeTy);
2403 if (!BuiltinTy)
2404 return false;
2405
2406 // Check the qualifiers.
2407 Qualifiers Quals = PointeeTy.getQualifiers();
2408 Quals.removeConst();
2409
2410 if (!Quals.empty())
2411 return false;
2412
2413 return TypeInfoIsInStandardLibrary(BuiltinTy);
2414}
2415
2416/// IsStandardLibraryRTTIDescriptor - Returns whether the type
2417/// information for the given type exists in the standard library.
2418static bool IsStandardLibraryRTTIDescriptor(QualType Ty) {
2419 // Type info for builtin types is defined in the standard library.
2420 if (const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(Ty))
2421 return TypeInfoIsInStandardLibrary(BuiltinTy);
2422
2423 // Type info for some pointer types to builtin types is defined in the
2424 // standard library.
2425 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2426 return TypeInfoIsInStandardLibrary(PointerTy);
2427
2428 return false;
2429}
2430
2431/// ShouldUseExternalRTTIDescriptor - Returns whether the type information for
2432/// the given type exists somewhere else, and that we should not emit the type
2433/// information in this translation unit. Assumes that it is not a
2434/// standard-library type.
2435static bool ShouldUseExternalRTTIDescriptor(CodeGenModule &CGM,
2436 QualType Ty) {
2437 ASTContext &Context = CGM.getContext();
2438
2439 // If RTTI is disabled, assume it might be disabled in the
2440 // translation unit that defines any potential key function, too.
2441 if (!Context.getLangOpts().RTTI) return false;
2442
2443 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2444 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
2445 if (!RD->hasDefinition())
2446 return false;
2447
2448 if (!RD->isDynamicClass())
2449 return false;
2450
2451 // FIXME: this may need to be reconsidered if the key function
2452 // changes.
David Majnemer1fb1a042014-11-07 07:26:38 +00002453 if (CGM.getVTables().isVTableExternal(RD))
2454 return true;
2455
2456 if (RD->hasAttr<DLLImportAttr>())
2457 return true;
David Majnemere2cb8d12014-07-07 06:20:47 +00002458 }
2459
2460 return false;
2461}
2462
2463/// IsIncompleteClassType - Returns whether the given record type is incomplete.
2464static bool IsIncompleteClassType(const RecordType *RecordTy) {
2465 return !RecordTy->getDecl()->isCompleteDefinition();
2466}
2467
2468/// ContainsIncompleteClassType - Returns whether the given type contains an
2469/// incomplete class type. This is true if
2470///
2471/// * The given type is an incomplete class type.
2472/// * The given type is a pointer type whose pointee type contains an
2473/// incomplete class type.
2474/// * The given type is a member pointer type whose class is an incomplete
2475/// class type.
2476/// * The given type is a member pointer type whoise pointee type contains an
2477/// incomplete class type.
2478/// is an indirect or direct pointer to an incomplete class type.
2479static bool ContainsIncompleteClassType(QualType Ty) {
2480 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2481 if (IsIncompleteClassType(RecordTy))
2482 return true;
2483 }
2484
2485 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2486 return ContainsIncompleteClassType(PointerTy->getPointeeType());
2487
2488 if (const MemberPointerType *MemberPointerTy =
2489 dyn_cast<MemberPointerType>(Ty)) {
2490 // Check if the class type is incomplete.
2491 const RecordType *ClassType = cast<RecordType>(MemberPointerTy->getClass());
2492 if (IsIncompleteClassType(ClassType))
2493 return true;
2494
2495 return ContainsIncompleteClassType(MemberPointerTy->getPointeeType());
2496 }
2497
2498 return false;
2499}
2500
2501// CanUseSingleInheritance - Return whether the given record decl has a "single,
2502// public, non-virtual base at offset zero (i.e. the derived class is dynamic
2503// iff the base is)", according to Itanium C++ ABI, 2.95p6b.
2504static bool CanUseSingleInheritance(const CXXRecordDecl *RD) {
2505 // Check the number of bases.
2506 if (RD->getNumBases() != 1)
2507 return false;
2508
2509 // Get the base.
2510 CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin();
2511
2512 // Check that the base is not virtual.
2513 if (Base->isVirtual())
2514 return false;
2515
2516 // Check that the base is public.
2517 if (Base->getAccessSpecifier() != AS_public)
2518 return false;
2519
2520 // Check that the class is dynamic iff the base is.
2521 const CXXRecordDecl *BaseDecl =
2522 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2523 if (!BaseDecl->isEmpty() &&
2524 BaseDecl->isDynamicClass() != RD->isDynamicClass())
2525 return false;
2526
2527 return true;
2528}
2529
2530void ItaniumRTTIBuilder::BuildVTablePointer(const Type *Ty) {
2531 // abi::__class_type_info.
2532 static const char * const ClassTypeInfo =
2533 "_ZTVN10__cxxabiv117__class_type_infoE";
2534 // abi::__si_class_type_info.
2535 static const char * const SIClassTypeInfo =
2536 "_ZTVN10__cxxabiv120__si_class_type_infoE";
2537 // abi::__vmi_class_type_info.
2538 static const char * const VMIClassTypeInfo =
2539 "_ZTVN10__cxxabiv121__vmi_class_type_infoE";
2540
2541 const char *VTableName = nullptr;
2542
2543 switch (Ty->getTypeClass()) {
2544#define TYPE(Class, Base)
2545#define ABSTRACT_TYPE(Class, Base)
2546#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2547#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2548#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2549#include "clang/AST/TypeNodes.def"
2550 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
2551
2552 case Type::LValueReference:
2553 case Type::RValueReference:
2554 llvm_unreachable("References shouldn't get here");
2555
2556 case Type::Auto:
2557 llvm_unreachable("Undeduced auto type shouldn't get here");
2558
2559 case Type::Builtin:
2560 // GCC treats vector and complex types as fundamental types.
2561 case Type::Vector:
2562 case Type::ExtVector:
2563 case Type::Complex:
2564 case Type::Atomic:
2565 // FIXME: GCC treats block pointers as fundamental types?!
2566 case Type::BlockPointer:
2567 // abi::__fundamental_type_info.
2568 VTableName = "_ZTVN10__cxxabiv123__fundamental_type_infoE";
2569 break;
2570
2571 case Type::ConstantArray:
2572 case Type::IncompleteArray:
2573 case Type::VariableArray:
2574 // abi::__array_type_info.
2575 VTableName = "_ZTVN10__cxxabiv117__array_type_infoE";
2576 break;
2577
2578 case Type::FunctionNoProto:
2579 case Type::FunctionProto:
2580 // abi::__function_type_info.
2581 VTableName = "_ZTVN10__cxxabiv120__function_type_infoE";
2582 break;
2583
2584 case Type::Enum:
2585 // abi::__enum_type_info.
2586 VTableName = "_ZTVN10__cxxabiv116__enum_type_infoE";
2587 break;
2588
2589 case Type::Record: {
2590 const CXXRecordDecl *RD =
2591 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
2592
2593 if (!RD->hasDefinition() || !RD->getNumBases()) {
2594 VTableName = ClassTypeInfo;
2595 } else if (CanUseSingleInheritance(RD)) {
2596 VTableName = SIClassTypeInfo;
2597 } else {
2598 VTableName = VMIClassTypeInfo;
2599 }
2600
2601 break;
2602 }
2603
2604 case Type::ObjCObject:
2605 // Ignore protocol qualifiers.
2606 Ty = cast<ObjCObjectType>(Ty)->getBaseType().getTypePtr();
2607
2608 // Handle id and Class.
2609 if (isa<BuiltinType>(Ty)) {
2610 VTableName = ClassTypeInfo;
2611 break;
2612 }
2613
2614 assert(isa<ObjCInterfaceType>(Ty));
2615 // Fall through.
2616
2617 case Type::ObjCInterface:
2618 if (cast<ObjCInterfaceType>(Ty)->getDecl()->getSuperClass()) {
2619 VTableName = SIClassTypeInfo;
2620 } else {
2621 VTableName = ClassTypeInfo;
2622 }
2623 break;
2624
2625 case Type::ObjCObjectPointer:
2626 case Type::Pointer:
2627 // abi::__pointer_type_info.
2628 VTableName = "_ZTVN10__cxxabiv119__pointer_type_infoE";
2629 break;
2630
2631 case Type::MemberPointer:
2632 // abi::__pointer_to_member_type_info.
2633 VTableName = "_ZTVN10__cxxabiv129__pointer_to_member_type_infoE";
2634 break;
2635 }
2636
2637 llvm::Constant *VTable =
2638 CGM.getModule().getOrInsertGlobal(VTableName, CGM.Int8PtrTy);
2639
2640 llvm::Type *PtrDiffTy =
2641 CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
2642
2643 // The vtable address point is 2.
2644 llvm::Constant *Two = llvm::ConstantInt::get(PtrDiffTy, 2);
David Blaikiee3b172a2015-04-02 18:55:21 +00002645 VTable =
2646 llvm::ConstantExpr::getInBoundsGetElementPtr(CGM.Int8PtrTy, VTable, Two);
David Majnemere2cb8d12014-07-07 06:20:47 +00002647 VTable = llvm::ConstantExpr::getBitCast(VTable, CGM.Int8PtrTy);
2648
2649 Fields.push_back(VTable);
2650}
2651
2652/// \brief Return the linkage that the type info and type info name constants
2653/// should have for the given type.
2654static llvm::GlobalVariable::LinkageTypes getTypeInfoLinkage(CodeGenModule &CGM,
2655 QualType Ty) {
2656 // Itanium C++ ABI 2.9.5p7:
2657 // In addition, it and all of the intermediate abi::__pointer_type_info
2658 // structs in the chain down to the abi::__class_type_info for the
2659 // incomplete class type must be prevented from resolving to the
2660 // corresponding type_info structs for the complete class type, possibly
2661 // by making them local static objects. Finally, a dummy class RTTI is
2662 // generated for the incomplete type that will not resolve to the final
2663 // complete class RTTI (because the latter need not exist), possibly by
2664 // making it a local static object.
2665 if (ContainsIncompleteClassType(Ty))
2666 return llvm::GlobalValue::InternalLinkage;
2667
2668 switch (Ty->getLinkage()) {
2669 case NoLinkage:
2670 case InternalLinkage:
2671 case UniqueExternalLinkage:
2672 return llvm::GlobalValue::InternalLinkage;
2673
2674 case VisibleNoLinkage:
2675 case ExternalLinkage:
2676 if (!CGM.getLangOpts().RTTI) {
2677 // RTTI is not enabled, which means that this type info struct is going
2678 // to be used for exception handling. Give it linkonce_odr linkage.
2679 return llvm::GlobalValue::LinkOnceODRLinkage;
2680 }
2681
2682 if (const RecordType *Record = dyn_cast<RecordType>(Ty)) {
2683 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2684 if (RD->hasAttr<WeakAttr>())
2685 return llvm::GlobalValue::WeakODRLinkage;
2686 if (RD->isDynamicClass())
2687 return CGM.getVTableLinkage(RD);
2688 }
2689
2690 return llvm::GlobalValue::LinkOnceODRLinkage;
2691 }
2692
2693 llvm_unreachable("Invalid linkage!");
2694}
2695
2696llvm::Constant *ItaniumRTTIBuilder::BuildTypeInfo(QualType Ty, bool Force) {
2697 // We want to operate on the canonical type.
2698 Ty = CGM.getContext().getCanonicalType(Ty);
2699
2700 // Check if we've already emitted an RTTI descriptor for this type.
Yaron Kerene46f7ed2015-07-29 14:21:47 +00002701 SmallString<256> Name;
2702 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00002703 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
2704 Out.flush();
David Majnemere2cb8d12014-07-07 06:20:47 +00002705
2706 llvm::GlobalVariable *OldGV = CGM.getModule().getNamedGlobal(Name);
2707 if (OldGV && !OldGV->isDeclaration()) {
2708 assert(!OldGV->hasAvailableExternallyLinkage() &&
2709 "available_externally typeinfos not yet implemented");
2710
2711 return llvm::ConstantExpr::getBitCast(OldGV, CGM.Int8PtrTy);
2712 }
2713
2714 // Check if there is already an external RTTI descriptor for this type.
2715 bool IsStdLib = IsStandardLibraryRTTIDescriptor(Ty);
2716 if (!Force && (IsStdLib || ShouldUseExternalRTTIDescriptor(CGM, Ty)))
2717 return GetAddrOfExternalRTTIDescriptor(Ty);
2718
2719 // Emit the standard library with external linkage.
2720 llvm::GlobalVariable::LinkageTypes Linkage;
2721 if (IsStdLib)
2722 Linkage = llvm::GlobalValue::ExternalLinkage;
2723 else
2724 Linkage = getTypeInfoLinkage(CGM, Ty);
2725
2726 // Add the vtable pointer.
2727 BuildVTablePointer(cast<Type>(Ty));
2728
2729 // And the name.
2730 llvm::GlobalVariable *TypeName = GetAddrOfTypeName(Ty, Linkage);
2731 llvm::Constant *TypeNameField;
2732
2733 // If we're supposed to demote the visibility, be sure to set a flag
2734 // to use a string comparison for type_info comparisons.
2735 ItaniumCXXABI::RTTIUniquenessKind RTTIUniqueness =
2736 CXXABI.classifyRTTIUniqueness(Ty, Linkage);
2737 if (RTTIUniqueness != ItaniumCXXABI::RUK_Unique) {
2738 // The flag is the sign bit, which on ARM64 is defined to be clear
2739 // for global pointers. This is very ARM64-specific.
2740 TypeNameField = llvm::ConstantExpr::getPtrToInt(TypeName, CGM.Int64Ty);
2741 llvm::Constant *flag =
2742 llvm::ConstantInt::get(CGM.Int64Ty, ((uint64_t)1) << 63);
2743 TypeNameField = llvm::ConstantExpr::getAdd(TypeNameField, flag);
2744 TypeNameField =
2745 llvm::ConstantExpr::getIntToPtr(TypeNameField, CGM.Int8PtrTy);
2746 } else {
2747 TypeNameField = llvm::ConstantExpr::getBitCast(TypeName, CGM.Int8PtrTy);
2748 }
2749 Fields.push_back(TypeNameField);
2750
2751 switch (Ty->getTypeClass()) {
2752#define TYPE(Class, Base)
2753#define ABSTRACT_TYPE(Class, Base)
2754#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2755#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2756#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2757#include "clang/AST/TypeNodes.def"
2758 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
2759
2760 // GCC treats vector types as fundamental types.
2761 case Type::Builtin:
2762 case Type::Vector:
2763 case Type::ExtVector:
2764 case Type::Complex:
2765 case Type::BlockPointer:
2766 // Itanium C++ ABI 2.9.5p4:
2767 // abi::__fundamental_type_info adds no data members to std::type_info.
2768 break;
2769
2770 case Type::LValueReference:
2771 case Type::RValueReference:
2772 llvm_unreachable("References shouldn't get here");
2773
2774 case Type::Auto:
2775 llvm_unreachable("Undeduced auto type shouldn't get here");
2776
2777 case Type::ConstantArray:
2778 case Type::IncompleteArray:
2779 case Type::VariableArray:
2780 // Itanium C++ ABI 2.9.5p5:
2781 // abi::__array_type_info adds no data members to std::type_info.
2782 break;
2783
2784 case Type::FunctionNoProto:
2785 case Type::FunctionProto:
2786 // Itanium C++ ABI 2.9.5p5:
2787 // abi::__function_type_info adds no data members to std::type_info.
2788 break;
2789
2790 case Type::Enum:
2791 // Itanium C++ ABI 2.9.5p5:
2792 // abi::__enum_type_info adds no data members to std::type_info.
2793 break;
2794
2795 case Type::Record: {
2796 const CXXRecordDecl *RD =
2797 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
2798 if (!RD->hasDefinition() || !RD->getNumBases()) {
2799 // We don't need to emit any fields.
2800 break;
2801 }
2802
2803 if (CanUseSingleInheritance(RD))
2804 BuildSIClassTypeInfo(RD);
2805 else
2806 BuildVMIClassTypeInfo(RD);
2807
2808 break;
2809 }
2810
2811 case Type::ObjCObject:
2812 case Type::ObjCInterface:
2813 BuildObjCObjectTypeInfo(cast<ObjCObjectType>(Ty));
2814 break;
2815
2816 case Type::ObjCObjectPointer:
2817 BuildPointerTypeInfo(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
2818 break;
2819
2820 case Type::Pointer:
2821 BuildPointerTypeInfo(cast<PointerType>(Ty)->getPointeeType());
2822 break;
2823
2824 case Type::MemberPointer:
2825 BuildPointerToMemberTypeInfo(cast<MemberPointerType>(Ty));
2826 break;
2827
2828 case Type::Atomic:
2829 // No fields, at least for the moment.
2830 break;
2831 }
2832
2833 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Fields);
2834
Rafael Espindolacb92c192015-01-15 23:18:01 +00002835 llvm::Module &M = CGM.getModule();
David Majnemere2cb8d12014-07-07 06:20:47 +00002836 llvm::GlobalVariable *GV =
Rafael Espindolacb92c192015-01-15 23:18:01 +00002837 new llvm::GlobalVariable(M, Init->getType(),
2838 /*Constant=*/true, Linkage, Init, Name);
2839
David Majnemere2cb8d12014-07-07 06:20:47 +00002840 // If there's already an old global variable, replace it with the new one.
2841 if (OldGV) {
2842 GV->takeName(OldGV);
2843 llvm::Constant *NewPtr =
2844 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
2845 OldGV->replaceAllUsesWith(NewPtr);
2846 OldGV->eraseFromParent();
2847 }
2848
Yaron Keren04da2382015-07-29 15:42:28 +00002849 if (CGM.supportsCOMDAT() && GV->isWeakForLinker())
2850 GV->setComdat(M.getOrInsertComdat(GV->getName()));
2851
David Majnemere2cb8d12014-07-07 06:20:47 +00002852 // The Itanium ABI specifies that type_info objects must be globally
2853 // unique, with one exception: if the type is an incomplete class
2854 // type or a (possibly indirect) pointer to one. That exception
2855 // affects the general case of comparing type_info objects produced
2856 // by the typeid operator, which is why the comparison operators on
2857 // std::type_info generally use the type_info name pointers instead
2858 // of the object addresses. However, the language's built-in uses
2859 // of RTTI generally require class types to be complete, even when
2860 // manipulating pointers to those class types. This allows the
2861 // implementation of dynamic_cast to rely on address equality tests,
2862 // which is much faster.
2863
2864 // All of this is to say that it's important that both the type_info
2865 // object and the type_info name be uniqued when weakly emitted.
2866
2867 // Give the type_info object and name the formal visibility of the
2868 // type itself.
2869 llvm::GlobalValue::VisibilityTypes llvmVisibility;
2870 if (llvm::GlobalValue::isLocalLinkage(Linkage))
2871 // If the linkage is local, only default visibility makes sense.
2872 llvmVisibility = llvm::GlobalValue::DefaultVisibility;
2873 else if (RTTIUniqueness == ItaniumCXXABI::RUK_NonUniqueHidden)
2874 llvmVisibility = llvm::GlobalValue::HiddenVisibility;
2875 else
2876 llvmVisibility = CodeGenModule::GetLLVMVisibility(Ty->getVisibility());
2877 TypeName->setVisibility(llvmVisibility);
2878 GV->setVisibility(llvmVisibility);
2879
2880 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
2881}
2882
2883/// ComputeQualifierFlags - Compute the pointer type info flags from the
2884/// given qualifier.
2885static unsigned ComputeQualifierFlags(Qualifiers Quals) {
2886 unsigned Flags = 0;
2887
2888 if (Quals.hasConst())
2889 Flags |= ItaniumRTTIBuilder::PTI_Const;
2890 if (Quals.hasVolatile())
2891 Flags |= ItaniumRTTIBuilder::PTI_Volatile;
2892 if (Quals.hasRestrict())
2893 Flags |= ItaniumRTTIBuilder::PTI_Restrict;
2894
2895 return Flags;
2896}
2897
2898/// BuildObjCObjectTypeInfo - Build the appropriate kind of type_info
2899/// for the given Objective-C object type.
2900void ItaniumRTTIBuilder::BuildObjCObjectTypeInfo(const ObjCObjectType *OT) {
2901 // Drop qualifiers.
2902 const Type *T = OT->getBaseType().getTypePtr();
2903 assert(isa<BuiltinType>(T) || isa<ObjCInterfaceType>(T));
2904
2905 // The builtin types are abi::__class_type_infos and don't require
2906 // extra fields.
2907 if (isa<BuiltinType>(T)) return;
2908
2909 ObjCInterfaceDecl *Class = cast<ObjCInterfaceType>(T)->getDecl();
2910 ObjCInterfaceDecl *Super = Class->getSuperClass();
2911
2912 // Root classes are also __class_type_info.
2913 if (!Super) return;
2914
2915 QualType SuperTy = CGM.getContext().getObjCInterfaceType(Super);
2916
2917 // Everything else is single inheritance.
2918 llvm::Constant *BaseTypeInfo =
2919 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(SuperTy);
2920 Fields.push_back(BaseTypeInfo);
2921}
2922
2923/// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
2924/// inheritance, according to the Itanium C++ ABI, 2.95p6b.
2925void ItaniumRTTIBuilder::BuildSIClassTypeInfo(const CXXRecordDecl *RD) {
2926 // Itanium C++ ABI 2.9.5p6b:
2927 // It adds to abi::__class_type_info a single member pointing to the
2928 // type_info structure for the base type,
2929 llvm::Constant *BaseTypeInfo =
2930 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(RD->bases_begin()->getType());
2931 Fields.push_back(BaseTypeInfo);
2932}
2933
2934namespace {
2935 /// SeenBases - Contains virtual and non-virtual bases seen when traversing
2936 /// a class hierarchy.
2937 struct SeenBases {
2938 llvm::SmallPtrSet<const CXXRecordDecl *, 16> NonVirtualBases;
2939 llvm::SmallPtrSet<const CXXRecordDecl *, 16> VirtualBases;
2940 };
2941}
2942
2943/// ComputeVMIClassTypeInfoFlags - Compute the value of the flags member in
2944/// abi::__vmi_class_type_info.
2945///
2946static unsigned ComputeVMIClassTypeInfoFlags(const CXXBaseSpecifier *Base,
2947 SeenBases &Bases) {
2948
2949 unsigned Flags = 0;
2950
2951 const CXXRecordDecl *BaseDecl =
2952 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2953
2954 if (Base->isVirtual()) {
2955 // Mark the virtual base as seen.
David Blaikie82e95a32014-11-19 07:49:47 +00002956 if (!Bases.VirtualBases.insert(BaseDecl).second) {
David Majnemere2cb8d12014-07-07 06:20:47 +00002957 // If this virtual base has been seen before, then the class is diamond
2958 // shaped.
2959 Flags |= ItaniumRTTIBuilder::VMI_DiamondShaped;
2960 } else {
2961 if (Bases.NonVirtualBases.count(BaseDecl))
2962 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
2963 }
2964 } else {
2965 // Mark the non-virtual base as seen.
David Blaikie82e95a32014-11-19 07:49:47 +00002966 if (!Bases.NonVirtualBases.insert(BaseDecl).second) {
David Majnemere2cb8d12014-07-07 06:20:47 +00002967 // If this non-virtual base has been seen before, then the class has non-
2968 // diamond shaped repeated inheritance.
2969 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
2970 } else {
2971 if (Bases.VirtualBases.count(BaseDecl))
2972 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
2973 }
2974 }
2975
2976 // Walk all bases.
2977 for (const auto &I : BaseDecl->bases())
2978 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
2979
2980 return Flags;
2981}
2982
2983static unsigned ComputeVMIClassTypeInfoFlags(const CXXRecordDecl *RD) {
2984 unsigned Flags = 0;
2985 SeenBases Bases;
2986
2987 // Walk all bases.
2988 for (const auto &I : RD->bases())
2989 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
2990
2991 return Flags;
2992}
2993
2994/// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
2995/// classes with bases that do not satisfy the abi::__si_class_type_info
2996/// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
2997void ItaniumRTTIBuilder::BuildVMIClassTypeInfo(const CXXRecordDecl *RD) {
2998 llvm::Type *UnsignedIntLTy =
2999 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3000
3001 // Itanium C++ ABI 2.9.5p6c:
3002 // __flags is a word with flags describing details about the class
3003 // structure, which may be referenced by using the __flags_masks
3004 // enumeration. These flags refer to both direct and indirect bases.
3005 unsigned Flags = ComputeVMIClassTypeInfoFlags(RD);
3006 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3007
3008 // Itanium C++ ABI 2.9.5p6c:
3009 // __base_count is a word with the number of direct proper base class
3010 // descriptions that follow.
3011 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, RD->getNumBases()));
3012
3013 if (!RD->getNumBases())
3014 return;
3015
3016 llvm::Type *LongLTy =
3017 CGM.getTypes().ConvertType(CGM.getContext().LongTy);
3018
3019 // Now add the base class descriptions.
3020
3021 // Itanium C++ ABI 2.9.5p6c:
3022 // __base_info[] is an array of base class descriptions -- one for every
3023 // direct proper base. Each description is of the type:
3024 //
3025 // struct abi::__base_class_type_info {
3026 // public:
3027 // const __class_type_info *__base_type;
3028 // long __offset_flags;
3029 //
3030 // enum __offset_flags_masks {
3031 // __virtual_mask = 0x1,
3032 // __public_mask = 0x2,
3033 // __offset_shift = 8
3034 // };
3035 // };
3036 for (const auto &Base : RD->bases()) {
3037 // The __base_type member points to the RTTI for the base type.
3038 Fields.push_back(ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(Base.getType()));
3039
3040 const CXXRecordDecl *BaseDecl =
3041 cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
3042
3043 int64_t OffsetFlags = 0;
3044
3045 // All but the lower 8 bits of __offset_flags are a signed offset.
3046 // For a non-virtual base, this is the offset in the object of the base
3047 // subobject. For a virtual base, this is the offset in the virtual table of
3048 // the virtual base offset for the virtual base referenced (negative).
3049 CharUnits Offset;
3050 if (Base.isVirtual())
3051 Offset =
3052 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(RD, BaseDecl);
3053 else {
3054 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
3055 Offset = Layout.getBaseClassOffset(BaseDecl);
3056 };
3057
3058 OffsetFlags = uint64_t(Offset.getQuantity()) << 8;
3059
3060 // The low-order byte of __offset_flags contains flags, as given by the
3061 // masks from the enumeration __offset_flags_masks.
3062 if (Base.isVirtual())
3063 OffsetFlags |= BCTI_Virtual;
3064 if (Base.getAccessSpecifier() == AS_public)
3065 OffsetFlags |= BCTI_Public;
3066
3067 Fields.push_back(llvm::ConstantInt::get(LongLTy, OffsetFlags));
3068 }
3069}
3070
3071/// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct,
3072/// used for pointer types.
3073void ItaniumRTTIBuilder::BuildPointerTypeInfo(QualType PointeeTy) {
3074 Qualifiers Quals;
3075 QualType UnqualifiedPointeeTy =
3076 CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals);
3077
3078 // Itanium C++ ABI 2.9.5p7:
3079 // __flags is a flag word describing the cv-qualification and other
3080 // attributes of the type pointed to
3081 unsigned Flags = ComputeQualifierFlags(Quals);
3082
3083 // Itanium C++ ABI 2.9.5p7:
3084 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
3085 // incomplete class type, the incomplete target type flag is set.
3086 if (ContainsIncompleteClassType(UnqualifiedPointeeTy))
3087 Flags |= PTI_Incomplete;
3088
3089 llvm::Type *UnsignedIntLTy =
3090 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3091 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3092
3093 // Itanium C++ ABI 2.9.5p7:
3094 // __pointee is a pointer to the std::type_info derivation for the
3095 // unqualified type being pointed to.
3096 llvm::Constant *PointeeTypeInfo =
3097 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(UnqualifiedPointeeTy);
3098 Fields.push_back(PointeeTypeInfo);
3099}
3100
3101/// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
3102/// struct, used for member pointer types.
3103void
3104ItaniumRTTIBuilder::BuildPointerToMemberTypeInfo(const MemberPointerType *Ty) {
3105 QualType PointeeTy = Ty->getPointeeType();
3106
3107 Qualifiers Quals;
3108 QualType UnqualifiedPointeeTy =
3109 CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals);
3110
3111 // Itanium C++ ABI 2.9.5p7:
3112 // __flags is a flag word describing the cv-qualification and other
3113 // attributes of the type pointed to.
3114 unsigned Flags = ComputeQualifierFlags(Quals);
3115
3116 const RecordType *ClassType = cast<RecordType>(Ty->getClass());
3117
3118 // Itanium C++ ABI 2.9.5p7:
3119 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
3120 // incomplete class type, the incomplete target type flag is set.
3121 if (ContainsIncompleteClassType(UnqualifiedPointeeTy))
3122 Flags |= PTI_Incomplete;
3123
3124 if (IsIncompleteClassType(ClassType))
3125 Flags |= PTI_ContainingClassIncomplete;
3126
3127 llvm::Type *UnsignedIntLTy =
3128 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3129 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3130
3131 // Itanium C++ ABI 2.9.5p7:
3132 // __pointee is a pointer to the std::type_info derivation for the
3133 // unqualified type being pointed to.
3134 llvm::Constant *PointeeTypeInfo =
3135 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(UnqualifiedPointeeTy);
3136 Fields.push_back(PointeeTypeInfo);
3137
3138 // Itanium C++ ABI 2.9.5p9:
3139 // __context is a pointer to an abi::__class_type_info corresponding to the
3140 // class type containing the member pointed to
3141 // (e.g., the "A" in "int A::*").
3142 Fields.push_back(
3143 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(QualType(ClassType, 0)));
3144}
3145
David Majnemer443250f2015-03-17 20:35:00 +00003146llvm::Constant *ItaniumCXXABI::getAddrOfRTTIDescriptor(QualType Ty) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003147 return ItaniumRTTIBuilder(*this).BuildTypeInfo(Ty);
3148}
3149
3150void ItaniumCXXABI::EmitFundamentalRTTIDescriptor(QualType Type) {
3151 QualType PointerType = getContext().getPointerType(Type);
3152 QualType PointerTypeConst = getContext().getPointerType(Type.withConst());
3153 ItaniumRTTIBuilder(*this).BuildTypeInfo(Type, true);
3154 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerType, true);
3155 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerTypeConst, true);
3156}
3157
3158void ItaniumCXXABI::EmitFundamentalRTTIDescriptors() {
3159 QualType FundamentalTypes[] = {
3160 getContext().VoidTy, getContext().NullPtrTy,
3161 getContext().BoolTy, getContext().WCharTy,
3162 getContext().CharTy, getContext().UnsignedCharTy,
3163 getContext().SignedCharTy, getContext().ShortTy,
3164 getContext().UnsignedShortTy, getContext().IntTy,
3165 getContext().UnsignedIntTy, getContext().LongTy,
3166 getContext().UnsignedLongTy, getContext().LongLongTy,
3167 getContext().UnsignedLongLongTy, getContext().HalfTy,
3168 getContext().FloatTy, getContext().DoubleTy,
3169 getContext().LongDoubleTy, getContext().Char16Ty,
3170 getContext().Char32Ty,
3171 };
3172 for (const QualType &FundamentalType : FundamentalTypes)
3173 EmitFundamentalRTTIDescriptor(FundamentalType);
3174}
3175
3176/// What sort of uniqueness rules should we use for the RTTI for the
3177/// given type?
3178ItaniumCXXABI::RTTIUniquenessKind ItaniumCXXABI::classifyRTTIUniqueness(
3179 QualType CanTy, llvm::GlobalValue::LinkageTypes Linkage) const {
3180 if (shouldRTTIBeUnique())
3181 return RUK_Unique;
3182
3183 // It's only necessary for linkonce_odr or weak_odr linkage.
3184 if (Linkage != llvm::GlobalValue::LinkOnceODRLinkage &&
3185 Linkage != llvm::GlobalValue::WeakODRLinkage)
3186 return RUK_Unique;
3187
3188 // It's only necessary with default visibility.
3189 if (CanTy->getVisibility() != DefaultVisibility)
3190 return RUK_Unique;
3191
3192 // If we're not required to publish this symbol, hide it.
3193 if (Linkage == llvm::GlobalValue::LinkOnceODRLinkage)
3194 return RUK_NonUniqueHidden;
3195
3196 // If we're required to publish this symbol, as we might be under an
3197 // explicit instantiation, leave it with default visibility but
3198 // enable string-comparisons.
3199 assert(Linkage == llvm::GlobalValue::WeakODRLinkage);
3200 return RUK_NonUniqueVisible;
3201}
Rafael Espindola91f68b42014-09-15 19:20:10 +00003202
Rafael Espindola1e4df922014-09-16 15:18:21 +00003203// Find out how to codegen the complete destructor and constructor
3204namespace {
3205enum class StructorCodegen { Emit, RAUW, Alias, COMDAT };
3206}
3207static StructorCodegen getCodegenToUse(CodeGenModule &CGM,
3208 const CXXMethodDecl *MD) {
3209 if (!CGM.getCodeGenOpts().CXXCtorDtorAliases)
3210 return StructorCodegen::Emit;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003211
Rafael Espindola1e4df922014-09-16 15:18:21 +00003212 // The complete and base structors are not equivalent if there are any virtual
3213 // bases, so emit separate functions.
3214 if (MD->getParent()->getNumVBases())
3215 return StructorCodegen::Emit;
3216
3217 GlobalDecl AliasDecl;
3218 if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) {
3219 AliasDecl = GlobalDecl(DD, Dtor_Complete);
3220 } else {
3221 const auto *CD = cast<CXXConstructorDecl>(MD);
3222 AliasDecl = GlobalDecl(CD, Ctor_Complete);
3223 }
3224 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3225
3226 if (llvm::GlobalValue::isDiscardableIfUnused(Linkage))
3227 return StructorCodegen::RAUW;
3228
3229 // FIXME: Should we allow available_externally aliases?
3230 if (!llvm::GlobalAlias::isValidLinkage(Linkage))
3231 return StructorCodegen::RAUW;
3232
Rafael Espindola0806f982014-09-16 20:19:43 +00003233 if (llvm::GlobalValue::isWeakForLinker(Linkage)) {
3234 // Only ELF supports COMDATs with arbitrary names (C5/D5).
3235 if (CGM.getTarget().getTriple().isOSBinFormatELF())
3236 return StructorCodegen::COMDAT;
3237 return StructorCodegen::Emit;
3238 }
Rafael Espindola1e4df922014-09-16 15:18:21 +00003239
3240 return StructorCodegen::Alias;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003241}
3242
Rafael Espindola1e4df922014-09-16 15:18:21 +00003243static void emitConstructorDestructorAlias(CodeGenModule &CGM,
3244 GlobalDecl AliasDecl,
3245 GlobalDecl TargetDecl) {
3246 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3247
3248 StringRef MangledName = CGM.getMangledName(AliasDecl);
3249 llvm::GlobalValue *Entry = CGM.GetGlobalValue(MangledName);
3250 if (Entry && !Entry->isDeclaration())
3251 return;
3252
3253 auto *Aliasee = cast<llvm::GlobalValue>(CGM.GetAddrOfGlobal(TargetDecl));
3254 llvm::PointerType *AliasType = Aliasee->getType();
3255
3256 // Create the alias with no name.
David Blaikie881b2342015-04-29 21:22:47 +00003257 auto *Alias = llvm::GlobalAlias::create(AliasType, Linkage, "", Aliasee,
3258 &CGM.getModule());
Rafael Espindola1e4df922014-09-16 15:18:21 +00003259
3260 // Switch any previous uses to the alias.
3261 if (Entry) {
3262 assert(Entry->getType() == AliasType &&
3263 "declaration exists with different type");
3264 Alias->takeName(Entry);
3265 Entry->replaceAllUsesWith(Alias);
3266 Entry->eraseFromParent();
3267 } else {
3268 Alias->setName(MangledName);
3269 }
3270
3271 // Finally, set up the alias with its proper name and attributes.
Dario Domiziolic4fb8ca72014-09-19 22:06:24 +00003272 CGM.setAliasAttributes(cast<NamedDecl>(AliasDecl.getDecl()), Alias);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003273}
3274
3275void ItaniumCXXABI::emitCXXStructor(const CXXMethodDecl *MD,
3276 StructorType Type) {
3277 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
3278 const CXXDestructorDecl *DD = CD ? nullptr : cast<CXXDestructorDecl>(MD);
3279
3280 StructorCodegen CGType = getCodegenToUse(CGM, MD);
3281
3282 if (Type == StructorType::Complete) {
3283 GlobalDecl CompleteDecl;
3284 GlobalDecl BaseDecl;
3285 if (CD) {
3286 CompleteDecl = GlobalDecl(CD, Ctor_Complete);
3287 BaseDecl = GlobalDecl(CD, Ctor_Base);
3288 } else {
3289 CompleteDecl = GlobalDecl(DD, Dtor_Complete);
3290 BaseDecl = GlobalDecl(DD, Dtor_Base);
3291 }
3292
3293 if (CGType == StructorCodegen::Alias || CGType == StructorCodegen::COMDAT) {
3294 emitConstructorDestructorAlias(CGM, CompleteDecl, BaseDecl);
3295 return;
3296 }
3297
3298 if (CGType == StructorCodegen::RAUW) {
3299 StringRef MangledName = CGM.getMangledName(CompleteDecl);
3300 auto *Aliasee = cast<llvm::GlobalValue>(CGM.GetAddrOfGlobal(BaseDecl));
3301 CGM.addReplacement(MangledName, Aliasee);
3302 return;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003303 }
3304 }
3305
3306 // The base destructor is equivalent to the base destructor of its
3307 // base class if there is exactly one non-virtual base class with a
3308 // non-trivial destructor, there are no fields with a non-trivial
3309 // destructor, and the body of the destructor is trivial.
Rafael Espindola1e4df922014-09-16 15:18:21 +00003310 if (DD && Type == StructorType::Base && CGType != StructorCodegen::COMDAT &&
3311 !CGM.TryEmitBaseDestructorAsAlias(DD))
Rafael Espindola91f68b42014-09-15 19:20:10 +00003312 return;
3313
Rafael Espindola1e4df922014-09-16 15:18:21 +00003314 llvm::Function *Fn = CGM.codegenCXXStructor(MD, Type);
Rafael Espindola91f68b42014-09-15 19:20:10 +00003315
Rafael Espindola1e4df922014-09-16 15:18:21 +00003316 if (CGType == StructorCodegen::COMDAT) {
3317 SmallString<256> Buffer;
3318 llvm::raw_svector_ostream Out(Buffer);
3319 if (DD)
3320 getMangleContext().mangleCXXDtorComdat(DD, Out);
3321 else
3322 getMangleContext().mangleCXXCtorComdat(CD, Out);
3323 llvm::Comdat *C = CGM.getModule().getOrInsertComdat(Out.str());
3324 Fn->setComdat(C);
Rafael Espindoladbee8a72015-01-15 21:36:08 +00003325 } else {
3326 CGM.maybeSetTrivialComdat(*MD, *Fn);
Rafael Espindola91f68b42014-09-15 19:20:10 +00003327 }
Rafael Espindola91f68b42014-09-15 19:20:10 +00003328}
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003329
3330static llvm::Constant *getBeginCatchFn(CodeGenModule &CGM) {
3331 // void *__cxa_begin_catch(void*);
3332 llvm::FunctionType *FTy = llvm::FunctionType::get(
3333 CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3334
3335 return CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
3336}
3337
3338static llvm::Constant *getEndCatchFn(CodeGenModule &CGM) {
3339 // void __cxa_end_catch();
3340 llvm::FunctionType *FTy =
3341 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
3342
3343 return CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
3344}
3345
3346static llvm::Constant *getGetExceptionPtrFn(CodeGenModule &CGM) {
3347 // void *__cxa_get_exception_ptr(void*);
3348 llvm::FunctionType *FTy = llvm::FunctionType::get(
3349 CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3350
3351 return CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
3352}
3353
3354namespace {
3355 /// A cleanup to call __cxa_end_catch. In many cases, the caught
3356 /// exception type lets us state definitively that the thrown exception
3357 /// type does not have a destructor. In particular:
3358 /// - Catch-alls tell us nothing, so we have to conservatively
3359 /// assume that the thrown exception might have a destructor.
3360 /// - Catches by reference behave according to their base types.
3361 /// - Catches of non-record types will only trigger for exceptions
3362 /// of non-record types, which never have destructors.
3363 /// - Catches of record types can trigger for arbitrary subclasses
3364 /// of the caught type, so we have to assume the actual thrown
3365 /// exception type might have a throwing destructor, even if the
3366 /// caught type's destructor is trivial or nothrow.
3367 struct CallEndCatch : EHScopeStack::Cleanup {
3368 CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
3369 bool MightThrow;
3370
3371 void Emit(CodeGenFunction &CGF, Flags flags) override {
3372 if (!MightThrow) {
3373 CGF.EmitNounwindRuntimeCall(getEndCatchFn(CGF.CGM));
3374 return;
3375 }
3376
3377 CGF.EmitRuntimeCallOrInvoke(getEndCatchFn(CGF.CGM));
3378 }
3379 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003380}
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003381
3382/// Emits a call to __cxa_begin_catch and enters a cleanup to call
3383/// __cxa_end_catch.
3384///
3385/// \param EndMightThrow - true if __cxa_end_catch might throw
3386static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
3387 llvm::Value *Exn,
3388 bool EndMightThrow) {
3389 llvm::CallInst *call =
3390 CGF.EmitNounwindRuntimeCall(getBeginCatchFn(CGF.CGM), Exn);
3391
3392 CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
3393
3394 return call;
3395}
3396
3397/// A "special initializer" callback for initializing a catch
3398/// parameter during catch initialization.
3399static void InitCatchParam(CodeGenFunction &CGF,
3400 const VarDecl &CatchParam,
3401 llvm::Value *ParamAddr,
3402 SourceLocation Loc) {
3403 // Load the exception from where the landing pad saved it.
3404 llvm::Value *Exn = CGF.getExceptionFromSlot();
3405
3406 CanQualType CatchType =
3407 CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
3408 llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
3409
3410 // If we're catching by reference, we can just cast the object
3411 // pointer to the appropriate pointer.
3412 if (isa<ReferenceType>(CatchType)) {
3413 QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
3414 bool EndCatchMightThrow = CaughtType->isRecordType();
3415
3416 // __cxa_begin_catch returns the adjusted object pointer.
3417 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
3418
3419 // We have no way to tell the personality function that we're
3420 // catching by reference, so if we're catching a pointer,
3421 // __cxa_begin_catch will actually return that pointer by value.
3422 if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
3423 QualType PointeeType = PT->getPointeeType();
3424
3425 // When catching by reference, generally we should just ignore
3426 // this by-value pointer and use the exception object instead.
3427 if (!PointeeType->isRecordType()) {
3428
3429 // Exn points to the struct _Unwind_Exception header, which
3430 // we have to skip past in order to reach the exception data.
3431 unsigned HeaderSize =
3432 CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
3433 AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
3434
3435 // However, if we're catching a pointer-to-record type that won't
3436 // work, because the personality function might have adjusted
3437 // the pointer. There's actually no way for us to fully satisfy
3438 // the language/ABI contract here: we can't use Exn because it
3439 // might have the wrong adjustment, but we can't use the by-value
3440 // pointer because it's off by a level of abstraction.
3441 //
3442 // The current solution is to dump the adjusted pointer into an
3443 // alloca, which breaks language semantics (because changing the
3444 // pointer doesn't change the exception) but at least works.
3445 // The better solution would be to filter out non-exact matches
3446 // and rethrow them, but this is tricky because the rethrow
3447 // really needs to be catchable by other sites at this landing
3448 // pad. The best solution is to fix the personality function.
3449 } else {
3450 // Pull the pointer for the reference type off.
3451 llvm::Type *PtrTy =
3452 cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
3453
3454 // Create the temporary and write the adjusted pointer into it.
3455 llvm::Value *ExnPtrTmp = CGF.CreateTempAlloca(PtrTy, "exn.byref.tmp");
3456 llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
3457 CGF.Builder.CreateStore(Casted, ExnPtrTmp);
3458
3459 // Bind the reference to the temporary.
3460 AdjustedExn = ExnPtrTmp;
3461 }
3462 }
3463
3464 llvm::Value *ExnCast =
3465 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
3466 CGF.Builder.CreateStore(ExnCast, ParamAddr);
3467 return;
3468 }
3469
3470 // Scalars and complexes.
3471 TypeEvaluationKind TEK = CGF.getEvaluationKind(CatchType);
3472 if (TEK != TEK_Aggregate) {
3473 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
3474
3475 // If the catch type is a pointer type, __cxa_begin_catch returns
3476 // the pointer by value.
3477 if (CatchType->hasPointerRepresentation()) {
3478 llvm::Value *CastExn =
3479 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
3480
3481 switch (CatchType.getQualifiers().getObjCLifetime()) {
3482 case Qualifiers::OCL_Strong:
3483 CastExn = CGF.EmitARCRetainNonBlock(CastExn);
3484 // fallthrough
3485
3486 case Qualifiers::OCL_None:
3487 case Qualifiers::OCL_ExplicitNone:
3488 case Qualifiers::OCL_Autoreleasing:
3489 CGF.Builder.CreateStore(CastExn, ParamAddr);
3490 return;
3491
3492 case Qualifiers::OCL_Weak:
3493 CGF.EmitARCInitWeak(ParamAddr, CastExn);
3494 return;
3495 }
3496 llvm_unreachable("bad ownership qualifier!");
3497 }
3498
3499 // Otherwise, it returns a pointer into the exception object.
3500
3501 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
3502 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
3503
3504 LValue srcLV = CGF.MakeNaturalAlignAddrLValue(Cast, CatchType);
3505 LValue destLV = CGF.MakeAddrLValue(ParamAddr, CatchType,
3506 CGF.getContext().getDeclAlign(&CatchParam));
3507 switch (TEK) {
3508 case TEK_Complex:
3509 CGF.EmitStoreOfComplex(CGF.EmitLoadOfComplex(srcLV, Loc), destLV,
3510 /*init*/ true);
3511 return;
3512 case TEK_Scalar: {
3513 llvm::Value *ExnLoad = CGF.EmitLoadOfScalar(srcLV, Loc);
3514 CGF.EmitStoreOfScalar(ExnLoad, destLV, /*init*/ true);
3515 return;
3516 }
3517 case TEK_Aggregate:
3518 llvm_unreachable("evaluation kind filtered out!");
3519 }
3520 llvm_unreachable("bad evaluation kind");
3521 }
3522
3523 assert(isa<RecordType>(CatchType) && "unexpected catch type!");
3524
3525 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
3526
3527 // Check for a copy expression. If we don't have a copy expression,
3528 // that means a trivial copy is okay.
3529 const Expr *copyExpr = CatchParam.getInit();
3530 if (!copyExpr) {
3531 llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true);
3532 llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
3533 CGF.EmitAggregateCopy(ParamAddr, adjustedExn, CatchType);
3534 return;
3535 }
3536
3537 // We have to call __cxa_get_exception_ptr to get the adjusted
3538 // pointer before copying.
3539 llvm::CallInst *rawAdjustedExn =
3540 CGF.EmitNounwindRuntimeCall(getGetExceptionPtrFn(CGF.CGM), Exn);
3541
3542 // Cast that to the appropriate type.
3543 llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
3544
3545 // The copy expression is defined in terms of an OpaqueValueExpr.
3546 // Find it and map it to the adjusted expression.
3547 CodeGenFunction::OpaqueValueMapping
3548 opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr),
3549 CGF.MakeAddrLValue(adjustedExn, CatchParam.getType()));
3550
3551 // Call the copy ctor in a terminate scope.
3552 CGF.EHStack.pushTerminate();
3553
3554 // Perform the copy construction.
3555 CharUnits Alignment = CGF.getContext().getDeclAlign(&CatchParam);
3556 CGF.EmitAggExpr(copyExpr,
3557 AggValueSlot::forAddr(ParamAddr, Alignment, Qualifiers(),
3558 AggValueSlot::IsNotDestructed,
3559 AggValueSlot::DoesNotNeedGCBarriers,
3560 AggValueSlot::IsNotAliased));
3561
3562 // Leave the terminate scope.
3563 CGF.EHStack.popTerminate();
3564
3565 // Undo the opaque value mapping.
3566 opaque.pop();
3567
3568 // Finally we can call __cxa_begin_catch.
3569 CallBeginCatch(CGF, Exn, true);
3570}
3571
3572/// Begins a catch statement by initializing the catch variable and
3573/// calling __cxa_begin_catch.
3574void ItaniumCXXABI::emitBeginCatch(CodeGenFunction &CGF,
3575 const CXXCatchStmt *S) {
3576 // We have to be very careful with the ordering of cleanups here:
3577 // C++ [except.throw]p4:
3578 // The destruction [of the exception temporary] occurs
3579 // immediately after the destruction of the object declared in
3580 // the exception-declaration in the handler.
3581 //
3582 // So the precise ordering is:
3583 // 1. Construct catch variable.
3584 // 2. __cxa_begin_catch
3585 // 3. Enter __cxa_end_catch cleanup
3586 // 4. Enter dtor cleanup
3587 //
3588 // We do this by using a slightly abnormal initialization process.
3589 // Delegation sequence:
3590 // - ExitCXXTryStmt opens a RunCleanupsScope
3591 // - EmitAutoVarAlloca creates the variable and debug info
3592 // - InitCatchParam initializes the variable from the exception
3593 // - CallBeginCatch calls __cxa_begin_catch
3594 // - CallBeginCatch enters the __cxa_end_catch cleanup
3595 // - EmitAutoVarCleanups enters the variable destructor cleanup
3596 // - EmitCXXTryStmt emits the code for the catch body
3597 // - EmitCXXTryStmt close the RunCleanupsScope
3598
3599 VarDecl *CatchParam = S->getExceptionDecl();
3600 if (!CatchParam) {
3601 llvm::Value *Exn = CGF.getExceptionFromSlot();
3602 CallBeginCatch(CGF, Exn, true);
3603 return;
3604 }
3605
3606 // Emit the local.
3607 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
3608 InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF), S->getLocStart());
3609 CGF.EmitAutoVarCleanups(var);
3610}
3611
3612/// Get or define the following function:
3613/// void @__clang_call_terminate(i8* %exn) nounwind noreturn
3614/// This code is used only in C++.
3615static llvm::Constant *getClangCallTerminateFn(CodeGenModule &CGM) {
3616 llvm::FunctionType *fnTy =
3617 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3618 llvm::Constant *fnRef =
3619 CGM.CreateRuntimeFunction(fnTy, "__clang_call_terminate");
3620
3621 llvm::Function *fn = dyn_cast<llvm::Function>(fnRef);
3622 if (fn && fn->empty()) {
3623 fn->setDoesNotThrow();
3624 fn->setDoesNotReturn();
3625
3626 // What we really want is to massively penalize inlining without
3627 // forbidding it completely. The difference between that and
3628 // 'noinline' is negligible.
3629 fn->addFnAttr(llvm::Attribute::NoInline);
3630
3631 // Allow this function to be shared across translation units, but
3632 // we don't want it to turn into an exported symbol.
3633 fn->setLinkage(llvm::Function::LinkOnceODRLinkage);
3634 fn->setVisibility(llvm::Function::HiddenVisibility);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00003635 if (CGM.supportsCOMDAT())
3636 fn->setComdat(CGM.getModule().getOrInsertComdat(fn->getName()));
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003637
3638 // Set up the function.
3639 llvm::BasicBlock *entry =
3640 llvm::BasicBlock::Create(CGM.getLLVMContext(), "", fn);
3641 CGBuilderTy builder(entry);
3642
3643 // Pull the exception pointer out of the parameter list.
3644 llvm::Value *exn = &*fn->arg_begin();
3645
3646 // Call __cxa_begin_catch(exn).
3647 llvm::CallInst *catchCall = builder.CreateCall(getBeginCatchFn(CGM), exn);
3648 catchCall->setDoesNotThrow();
3649 catchCall->setCallingConv(CGM.getRuntimeCC());
3650
3651 // Call std::terminate().
David Blaikie4ba525b2015-07-14 17:27:39 +00003652 llvm::CallInst *termCall = builder.CreateCall(CGM.getTerminateFn());
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003653 termCall->setDoesNotThrow();
3654 termCall->setDoesNotReturn();
3655 termCall->setCallingConv(CGM.getRuntimeCC());
3656
3657 // std::terminate cannot return.
3658 builder.CreateUnreachable();
3659 }
3660
3661 return fnRef;
3662}
3663
3664llvm::CallInst *
3665ItaniumCXXABI::emitTerminateForUnexpectedException(CodeGenFunction &CGF,
3666 llvm::Value *Exn) {
3667 // In C++, we want to call __cxa_begin_catch() before terminating.
3668 if (Exn) {
3669 assert(CGF.CGM.getLangOpts().CPlusPlus);
3670 return CGF.EmitNounwindRuntimeCall(getClangCallTerminateFn(CGF.CGM), Exn);
3671 }
3672 return CGF.EmitNounwindRuntimeCall(CGF.CGM.getTerminateFn());
3673}