blob: 3f5ad5db01b535c94905b2d6848576b19cb677a2 [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
Craig Topper4f12f102014-03-12 06:41:41 +000097 llvm::Constant *EmitMemberPointer(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
Hans Wennborgc94391d2014-06-06 20:04:01 +0000218 void setThunkLinkage(llvm::Function *Thunk, bool ForVTable, GlobalDecl GD,
219 bool ReturnAdjustment) override {
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000220 // Allow inlining of thunks by emitting them with available_externally
221 // linkage together with vtables when needed.
222 if (ForVTable)
223 Thunk->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
224 }
225
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000226 llvm::Value *performThisAdjustment(CodeGenFunction &CGF, llvm::Value *This,
Craig Topper4f12f102014-03-12 06:41:41 +0000227 const ThisAdjustment &TA) override;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000228
229 llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
Craig Topper4f12f102014-03-12 06:41:41 +0000230 const ReturnAdjustment &RA) override;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000231
David Majnemer196ac332014-09-11 23:05:02 +0000232 size_t getSrcArgforCopyCtor(const CXXConstructorDecl *,
233 FunctionArgList &Args) const override {
234 assert(!Args.empty() && "expected the arglist to not be empty!");
235 return Args.size() - 1;
236 }
237
Craig Topper4f12f102014-03-12 06:41:41 +0000238 StringRef GetPureVirtualCallName() override { return "__cxa_pure_virtual"; }
239 StringRef GetDeletedVirtualCallName() override
240 { return "__cxa_deleted_virtual"; }
Joao Matos2ce88ef2012-07-17 17:10:11 +0000241
Craig Topper4f12f102014-03-12 06:41:41 +0000242 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
John McCall8ed55a52010-09-02 09:58:18 +0000243 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
244 llvm::Value *NewPtr,
245 llvm::Value *NumElements,
John McCall284c48f2011-01-27 09:37:56 +0000246 const CXXNewExpr *expr,
Craig Topper4f12f102014-03-12 06:41:41 +0000247 QualType ElementType) override;
John McCallb91cd662012-05-01 05:23:51 +0000248 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
249 llvm::Value *allocPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000250 CharUnits cookieSize) override;
John McCall68ff0372010-09-08 01:44:27 +0000251
John McCallcdf7ef52010-11-06 09:44:32 +0000252 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
Craig Topper4f12f102014-03-12 06:41:41 +0000253 llvm::GlobalVariable *DeclPtr,
254 bool PerformInit) override;
Richard Smithdbf74ba2013-04-14 23:01:42 +0000255 void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
Craig Topper4f12f102014-03-12 06:41:41 +0000256 llvm::Constant *dtor, llvm::Constant *addr) override;
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000257
258 llvm::Function *getOrCreateThreadLocalWrapper(const VarDecl *VD,
Alexander Musmanf94c3182014-09-26 06:28:25 +0000259 llvm::Value *Val);
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000260 void EmitThreadLocalInitFuncs(
David Majnemerb3341ea2014-10-05 05:05:40 +0000261 CodeGenModule &CGM,
262 ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *>>
263 CXXThreadLocals,
264 ArrayRef<llvm::Function *> CXXThreadLocalInits,
265 ArrayRef<llvm::GlobalVariable *> CXXThreadLocalInitVars) override;
266
267 bool usesThreadWrapperFunction() const override { return true; }
Richard Smith0f383742014-03-26 22:48:22 +0000268 LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD,
269 QualType LValType) override;
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000270
Craig Topper4f12f102014-03-12 06:41:41 +0000271 bool NeedsVTTParameter(GlobalDecl GD) override;
David Majnemere2cb8d12014-07-07 06:20:47 +0000272
273 /**************************** RTTI Uniqueness ******************************/
274
275protected:
276 /// Returns true if the ABI requires RTTI type_info objects to be unique
277 /// across a program.
278 virtual bool shouldRTTIBeUnique() const { return true; }
279
280public:
281 /// What sort of unique-RTTI behavior should we use?
282 enum RTTIUniquenessKind {
283 /// We are guaranteeing, or need to guarantee, that the RTTI string
284 /// is unique.
285 RUK_Unique,
286
287 /// We are not guaranteeing uniqueness for the RTTI string, so we
288 /// can demote to hidden visibility but must use string comparisons.
289 RUK_NonUniqueHidden,
290
291 /// We are not guaranteeing uniqueness for the RTTI string, so we
292 /// have to use string comparisons, but we also have to emit it with
293 /// non-hidden visibility.
294 RUK_NonUniqueVisible
295 };
296
297 /// Return the required visibility status for the given type and linkage in
298 /// the current ABI.
299 RTTIUniquenessKind
300 classifyRTTIUniqueness(QualType CanTy,
301 llvm::GlobalValue::LinkageTypes Linkage) const;
302 friend class ItaniumRTTIBuilder;
Rafael Espindola91f68b42014-09-15 19:20:10 +0000303
304 void emitCXXStructor(const CXXMethodDecl *MD, StructorType Type) override;
Charles Davis4e786dd2010-05-25 19:52:27 +0000305};
John McCall86353412010-08-21 22:46:04 +0000306
307class ARMCXXABI : public ItaniumCXXABI {
308public:
Mark Seabornedf0d382013-07-24 16:25:13 +0000309 ARMCXXABI(CodeGen::CodeGenModule &CGM) :
310 ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
311 /* UseARMGuardVarABI = */ true) {}
John McCall5d865c322010-08-31 07:33:07 +0000312
Craig Topper4f12f102014-03-12 06:41:41 +0000313 bool HasThisReturn(GlobalDecl GD) const override {
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000314 return (isa<CXXConstructorDecl>(GD.getDecl()) || (
315 isa<CXXDestructorDecl>(GD.getDecl()) &&
316 GD.getDtorType() != Dtor_Deleting));
317 }
John McCall5d865c322010-08-31 07:33:07 +0000318
Craig Topper4f12f102014-03-12 06:41:41 +0000319 void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV,
320 QualType ResTy) override;
John McCall5d865c322010-08-31 07:33:07 +0000321
Craig Topper4f12f102014-03-12 06:41:41 +0000322 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
John McCall8ed55a52010-09-02 09:58:18 +0000323 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
324 llvm::Value *NewPtr,
325 llvm::Value *NumElements,
John McCall284c48f2011-01-27 09:37:56 +0000326 const CXXNewExpr *expr,
Craig Topper4f12f102014-03-12 06:41:41 +0000327 QualType ElementType) override;
John McCallb91cd662012-05-01 05:23:51 +0000328 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, llvm::Value *allocPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000329 CharUnits cookieSize) override;
John McCall86353412010-08-21 22:46:04 +0000330};
Tim Northovera2ee4332014-03-29 15:09:45 +0000331
332class iOS64CXXABI : public ARMCXXABI {
333public:
334 iOS64CXXABI(CodeGen::CodeGenModule &CGM) : ARMCXXABI(CGM) {}
Tim Northover65f582f2014-03-30 17:32:48 +0000335
336 // ARM64 libraries are prepared for non-unique RTTI.
David Majnemere2cb8d12014-07-07 06:20:47 +0000337 bool shouldRTTIBeUnique() const override { return false; }
Tim Northovera2ee4332014-03-29 15:09:45 +0000338};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000339}
Charles Davis4e786dd2010-05-25 19:52:27 +0000340
Charles Davis53c59df2010-08-16 03:33:14 +0000341CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
John McCallc8e01702013-04-16 22:48:15 +0000342 switch (CGM.getTarget().getCXXABI().getKind()) {
John McCall57625922013-01-25 23:36:14 +0000343 // For IR-generation purposes, there's no significant difference
344 // between the ARM and iOS ABIs.
345 case TargetCXXABI::GenericARM:
346 case TargetCXXABI::iOS:
347 return new ARMCXXABI(CGM);
Charles Davis4e786dd2010-05-25 19:52:27 +0000348
Tim Northovera2ee4332014-03-29 15:09:45 +0000349 case TargetCXXABI::iOS64:
350 return new iOS64CXXABI(CGM);
351
Tim Northover9bb857a2013-01-31 12:13:10 +0000352 // Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't
353 // include the other 32-bit ARM oddities: constructor/destructor return values
354 // and array cookies.
355 case TargetCXXABI::GenericAArch64:
Mark Seabornedf0d382013-07-24 16:25:13 +0000356 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
357 /* UseARMGuardVarABI = */ true);
Tim Northover9bb857a2013-01-31 12:13:10 +0000358
Zoran Jovanovic26a12162015-02-18 15:21:35 +0000359 case TargetCXXABI::GenericMIPS:
360 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true);
361
John McCall57625922013-01-25 23:36:14 +0000362 case TargetCXXABI::GenericItanium:
Mark Seabornedf0d382013-07-24 16:25:13 +0000363 if (CGM.getContext().getTargetInfo().getTriple().getArch()
364 == llvm::Triple::le32) {
365 // For PNaCl, use ARM-style method pointers so that PNaCl code
366 // does not assume anything about the alignment of function
367 // pointers.
368 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
369 /* UseARMGuardVarABI = */ false);
370 }
John McCall57625922013-01-25 23:36:14 +0000371 return new ItaniumCXXABI(CGM);
372
373 case TargetCXXABI::Microsoft:
374 llvm_unreachable("Microsoft ABI is not Itanium-based");
375 }
376 llvm_unreachable("bad ABI kind");
John McCall86353412010-08-21 22:46:04 +0000377}
378
Chris Lattnera5f58b02011-07-09 17:41:47 +0000379llvm::Type *
John McCall7a9aac22010-08-23 01:21:21 +0000380ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
381 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000382 return CGM.PtrDiffTy;
Reid Kleckneree7cf842014-12-01 22:02:27 +0000383 return llvm::StructType::get(CGM.PtrDiffTy, CGM.PtrDiffTy, nullptr);
John McCall1c456c82010-08-22 06:43:33 +0000384}
385
John McCalld9c6c0b2010-08-22 00:59:17 +0000386/// In the Itanium and ARM ABIs, method pointers have the form:
387/// struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
388///
389/// In the Itanium ABI:
390/// - method pointers are virtual if (memptr.ptr & 1) is nonzero
391/// - the this-adjustment is (memptr.adj)
392/// - the virtual offset is (memptr.ptr - 1)
393///
394/// In the ARM ABI:
395/// - method pointers are virtual if (memptr.adj & 1) is nonzero
396/// - the this-adjustment is (memptr.adj >> 1)
397/// - the virtual offset is (memptr.ptr)
398/// ARM uses 'adj' for the virtual flag because Thumb functions
399/// may be only single-byte aligned.
400///
401/// If the member is virtual, the adjusted 'this' pointer points
402/// to a vtable pointer from which the virtual offset is applied.
403///
404/// If the member is non-virtual, memptr.ptr is the address of
405/// the function to call.
David Majnemer2b0d66d2014-02-20 23:22:07 +0000406llvm::Value *ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(
407 CodeGenFunction &CGF, const Expr *E, llvm::Value *&This,
408 llvm::Value *MemFnPtr, const MemberPointerType *MPT) {
John McCall475999d2010-08-22 00:05:51 +0000409 CGBuilderTy &Builder = CGF.Builder;
410
411 const FunctionProtoType *FPT =
412 MPT->getPointeeType()->getAs<FunctionProtoType>();
413 const CXXRecordDecl *RD =
414 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
415
Chris Lattner2192fe52011-07-18 04:24:23 +0000416 llvm::FunctionType *FTy =
John McCalla729c622012-02-17 03:33:10 +0000417 CGM.getTypes().GetFunctionType(
418 CGM.getTypes().arrangeCXXMethodType(RD, FPT));
John McCall475999d2010-08-22 00:05:51 +0000419
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000420 llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(CGM.PtrDiffTy, 1);
John McCall475999d2010-08-22 00:05:51 +0000421
John McCalld9c6c0b2010-08-22 00:59:17 +0000422 llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
423 llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
424 llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
425
John McCalla1dee5302010-08-22 10:59:02 +0000426 // Extract memptr.adj, which is in the second field.
427 llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
John McCalld9c6c0b2010-08-22 00:59:17 +0000428
429 // Compute the true adjustment.
430 llvm::Value *Adj = RawAdj;
Mark Seabornedf0d382013-07-24 16:25:13 +0000431 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000432 Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
John McCall475999d2010-08-22 00:05:51 +0000433
434 // Apply the adjustment and cast back to the original struct type
435 // for consistency.
John McCalld9c6c0b2010-08-22 00:59:17 +0000436 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
437 Ptr = Builder.CreateInBoundsGEP(Ptr, Adj);
438 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
John McCall475999d2010-08-22 00:05:51 +0000439
440 // Load the function pointer.
John McCalla1dee5302010-08-22 10:59:02 +0000441 llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
John McCall475999d2010-08-22 00:05:51 +0000442
443 // If the LSB in the function pointer is 1, the function pointer points to
444 // a virtual function.
John McCalld9c6c0b2010-08-22 00:59:17 +0000445 llvm::Value *IsVirtual;
Mark Seabornedf0d382013-07-24 16:25:13 +0000446 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000447 IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
448 else
449 IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
450 IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
John McCall475999d2010-08-22 00:05:51 +0000451 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
452
453 // In the virtual path, the adjustment left 'This' pointing to the
454 // vtable of the correct base subobject. The "function pointer" is an
John McCalld9c6c0b2010-08-22 00:59:17 +0000455 // offset within the vtable (+1 for the virtual flag on non-ARM).
John McCall475999d2010-08-22 00:05:51 +0000456 CGF.EmitBlock(FnVirtual);
457
458 // Cast the adjusted this to a pointer to vtable pointer and load.
Chris Lattner2192fe52011-07-18 04:24:23 +0000459 llvm::Type *VTableTy = Builder.getInt8PtrTy();
Richard Smith0fc7bdc2014-03-12 18:26:14 +0000460 llvm::Value *VTable = CGF.GetVTablePtr(This, VTableTy);
John McCall475999d2010-08-22 00:05:51 +0000461
462 // Apply the offset.
John McCalld9c6c0b2010-08-22 00:59:17 +0000463 llvm::Value *VTableOffset = FnAsInt;
Mark Seabornedf0d382013-07-24 16:25:13 +0000464 if (!UseARMMethodPtrABI)
465 VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
John McCalld9c6c0b2010-08-22 00:59:17 +0000466 VTable = Builder.CreateGEP(VTable, VTableOffset);
John McCall475999d2010-08-22 00:05:51 +0000467
468 // Load the virtual function to call.
469 VTable = Builder.CreateBitCast(VTable, FTy->getPointerTo()->getPointerTo());
John McCalld9c6c0b2010-08-22 00:59:17 +0000470 llvm::Value *VirtualFn = Builder.CreateLoad(VTable, "memptr.virtualfn");
John McCall475999d2010-08-22 00:05:51 +0000471 CGF.EmitBranch(FnEnd);
472
473 // In the non-virtual path, the function pointer is actually a
474 // function pointer.
475 CGF.EmitBlock(FnNonVirtual);
476 llvm::Value *NonVirtualFn =
John McCalld9c6c0b2010-08-22 00:59:17 +0000477 Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn");
John McCall475999d2010-08-22 00:05:51 +0000478
479 // We're done.
480 CGF.EmitBlock(FnEnd);
Jay Foad20c0f022011-03-30 11:28:58 +0000481 llvm::PHINode *Callee = Builder.CreatePHI(FTy->getPointerTo(), 2);
John McCall475999d2010-08-22 00:05:51 +0000482 Callee->addIncoming(VirtualFn, FnVirtual);
483 Callee->addIncoming(NonVirtualFn, FnNonVirtual);
484 return Callee;
485}
John McCalla8bbb822010-08-22 03:04:22 +0000486
John McCallc134eb52010-08-31 21:07:20 +0000487/// Compute an l-value by applying the given pointer-to-member to a
488/// base object.
David Majnemer2b0d66d2014-02-20 23:22:07 +0000489llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(
490 CodeGenFunction &CGF, const Expr *E, llvm::Value *Base, llvm::Value *MemPtr,
491 const MemberPointerType *MPT) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000492 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCallc134eb52010-08-31 21:07:20 +0000493
494 CGBuilderTy &Builder = CGF.Builder;
495
Micah Villmowea2fea22012-10-25 15:39:14 +0000496 unsigned AS = Base->getType()->getPointerAddressSpace();
John McCallc134eb52010-08-31 21:07:20 +0000497
498 // Cast to char*.
499 Base = Builder.CreateBitCast(Base, Builder.getInt8Ty()->getPointerTo(AS));
500
501 // Apply the offset, which we assume is non-null.
502 llvm::Value *Addr = Builder.CreateInBoundsGEP(Base, MemPtr, "memptr.offset");
503
504 // Cast the address to the appropriate pointer type, adopting the
505 // address space of the base pointer.
Chris Lattner2192fe52011-07-18 04:24:23 +0000506 llvm::Type *PType
Douglas Gregor04f36212010-09-02 17:38:50 +0000507 = CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
John McCallc134eb52010-08-31 21:07:20 +0000508 return Builder.CreateBitCast(Addr, PType);
509}
510
John McCallc62bb392012-02-15 01:22:51 +0000511/// Perform a bitcast, derived-to-base, or base-to-derived member pointer
512/// conversion.
513///
514/// Bitcast conversions are always a no-op under Itanium.
John McCall7a9aac22010-08-23 01:21:21 +0000515///
516/// Obligatory offset/adjustment diagram:
517/// <-- offset --> <-- adjustment -->
518/// |--------------------------|----------------------|--------------------|
519/// ^Derived address point ^Base address point ^Member address point
520///
521/// So when converting a base member pointer to a derived member pointer,
522/// we add the offset to the adjustment because the address point has
523/// decreased; and conversely, when converting a derived MP to a base MP
524/// we subtract the offset from the adjustment because the address point
525/// has increased.
526///
527/// The standard forbids (at compile time) conversion to and from
528/// virtual bases, which is why we don't have to consider them here.
529///
530/// The standard forbids (at run time) casting a derived MP to a base
531/// MP when the derived MP does not point to a member of the base.
532/// This is why -1 is a reasonable choice for null data member
533/// pointers.
John McCalla1dee5302010-08-22 10:59:02 +0000534llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000535ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
536 const CastExpr *E,
John McCallc62bb392012-02-15 01:22:51 +0000537 llvm::Value *src) {
John McCalle3027922010-08-25 11:45:40 +0000538 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
John McCallc62bb392012-02-15 01:22:51 +0000539 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
540 E->getCastKind() == CK_ReinterpretMemberPointer);
541
542 // Under Itanium, reinterprets don't require any additional processing.
543 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
544
545 // Use constant emission if we can.
546 if (isa<llvm::Constant>(src))
547 return EmitMemberPointerConversion(E, cast<llvm::Constant>(src));
548
549 llvm::Constant *adj = getMemberPointerAdjustment(E);
550 if (!adj) return src;
John McCalla8bbb822010-08-22 03:04:22 +0000551
552 CGBuilderTy &Builder = CGF.Builder;
John McCallc62bb392012-02-15 01:22:51 +0000553 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
John McCalla8bbb822010-08-22 03:04:22 +0000554
John McCallc62bb392012-02-15 01:22:51 +0000555 const MemberPointerType *destTy =
556 E->getType()->castAs<MemberPointerType>();
John McCall1c456c82010-08-22 06:43:33 +0000557
John McCall7a9aac22010-08-23 01:21:21 +0000558 // For member data pointers, this is just a matter of adding the
559 // offset if the source is non-null.
John McCallc62bb392012-02-15 01:22:51 +0000560 if (destTy->isMemberDataPointer()) {
561 llvm::Value *dst;
562 if (isDerivedToBase)
563 dst = Builder.CreateNSWSub(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000564 else
John McCallc62bb392012-02-15 01:22:51 +0000565 dst = Builder.CreateNSWAdd(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000566
567 // Null check.
John McCallc62bb392012-02-15 01:22:51 +0000568 llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType());
569 llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull");
570 return Builder.CreateSelect(isNull, src, dst);
John McCall7a9aac22010-08-23 01:21:21 +0000571 }
572
John McCalla1dee5302010-08-22 10:59:02 +0000573 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000574 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000575 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
576 offset <<= 1;
577 adj = llvm::ConstantInt::get(adj->getType(), offset);
John McCalla1dee5302010-08-22 10:59:02 +0000578 }
579
John McCallc62bb392012-02-15 01:22:51 +0000580 llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj");
581 llvm::Value *dstAdj;
582 if (isDerivedToBase)
583 dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000584 else
John McCallc62bb392012-02-15 01:22:51 +0000585 dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000586
John McCallc62bb392012-02-15 01:22:51 +0000587 return Builder.CreateInsertValue(src, dstAdj, 1);
588}
589
590llvm::Constant *
591ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E,
592 llvm::Constant *src) {
593 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
594 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
595 E->getCastKind() == CK_ReinterpretMemberPointer);
596
597 // Under Itanium, reinterprets don't require any additional processing.
598 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
599
600 // If the adjustment is trivial, we don't need to do anything.
601 llvm::Constant *adj = getMemberPointerAdjustment(E);
602 if (!adj) return src;
603
604 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
605
606 const MemberPointerType *destTy =
607 E->getType()->castAs<MemberPointerType>();
608
609 // For member data pointers, this is just a matter of adding the
610 // offset if the source is non-null.
611 if (destTy->isMemberDataPointer()) {
612 // null maps to null.
613 if (src->isAllOnesValue()) return src;
614
615 if (isDerivedToBase)
616 return llvm::ConstantExpr::getNSWSub(src, adj);
617 else
618 return llvm::ConstantExpr::getNSWAdd(src, adj);
619 }
620
621 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000622 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000623 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
624 offset <<= 1;
625 adj = llvm::ConstantInt::get(adj->getType(), offset);
626 }
627
628 llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1);
629 llvm::Constant *dstAdj;
630 if (isDerivedToBase)
631 dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj);
632 else
633 dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj);
634
635 return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1);
John McCalla8bbb822010-08-22 03:04:22 +0000636}
John McCall84fa5102010-08-22 04:16:24 +0000637
638llvm::Constant *
John McCall7a9aac22010-08-23 01:21:21 +0000639ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
John McCall7a9aac22010-08-23 01:21:21 +0000640 // Itanium C++ ABI 2.3:
641 // A NULL pointer is represented as -1.
642 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000643 return llvm::ConstantInt::get(CGM.PtrDiffTy, -1ULL, /*isSigned=*/true);
John McCalla1dee5302010-08-22 10:59:02 +0000644
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000645 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.PtrDiffTy, 0);
John McCalla1dee5302010-08-22 10:59:02 +0000646 llvm::Constant *Values[2] = { Zero, Zero };
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000647 return llvm::ConstantStruct::getAnon(Values);
John McCall84fa5102010-08-22 04:16:24 +0000648}
649
John McCallf3a88602011-02-03 08:15:49 +0000650llvm::Constant *
651ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
652 CharUnits offset) {
John McCall7a9aac22010-08-23 01:21:21 +0000653 // Itanium C++ ABI 2.3:
654 // A pointer to data member is an offset from the base address of
655 // the class object containing it, represented as a ptrdiff_t
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000656 return llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity());
John McCall7a9aac22010-08-23 01:21:21 +0000657}
658
John McCall2979fe02011-04-12 00:42:48 +0000659llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) {
Richard Smithdafff942012-01-14 04:30:29 +0000660 return BuildMemberPointer(MD, CharUnits::Zero());
661}
662
663llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD,
664 CharUnits ThisAdjustment) {
John McCalla1dee5302010-08-22 10:59:02 +0000665 assert(MD->isInstance() && "Member function must not be static!");
666 MD = MD->getCanonicalDecl();
667
668 CodeGenTypes &Types = CGM.getTypes();
John McCalla1dee5302010-08-22 10:59:02 +0000669
670 // Get the function pointer (or index if this is a virtual function).
671 llvm::Constant *MemPtr[2];
672 if (MD->isVirtual()) {
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000673 uint64_t Index = CGM.getItaniumVTableContext().getMethodVTableIndex(MD);
John McCalla1dee5302010-08-22 10:59:02 +0000674
Ken Dyckdf016282011-04-09 01:30:02 +0000675 const ASTContext &Context = getContext();
676 CharUnits PointerWidth =
Douglas Gregore8bbc122011-09-02 00:18:52 +0000677 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Ken Dyckdf016282011-04-09 01:30:02 +0000678 uint64_t VTableOffset = (Index * PointerWidth.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000679
Mark Seabornedf0d382013-07-24 16:25:13 +0000680 if (UseARMMethodPtrABI) {
John McCalla1dee5302010-08-22 10:59:02 +0000681 // ARM C++ ABI 3.2.1:
682 // This ABI specifies that adj contains twice the this
683 // adjustment, plus 1 if the member function is virtual. The
684 // least significant bit of adj then makes exactly the same
685 // discrimination as the least significant bit of ptr does for
686 // Itanium.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000687 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset);
688 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000689 2 * ThisAdjustment.getQuantity() + 1);
John McCalla1dee5302010-08-22 10:59:02 +0000690 } else {
691 // Itanium C++ ABI 2.3:
692 // For a virtual function, [the pointer field] is 1 plus the
693 // virtual table offset (in bytes) of the function,
694 // represented as a ptrdiff_t.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000695 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset + 1);
696 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000697 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000698 }
699 } else {
John McCall2979fe02011-04-12 00:42:48 +0000700 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
Chris Lattner2192fe52011-07-18 04:24:23 +0000701 llvm::Type *Ty;
John McCall2979fe02011-04-12 00:42:48 +0000702 // Check whether the function has a computable LLVM signature.
Chris Lattner8806e322011-07-10 00:18:59 +0000703 if (Types.isFuncTypeConvertible(FPT)) {
John McCall2979fe02011-04-12 00:42:48 +0000704 // The function has a computable LLVM signature; use the correct type.
John McCalla729c622012-02-17 03:33:10 +0000705 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
John McCalla1dee5302010-08-22 10:59:02 +0000706 } else {
John McCall2979fe02011-04-12 00:42:48 +0000707 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
708 // function type is incomplete.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000709 Ty = CGM.PtrDiffTy;
John McCalla1dee5302010-08-22 10:59:02 +0000710 }
John McCall2979fe02011-04-12 00:42:48 +0000711 llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty);
John McCalla1dee5302010-08-22 10:59:02 +0000712
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000713 MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, CGM.PtrDiffTy);
Mark Seabornedf0d382013-07-24 16:25:13 +0000714 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
715 (UseARMMethodPtrABI ? 2 : 1) *
Richard Smithdafff942012-01-14 04:30:29 +0000716 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000717 }
John McCall1c456c82010-08-22 06:43:33 +0000718
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000719 return llvm::ConstantStruct::getAnon(MemPtr);
John McCall1c456c82010-08-22 06:43:33 +0000720}
721
Richard Smithdafff942012-01-14 04:30:29 +0000722llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP,
723 QualType MPType) {
724 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
725 const ValueDecl *MPD = MP.getMemberPointerDecl();
726 if (!MPD)
727 return EmitNullMemberPointer(MPT);
728
Reid Kleckner452abac2013-05-09 21:01:17 +0000729 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
Richard Smithdafff942012-01-14 04:30:29 +0000730
731 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
732 return BuildMemberPointer(MD, ThisAdjustment);
733
734 CharUnits FieldOffset =
735 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
736 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
737}
738
John McCall131d97d2010-08-22 08:30:07 +0000739/// The comparison algorithm is pretty easy: the member pointers are
740/// the same if they're either bitwise identical *or* both null.
741///
742/// ARM is different here only because null-ness is more complicated.
743llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000744ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
745 llvm::Value *L,
746 llvm::Value *R,
747 const MemberPointerType *MPT,
748 bool Inequality) {
John McCall131d97d2010-08-22 08:30:07 +0000749 CGBuilderTy &Builder = CGF.Builder;
750
John McCall131d97d2010-08-22 08:30:07 +0000751 llvm::ICmpInst::Predicate Eq;
752 llvm::Instruction::BinaryOps And, Or;
753 if (Inequality) {
754 Eq = llvm::ICmpInst::ICMP_NE;
755 And = llvm::Instruction::Or;
756 Or = llvm::Instruction::And;
757 } else {
758 Eq = llvm::ICmpInst::ICMP_EQ;
759 And = llvm::Instruction::And;
760 Or = llvm::Instruction::Or;
761 }
762
John McCall7a9aac22010-08-23 01:21:21 +0000763 // Member data pointers are easy because there's a unique null
764 // value, so it just comes down to bitwise equality.
765 if (MPT->isMemberDataPointer())
766 return Builder.CreateICmp(Eq, L, R);
767
768 // For member function pointers, the tautologies are more complex.
769 // The Itanium tautology is:
John McCall61a14882010-08-23 06:56:36 +0000770 // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
John McCall7a9aac22010-08-23 01:21:21 +0000771 // The ARM tautology is:
John McCall61a14882010-08-23 06:56:36 +0000772 // (L == R) <==> (L.ptr == R.ptr &&
773 // (L.adj == R.adj ||
774 // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
John McCall7a9aac22010-08-23 01:21:21 +0000775 // The inequality tautologies have exactly the same structure, except
776 // applying De Morgan's laws.
777
778 llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
779 llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
780
John McCall131d97d2010-08-22 08:30:07 +0000781 // This condition tests whether L.ptr == R.ptr. This must always be
782 // true for equality to hold.
783 llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
784
785 // This condition, together with the assumption that L.ptr == R.ptr,
786 // tests whether the pointers are both null. ARM imposes an extra
787 // condition.
788 llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
789 llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
790
791 // This condition tests whether L.adj == R.adj. If this isn't
792 // true, the pointers are unequal unless they're both null.
John McCalla1dee5302010-08-22 10:59:02 +0000793 llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
794 llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000795 llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
796
797 // Null member function pointers on ARM clear the low bit of Adj,
798 // so the zero condition has to check that neither low bit is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000799 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000800 llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
801
802 // Compute (l.adj | r.adj) & 1 and test it against zero.
803 llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
804 llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
805 llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
806 "cmp.or.adj");
807 EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
808 }
809
810 // Tie together all our conditions.
811 llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
812 Result = Builder.CreateBinOp(And, PtrEq, Result,
813 Inequality ? "memptr.ne" : "memptr.eq");
814 return Result;
815}
816
817llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000818ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
819 llvm::Value *MemPtr,
820 const MemberPointerType *MPT) {
John McCall131d97d2010-08-22 08:30:07 +0000821 CGBuilderTy &Builder = CGF.Builder;
John McCall7a9aac22010-08-23 01:21:21 +0000822
823 /// For member data pointers, this is just a check against -1.
824 if (MPT->isMemberDataPointer()) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000825 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCall7a9aac22010-08-23 01:21:21 +0000826 llvm::Value *NegativeOne =
827 llvm::Constant::getAllOnesValue(MemPtr->getType());
828 return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
829 }
John McCall131d97d2010-08-22 08:30:07 +0000830
Daniel Dunbar914bc412011-04-19 23:10:47 +0000831 // In Itanium, a member function pointer is not null if 'ptr' is not null.
John McCalla1dee5302010-08-22 10:59:02 +0000832 llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
John McCall131d97d2010-08-22 08:30:07 +0000833
834 llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
835 llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
836
Daniel Dunbar914bc412011-04-19 23:10:47 +0000837 // On ARM, a member function pointer is also non-null if the low bit of 'adj'
838 // (the virtual bit) is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000839 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000840 llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
John McCalla1dee5302010-08-22 10:59:02 +0000841 llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000842 llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
Daniel Dunbar914bc412011-04-19 23:10:47 +0000843 llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero,
844 "memptr.isvirtual");
845 Result = Builder.CreateOr(Result, IsVirtual);
John McCall131d97d2010-08-22 08:30:07 +0000846 }
847
848 return Result;
849}
John McCall1c456c82010-08-22 06:43:33 +0000850
Reid Kleckner40ca9132014-05-13 22:05:45 +0000851bool ItaniumCXXABI::classifyReturnType(CGFunctionInfo &FI) const {
852 const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl();
853 if (!RD)
854 return false;
855
Reid Klecknerd355ca72014-05-15 01:26:32 +0000856 // Return indirectly if we have a non-trivial copy ctor or non-trivial dtor.
857 // FIXME: Use canCopyArgument() when it is fixed to handle lazily declared
858 // special members.
859 if (RD->hasNonTrivialDestructor() || RD->hasNonTrivialCopyConstructor()) {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000860 FI.getReturnInfo() = ABIArgInfo::getIndirect(0, /*ByVal=*/false);
861 return true;
862 }
Reid Kleckner40ca9132014-05-13 22:05:45 +0000863 return false;
864}
865
John McCall614dbdc2010-08-22 21:01:12 +0000866/// The Itanium ABI requires non-zero initialization only for data
867/// member pointers, for which '0' is a valid offset.
868bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
David Majnemer5fd33e02015-04-24 01:25:08 +0000869 return MPT->isMemberFunctionPointer();
John McCall84fa5102010-08-22 04:16:24 +0000870}
John McCall5d865c322010-08-31 07:33:07 +0000871
John McCall82fb8922012-09-25 10:10:39 +0000872/// The Itanium ABI always places an offset to the complete object
873/// at entry -2 in the vtable.
David Majnemer08681372014-11-01 07:37:17 +0000874void ItaniumCXXABI::emitVirtualObjectDelete(CodeGenFunction &CGF,
875 const CXXDeleteExpr *DE,
876 llvm::Value *Ptr,
877 QualType ElementType,
878 const CXXDestructorDecl *Dtor) {
879 bool UseGlobalDelete = DE->isGlobalDelete();
David Majnemer0c0b6d92014-10-31 20:09:12 +0000880 if (UseGlobalDelete) {
881 // Derive the complete-object pointer, which is what we need
882 // to pass to the deallocation function.
John McCall82fb8922012-09-25 10:10:39 +0000883
David Majnemer0c0b6d92014-10-31 20:09:12 +0000884 // Grab the vtable pointer as an intptr_t*.
885 llvm::Value *VTable = CGF.GetVTablePtr(Ptr, CGF.IntPtrTy->getPointerTo());
John McCall82fb8922012-09-25 10:10:39 +0000886
David Majnemer0c0b6d92014-10-31 20:09:12 +0000887 // Track back to entry -2 and pull out the offset there.
888 llvm::Value *OffsetPtr = CGF.Builder.CreateConstInBoundsGEP1_64(
889 VTable, -2, "complete-offset.ptr");
890 llvm::LoadInst *Offset = CGF.Builder.CreateLoad(OffsetPtr);
891 Offset->setAlignment(CGF.PointerAlignInBytes);
892
893 // Apply the offset.
894 llvm::Value *CompletePtr = CGF.Builder.CreateBitCast(Ptr, CGF.Int8PtrTy);
895 CompletePtr = CGF.Builder.CreateInBoundsGEP(CompletePtr, Offset);
896
897 // If we're supposed to call the global delete, make sure we do so
898 // even if the destructor throws.
David Majnemer08681372014-11-01 07:37:17 +0000899 CGF.pushCallObjectDeleteCleanup(DE->getOperatorDelete(), CompletePtr,
900 ElementType);
David Majnemer0c0b6d92014-10-31 20:09:12 +0000901 }
902
903 // FIXME: Provide a source location here even though there's no
904 // CXXMemberCallExpr for dtor call.
905 CXXDtorType DtorType = UseGlobalDelete ? Dtor_Complete : Dtor_Deleting;
906 EmitVirtualDestructorCall(CGF, Dtor, DtorType, Ptr, /*CE=*/nullptr);
907
908 if (UseGlobalDelete)
909 CGF.PopCleanupBlock();
John McCall82fb8922012-09-25 10:10:39 +0000910}
911
David Majnemer442d0a22014-11-25 07:20:20 +0000912void ItaniumCXXABI::emitRethrow(CodeGenFunction &CGF, bool isNoReturn) {
913 // void __cxa_rethrow();
914
915 llvm::FunctionType *FTy =
916 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
917
918 llvm::Constant *Fn = CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow");
919
920 if (isNoReturn)
921 CGF.EmitNoreturnRuntimeCallOrInvoke(Fn, None);
922 else
923 CGF.EmitRuntimeCallOrInvoke(Fn);
924}
925
David Majnemer7c237072015-03-05 00:46:22 +0000926static llvm::Constant *getAllocateExceptionFn(CodeGenModule &CGM) {
927 // void *__cxa_allocate_exception(size_t thrown_size);
928
929 llvm::FunctionType *FTy =
930 llvm::FunctionType::get(CGM.Int8PtrTy, CGM.SizeTy, /*IsVarArgs=*/false);
931
932 return CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
933}
934
935static llvm::Constant *getThrowFn(CodeGenModule &CGM) {
936 // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
937 // void (*dest) (void *));
938
939 llvm::Type *Args[3] = { CGM.Int8PtrTy, CGM.Int8PtrTy, CGM.Int8PtrTy };
940 llvm::FunctionType *FTy =
941 llvm::FunctionType::get(CGM.VoidTy, Args, /*IsVarArgs=*/false);
942
943 return CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
944}
945
946void ItaniumCXXABI::emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) {
947 QualType ThrowType = E->getSubExpr()->getType();
948 // Now allocate the exception object.
949 llvm::Type *SizeTy = CGF.ConvertType(getContext().getSizeType());
950 uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
951
952 llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(CGM);
953 llvm::CallInst *ExceptionPtr = CGF.EmitNounwindRuntimeCall(
954 AllocExceptionFn, llvm::ConstantInt::get(SizeTy, TypeSize), "exception");
955
956 CGF.EmitAnyExprToExn(E->getSubExpr(), ExceptionPtr);
957
958 // Now throw the exception.
959 llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType,
960 /*ForEH=*/true);
961
962 // The address of the destructor. If the exception type has a
963 // trivial destructor (or isn't a record), we just pass null.
964 llvm::Constant *Dtor = nullptr;
965 if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
966 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
967 if (!Record->hasTrivialDestructor()) {
968 CXXDestructorDecl *DtorD = Record->getDestructor();
969 Dtor = CGM.getAddrOfCXXStructor(DtorD, StructorType::Complete);
970 Dtor = llvm::ConstantExpr::getBitCast(Dtor, CGM.Int8PtrTy);
971 }
972 }
973 if (!Dtor) Dtor = llvm::Constant::getNullValue(CGM.Int8PtrTy);
974
975 llvm::Value *args[] = { ExceptionPtr, TypeInfo, Dtor };
976 CGF.EmitNoreturnRuntimeCallOrInvoke(getThrowFn(CGM), args);
977}
978
David Majnemer1162d252014-06-22 19:05:33 +0000979static llvm::Constant *getItaniumDynamicCastFn(CodeGenFunction &CGF) {
980 // void *__dynamic_cast(const void *sub,
981 // const abi::__class_type_info *src,
982 // const abi::__class_type_info *dst,
983 // std::ptrdiff_t src2dst_offset);
984
985 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
986 llvm::Type *PtrDiffTy =
987 CGF.ConvertType(CGF.getContext().getPointerDiffType());
988
989 llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
990
991 llvm::FunctionType *FTy = llvm::FunctionType::get(Int8PtrTy, Args, false);
992
993 // Mark the function as nounwind readonly.
994 llvm::Attribute::AttrKind FuncAttrs[] = { llvm::Attribute::NoUnwind,
995 llvm::Attribute::ReadOnly };
996 llvm::AttributeSet Attrs = llvm::AttributeSet::get(
997 CGF.getLLVMContext(), llvm::AttributeSet::FunctionIndex, FuncAttrs);
998
999 return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast", Attrs);
1000}
1001
1002static llvm::Constant *getBadCastFn(CodeGenFunction &CGF) {
1003 // void __cxa_bad_cast();
1004 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1005 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
1006}
1007
1008/// \brief Compute the src2dst_offset hint as described in the
1009/// Itanium C++ ABI [2.9.7]
1010static CharUnits computeOffsetHint(ASTContext &Context,
1011 const CXXRecordDecl *Src,
1012 const CXXRecordDecl *Dst) {
1013 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1014 /*DetectVirtual=*/false);
1015
1016 // If Dst is not derived from Src we can skip the whole computation below and
1017 // return that Src is not a public base of Dst. Record all inheritance paths.
1018 if (!Dst->isDerivedFrom(Src, Paths))
1019 return CharUnits::fromQuantity(-2ULL);
1020
1021 unsigned NumPublicPaths = 0;
1022 CharUnits Offset;
1023
1024 // Now walk all possible inheritance paths.
1025 for (CXXBasePaths::paths_iterator I = Paths.begin(), E = Paths.end(); I != E;
1026 ++I) {
1027 if (I->Access != AS_public) // Ignore non-public inheritance.
1028 continue;
1029
1030 ++NumPublicPaths;
1031
1032 for (CXXBasePath::iterator J = I->begin(), JE = I->end(); J != JE; ++J) {
1033 // If the path contains a virtual base class we can't give any hint.
1034 // -1: no hint.
1035 if (J->Base->isVirtual())
1036 return CharUnits::fromQuantity(-1ULL);
1037
1038 if (NumPublicPaths > 1) // Won't use offsets, skip computation.
1039 continue;
1040
1041 // Accumulate the base class offsets.
1042 const ASTRecordLayout &L = Context.getASTRecordLayout(J->Class);
1043 Offset += L.getBaseClassOffset(J->Base->getType()->getAsCXXRecordDecl());
1044 }
1045 }
1046
1047 // -2: Src is not a public base of Dst.
1048 if (NumPublicPaths == 0)
1049 return CharUnits::fromQuantity(-2ULL);
1050
1051 // -3: Src is a multiple public base type but never a virtual base type.
1052 if (NumPublicPaths > 1)
1053 return CharUnits::fromQuantity(-3ULL);
1054
1055 // Otherwise, the Src type is a unique public nonvirtual base type of Dst.
1056 // Return the offset of Src from the origin of Dst.
1057 return Offset;
1058}
1059
1060static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) {
1061 // void __cxa_bad_typeid();
1062 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1063
1064 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
1065}
1066
1067bool ItaniumCXXABI::shouldTypeidBeNullChecked(bool IsDeref,
1068 QualType SrcRecordTy) {
1069 return IsDeref;
1070}
1071
1072void ItaniumCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) {
1073 llvm::Value *Fn = getBadTypeidFn(CGF);
1074 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
1075 CGF.Builder.CreateUnreachable();
1076}
1077
1078llvm::Value *ItaniumCXXABI::EmitTypeid(CodeGenFunction &CGF,
1079 QualType SrcRecordTy,
1080 llvm::Value *ThisPtr,
1081 llvm::Type *StdTypeInfoPtrTy) {
1082 llvm::Value *Value =
1083 CGF.GetVTablePtr(ThisPtr, StdTypeInfoPtrTy->getPointerTo());
1084
1085 // Load the type info.
1086 Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL);
1087 return CGF.Builder.CreateLoad(Value);
1088}
1089
1090bool ItaniumCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
1091 QualType SrcRecordTy) {
1092 return SrcIsPtr;
1093}
1094
1095llvm::Value *ItaniumCXXABI::EmitDynamicCastCall(
1096 CodeGenFunction &CGF, llvm::Value *Value, QualType SrcRecordTy,
1097 QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) {
1098 llvm::Type *PtrDiffLTy =
1099 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1100 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1101
1102 llvm::Value *SrcRTTI =
1103 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
1104 llvm::Value *DestRTTI =
1105 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
1106
1107 // Compute the offset hint.
1108 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
1109 const CXXRecordDecl *DestDecl = DestRecordTy->getAsCXXRecordDecl();
1110 llvm::Value *OffsetHint = llvm::ConstantInt::get(
1111 PtrDiffLTy,
1112 computeOffsetHint(CGF.getContext(), SrcDecl, DestDecl).getQuantity());
1113
1114 // Emit the call to __dynamic_cast.
1115 Value = CGF.EmitCastToVoidPtr(Value);
1116
1117 llvm::Value *args[] = {Value, SrcRTTI, DestRTTI, OffsetHint};
1118 Value = CGF.EmitNounwindRuntimeCall(getItaniumDynamicCastFn(CGF), args);
1119 Value = CGF.Builder.CreateBitCast(Value, DestLTy);
1120
1121 /// C++ [expr.dynamic.cast]p9:
1122 /// A failed cast to reference type throws std::bad_cast
1123 if (DestTy->isReferenceType()) {
1124 llvm::BasicBlock *BadCastBlock =
1125 CGF.createBasicBlock("dynamic_cast.bad_cast");
1126
1127 llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
1128 CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
1129
1130 CGF.EmitBlock(BadCastBlock);
1131 EmitBadCastCall(CGF);
1132 }
1133
1134 return Value;
1135}
1136
1137llvm::Value *ItaniumCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF,
1138 llvm::Value *Value,
1139 QualType SrcRecordTy,
1140 QualType DestTy) {
1141 llvm::Type *PtrDiffLTy =
1142 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1143 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1144
1145 // Get the vtable pointer.
1146 llvm::Value *VTable = CGF.GetVTablePtr(Value, PtrDiffLTy->getPointerTo());
1147
1148 // Get the offset-to-top from the vtable.
1149 llvm::Value *OffsetToTop =
1150 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL);
1151 OffsetToTop = CGF.Builder.CreateLoad(OffsetToTop, "offset.to.top");
1152
1153 // Finally, add the offset to the pointer.
1154 Value = CGF.EmitCastToVoidPtr(Value);
1155 Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop);
1156
1157 return CGF.Builder.CreateBitCast(Value, DestLTy);
1158}
1159
1160bool ItaniumCXXABI::EmitBadCastCall(CodeGenFunction &CGF) {
1161 llvm::Value *Fn = getBadCastFn(CGF);
1162 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
1163 CGF.Builder.CreateUnreachable();
1164 return true;
1165}
1166
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001167llvm::Value *
1168ItaniumCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
1169 llvm::Value *This,
1170 const CXXRecordDecl *ClassDecl,
1171 const CXXRecordDecl *BaseClassDecl) {
1172 llvm::Value *VTablePtr = CGF.GetVTablePtr(This, CGM.Int8PtrTy);
1173 CharUnits VBaseOffsetOffset =
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001174 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(ClassDecl,
1175 BaseClassDecl);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001176
1177 llvm::Value *VBaseOffsetPtr =
1178 CGF.Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
1179 "vbase.offset.ptr");
1180 VBaseOffsetPtr = CGF.Builder.CreateBitCast(VBaseOffsetPtr,
1181 CGM.PtrDiffTy->getPointerTo());
1182
1183 llvm::Value *VBaseOffset =
1184 CGF.Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
1185
1186 return VBaseOffset;
1187}
1188
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001189void ItaniumCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
1190 // Just make sure we're in sync with TargetCXXABI.
1191 assert(CGM.getTarget().getCXXABI().hasConstructorVariants());
1192
Rafael Espindolac3cde362013-12-09 14:51:17 +00001193 // The constructor used for constructing this as a base class;
1194 // ignores virtual bases.
1195 CGM.EmitGlobal(GlobalDecl(D, Ctor_Base));
1196
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001197 // The constructor used for constructing this as a complete class;
Nico Weber4c2ffb22015-01-07 05:25:05 +00001198 // constructs the virtual bases, then calls the base constructor.
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001199 if (!D->getParent()->isAbstract()) {
1200 // We don't need to emit the complete ctor if the class is abstract.
1201 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
1202 }
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001203}
1204
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001205void
1206ItaniumCXXABI::buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
1207 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9bca9232010-09-02 10:25:57 +00001208 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001209
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001210 // All parameters are already in place except VTT, which goes after 'this'.
1211 // These are Clang types, so we don't need to worry about sret yet.
John McCall5d865c322010-08-31 07:33:07 +00001212
1213 // Check if we need to add a VTT parameter (which has type void **).
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001214 if (T == StructorType::Base && MD->getParent()->getNumVBases() != 0)
1215 ArgTys.insert(ArgTys.begin() + 1,
1216 Context.getPointerType(Context.VoidPtrTy));
John McCall5d865c322010-08-31 07:33:07 +00001217}
1218
Reid Klecknere7de47e2013-07-22 13:51:44 +00001219void ItaniumCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
Rafael Espindolac3cde362013-12-09 14:51:17 +00001220 // The destructor used for destructing this as a base class; ignores
1221 // virtual bases.
1222 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001223
1224 // The destructor used for destructing this as a most-derived class;
1225 // call the base destructor and then destructs any virtual bases.
1226 CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));
1227
Rafael Espindolac3cde362013-12-09 14:51:17 +00001228 // The destructor in a virtual table is always a 'deleting'
1229 // destructor, which calls the complete destructor and then uses the
1230 // appropriate operator delete.
1231 if (D->isVirtual())
1232 CGM.EmitGlobal(GlobalDecl(D, Dtor_Deleting));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001233}
1234
Reid Kleckner89077a12013-12-17 19:46:40 +00001235void ItaniumCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
1236 QualType &ResTy,
1237 FunctionArgList &Params) {
John McCall5d865c322010-08-31 07:33:07 +00001238 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
Reid Kleckner89077a12013-12-17 19:46:40 +00001239 assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
John McCall5d865c322010-08-31 07:33:07 +00001240
1241 // Check if we need a VTT parameter as well.
Peter Collingbourne66f82e62013-06-28 20:45:28 +00001242 if (NeedsVTTParameter(CGF.CurGD)) {
John McCall9bca9232010-09-02 10:25:57 +00001243 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001244
1245 // FIXME: avoid the fake decl
1246 QualType T = Context.getPointerType(Context.VoidPtrTy);
1247 ImplicitParamDecl *VTTDecl
Craig Topper8a13c412014-05-21 05:09:00 +00001248 = ImplicitParamDecl::Create(Context, nullptr, MD->getLocation(),
John McCall5d865c322010-08-31 07:33:07 +00001249 &Context.Idents.get("vtt"), T);
Reid Kleckner89077a12013-12-17 19:46:40 +00001250 Params.insert(Params.begin() + 1, VTTDecl);
Reid Kleckner2af6d732013-12-13 00:09:59 +00001251 getStructorImplicitParamDecl(CGF) = VTTDecl;
John McCall5d865c322010-08-31 07:33:07 +00001252 }
1253}
1254
John McCall5d865c322010-08-31 07:33:07 +00001255void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
1256 /// Initialize the 'this' slot.
1257 EmitThisParam(CGF);
1258
1259 /// Initialize the 'vtt' slot if needed.
Reid Kleckner2af6d732013-12-13 00:09:59 +00001260 if (getStructorImplicitParamDecl(CGF)) {
1261 getStructorImplicitParamValue(CGF) = CGF.Builder.CreateLoad(
1262 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), "vtt");
John McCall5d865c322010-08-31 07:33:07 +00001263 }
John McCall5d865c322010-08-31 07:33:07 +00001264
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001265 /// If this is a function that the ABI specifies returns 'this', initialize
1266 /// the return slot to 'this' at the start of the function.
1267 ///
1268 /// Unlike the setting of return types, this is done within the ABI
1269 /// implementation instead of by clients of CGCXXABI because:
1270 /// 1) getThisValue is currently protected
1271 /// 2) in theory, an ABI could implement 'this' returns some other way;
1272 /// HasThisReturn only specifies a contract, not the implementation
John McCall5d865c322010-08-31 07:33:07 +00001273 if (HasThisReturn(CGF.CurGD))
Eli Friedman9fbeba02012-02-11 02:57:39 +00001274 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
John McCall5d865c322010-08-31 07:33:07 +00001275}
1276
Reid Kleckner89077a12013-12-17 19:46:40 +00001277unsigned ItaniumCXXABI::addImplicitConstructorArgs(
1278 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
1279 bool ForVirtualBase, bool Delegating, CallArgList &Args) {
1280 if (!NeedsVTTParameter(GlobalDecl(D, Type)))
1281 return 0;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001282
Reid Kleckner89077a12013-12-17 19:46:40 +00001283 // Insert the implicit 'vtt' argument as the second argument.
1284 llvm::Value *VTT =
1285 CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase, Delegating);
1286 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1287 Args.insert(Args.begin() + 1,
1288 CallArg(RValue::get(VTT), VTTTy, /*needscopy=*/false));
1289 return 1; // Added one arg.
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001290}
1291
1292void ItaniumCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
1293 const CXXDestructorDecl *DD,
1294 CXXDtorType Type, bool ForVirtualBase,
1295 bool Delegating, llvm::Value *This) {
1296 GlobalDecl GD(DD, Type);
1297 llvm::Value *VTT = CGF.GetVTTParameter(GD, ForVirtualBase, Delegating);
1298 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1299
Craig Topper8a13c412014-05-21 05:09:00 +00001300 llvm::Value *Callee = nullptr;
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001301 if (getContext().getLangOpts().AppleKext)
1302 Callee = CGF.BuildAppleKextVirtualDestructorCall(DD, Type, DD->getParent());
1303
1304 if (!Callee)
Rafael Espindola1ac0ec82014-09-11 15:42:06 +00001305 Callee = CGM.getAddrOfCXXStructor(DD, getFromDtorType(Type));
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001306
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001307 CGF.EmitCXXMemberOrOperatorCall(DD, Callee, ReturnValueSlot(), This, VTT,
1308 VTTTy, nullptr);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001309}
1310
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001311void ItaniumCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
1312 const CXXRecordDecl *RD) {
1313 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, CharUnits());
1314 if (VTable->hasInitializer())
1315 return;
1316
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001317 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001318 const VTableLayout &VTLayout = VTContext.getVTableLayout(RD);
1319 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
David Majnemerd905da42014-07-01 20:30:31 +00001320 llvm::Constant *RTTI =
1321 CGM.GetAddrOfRTTIDescriptor(CGM.getContext().getTagDeclType(RD));
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001322
1323 // Create and set the initializer.
1324 llvm::Constant *Init = CGVT.CreateVTableInitializer(
1325 RD, VTLayout.vtable_component_begin(), VTLayout.getNumVTableComponents(),
David Majnemerd905da42014-07-01 20:30:31 +00001326 VTLayout.vtable_thunk_begin(), VTLayout.getNumVTableThunks(), RTTI);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001327 VTable->setInitializer(Init);
1328
1329 // Set the correct linkage.
1330 VTable->setLinkage(Linkage);
1331
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00001332 if (CGM.supportsCOMDAT() && VTable->isWeakForLinker())
1333 VTable->setComdat(CGM.getModule().getOrInsertComdat(VTable->getName()));
Rafael Espindolacb92c192015-01-15 23:18:01 +00001334
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001335 // Set the right visibility.
John McCall8f80a612014-02-08 00:41:16 +00001336 CGM.setGlobalVisibility(VTable, RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001337
Benjamin Kramer5d34a2b2014-09-10 12:50:59 +00001338 // Use pointer alignment for the vtable. Otherwise we would align them based
1339 // on the size of the initializer which doesn't make sense as only single
1340 // values are read.
1341 unsigned PAlign = CGM.getTarget().getPointerAlign(0);
1342 VTable->setAlignment(getContext().toCharUnitsFromBits(PAlign).getQuantity());
1343
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001344 // If this is the magic class __cxxabiv1::__fundamental_type_info,
1345 // we will emit the typeinfo for the fundamental types. This is the
1346 // same behaviour as GCC.
1347 const DeclContext *DC = RD->getDeclContext();
1348 if (RD->getIdentifier() &&
1349 RD->getIdentifier()->isStr("__fundamental_type_info") &&
1350 isa<NamespaceDecl>(DC) && cast<NamespaceDecl>(DC)->getIdentifier() &&
1351 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
1352 DC->getParent()->isTranslationUnit())
David Majnemere2cb8d12014-07-07 06:20:47 +00001353 EmitFundamentalRTTIDescriptors();
Peter Collingbournea4ccff32015-02-20 20:30:56 +00001354
1355 CGM.EmitVTableBitSetEntries(VTable, VTLayout);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001356}
1357
1358llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructor(
1359 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1360 const CXXRecordDecl *NearestVBase, bool &NeedsVirtualOffset) {
1361 bool NeedsVTTParam = CGM.getCXXABI().NeedsVTTParameter(CGF.CurGD);
1362 NeedsVirtualOffset = (NeedsVTTParam && NearestVBase);
1363
1364 llvm::Value *VTableAddressPoint;
1365 if (NeedsVTTParam && (Base.getBase()->getNumVBases() || NearestVBase)) {
1366 // Get the secondary vpointer index.
1367 uint64_t VirtualPointerIndex =
1368 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1369
1370 /// Load the VTT.
1371 llvm::Value *VTT = CGF.LoadCXXVTT();
1372 if (VirtualPointerIndex)
1373 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1374
1375 // And load the address point from the VTT.
1376 VTableAddressPoint = CGF.Builder.CreateLoad(VTT);
1377 } else {
1378 llvm::Constant *VTable =
1379 CGM.getCXXABI().getAddrOfVTable(VTableClass, CharUnits());
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001380 uint64_t AddressPoint = CGM.getItaniumVTableContext()
1381 .getVTableLayout(VTableClass)
1382 .getAddressPoint(Base);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001383 VTableAddressPoint =
1384 CGF.Builder.CreateConstInBoundsGEP2_64(VTable, 0, AddressPoint);
1385 }
1386
1387 return VTableAddressPoint;
1388}
1389
1390llvm::Constant *ItaniumCXXABI::getVTableAddressPointForConstExpr(
1391 BaseSubobject Base, const CXXRecordDecl *VTableClass) {
David Blaikiee3b172a2015-04-02 18:55:21 +00001392 auto *VTable = getAddrOfVTable(VTableClass, CharUnits());
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001393
1394 // Find the appropriate vtable within the vtable group.
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001395 uint64_t AddressPoint = CGM.getItaniumVTableContext()
1396 .getVTableLayout(VTableClass)
1397 .getAddressPoint(Base);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001398 llvm::Value *Indices[] = {
1399 llvm::ConstantInt::get(CGM.Int64Ty, 0),
1400 llvm::ConstantInt::get(CGM.Int64Ty, AddressPoint)
1401 };
1402
David Blaikiee3b172a2015-04-02 18:55:21 +00001403 return llvm::ConstantExpr::getInBoundsGetElementPtr(VTable->getValueType(),
1404 VTable, Indices);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001405}
1406
1407llvm::GlobalVariable *ItaniumCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
1408 CharUnits VPtrOffset) {
1409 assert(VPtrOffset.isZero() && "Itanium ABI only supports zero vptr offsets");
1410
1411 llvm::GlobalVariable *&VTable = VTables[RD];
1412 if (VTable)
1413 return VTable;
1414
1415 // Queue up this v-table for possible deferred emission.
1416 CGM.addDeferredVTable(RD);
1417
1418 SmallString<256> OutName;
1419 llvm::raw_svector_ostream Out(OutName);
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00001420 getMangleContext().mangleCXXVTable(RD, Out);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001421 Out.flush();
1422 StringRef Name = OutName.str();
1423
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001424 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001425 llvm::ArrayType *ArrayType = llvm::ArrayType::get(
1426 CGM.Int8PtrTy, VTContext.getVTableLayout(RD).getNumVTableComponents());
1427
1428 VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
1429 Name, ArrayType, llvm::GlobalValue::ExternalLinkage);
1430 VTable->setUnnamedAddr(true);
Hans Wennborgda24e9c2014-06-02 23:13:03 +00001431
1432 if (RD->hasAttr<DLLImportAttr>())
1433 VTable->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1434 else if (RD->hasAttr<DLLExportAttr>())
1435 VTable->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1436
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001437 return VTable;
1438}
1439
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001440llvm::Value *ItaniumCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
1441 GlobalDecl GD,
1442 llvm::Value *This,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00001443 llvm::Type *Ty,
1444 SourceLocation Loc) {
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001445 GD = GD.getCanonicalDecl();
1446 Ty = Ty->getPointerTo()->getPointerTo();
1447 llvm::Value *VTable = CGF.GetVTablePtr(This, Ty);
1448
Peter Collingbourne1a7488a2015-04-02 00:23:30 +00001449 if (CGF.SanOpts.has(SanitizerKind::CFIVCall))
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00001450 CGF.EmitVTablePtrCheckForCall(cast<CXXMethodDecl>(GD.getDecl()), VTable,
1451 CodeGenFunction::CFITCK_VCall, Loc);
Peter Collingbournea4ccff32015-02-20 20:30:56 +00001452
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001453 uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001454 llvm::Value *VFuncPtr =
1455 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfn");
1456 return CGF.Builder.CreateLoad(VFuncPtr);
1457}
1458
David Majnemer0c0b6d92014-10-31 20:09:12 +00001459llvm::Value *ItaniumCXXABI::EmitVirtualDestructorCall(
1460 CodeGenFunction &CGF, const CXXDestructorDecl *Dtor, CXXDtorType DtorType,
1461 llvm::Value *This, const CXXMemberCallExpr *CE) {
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001462 assert(CE == nullptr || CE->arg_begin() == CE->arg_end());
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001463 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
1464
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001465 const CGFunctionInfo *FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
1466 Dtor, getFromDtorType(DtorType));
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001467 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001468 llvm::Value *Callee =
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00001469 getVirtualFunctionPointer(CGF, GlobalDecl(Dtor, DtorType), This, Ty,
1470 CE ? CE->getLocStart() : SourceLocation());
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001471
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001472 CGF.EmitCXXMemberOrOperatorCall(Dtor, Callee, ReturnValueSlot(), This,
1473 /*ImplicitParam=*/nullptr, QualType(), CE);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001474 return nullptr;
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001475}
1476
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001477void ItaniumCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
Reid Kleckner7810af02013-06-19 15:20:38 +00001478 CodeGenVTables &VTables = CGM.getVTables();
1479 llvm::GlobalVariable *VTT = VTables.GetAddrOfVTT(RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001480 VTables.EmitVTTDefinition(VTT, CGM.getVTableLinkage(RD), RD);
Reid Kleckner7810af02013-06-19 15:20:38 +00001481}
1482
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001483static llvm::Value *performTypeAdjustment(CodeGenFunction &CGF,
1484 llvm::Value *Ptr,
1485 int64_t NonVirtualAdjustment,
1486 int64_t VirtualAdjustment,
1487 bool IsReturnAdjustment) {
1488 if (!NonVirtualAdjustment && !VirtualAdjustment)
1489 return Ptr;
1490
1491 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
1492 llvm::Value *V = CGF.Builder.CreateBitCast(Ptr, Int8PtrTy);
1493
1494 if (NonVirtualAdjustment && !IsReturnAdjustment) {
1495 // Perform the non-virtual adjustment for a base-to-derived cast.
1496 V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
1497 }
1498
1499 if (VirtualAdjustment) {
1500 llvm::Type *PtrDiffTy =
1501 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1502
1503 // Perform the virtual adjustment.
1504 llvm::Value *VTablePtrPtr =
1505 CGF.Builder.CreateBitCast(V, Int8PtrTy->getPointerTo());
1506
1507 llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr);
1508
1509 llvm::Value *OffsetPtr =
1510 CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
1511
1512 OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo());
1513
1514 // Load the adjustment offset from the vtable.
1515 llvm::Value *Offset = CGF.Builder.CreateLoad(OffsetPtr);
1516
1517 // Adjust our pointer.
1518 V = CGF.Builder.CreateInBoundsGEP(V, Offset);
1519 }
1520
1521 if (NonVirtualAdjustment && IsReturnAdjustment) {
1522 // Perform the non-virtual adjustment for a derived-to-base cast.
1523 V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
1524 }
1525
1526 // Cast back to the original type.
1527 return CGF.Builder.CreateBitCast(V, Ptr->getType());
1528}
1529
1530llvm::Value *ItaniumCXXABI::performThisAdjustment(CodeGenFunction &CGF,
1531 llvm::Value *This,
1532 const ThisAdjustment &TA) {
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00001533 return performTypeAdjustment(CGF, This, TA.NonVirtual,
1534 TA.Virtual.Itanium.VCallOffsetOffset,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001535 /*IsReturnAdjustment=*/false);
1536}
1537
1538llvm::Value *
1539ItaniumCXXABI::performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
1540 const ReturnAdjustment &RA) {
1541 return performTypeAdjustment(CGF, Ret, RA.NonVirtual,
1542 RA.Virtual.Itanium.VBaseOffsetOffset,
1543 /*IsReturnAdjustment=*/true);
1544}
1545
John McCall5d865c322010-08-31 07:33:07 +00001546void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
1547 RValue RV, QualType ResultType) {
1548 if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
1549 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
1550
1551 // Destructor thunks in the ARM ABI have indeterminate results.
Chris Lattner2192fe52011-07-18 04:24:23 +00001552 llvm::Type *T =
John McCall5d865c322010-08-31 07:33:07 +00001553 cast<llvm::PointerType>(CGF.ReturnValue->getType())->getElementType();
1554 RValue Undef = RValue::get(llvm::UndefValue::get(T));
1555 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
1556}
John McCall8ed55a52010-09-02 09:58:18 +00001557
1558/************************** Array allocation cookies **************************/
1559
John McCallb91cd662012-05-01 05:23:51 +00001560CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
1561 // The array cookie is a size_t; pad that up to the element alignment.
1562 // The cookie is actually right-justified in that space.
1563 return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
1564 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001565}
1566
1567llvm::Value *ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1568 llvm::Value *NewPtr,
1569 llvm::Value *NumElements,
John McCall284c48f2011-01-27 09:37:56 +00001570 const CXXNewExpr *expr,
John McCall8ed55a52010-09-02 09:58:18 +00001571 QualType ElementType) {
John McCallb91cd662012-05-01 05:23:51 +00001572 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001573
Micah Villmowea2fea22012-10-25 15:39:14 +00001574 unsigned AS = NewPtr->getType()->getPointerAddressSpace();
John McCall8ed55a52010-09-02 09:58:18 +00001575
John McCall9bca9232010-09-02 10:25:57 +00001576 ASTContext &Ctx = getContext();
John McCall8ed55a52010-09-02 09:58:18 +00001577 QualType SizeTy = Ctx.getSizeType();
1578 CharUnits SizeSize = Ctx.getTypeSizeInChars(SizeTy);
1579
1580 // The size of the cookie.
1581 CharUnits CookieSize =
1582 std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
John McCallb91cd662012-05-01 05:23:51 +00001583 assert(CookieSize == getArrayCookieSizeImpl(ElementType));
John McCall8ed55a52010-09-02 09:58:18 +00001584
1585 // Compute an offset to the cookie.
1586 llvm::Value *CookiePtr = NewPtr;
1587 CharUnits CookieOffset = CookieSize - SizeSize;
1588 if (!CookieOffset.isZero())
1589 CookiePtr = CGF.Builder.CreateConstInBoundsGEP1_64(CookiePtr,
1590 CookieOffset.getQuantity());
1591
1592 // Write the number of elements into the appropriate slot.
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001593 llvm::Type *NumElementsTy = CGF.ConvertType(SizeTy)->getPointerTo(AS);
1594 llvm::Value *NumElementsPtr =
1595 CGF.Builder.CreateBitCast(CookiePtr, NumElementsTy);
1596 llvm::Instruction *SI = CGF.Builder.CreateStore(NumElements, NumElementsPtr);
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001597 if (CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) && AS == 0 &&
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001598 expr->getOperatorNew()->isReplaceableGlobalAllocationFunction()) {
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001599 // The store to the CookiePtr does not need to be instrumented.
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001600 CGM.getSanitizerMetadata()->disableSanitizerForInstruction(SI);
1601 llvm::FunctionType *FTy =
1602 llvm::FunctionType::get(CGM.VoidTy, NumElementsTy, false);
1603 llvm::Constant *F =
1604 CGM.CreateRuntimeFunction(FTy, "__asan_poison_cxx_array_cookie");
1605 CGF.Builder.CreateCall(F, NumElementsPtr);
1606 }
John McCall8ed55a52010-09-02 09:58:18 +00001607
1608 // Finally, compute a pointer to the actual data buffer by skipping
1609 // over the cookie completely.
1610 return CGF.Builder.CreateConstInBoundsGEP1_64(NewPtr,
1611 CookieSize.getQuantity());
1612}
1613
John McCallb91cd662012-05-01 05:23:51 +00001614llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1615 llvm::Value *allocPtr,
1616 CharUnits cookieSize) {
1617 // The element size is right-justified in the cookie.
1618 llvm::Value *numElementsPtr = allocPtr;
1619 CharUnits numElementsOffset =
1620 cookieSize - CharUnits::fromQuantity(CGF.SizeSizeInBytes);
1621 if (!numElementsOffset.isZero())
1622 numElementsPtr =
1623 CGF.Builder.CreateConstInBoundsGEP1_64(numElementsPtr,
1624 numElementsOffset.getQuantity());
John McCall8ed55a52010-09-02 09:58:18 +00001625
Micah Villmowea2fea22012-10-25 15:39:14 +00001626 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCallb91cd662012-05-01 05:23:51 +00001627 numElementsPtr =
1628 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001629 if (!CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) || AS != 0)
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001630 return CGF.Builder.CreateLoad(numElementsPtr);
1631 // In asan mode emit a function call instead of a regular load and let the
1632 // run-time deal with it: if the shadow is properly poisoned return the
1633 // cookie, otherwise return 0 to avoid an infinite loop calling DTORs.
1634 // We can't simply ignore this load using nosanitize metadata because
1635 // the metadata may be lost.
1636 llvm::FunctionType *FTy =
1637 llvm::FunctionType::get(CGF.SizeTy, CGF.SizeTy->getPointerTo(0), false);
1638 llvm::Constant *F =
1639 CGM.CreateRuntimeFunction(FTy, "__asan_load_cxx_array_cookie");
1640 return CGF.Builder.CreateCall(F, numElementsPtr);
John McCall8ed55a52010-09-02 09:58:18 +00001641}
1642
John McCallb91cd662012-05-01 05:23:51 +00001643CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
John McCallc19c7062013-01-25 23:36:19 +00001644 // ARM says that the cookie is always:
John McCall8ed55a52010-09-02 09:58:18 +00001645 // struct array_cookie {
1646 // std::size_t element_size; // element_size != 0
1647 // std::size_t element_count;
1648 // };
John McCallc19c7062013-01-25 23:36:19 +00001649 // But the base ABI doesn't give anything an alignment greater than
1650 // 8, so we can dismiss this as typical ABI-author blindness to
1651 // actual language complexity and round up to the element alignment.
1652 return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes),
1653 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001654}
1655
1656llvm::Value *ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
John McCallc19c7062013-01-25 23:36:19 +00001657 llvm::Value *newPtr,
1658 llvm::Value *numElements,
John McCall284c48f2011-01-27 09:37:56 +00001659 const CXXNewExpr *expr,
John McCallc19c7062013-01-25 23:36:19 +00001660 QualType elementType) {
John McCallb91cd662012-05-01 05:23:51 +00001661 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001662
John McCallc19c7062013-01-25 23:36:19 +00001663 // NewPtr is a char*, but we generalize to arbitrary addrspaces.
1664 unsigned AS = newPtr->getType()->getPointerAddressSpace();
John McCall8ed55a52010-09-02 09:58:18 +00001665
1666 // The cookie is always at the start of the buffer.
John McCallc19c7062013-01-25 23:36:19 +00001667 llvm::Value *cookie = newPtr;
John McCall8ed55a52010-09-02 09:58:18 +00001668
1669 // The first element is the element size.
John McCallc19c7062013-01-25 23:36:19 +00001670 cookie = CGF.Builder.CreateBitCast(cookie, CGF.SizeTy->getPointerTo(AS));
1671 llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy,
1672 getContext().getTypeSizeInChars(elementType).getQuantity());
1673 CGF.Builder.CreateStore(elementSize, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001674
1675 // The second element is the element count.
David Blaikiefb901c7a2015-04-04 15:12:29 +00001676 cookie = CGF.Builder.CreateConstInBoundsGEP1_32(CGF.SizeTy, cookie, 1);
John McCallc19c7062013-01-25 23:36:19 +00001677 CGF.Builder.CreateStore(numElements, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001678
1679 // Finally, compute a pointer to the actual data buffer by skipping
1680 // over the cookie completely.
John McCallc19c7062013-01-25 23:36:19 +00001681 CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType);
1682 return CGF.Builder.CreateConstInBoundsGEP1_64(newPtr,
1683 cookieSize.getQuantity());
John McCall8ed55a52010-09-02 09:58:18 +00001684}
1685
John McCallb91cd662012-05-01 05:23:51 +00001686llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1687 llvm::Value *allocPtr,
1688 CharUnits cookieSize) {
1689 // The number of elements is at offset sizeof(size_t) relative to
1690 // the allocated pointer.
1691 llvm::Value *numElementsPtr
1692 = CGF.Builder.CreateConstInBoundsGEP1_64(allocPtr, CGF.SizeSizeInBytes);
John McCall8ed55a52010-09-02 09:58:18 +00001693
Micah Villmowea2fea22012-10-25 15:39:14 +00001694 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCallb91cd662012-05-01 05:23:51 +00001695 numElementsPtr =
1696 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
1697 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall8ed55a52010-09-02 09:58:18 +00001698}
1699
John McCall68ff0372010-09-08 01:44:27 +00001700/*********************** Static local initialization **************************/
1701
1702static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001703 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001704 // int __cxa_guard_acquire(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001705 llvm::FunctionType *FTy =
John McCall68ff0372010-09-08 01:44:27 +00001706 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
Jay Foad5709f7c2011-07-29 13:56:53 +00001707 GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001708 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_acquire",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001709 llvm::AttributeSet::get(CGM.getLLVMContext(),
1710 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001711 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001712}
1713
1714static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001715 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001716 // void __cxa_guard_release(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001717 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001718 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001719 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_release",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001720 llvm::AttributeSet::get(CGM.getLLVMContext(),
1721 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001722 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001723}
1724
1725static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001726 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001727 // void __cxa_guard_abort(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001728 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001729 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001730 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_abort",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001731 llvm::AttributeSet::get(CGM.getLLVMContext(),
1732 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001733 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001734}
1735
1736namespace {
1737 struct CallGuardAbort : EHScopeStack::Cleanup {
1738 llvm::GlobalVariable *Guard;
Chandler Carruth84537952012-03-30 19:44:53 +00001739 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
John McCall68ff0372010-09-08 01:44:27 +00001740
Craig Topper4f12f102014-03-12 06:41:41 +00001741 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall882987f2013-02-28 19:01:20 +00001742 CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()),
1743 Guard);
John McCall68ff0372010-09-08 01:44:27 +00001744 }
1745 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001746}
John McCall68ff0372010-09-08 01:44:27 +00001747
1748/// The ARM code here follows the Itanium code closely enough that we
1749/// just special-case it at particular places.
John McCallcdf7ef52010-11-06 09:44:32 +00001750void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
1751 const VarDecl &D,
John McCallb88a5662012-03-30 21:00:39 +00001752 llvm::GlobalVariable *var,
1753 bool shouldPerformInit) {
John McCall68ff0372010-09-08 01:44:27 +00001754 CGBuilderTy &Builder = CGF.Builder;
John McCallcdf7ef52010-11-06 09:44:32 +00001755
Richard Smithdbf74ba2013-04-14 23:01:42 +00001756 // We only need to use thread-safe statics for local non-TLS variables;
John McCallcdf7ef52010-11-06 09:44:32 +00001757 // global initialization is always single-threaded.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001758 bool threadsafe = getContext().getLangOpts().ThreadsafeStatics &&
1759 D.isLocalVarDecl() && !D.getTLSKind();
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001760
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001761 // If we have a global variable with internal linkage and thread-safe statics
1762 // are disabled, we can just let the guard variable be of type i8.
John McCallb88a5662012-03-30 21:00:39 +00001763 bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
1764
1765 llvm::IntegerType *guardTy;
John McCall5aa52592011-06-17 07:33:57 +00001766 if (useInt8GuardVariable) {
John McCallb88a5662012-03-30 21:00:39 +00001767 guardTy = CGF.Int8Ty;
John McCall5aa52592011-06-17 07:33:57 +00001768 } else {
Tim Northover9bb857a2013-01-31 12:13:10 +00001769 // Guard variables are 64 bits in the generic ABI and size width on ARM
1770 // (i.e. 32-bit on AArch32, 64-bit on AArch64).
Mark Seabornedf0d382013-07-24 16:25:13 +00001771 guardTy = (UseARMGuardVarABI ? CGF.SizeTy : CGF.Int64Ty);
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001772 }
John McCallb88a5662012-03-30 21:00:39 +00001773 llvm::PointerType *guardPtrTy = guardTy->getPointerTo();
John McCall68ff0372010-09-08 01:44:27 +00001774
John McCallb88a5662012-03-30 21:00:39 +00001775 // Create the guard variable if we don't already have it (as we
1776 // might if we're double-emitting this function body).
1777 llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
1778 if (!guard) {
1779 // Mangle the name for the guard.
1780 SmallString<256> guardName;
1781 {
1782 llvm::raw_svector_ostream out(guardName);
Reid Klecknerd8110b62013-09-10 20:14:30 +00001783 getMangleContext().mangleStaticGuardVariable(&D, out);
John McCallb88a5662012-03-30 21:00:39 +00001784 out.flush();
1785 }
John McCall8e7cb6d2010-11-02 21:04:24 +00001786
John McCallb88a5662012-03-30 21:00:39 +00001787 // Create the guard variable with a zero-initializer.
1788 // Just absorb linkage and visibility from the guarded variable.
1789 guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
1790 false, var->getLinkage(),
1791 llvm::ConstantInt::get(guardTy, 0),
1792 guardName.str());
1793 guard->setVisibility(var->getVisibility());
Richard Smithdbf74ba2013-04-14 23:01:42 +00001794 // If the variable is thread-local, so is its guard variable.
1795 guard->setThreadLocalMode(var->getThreadLocalMode());
John McCallb88a5662012-03-30 21:00:39 +00001796
Rafael Espindola2ae4b632014-09-19 19:43:18 +00001797 // The ABI says: It is suggested that it be emitted in the same COMDAT group
1798 // as the associated data object
Rafael Espindola0d4fb982015-01-12 22:13:53 +00001799 llvm::Comdat *C = var->getComdat();
1800 if (!D.isLocalVarDecl() && C) {
Rafael Espindola2ae4b632014-09-19 19:43:18 +00001801 guard->setComdat(C);
Rafael Espindola2ae4b632014-09-19 19:43:18 +00001802 CGF.CurFn->setComdat(C);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00001803 } else if (CGM.supportsCOMDAT() && guard->isWeakForLinker()) {
1804 guard->setComdat(CGM.getModule().getOrInsertComdat(guard->getName()));
Rafael Espindola2ae4b632014-09-19 19:43:18 +00001805 }
1806
John McCallb88a5662012-03-30 21:00:39 +00001807 CGM.setStaticLocalDeclGuardAddress(&D, guard);
1808 }
John McCall87590e62012-03-30 07:09:50 +00001809
John McCall68ff0372010-09-08 01:44:27 +00001810 // Test whether the variable has completed initialization.
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001811 //
John McCall68ff0372010-09-08 01:44:27 +00001812 // Itanium C++ ABI 3.3.2:
1813 // The following is pseudo-code showing how these functions can be used:
1814 // if (obj_guard.first_byte == 0) {
1815 // if ( __cxa_guard_acquire (&obj_guard) ) {
1816 // try {
1817 // ... initialize the object ...;
1818 // } catch (...) {
1819 // __cxa_guard_abort (&obj_guard);
1820 // throw;
1821 // }
1822 // ... queue object destructor with __cxa_atexit() ...;
1823 // __cxa_guard_release (&obj_guard);
1824 // }
1825 // }
Tim Northovera2ee4332014-03-29 15:09:45 +00001826
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001827 // Load the first byte of the guard variable.
1828 llvm::LoadInst *LI =
John McCallb88a5662012-03-30 21:00:39 +00001829 Builder.CreateLoad(Builder.CreateBitCast(guard, CGM.Int8PtrTy));
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001830 LI->setAlignment(1);
John McCall68ff0372010-09-08 01:44:27 +00001831
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001832 // Itanium ABI:
1833 // An implementation supporting thread-safety on multiprocessor
1834 // systems must also guarantee that references to the initialized
1835 // object do not occur before the load of the initialization flag.
1836 //
1837 // In LLVM, we do this by marking the load Acquire.
1838 if (threadsafe)
1839 LI->setAtomic(llvm::Acquire);
Eli Friedman84d28122011-09-13 22:21:56 +00001840
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001841 // For ARM, we should only check the first bit, rather than the entire byte:
1842 //
1843 // ARM C++ ABI 3.2.3.1:
1844 // To support the potential use of initialization guard variables
1845 // as semaphores that are the target of ARM SWP and LDREX/STREX
1846 // synchronizing instructions we define a static initialization
1847 // guard variable to be a 4-byte aligned, 4-byte word with the
1848 // following inline access protocol.
1849 // #define INITIALIZED 1
1850 // if ((obj_guard & INITIALIZED) != INITIALIZED) {
1851 // if (__cxa_guard_acquire(&obj_guard))
1852 // ...
1853 // }
1854 //
1855 // and similarly for ARM64:
1856 //
1857 // ARM64 C++ ABI 3.2.2:
1858 // This ABI instead only specifies the value bit 0 of the static guard
1859 // variable; all other bits are platform defined. Bit 0 shall be 0 when the
1860 // variable is not initialized and 1 when it is.
1861 llvm::Value *V =
1862 (UseARMGuardVarABI && !useInt8GuardVariable)
1863 ? Builder.CreateAnd(LI, llvm::ConstantInt::get(CGM.Int8Ty, 1))
1864 : LI;
1865 llvm::Value *isInitialized = Builder.CreateIsNull(V, "guard.uninitialized");
John McCall68ff0372010-09-08 01:44:27 +00001866
1867 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
1868 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
1869
1870 // Check if the first byte of the guard variable is zero.
John McCallb88a5662012-03-30 21:00:39 +00001871 Builder.CreateCondBr(isInitialized, InitCheckBlock, EndBlock);
John McCall68ff0372010-09-08 01:44:27 +00001872
1873 CGF.EmitBlock(InitCheckBlock);
1874
1875 // Variables used when coping with thread-safe statics and exceptions.
John McCall5aa52592011-06-17 07:33:57 +00001876 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00001877 // Call __cxa_guard_acquire.
1878 llvm::Value *V
John McCall882987f2013-02-28 19:01:20 +00001879 = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
John McCall68ff0372010-09-08 01:44:27 +00001880
1881 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
1882
1883 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
1884 InitBlock, EndBlock);
1885
1886 // Call __cxa_guard_abort along the exceptional edge.
John McCallb88a5662012-03-30 21:00:39 +00001887 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
John McCall68ff0372010-09-08 01:44:27 +00001888
1889 CGF.EmitBlock(InitBlock);
1890 }
1891
1892 // Emit the initializer and add a global destructor if appropriate.
John McCallb88a5662012-03-30 21:00:39 +00001893 CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
John McCall68ff0372010-09-08 01:44:27 +00001894
John McCall5aa52592011-06-17 07:33:57 +00001895 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00001896 // Pop the guard-abort cleanup if we pushed one.
1897 CGF.PopCleanupBlock();
1898
1899 // Call __cxa_guard_release. This cannot throw.
John McCall882987f2013-02-28 19:01:20 +00001900 CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy), guard);
John McCall68ff0372010-09-08 01:44:27 +00001901 } else {
John McCallb88a5662012-03-30 21:00:39 +00001902 Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guard);
John McCall68ff0372010-09-08 01:44:27 +00001903 }
1904
1905 CGF.EmitBlock(EndBlock);
1906}
John McCallc84ed6a2012-05-01 06:13:13 +00001907
1908/// Register a global destructor using __cxa_atexit.
1909static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
1910 llvm::Constant *dtor,
Richard Smithdbf74ba2013-04-14 23:01:42 +00001911 llvm::Constant *addr,
1912 bool TLS) {
Bill Wendling95cae882013-05-02 19:18:03 +00001913 const char *Name = "__cxa_atexit";
1914 if (TLS) {
1915 const llvm::Triple &T = CGF.getTarget().getTriple();
1916 Name = T.isMacOSX() ? "_tlv_atexit" : "__cxa_thread_atexit";
1917 }
Richard Smithdbf74ba2013-04-14 23:01:42 +00001918
John McCallc84ed6a2012-05-01 06:13:13 +00001919 // We're assuming that the destructor function is something we can
1920 // reasonably call with the default CC. Go ahead and cast it to the
1921 // right prototype.
1922 llvm::Type *dtorTy =
1923 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo();
1924
1925 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
1926 llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
1927 llvm::FunctionType *atexitTy =
1928 llvm::FunctionType::get(CGF.IntTy, paramTys, false);
1929
1930 // Fetch the actual function.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001931 llvm::Constant *atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name);
John McCallc84ed6a2012-05-01 06:13:13 +00001932 if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit))
1933 fn->setDoesNotThrow();
1934
1935 // Create a variable that binds the atexit to this shared object.
1936 llvm::Constant *handle =
1937 CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
1938
1939 llvm::Value *args[] = {
1940 llvm::ConstantExpr::getBitCast(dtor, dtorTy),
1941 llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy),
1942 handle
1943 };
John McCall882987f2013-02-28 19:01:20 +00001944 CGF.EmitNounwindRuntimeCall(atexit, args);
John McCallc84ed6a2012-05-01 06:13:13 +00001945}
1946
1947/// Register a global destructor as best as we know how.
1948void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF,
Richard Smithdbf74ba2013-04-14 23:01:42 +00001949 const VarDecl &D,
John McCallc84ed6a2012-05-01 06:13:13 +00001950 llvm::Constant *dtor,
1951 llvm::Constant *addr) {
1952 // Use __cxa_atexit if available.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001953 if (CGM.getCodeGenOpts().CXAAtExit)
1954 return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind());
1955
1956 if (D.getTLSKind())
1957 CGM.ErrorUnsupported(&D, "non-trivial TLS destruction");
John McCallc84ed6a2012-05-01 06:13:13 +00001958
1959 // In Apple kexts, we want to add a global destructor entry.
1960 // FIXME: shouldn't this be guarded by some variable?
Richard Smith9c6890a2012-11-01 22:30:59 +00001961 if (CGM.getLangOpts().AppleKext) {
John McCallc84ed6a2012-05-01 06:13:13 +00001962 // Generate a global destructor entry.
1963 return CGM.AddCXXDtorEntry(dtor, addr);
1964 }
1965
David Blaikieebe87e12013-08-27 23:57:18 +00001966 CGF.registerGlobalDtorWithAtExit(D, dtor, addr);
John McCallc84ed6a2012-05-01 06:13:13 +00001967}
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001968
David Majnemer9b21c332014-07-11 20:28:10 +00001969static bool isThreadWrapperReplaceable(const VarDecl *VD,
1970 CodeGen::CodeGenModule &CGM) {
1971 assert(!VD->isStaticLocal() && "static local VarDecls don't need wrappers!");
1972 // OS X prefers to have references to thread local variables to go through
1973 // the thread wrapper instead of directly referencing the backing variable.
1974 return VD->getTLSKind() == VarDecl::TLS_Dynamic &&
1975 CGM.getTarget().getTriple().isMacOSX();
1976}
1977
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001978/// Get the appropriate linkage for the wrapper function. This is essentially
David Majnemer4632e1e2014-06-27 16:56:27 +00001979/// the weak form of the variable's linkage; every translation unit which needs
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001980/// the wrapper emits a copy, and we want the linker to merge them.
David Majnemer35ab3282014-06-11 04:08:55 +00001981static llvm::GlobalValue::LinkageTypes
1982getThreadLocalWrapperLinkage(const VarDecl *VD, CodeGen::CodeGenModule &CGM) {
1983 llvm::GlobalValue::LinkageTypes VarLinkage =
1984 CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false);
1985
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001986 // For internal linkage variables, we don't need an external or weak wrapper.
1987 if (llvm::GlobalValue::isLocalLinkage(VarLinkage))
1988 return VarLinkage;
David Majnemer35ab3282014-06-11 04:08:55 +00001989
David Majnemer9b21c332014-07-11 20:28:10 +00001990 // If the thread wrapper is replaceable, give it appropriate linkage.
1991 if (isThreadWrapperReplaceable(VD, CGM)) {
1992 if (llvm::GlobalVariable::isLinkOnceLinkage(VarLinkage) ||
1993 llvm::GlobalVariable::isWeakODRLinkage(VarLinkage))
1994 return llvm::GlobalVariable::WeakAnyLinkage;
1995 return VarLinkage;
1996 }
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001997 return llvm::GlobalValue::WeakODRLinkage;
1998}
1999
2000llvm::Function *
2001ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD,
Alexander Musmanf94c3182014-09-26 06:28:25 +00002002 llvm::Value *Val) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002003 // Mangle the name for the thread_local wrapper function.
2004 SmallString<256> WrapperName;
2005 {
2006 llvm::raw_svector_ostream Out(WrapperName);
2007 getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out);
2008 Out.flush();
2009 }
2010
Alexander Musmanf94c3182014-09-26 06:28:25 +00002011 if (llvm::Value *V = CGM.getModule().getNamedValue(WrapperName))
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002012 return cast<llvm::Function>(V);
2013
Alexander Musmanf94c3182014-09-26 06:28:25 +00002014 llvm::Type *RetTy = Val->getType();
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002015 if (VD->getType()->isReferenceType())
2016 RetTy = RetTy->getPointerElementType();
2017
2018 llvm::FunctionType *FnTy = llvm::FunctionType::get(RetTy, false);
David Majnemer35ab3282014-06-11 04:08:55 +00002019 llvm::Function *Wrapper =
2020 llvm::Function::Create(FnTy, getThreadLocalWrapperLinkage(VD, CGM),
2021 WrapperName.str(), &CGM.getModule());
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002022 // Always resolve references to the wrapper at link time.
David Majnemer9b21c332014-07-11 20:28:10 +00002023 if (!Wrapper->hasLocalLinkage() && !isThreadWrapperReplaceable(VD, CGM))
Duncan P. N. Exon Smith4434d362014-05-07 22:36:11 +00002024 Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002025 return Wrapper;
2026}
2027
2028void ItaniumCXXABI::EmitThreadLocalInitFuncs(
David Majnemerb3341ea2014-10-05 05:05:40 +00002029 CodeGenModule &CGM,
2030 ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *>>
2031 CXXThreadLocals, ArrayRef<llvm::Function *> CXXThreadLocalInits,
2032 ArrayRef<llvm::GlobalVariable *> CXXThreadLocalInitVars) {
2033 llvm::Function *InitFunc = nullptr;
2034 if (!CXXThreadLocalInits.empty()) {
2035 // Generate a guarded initialization function.
2036 llvm::FunctionType *FTy =
2037 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
2038 InitFunc = CGM.CreateGlobalInitOrDestructFunction(FTy, "__tls_init",
Alexey Samsonov1444bb92014-10-17 00:20:19 +00002039 SourceLocation(),
David Majnemerb3341ea2014-10-05 05:05:40 +00002040 /*TLS=*/true);
2041 llvm::GlobalVariable *Guard = new llvm::GlobalVariable(
2042 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false,
2043 llvm::GlobalVariable::InternalLinkage,
2044 llvm::ConstantInt::get(CGM.Int8Ty, 0), "__tls_guard");
2045 Guard->setThreadLocal(true);
2046 CodeGenFunction(CGM)
2047 .GenerateCXXGlobalInitFunc(InitFunc, CXXThreadLocalInits, Guard);
2048 }
2049 for (unsigned I = 0, N = CXXThreadLocals.size(); I != N; ++I) {
2050 const VarDecl *VD = CXXThreadLocals[I].first;
2051 llvm::GlobalVariable *Var = CXXThreadLocals[I].second;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002052
David Majnemer9b21c332014-07-11 20:28:10 +00002053 // Some targets require that all access to thread local variables go through
2054 // the thread wrapper. This means that we cannot attempt to create a thread
2055 // wrapper or a thread helper.
2056 if (isThreadWrapperReplaceable(VD, CGM) && !VD->hasDefinition())
2057 continue;
2058
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002059 // Mangle the name for the thread_local initialization function.
2060 SmallString<256> InitFnName;
2061 {
2062 llvm::raw_svector_ostream Out(InitFnName);
2063 getMangleContext().mangleItaniumThreadLocalInit(VD, Out);
2064 Out.flush();
2065 }
2066
2067 // If we have a definition for the variable, emit the initialization
2068 // function as an alias to the global Init function (if any). Otherwise,
2069 // produce a declaration of the initialization function.
Craig Topper8a13c412014-05-21 05:09:00 +00002070 llvm::GlobalValue *Init = nullptr;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002071 bool InitIsInitFunc = false;
2072 if (VD->hasDefinition()) {
2073 InitIsInitFunc = true;
2074 if (InitFunc)
Rafael Espindola234405b2014-05-17 21:30:14 +00002075 Init = llvm::GlobalAlias::create(Var->getLinkage(), InitFnName.str(),
2076 InitFunc);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002077 } else {
2078 // Emit a weak global function referring to the initialization function.
2079 // This function will not exist if the TU defining the thread_local
2080 // variable in question does not need any dynamic initialization for
2081 // its thread_local variables.
2082 llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, false);
2083 Init = llvm::Function::Create(
2084 FnTy, llvm::GlobalVariable::ExternalWeakLinkage, InitFnName.str(),
2085 &CGM.getModule());
2086 }
2087
2088 if (Init)
2089 Init->setVisibility(Var->getVisibility());
2090
2091 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Var);
2092 llvm::LLVMContext &Context = CGM.getModule().getContext();
2093 llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper);
2094 CGBuilderTy Builder(Entry);
2095 if (InitIsInitFunc) {
2096 if (Init)
David Blaikie43f9bb72015-05-18 22:14:03 +00002097 Builder.CreateCall(Init, {});
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002098 } else {
2099 // Don't know whether we have an init function. Call it if it exists.
2100 llvm::Value *Have = Builder.CreateIsNotNull(Init);
2101 llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2102 llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2103 Builder.CreateCondBr(Have, InitBB, ExitBB);
2104
2105 Builder.SetInsertPoint(InitBB);
David Blaikie43f9bb72015-05-18 22:14:03 +00002106 Builder.CreateCall(Init, {});
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002107 Builder.CreateBr(ExitBB);
2108
2109 Builder.SetInsertPoint(ExitBB);
2110 }
2111
2112 // For a reference, the result of the wrapper function is a pointer to
2113 // the referenced object.
2114 llvm::Value *Val = Var;
2115 if (VD->getType()->isReferenceType()) {
2116 llvm::LoadInst *LI = Builder.CreateLoad(Val);
2117 LI->setAlignment(CGM.getContext().getDeclAlign(VD).getQuantity());
2118 Val = LI;
2119 }
Alexander Musmanf94c3182014-09-26 06:28:25 +00002120 if (Val->getType() != Wrapper->getReturnType())
2121 Val = Builder.CreatePointerBitCastOrAddrSpaceCast(
2122 Val, Wrapper->getReturnType(), "");
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002123 Builder.CreateRet(Val);
2124 }
2125}
2126
Richard Smith0f383742014-03-26 22:48:22 +00002127LValue ItaniumCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
2128 const VarDecl *VD,
2129 QualType LValType) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002130 QualType T = VD->getType();
2131 llvm::Type *Ty = CGF.getTypes().ConvertTypeForMem(T);
2132 llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD, Ty);
Alexander Musmanf94c3182014-09-26 06:28:25 +00002133 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Val);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002134
David Blaikie43f9bb72015-05-18 22:14:03 +00002135 Val = CGF.Builder.CreateCall(Wrapper, {});
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002136
2137 LValue LV;
2138 if (VD->getType()->isReferenceType())
Richard Smith0f383742014-03-26 22:48:22 +00002139 LV = CGF.MakeNaturalAlignAddrLValue(Val, LValType);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002140 else
Richard Smith0f383742014-03-26 22:48:22 +00002141 LV = CGF.MakeAddrLValue(Val, LValType, CGF.getContext().getDeclAlign(VD));
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002142 // FIXME: need setObjCGCLValueClass?
2143 return LV;
2144}
Peter Collingbourne66f82e62013-06-28 20:45:28 +00002145
2146/// Return whether the given global decl needs a VTT parameter, which it does
2147/// if it's a base constructor or destructor with virtual bases.
2148bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) {
2149 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
2150
2151 // We don't have any virtual bases, just return early.
2152 if (!MD->getParent()->getNumVBases())
2153 return false;
2154
2155 // Check if we have a base constructor.
2156 if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base)
2157 return true;
2158
2159 // Check if we have a base destructor.
2160 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
2161 return true;
2162
2163 return false;
2164}
David Majnemere2cb8d12014-07-07 06:20:47 +00002165
2166namespace {
2167class ItaniumRTTIBuilder {
2168 CodeGenModule &CGM; // Per-module state.
2169 llvm::LLVMContext &VMContext;
2170 const ItaniumCXXABI &CXXABI; // Per-module state.
2171
2172 /// Fields - The fields of the RTTI descriptor currently being built.
2173 SmallVector<llvm::Constant *, 16> Fields;
2174
2175 /// GetAddrOfTypeName - Returns the mangled type name of the given type.
2176 llvm::GlobalVariable *
2177 GetAddrOfTypeName(QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage);
2178
2179 /// GetAddrOfExternalRTTIDescriptor - Returns the constant for the RTTI
2180 /// descriptor of the given type.
2181 llvm::Constant *GetAddrOfExternalRTTIDescriptor(QualType Ty);
2182
2183 /// BuildVTablePointer - Build the vtable pointer for the given type.
2184 void BuildVTablePointer(const Type *Ty);
2185
2186 /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
2187 /// inheritance, according to the Itanium C++ ABI, 2.9.5p6b.
2188 void BuildSIClassTypeInfo(const CXXRecordDecl *RD);
2189
2190 /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
2191 /// classes with bases that do not satisfy the abi::__si_class_type_info
2192 /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
2193 void BuildVMIClassTypeInfo(const CXXRecordDecl *RD);
2194
2195 /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct, used
2196 /// for pointer types.
2197 void BuildPointerTypeInfo(QualType PointeeTy);
2198
2199 /// BuildObjCObjectTypeInfo - Build the appropriate kind of
2200 /// type_info for an object type.
2201 void BuildObjCObjectTypeInfo(const ObjCObjectType *Ty);
2202
2203 /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
2204 /// struct, used for member pointer types.
2205 void BuildPointerToMemberTypeInfo(const MemberPointerType *Ty);
2206
2207public:
2208 ItaniumRTTIBuilder(const ItaniumCXXABI &ABI)
2209 : CGM(ABI.CGM), VMContext(CGM.getModule().getContext()), CXXABI(ABI) {}
2210
2211 // Pointer type info flags.
2212 enum {
2213 /// PTI_Const - Type has const qualifier.
2214 PTI_Const = 0x1,
2215
2216 /// PTI_Volatile - Type has volatile qualifier.
2217 PTI_Volatile = 0x2,
2218
2219 /// PTI_Restrict - Type has restrict qualifier.
2220 PTI_Restrict = 0x4,
2221
2222 /// PTI_Incomplete - Type is incomplete.
2223 PTI_Incomplete = 0x8,
2224
2225 /// PTI_ContainingClassIncomplete - Containing class is incomplete.
2226 /// (in pointer to member).
2227 PTI_ContainingClassIncomplete = 0x10
2228 };
2229
2230 // VMI type info flags.
2231 enum {
2232 /// VMI_NonDiamondRepeat - Class has non-diamond repeated inheritance.
2233 VMI_NonDiamondRepeat = 0x1,
2234
2235 /// VMI_DiamondShaped - Class is diamond shaped.
2236 VMI_DiamondShaped = 0x2
2237 };
2238
2239 // Base class type info flags.
2240 enum {
2241 /// BCTI_Virtual - Base class is virtual.
2242 BCTI_Virtual = 0x1,
2243
2244 /// BCTI_Public - Base class is public.
2245 BCTI_Public = 0x2
2246 };
2247
2248 /// BuildTypeInfo - Build the RTTI type info struct for the given type.
2249 ///
2250 /// \param Force - true to force the creation of this RTTI value
2251 llvm::Constant *BuildTypeInfo(QualType Ty, bool Force = false);
2252};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002253}
David Majnemere2cb8d12014-07-07 06:20:47 +00002254
2255llvm::GlobalVariable *ItaniumRTTIBuilder::GetAddrOfTypeName(
2256 QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage) {
2257 SmallString<256> OutName;
2258 llvm::raw_svector_ostream Out(OutName);
2259 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(Ty, Out);
2260 Out.flush();
2261 StringRef Name = OutName.str();
2262
2263 // We know that the mangled name of the type starts at index 4 of the
2264 // mangled name of the typename, so we can just index into it in order to
2265 // get the mangled name of the type.
2266 llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,
2267 Name.substr(4));
2268
2269 llvm::GlobalVariable *GV =
2270 CGM.CreateOrReplaceCXXRuntimeVariable(Name, Init->getType(), Linkage);
2271
2272 GV->setInitializer(Init);
2273
2274 return GV;
2275}
2276
2277llvm::Constant *
2278ItaniumRTTIBuilder::GetAddrOfExternalRTTIDescriptor(QualType Ty) {
2279 // Mangle the RTTI name.
2280 SmallString<256> OutName;
2281 llvm::raw_svector_ostream Out(OutName);
2282 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
2283 Out.flush();
2284 StringRef Name = OutName.str();
2285
2286 // Look for an existing global.
2287 llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name);
2288
2289 if (!GV) {
2290 // Create a new global variable.
2291 GV = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
2292 /*Constant=*/true,
2293 llvm::GlobalValue::ExternalLinkage, nullptr,
2294 Name);
David Majnemer1fb1a042014-11-07 07:26:38 +00002295 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2296 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
2297 if (RD->hasAttr<DLLImportAttr>())
2298 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
2299 }
David Majnemere2cb8d12014-07-07 06:20:47 +00002300 }
2301
2302 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
2303}
2304
2305/// TypeInfoIsInStandardLibrary - Given a builtin type, returns whether the type
2306/// info for that type is defined in the standard library.
2307static bool TypeInfoIsInStandardLibrary(const BuiltinType *Ty) {
2308 // Itanium C++ ABI 2.9.2:
2309 // Basic type information (e.g. for "int", "bool", etc.) will be kept in
2310 // the run-time support library. Specifically, the run-time support
2311 // library should contain type_info objects for the types X, X* and
2312 // X const*, for every X in: void, std::nullptr_t, bool, wchar_t, char,
2313 // unsigned char, signed char, short, unsigned short, int, unsigned int,
2314 // long, unsigned long, long long, unsigned long long, float, double,
2315 // long double, char16_t, char32_t, and the IEEE 754r decimal and
2316 // half-precision floating point types.
2317 switch (Ty->getKind()) {
2318 case BuiltinType::Void:
2319 case BuiltinType::NullPtr:
2320 case BuiltinType::Bool:
2321 case BuiltinType::WChar_S:
2322 case BuiltinType::WChar_U:
2323 case BuiltinType::Char_U:
2324 case BuiltinType::Char_S:
2325 case BuiltinType::UChar:
2326 case BuiltinType::SChar:
2327 case BuiltinType::Short:
2328 case BuiltinType::UShort:
2329 case BuiltinType::Int:
2330 case BuiltinType::UInt:
2331 case BuiltinType::Long:
2332 case BuiltinType::ULong:
2333 case BuiltinType::LongLong:
2334 case BuiltinType::ULongLong:
2335 case BuiltinType::Half:
2336 case BuiltinType::Float:
2337 case BuiltinType::Double:
2338 case BuiltinType::LongDouble:
2339 case BuiltinType::Char16:
2340 case BuiltinType::Char32:
2341 case BuiltinType::Int128:
2342 case BuiltinType::UInt128:
2343 case BuiltinType::OCLImage1d:
2344 case BuiltinType::OCLImage1dArray:
2345 case BuiltinType::OCLImage1dBuffer:
2346 case BuiltinType::OCLImage2d:
2347 case BuiltinType::OCLImage2dArray:
2348 case BuiltinType::OCLImage3d:
2349 case BuiltinType::OCLSampler:
2350 case BuiltinType::OCLEvent:
2351 return true;
2352
2353 case BuiltinType::Dependent:
2354#define BUILTIN_TYPE(Id, SingletonId)
2355#define PLACEHOLDER_TYPE(Id, SingletonId) \
2356 case BuiltinType::Id:
2357#include "clang/AST/BuiltinTypes.def"
2358 llvm_unreachable("asking for RRTI for a placeholder type!");
2359
2360 case BuiltinType::ObjCId:
2361 case BuiltinType::ObjCClass:
2362 case BuiltinType::ObjCSel:
2363 llvm_unreachable("FIXME: Objective-C types are unsupported!");
2364 }
2365
2366 llvm_unreachable("Invalid BuiltinType Kind!");
2367}
2368
2369static bool TypeInfoIsInStandardLibrary(const PointerType *PointerTy) {
2370 QualType PointeeTy = PointerTy->getPointeeType();
2371 const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(PointeeTy);
2372 if (!BuiltinTy)
2373 return false;
2374
2375 // Check the qualifiers.
2376 Qualifiers Quals = PointeeTy.getQualifiers();
2377 Quals.removeConst();
2378
2379 if (!Quals.empty())
2380 return false;
2381
2382 return TypeInfoIsInStandardLibrary(BuiltinTy);
2383}
2384
2385/// IsStandardLibraryRTTIDescriptor - Returns whether the type
2386/// information for the given type exists in the standard library.
2387static bool IsStandardLibraryRTTIDescriptor(QualType Ty) {
2388 // Type info for builtin types is defined in the standard library.
2389 if (const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(Ty))
2390 return TypeInfoIsInStandardLibrary(BuiltinTy);
2391
2392 // Type info for some pointer types to builtin types is defined in the
2393 // standard library.
2394 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2395 return TypeInfoIsInStandardLibrary(PointerTy);
2396
2397 return false;
2398}
2399
2400/// ShouldUseExternalRTTIDescriptor - Returns whether the type information for
2401/// the given type exists somewhere else, and that we should not emit the type
2402/// information in this translation unit. Assumes that it is not a
2403/// standard-library type.
2404static bool ShouldUseExternalRTTIDescriptor(CodeGenModule &CGM,
2405 QualType Ty) {
2406 ASTContext &Context = CGM.getContext();
2407
2408 // If RTTI is disabled, assume it might be disabled in the
2409 // translation unit that defines any potential key function, too.
2410 if (!Context.getLangOpts().RTTI) return false;
2411
2412 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2413 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
2414 if (!RD->hasDefinition())
2415 return false;
2416
2417 if (!RD->isDynamicClass())
2418 return false;
2419
2420 // FIXME: this may need to be reconsidered if the key function
2421 // changes.
David Majnemer1fb1a042014-11-07 07:26:38 +00002422 if (CGM.getVTables().isVTableExternal(RD))
2423 return true;
2424
2425 if (RD->hasAttr<DLLImportAttr>())
2426 return true;
David Majnemere2cb8d12014-07-07 06:20:47 +00002427 }
2428
2429 return false;
2430}
2431
2432/// IsIncompleteClassType - Returns whether the given record type is incomplete.
2433static bool IsIncompleteClassType(const RecordType *RecordTy) {
2434 return !RecordTy->getDecl()->isCompleteDefinition();
2435}
2436
2437/// ContainsIncompleteClassType - Returns whether the given type contains an
2438/// incomplete class type. This is true if
2439///
2440/// * The given type is an incomplete class type.
2441/// * The given type is a pointer type whose pointee type contains an
2442/// incomplete class type.
2443/// * The given type is a member pointer type whose class is an incomplete
2444/// class type.
2445/// * The given type is a member pointer type whoise pointee type contains an
2446/// incomplete class type.
2447/// is an indirect or direct pointer to an incomplete class type.
2448static bool ContainsIncompleteClassType(QualType Ty) {
2449 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2450 if (IsIncompleteClassType(RecordTy))
2451 return true;
2452 }
2453
2454 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2455 return ContainsIncompleteClassType(PointerTy->getPointeeType());
2456
2457 if (const MemberPointerType *MemberPointerTy =
2458 dyn_cast<MemberPointerType>(Ty)) {
2459 // Check if the class type is incomplete.
2460 const RecordType *ClassType = cast<RecordType>(MemberPointerTy->getClass());
2461 if (IsIncompleteClassType(ClassType))
2462 return true;
2463
2464 return ContainsIncompleteClassType(MemberPointerTy->getPointeeType());
2465 }
2466
2467 return false;
2468}
2469
2470// CanUseSingleInheritance - Return whether the given record decl has a "single,
2471// public, non-virtual base at offset zero (i.e. the derived class is dynamic
2472// iff the base is)", according to Itanium C++ ABI, 2.95p6b.
2473static bool CanUseSingleInheritance(const CXXRecordDecl *RD) {
2474 // Check the number of bases.
2475 if (RD->getNumBases() != 1)
2476 return false;
2477
2478 // Get the base.
2479 CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin();
2480
2481 // Check that the base is not virtual.
2482 if (Base->isVirtual())
2483 return false;
2484
2485 // Check that the base is public.
2486 if (Base->getAccessSpecifier() != AS_public)
2487 return false;
2488
2489 // Check that the class is dynamic iff the base is.
2490 const CXXRecordDecl *BaseDecl =
2491 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2492 if (!BaseDecl->isEmpty() &&
2493 BaseDecl->isDynamicClass() != RD->isDynamicClass())
2494 return false;
2495
2496 return true;
2497}
2498
2499void ItaniumRTTIBuilder::BuildVTablePointer(const Type *Ty) {
2500 // abi::__class_type_info.
2501 static const char * const ClassTypeInfo =
2502 "_ZTVN10__cxxabiv117__class_type_infoE";
2503 // abi::__si_class_type_info.
2504 static const char * const SIClassTypeInfo =
2505 "_ZTVN10__cxxabiv120__si_class_type_infoE";
2506 // abi::__vmi_class_type_info.
2507 static const char * const VMIClassTypeInfo =
2508 "_ZTVN10__cxxabiv121__vmi_class_type_infoE";
2509
2510 const char *VTableName = nullptr;
2511
2512 switch (Ty->getTypeClass()) {
2513#define TYPE(Class, Base)
2514#define ABSTRACT_TYPE(Class, Base)
2515#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2516#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2517#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2518#include "clang/AST/TypeNodes.def"
2519 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
2520
2521 case Type::LValueReference:
2522 case Type::RValueReference:
2523 llvm_unreachable("References shouldn't get here");
2524
2525 case Type::Auto:
2526 llvm_unreachable("Undeduced auto type shouldn't get here");
2527
2528 case Type::Builtin:
2529 // GCC treats vector and complex types as fundamental types.
2530 case Type::Vector:
2531 case Type::ExtVector:
2532 case Type::Complex:
2533 case Type::Atomic:
2534 // FIXME: GCC treats block pointers as fundamental types?!
2535 case Type::BlockPointer:
2536 // abi::__fundamental_type_info.
2537 VTableName = "_ZTVN10__cxxabiv123__fundamental_type_infoE";
2538 break;
2539
2540 case Type::ConstantArray:
2541 case Type::IncompleteArray:
2542 case Type::VariableArray:
2543 // abi::__array_type_info.
2544 VTableName = "_ZTVN10__cxxabiv117__array_type_infoE";
2545 break;
2546
2547 case Type::FunctionNoProto:
2548 case Type::FunctionProto:
2549 // abi::__function_type_info.
2550 VTableName = "_ZTVN10__cxxabiv120__function_type_infoE";
2551 break;
2552
2553 case Type::Enum:
2554 // abi::__enum_type_info.
2555 VTableName = "_ZTVN10__cxxabiv116__enum_type_infoE";
2556 break;
2557
2558 case Type::Record: {
2559 const CXXRecordDecl *RD =
2560 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
2561
2562 if (!RD->hasDefinition() || !RD->getNumBases()) {
2563 VTableName = ClassTypeInfo;
2564 } else if (CanUseSingleInheritance(RD)) {
2565 VTableName = SIClassTypeInfo;
2566 } else {
2567 VTableName = VMIClassTypeInfo;
2568 }
2569
2570 break;
2571 }
2572
2573 case Type::ObjCObject:
2574 // Ignore protocol qualifiers.
2575 Ty = cast<ObjCObjectType>(Ty)->getBaseType().getTypePtr();
2576
2577 // Handle id and Class.
2578 if (isa<BuiltinType>(Ty)) {
2579 VTableName = ClassTypeInfo;
2580 break;
2581 }
2582
2583 assert(isa<ObjCInterfaceType>(Ty));
2584 // Fall through.
2585
2586 case Type::ObjCInterface:
2587 if (cast<ObjCInterfaceType>(Ty)->getDecl()->getSuperClass()) {
2588 VTableName = SIClassTypeInfo;
2589 } else {
2590 VTableName = ClassTypeInfo;
2591 }
2592 break;
2593
2594 case Type::ObjCObjectPointer:
2595 case Type::Pointer:
2596 // abi::__pointer_type_info.
2597 VTableName = "_ZTVN10__cxxabiv119__pointer_type_infoE";
2598 break;
2599
2600 case Type::MemberPointer:
2601 // abi::__pointer_to_member_type_info.
2602 VTableName = "_ZTVN10__cxxabiv129__pointer_to_member_type_infoE";
2603 break;
2604 }
2605
2606 llvm::Constant *VTable =
2607 CGM.getModule().getOrInsertGlobal(VTableName, CGM.Int8PtrTy);
2608
2609 llvm::Type *PtrDiffTy =
2610 CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
2611
2612 // The vtable address point is 2.
2613 llvm::Constant *Two = llvm::ConstantInt::get(PtrDiffTy, 2);
David Blaikiee3b172a2015-04-02 18:55:21 +00002614 VTable =
2615 llvm::ConstantExpr::getInBoundsGetElementPtr(CGM.Int8PtrTy, VTable, Two);
David Majnemere2cb8d12014-07-07 06:20:47 +00002616 VTable = llvm::ConstantExpr::getBitCast(VTable, CGM.Int8PtrTy);
2617
2618 Fields.push_back(VTable);
2619}
2620
2621/// \brief Return the linkage that the type info and type info name constants
2622/// should have for the given type.
2623static llvm::GlobalVariable::LinkageTypes getTypeInfoLinkage(CodeGenModule &CGM,
2624 QualType Ty) {
2625 // Itanium C++ ABI 2.9.5p7:
2626 // In addition, it and all of the intermediate abi::__pointer_type_info
2627 // structs in the chain down to the abi::__class_type_info for the
2628 // incomplete class type must be prevented from resolving to the
2629 // corresponding type_info structs for the complete class type, possibly
2630 // by making them local static objects. Finally, a dummy class RTTI is
2631 // generated for the incomplete type that will not resolve to the final
2632 // complete class RTTI (because the latter need not exist), possibly by
2633 // making it a local static object.
2634 if (ContainsIncompleteClassType(Ty))
2635 return llvm::GlobalValue::InternalLinkage;
2636
2637 switch (Ty->getLinkage()) {
2638 case NoLinkage:
2639 case InternalLinkage:
2640 case UniqueExternalLinkage:
2641 return llvm::GlobalValue::InternalLinkage;
2642
2643 case VisibleNoLinkage:
2644 case ExternalLinkage:
2645 if (!CGM.getLangOpts().RTTI) {
2646 // RTTI is not enabled, which means that this type info struct is going
2647 // to be used for exception handling. Give it linkonce_odr linkage.
2648 return llvm::GlobalValue::LinkOnceODRLinkage;
2649 }
2650
2651 if (const RecordType *Record = dyn_cast<RecordType>(Ty)) {
2652 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2653 if (RD->hasAttr<WeakAttr>())
2654 return llvm::GlobalValue::WeakODRLinkage;
2655 if (RD->isDynamicClass())
2656 return CGM.getVTableLinkage(RD);
2657 }
2658
2659 return llvm::GlobalValue::LinkOnceODRLinkage;
2660 }
2661
2662 llvm_unreachable("Invalid linkage!");
2663}
2664
2665llvm::Constant *ItaniumRTTIBuilder::BuildTypeInfo(QualType Ty, bool Force) {
2666 // We want to operate on the canonical type.
2667 Ty = CGM.getContext().getCanonicalType(Ty);
2668
2669 // Check if we've already emitted an RTTI descriptor for this type.
2670 SmallString<256> OutName;
2671 llvm::raw_svector_ostream Out(OutName);
2672 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
2673 Out.flush();
2674 StringRef Name = OutName.str();
2675
2676 llvm::GlobalVariable *OldGV = CGM.getModule().getNamedGlobal(Name);
2677 if (OldGV && !OldGV->isDeclaration()) {
2678 assert(!OldGV->hasAvailableExternallyLinkage() &&
2679 "available_externally typeinfos not yet implemented");
2680
2681 return llvm::ConstantExpr::getBitCast(OldGV, CGM.Int8PtrTy);
2682 }
2683
2684 // Check if there is already an external RTTI descriptor for this type.
2685 bool IsStdLib = IsStandardLibraryRTTIDescriptor(Ty);
2686 if (!Force && (IsStdLib || ShouldUseExternalRTTIDescriptor(CGM, Ty)))
2687 return GetAddrOfExternalRTTIDescriptor(Ty);
2688
2689 // Emit the standard library with external linkage.
2690 llvm::GlobalVariable::LinkageTypes Linkage;
2691 if (IsStdLib)
2692 Linkage = llvm::GlobalValue::ExternalLinkage;
2693 else
2694 Linkage = getTypeInfoLinkage(CGM, Ty);
2695
2696 // Add the vtable pointer.
2697 BuildVTablePointer(cast<Type>(Ty));
2698
2699 // And the name.
2700 llvm::GlobalVariable *TypeName = GetAddrOfTypeName(Ty, Linkage);
2701 llvm::Constant *TypeNameField;
2702
2703 // If we're supposed to demote the visibility, be sure to set a flag
2704 // to use a string comparison for type_info comparisons.
2705 ItaniumCXXABI::RTTIUniquenessKind RTTIUniqueness =
2706 CXXABI.classifyRTTIUniqueness(Ty, Linkage);
2707 if (RTTIUniqueness != ItaniumCXXABI::RUK_Unique) {
2708 // The flag is the sign bit, which on ARM64 is defined to be clear
2709 // for global pointers. This is very ARM64-specific.
2710 TypeNameField = llvm::ConstantExpr::getPtrToInt(TypeName, CGM.Int64Ty);
2711 llvm::Constant *flag =
2712 llvm::ConstantInt::get(CGM.Int64Ty, ((uint64_t)1) << 63);
2713 TypeNameField = llvm::ConstantExpr::getAdd(TypeNameField, flag);
2714 TypeNameField =
2715 llvm::ConstantExpr::getIntToPtr(TypeNameField, CGM.Int8PtrTy);
2716 } else {
2717 TypeNameField = llvm::ConstantExpr::getBitCast(TypeName, CGM.Int8PtrTy);
2718 }
2719 Fields.push_back(TypeNameField);
2720
2721 switch (Ty->getTypeClass()) {
2722#define TYPE(Class, Base)
2723#define ABSTRACT_TYPE(Class, Base)
2724#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2725#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2726#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2727#include "clang/AST/TypeNodes.def"
2728 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
2729
2730 // GCC treats vector types as fundamental types.
2731 case Type::Builtin:
2732 case Type::Vector:
2733 case Type::ExtVector:
2734 case Type::Complex:
2735 case Type::BlockPointer:
2736 // Itanium C++ ABI 2.9.5p4:
2737 // abi::__fundamental_type_info adds no data members to std::type_info.
2738 break;
2739
2740 case Type::LValueReference:
2741 case Type::RValueReference:
2742 llvm_unreachable("References shouldn't get here");
2743
2744 case Type::Auto:
2745 llvm_unreachable("Undeduced auto type shouldn't get here");
2746
2747 case Type::ConstantArray:
2748 case Type::IncompleteArray:
2749 case Type::VariableArray:
2750 // Itanium C++ ABI 2.9.5p5:
2751 // abi::__array_type_info adds no data members to std::type_info.
2752 break;
2753
2754 case Type::FunctionNoProto:
2755 case Type::FunctionProto:
2756 // Itanium C++ ABI 2.9.5p5:
2757 // abi::__function_type_info adds no data members to std::type_info.
2758 break;
2759
2760 case Type::Enum:
2761 // Itanium C++ ABI 2.9.5p5:
2762 // abi::__enum_type_info adds no data members to std::type_info.
2763 break;
2764
2765 case Type::Record: {
2766 const CXXRecordDecl *RD =
2767 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
2768 if (!RD->hasDefinition() || !RD->getNumBases()) {
2769 // We don't need to emit any fields.
2770 break;
2771 }
2772
2773 if (CanUseSingleInheritance(RD))
2774 BuildSIClassTypeInfo(RD);
2775 else
2776 BuildVMIClassTypeInfo(RD);
2777
2778 break;
2779 }
2780
2781 case Type::ObjCObject:
2782 case Type::ObjCInterface:
2783 BuildObjCObjectTypeInfo(cast<ObjCObjectType>(Ty));
2784 break;
2785
2786 case Type::ObjCObjectPointer:
2787 BuildPointerTypeInfo(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
2788 break;
2789
2790 case Type::Pointer:
2791 BuildPointerTypeInfo(cast<PointerType>(Ty)->getPointeeType());
2792 break;
2793
2794 case Type::MemberPointer:
2795 BuildPointerToMemberTypeInfo(cast<MemberPointerType>(Ty));
2796 break;
2797
2798 case Type::Atomic:
2799 // No fields, at least for the moment.
2800 break;
2801 }
2802
2803 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Fields);
2804
Rafael Espindolacb92c192015-01-15 23:18:01 +00002805 llvm::Module &M = CGM.getModule();
David Majnemere2cb8d12014-07-07 06:20:47 +00002806 llvm::GlobalVariable *GV =
Rafael Espindolacb92c192015-01-15 23:18:01 +00002807 new llvm::GlobalVariable(M, Init->getType(),
2808 /*Constant=*/true, Linkage, Init, Name);
2809
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00002810 if (CGM.supportsCOMDAT() && GV->isWeakForLinker())
2811 GV->setComdat(M.getOrInsertComdat(GV->getName()));
David Majnemere2cb8d12014-07-07 06:20:47 +00002812
2813 // If there's already an old global variable, replace it with the new one.
2814 if (OldGV) {
2815 GV->takeName(OldGV);
2816 llvm::Constant *NewPtr =
2817 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
2818 OldGV->replaceAllUsesWith(NewPtr);
2819 OldGV->eraseFromParent();
2820 }
2821
2822 // The Itanium ABI specifies that type_info objects must be globally
2823 // unique, with one exception: if the type is an incomplete class
2824 // type or a (possibly indirect) pointer to one. That exception
2825 // affects the general case of comparing type_info objects produced
2826 // by the typeid operator, which is why the comparison operators on
2827 // std::type_info generally use the type_info name pointers instead
2828 // of the object addresses. However, the language's built-in uses
2829 // of RTTI generally require class types to be complete, even when
2830 // manipulating pointers to those class types. This allows the
2831 // implementation of dynamic_cast to rely on address equality tests,
2832 // which is much faster.
2833
2834 // All of this is to say that it's important that both the type_info
2835 // object and the type_info name be uniqued when weakly emitted.
2836
2837 // Give the type_info object and name the formal visibility of the
2838 // type itself.
2839 llvm::GlobalValue::VisibilityTypes llvmVisibility;
2840 if (llvm::GlobalValue::isLocalLinkage(Linkage))
2841 // If the linkage is local, only default visibility makes sense.
2842 llvmVisibility = llvm::GlobalValue::DefaultVisibility;
2843 else if (RTTIUniqueness == ItaniumCXXABI::RUK_NonUniqueHidden)
2844 llvmVisibility = llvm::GlobalValue::HiddenVisibility;
2845 else
2846 llvmVisibility = CodeGenModule::GetLLVMVisibility(Ty->getVisibility());
2847 TypeName->setVisibility(llvmVisibility);
2848 GV->setVisibility(llvmVisibility);
2849
2850 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
2851}
2852
2853/// ComputeQualifierFlags - Compute the pointer type info flags from the
2854/// given qualifier.
2855static unsigned ComputeQualifierFlags(Qualifiers Quals) {
2856 unsigned Flags = 0;
2857
2858 if (Quals.hasConst())
2859 Flags |= ItaniumRTTIBuilder::PTI_Const;
2860 if (Quals.hasVolatile())
2861 Flags |= ItaniumRTTIBuilder::PTI_Volatile;
2862 if (Quals.hasRestrict())
2863 Flags |= ItaniumRTTIBuilder::PTI_Restrict;
2864
2865 return Flags;
2866}
2867
2868/// BuildObjCObjectTypeInfo - Build the appropriate kind of type_info
2869/// for the given Objective-C object type.
2870void ItaniumRTTIBuilder::BuildObjCObjectTypeInfo(const ObjCObjectType *OT) {
2871 // Drop qualifiers.
2872 const Type *T = OT->getBaseType().getTypePtr();
2873 assert(isa<BuiltinType>(T) || isa<ObjCInterfaceType>(T));
2874
2875 // The builtin types are abi::__class_type_infos and don't require
2876 // extra fields.
2877 if (isa<BuiltinType>(T)) return;
2878
2879 ObjCInterfaceDecl *Class = cast<ObjCInterfaceType>(T)->getDecl();
2880 ObjCInterfaceDecl *Super = Class->getSuperClass();
2881
2882 // Root classes are also __class_type_info.
2883 if (!Super) return;
2884
2885 QualType SuperTy = CGM.getContext().getObjCInterfaceType(Super);
2886
2887 // Everything else is single inheritance.
2888 llvm::Constant *BaseTypeInfo =
2889 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(SuperTy);
2890 Fields.push_back(BaseTypeInfo);
2891}
2892
2893/// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
2894/// inheritance, according to the Itanium C++ ABI, 2.95p6b.
2895void ItaniumRTTIBuilder::BuildSIClassTypeInfo(const CXXRecordDecl *RD) {
2896 // Itanium C++ ABI 2.9.5p6b:
2897 // It adds to abi::__class_type_info a single member pointing to the
2898 // type_info structure for the base type,
2899 llvm::Constant *BaseTypeInfo =
2900 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(RD->bases_begin()->getType());
2901 Fields.push_back(BaseTypeInfo);
2902}
2903
2904namespace {
2905 /// SeenBases - Contains virtual and non-virtual bases seen when traversing
2906 /// a class hierarchy.
2907 struct SeenBases {
2908 llvm::SmallPtrSet<const CXXRecordDecl *, 16> NonVirtualBases;
2909 llvm::SmallPtrSet<const CXXRecordDecl *, 16> VirtualBases;
2910 };
2911}
2912
2913/// ComputeVMIClassTypeInfoFlags - Compute the value of the flags member in
2914/// abi::__vmi_class_type_info.
2915///
2916static unsigned ComputeVMIClassTypeInfoFlags(const CXXBaseSpecifier *Base,
2917 SeenBases &Bases) {
2918
2919 unsigned Flags = 0;
2920
2921 const CXXRecordDecl *BaseDecl =
2922 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2923
2924 if (Base->isVirtual()) {
2925 // Mark the virtual base as seen.
David Blaikie82e95a32014-11-19 07:49:47 +00002926 if (!Bases.VirtualBases.insert(BaseDecl).second) {
David Majnemere2cb8d12014-07-07 06:20:47 +00002927 // If this virtual base has been seen before, then the class is diamond
2928 // shaped.
2929 Flags |= ItaniumRTTIBuilder::VMI_DiamondShaped;
2930 } else {
2931 if (Bases.NonVirtualBases.count(BaseDecl))
2932 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
2933 }
2934 } else {
2935 // Mark the non-virtual base as seen.
David Blaikie82e95a32014-11-19 07:49:47 +00002936 if (!Bases.NonVirtualBases.insert(BaseDecl).second) {
David Majnemere2cb8d12014-07-07 06:20:47 +00002937 // If this non-virtual base has been seen before, then the class has non-
2938 // diamond shaped repeated inheritance.
2939 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
2940 } else {
2941 if (Bases.VirtualBases.count(BaseDecl))
2942 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
2943 }
2944 }
2945
2946 // Walk all bases.
2947 for (const auto &I : BaseDecl->bases())
2948 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
2949
2950 return Flags;
2951}
2952
2953static unsigned ComputeVMIClassTypeInfoFlags(const CXXRecordDecl *RD) {
2954 unsigned Flags = 0;
2955 SeenBases Bases;
2956
2957 // Walk all bases.
2958 for (const auto &I : RD->bases())
2959 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
2960
2961 return Flags;
2962}
2963
2964/// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
2965/// classes with bases that do not satisfy the abi::__si_class_type_info
2966/// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
2967void ItaniumRTTIBuilder::BuildVMIClassTypeInfo(const CXXRecordDecl *RD) {
2968 llvm::Type *UnsignedIntLTy =
2969 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
2970
2971 // Itanium C++ ABI 2.9.5p6c:
2972 // __flags is a word with flags describing details about the class
2973 // structure, which may be referenced by using the __flags_masks
2974 // enumeration. These flags refer to both direct and indirect bases.
2975 unsigned Flags = ComputeVMIClassTypeInfoFlags(RD);
2976 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
2977
2978 // Itanium C++ ABI 2.9.5p6c:
2979 // __base_count is a word with the number of direct proper base class
2980 // descriptions that follow.
2981 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, RD->getNumBases()));
2982
2983 if (!RD->getNumBases())
2984 return;
2985
2986 llvm::Type *LongLTy =
2987 CGM.getTypes().ConvertType(CGM.getContext().LongTy);
2988
2989 // Now add the base class descriptions.
2990
2991 // Itanium C++ ABI 2.9.5p6c:
2992 // __base_info[] is an array of base class descriptions -- one for every
2993 // direct proper base. Each description is of the type:
2994 //
2995 // struct abi::__base_class_type_info {
2996 // public:
2997 // const __class_type_info *__base_type;
2998 // long __offset_flags;
2999 //
3000 // enum __offset_flags_masks {
3001 // __virtual_mask = 0x1,
3002 // __public_mask = 0x2,
3003 // __offset_shift = 8
3004 // };
3005 // };
3006 for (const auto &Base : RD->bases()) {
3007 // The __base_type member points to the RTTI for the base type.
3008 Fields.push_back(ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(Base.getType()));
3009
3010 const CXXRecordDecl *BaseDecl =
3011 cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
3012
3013 int64_t OffsetFlags = 0;
3014
3015 // All but the lower 8 bits of __offset_flags are a signed offset.
3016 // For a non-virtual base, this is the offset in the object of the base
3017 // subobject. For a virtual base, this is the offset in the virtual table of
3018 // the virtual base offset for the virtual base referenced (negative).
3019 CharUnits Offset;
3020 if (Base.isVirtual())
3021 Offset =
3022 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(RD, BaseDecl);
3023 else {
3024 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
3025 Offset = Layout.getBaseClassOffset(BaseDecl);
3026 };
3027
3028 OffsetFlags = uint64_t(Offset.getQuantity()) << 8;
3029
3030 // The low-order byte of __offset_flags contains flags, as given by the
3031 // masks from the enumeration __offset_flags_masks.
3032 if (Base.isVirtual())
3033 OffsetFlags |= BCTI_Virtual;
3034 if (Base.getAccessSpecifier() == AS_public)
3035 OffsetFlags |= BCTI_Public;
3036
3037 Fields.push_back(llvm::ConstantInt::get(LongLTy, OffsetFlags));
3038 }
3039}
3040
3041/// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct,
3042/// used for pointer types.
3043void ItaniumRTTIBuilder::BuildPointerTypeInfo(QualType PointeeTy) {
3044 Qualifiers Quals;
3045 QualType UnqualifiedPointeeTy =
3046 CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals);
3047
3048 // Itanium C++ ABI 2.9.5p7:
3049 // __flags is a flag word describing the cv-qualification and other
3050 // attributes of the type pointed to
3051 unsigned Flags = ComputeQualifierFlags(Quals);
3052
3053 // Itanium C++ ABI 2.9.5p7:
3054 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
3055 // incomplete class type, the incomplete target type flag is set.
3056 if (ContainsIncompleteClassType(UnqualifiedPointeeTy))
3057 Flags |= PTI_Incomplete;
3058
3059 llvm::Type *UnsignedIntLTy =
3060 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3061 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3062
3063 // Itanium C++ ABI 2.9.5p7:
3064 // __pointee is a pointer to the std::type_info derivation for the
3065 // unqualified type being pointed to.
3066 llvm::Constant *PointeeTypeInfo =
3067 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(UnqualifiedPointeeTy);
3068 Fields.push_back(PointeeTypeInfo);
3069}
3070
3071/// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
3072/// struct, used for member pointer types.
3073void
3074ItaniumRTTIBuilder::BuildPointerToMemberTypeInfo(const MemberPointerType *Ty) {
3075 QualType PointeeTy = Ty->getPointeeType();
3076
3077 Qualifiers Quals;
3078 QualType UnqualifiedPointeeTy =
3079 CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals);
3080
3081 // Itanium C++ ABI 2.9.5p7:
3082 // __flags is a flag word describing the cv-qualification and other
3083 // attributes of the type pointed to.
3084 unsigned Flags = ComputeQualifierFlags(Quals);
3085
3086 const RecordType *ClassType = cast<RecordType>(Ty->getClass());
3087
3088 // Itanium C++ ABI 2.9.5p7:
3089 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
3090 // incomplete class type, the incomplete target type flag is set.
3091 if (ContainsIncompleteClassType(UnqualifiedPointeeTy))
3092 Flags |= PTI_Incomplete;
3093
3094 if (IsIncompleteClassType(ClassType))
3095 Flags |= PTI_ContainingClassIncomplete;
3096
3097 llvm::Type *UnsignedIntLTy =
3098 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3099 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3100
3101 // Itanium C++ ABI 2.9.5p7:
3102 // __pointee is a pointer to the std::type_info derivation for the
3103 // unqualified type being pointed to.
3104 llvm::Constant *PointeeTypeInfo =
3105 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(UnqualifiedPointeeTy);
3106 Fields.push_back(PointeeTypeInfo);
3107
3108 // Itanium C++ ABI 2.9.5p9:
3109 // __context is a pointer to an abi::__class_type_info corresponding to the
3110 // class type containing the member pointed to
3111 // (e.g., the "A" in "int A::*").
3112 Fields.push_back(
3113 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(QualType(ClassType, 0)));
3114}
3115
David Majnemer443250f2015-03-17 20:35:00 +00003116llvm::Constant *ItaniumCXXABI::getAddrOfRTTIDescriptor(QualType Ty) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003117 return ItaniumRTTIBuilder(*this).BuildTypeInfo(Ty);
3118}
3119
3120void ItaniumCXXABI::EmitFundamentalRTTIDescriptor(QualType Type) {
3121 QualType PointerType = getContext().getPointerType(Type);
3122 QualType PointerTypeConst = getContext().getPointerType(Type.withConst());
3123 ItaniumRTTIBuilder(*this).BuildTypeInfo(Type, true);
3124 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerType, true);
3125 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerTypeConst, true);
3126}
3127
3128void ItaniumCXXABI::EmitFundamentalRTTIDescriptors() {
3129 QualType FundamentalTypes[] = {
3130 getContext().VoidTy, getContext().NullPtrTy,
3131 getContext().BoolTy, getContext().WCharTy,
3132 getContext().CharTy, getContext().UnsignedCharTy,
3133 getContext().SignedCharTy, getContext().ShortTy,
3134 getContext().UnsignedShortTy, getContext().IntTy,
3135 getContext().UnsignedIntTy, getContext().LongTy,
3136 getContext().UnsignedLongTy, getContext().LongLongTy,
3137 getContext().UnsignedLongLongTy, getContext().HalfTy,
3138 getContext().FloatTy, getContext().DoubleTy,
3139 getContext().LongDoubleTy, getContext().Char16Ty,
3140 getContext().Char32Ty,
3141 };
3142 for (const QualType &FundamentalType : FundamentalTypes)
3143 EmitFundamentalRTTIDescriptor(FundamentalType);
3144}
3145
3146/// What sort of uniqueness rules should we use for the RTTI for the
3147/// given type?
3148ItaniumCXXABI::RTTIUniquenessKind ItaniumCXXABI::classifyRTTIUniqueness(
3149 QualType CanTy, llvm::GlobalValue::LinkageTypes Linkage) const {
3150 if (shouldRTTIBeUnique())
3151 return RUK_Unique;
3152
3153 // It's only necessary for linkonce_odr or weak_odr linkage.
3154 if (Linkage != llvm::GlobalValue::LinkOnceODRLinkage &&
3155 Linkage != llvm::GlobalValue::WeakODRLinkage)
3156 return RUK_Unique;
3157
3158 // It's only necessary with default visibility.
3159 if (CanTy->getVisibility() != DefaultVisibility)
3160 return RUK_Unique;
3161
3162 // If we're not required to publish this symbol, hide it.
3163 if (Linkage == llvm::GlobalValue::LinkOnceODRLinkage)
3164 return RUK_NonUniqueHidden;
3165
3166 // If we're required to publish this symbol, as we might be under an
3167 // explicit instantiation, leave it with default visibility but
3168 // enable string-comparisons.
3169 assert(Linkage == llvm::GlobalValue::WeakODRLinkage);
3170 return RUK_NonUniqueVisible;
3171}
Rafael Espindola91f68b42014-09-15 19:20:10 +00003172
Rafael Espindola1e4df922014-09-16 15:18:21 +00003173// Find out how to codegen the complete destructor and constructor
3174namespace {
3175enum class StructorCodegen { Emit, RAUW, Alias, COMDAT };
3176}
3177static StructorCodegen getCodegenToUse(CodeGenModule &CGM,
3178 const CXXMethodDecl *MD) {
3179 if (!CGM.getCodeGenOpts().CXXCtorDtorAliases)
3180 return StructorCodegen::Emit;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003181
Rafael Espindola1e4df922014-09-16 15:18:21 +00003182 // The complete and base structors are not equivalent if there are any virtual
3183 // bases, so emit separate functions.
3184 if (MD->getParent()->getNumVBases())
3185 return StructorCodegen::Emit;
3186
3187 GlobalDecl AliasDecl;
3188 if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) {
3189 AliasDecl = GlobalDecl(DD, Dtor_Complete);
3190 } else {
3191 const auto *CD = cast<CXXConstructorDecl>(MD);
3192 AliasDecl = GlobalDecl(CD, Ctor_Complete);
3193 }
3194 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3195
3196 if (llvm::GlobalValue::isDiscardableIfUnused(Linkage))
3197 return StructorCodegen::RAUW;
3198
3199 // FIXME: Should we allow available_externally aliases?
3200 if (!llvm::GlobalAlias::isValidLinkage(Linkage))
3201 return StructorCodegen::RAUW;
3202
Rafael Espindola0806f982014-09-16 20:19:43 +00003203 if (llvm::GlobalValue::isWeakForLinker(Linkage)) {
3204 // Only ELF supports COMDATs with arbitrary names (C5/D5).
3205 if (CGM.getTarget().getTriple().isOSBinFormatELF())
3206 return StructorCodegen::COMDAT;
3207 return StructorCodegen::Emit;
3208 }
Rafael Espindola1e4df922014-09-16 15:18:21 +00003209
3210 return StructorCodegen::Alias;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003211}
3212
Rafael Espindola1e4df922014-09-16 15:18:21 +00003213static void emitConstructorDestructorAlias(CodeGenModule &CGM,
3214 GlobalDecl AliasDecl,
3215 GlobalDecl TargetDecl) {
3216 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3217
3218 StringRef MangledName = CGM.getMangledName(AliasDecl);
3219 llvm::GlobalValue *Entry = CGM.GetGlobalValue(MangledName);
3220 if (Entry && !Entry->isDeclaration())
3221 return;
3222
3223 auto *Aliasee = cast<llvm::GlobalValue>(CGM.GetAddrOfGlobal(TargetDecl));
3224 llvm::PointerType *AliasType = Aliasee->getType();
3225
3226 // Create the alias with no name.
David Blaikie881b2342015-04-29 21:22:47 +00003227 auto *Alias = llvm::GlobalAlias::create(AliasType, Linkage, "", Aliasee,
3228 &CGM.getModule());
Rafael Espindola1e4df922014-09-16 15:18:21 +00003229
3230 // Switch any previous uses to the alias.
3231 if (Entry) {
3232 assert(Entry->getType() == AliasType &&
3233 "declaration exists with different type");
3234 Alias->takeName(Entry);
3235 Entry->replaceAllUsesWith(Alias);
3236 Entry->eraseFromParent();
3237 } else {
3238 Alias->setName(MangledName);
3239 }
3240
3241 // Finally, set up the alias with its proper name and attributes.
Dario Domiziolic4fb8ca72014-09-19 22:06:24 +00003242 CGM.setAliasAttributes(cast<NamedDecl>(AliasDecl.getDecl()), Alias);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003243}
3244
3245void ItaniumCXXABI::emitCXXStructor(const CXXMethodDecl *MD,
3246 StructorType Type) {
3247 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
3248 const CXXDestructorDecl *DD = CD ? nullptr : cast<CXXDestructorDecl>(MD);
3249
3250 StructorCodegen CGType = getCodegenToUse(CGM, MD);
3251
3252 if (Type == StructorType::Complete) {
3253 GlobalDecl CompleteDecl;
3254 GlobalDecl BaseDecl;
3255 if (CD) {
3256 CompleteDecl = GlobalDecl(CD, Ctor_Complete);
3257 BaseDecl = GlobalDecl(CD, Ctor_Base);
3258 } else {
3259 CompleteDecl = GlobalDecl(DD, Dtor_Complete);
3260 BaseDecl = GlobalDecl(DD, Dtor_Base);
3261 }
3262
3263 if (CGType == StructorCodegen::Alias || CGType == StructorCodegen::COMDAT) {
3264 emitConstructorDestructorAlias(CGM, CompleteDecl, BaseDecl);
3265 return;
3266 }
3267
3268 if (CGType == StructorCodegen::RAUW) {
3269 StringRef MangledName = CGM.getMangledName(CompleteDecl);
3270 auto *Aliasee = cast<llvm::GlobalValue>(CGM.GetAddrOfGlobal(BaseDecl));
3271 CGM.addReplacement(MangledName, Aliasee);
3272 return;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003273 }
3274 }
3275
3276 // The base destructor is equivalent to the base destructor of its
3277 // base class if there is exactly one non-virtual base class with a
3278 // non-trivial destructor, there are no fields with a non-trivial
3279 // destructor, and the body of the destructor is trivial.
Rafael Espindola1e4df922014-09-16 15:18:21 +00003280 if (DD && Type == StructorType::Base && CGType != StructorCodegen::COMDAT &&
3281 !CGM.TryEmitBaseDestructorAsAlias(DD))
Rafael Espindola91f68b42014-09-15 19:20:10 +00003282 return;
3283
Rafael Espindola1e4df922014-09-16 15:18:21 +00003284 llvm::Function *Fn = CGM.codegenCXXStructor(MD, Type);
Rafael Espindola91f68b42014-09-15 19:20:10 +00003285
Rafael Espindola1e4df922014-09-16 15:18:21 +00003286 if (CGType == StructorCodegen::COMDAT) {
3287 SmallString<256> Buffer;
3288 llvm::raw_svector_ostream Out(Buffer);
3289 if (DD)
3290 getMangleContext().mangleCXXDtorComdat(DD, Out);
3291 else
3292 getMangleContext().mangleCXXCtorComdat(CD, Out);
3293 llvm::Comdat *C = CGM.getModule().getOrInsertComdat(Out.str());
3294 Fn->setComdat(C);
Rafael Espindoladbee8a72015-01-15 21:36:08 +00003295 } else {
3296 CGM.maybeSetTrivialComdat(*MD, *Fn);
Rafael Espindola91f68b42014-09-15 19:20:10 +00003297 }
Rafael Espindola91f68b42014-09-15 19:20:10 +00003298}
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003299
3300static llvm::Constant *getBeginCatchFn(CodeGenModule &CGM) {
3301 // void *__cxa_begin_catch(void*);
3302 llvm::FunctionType *FTy = llvm::FunctionType::get(
3303 CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3304
3305 return CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
3306}
3307
3308static llvm::Constant *getEndCatchFn(CodeGenModule &CGM) {
3309 // void __cxa_end_catch();
3310 llvm::FunctionType *FTy =
3311 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
3312
3313 return CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
3314}
3315
3316static llvm::Constant *getGetExceptionPtrFn(CodeGenModule &CGM) {
3317 // void *__cxa_get_exception_ptr(void*);
3318 llvm::FunctionType *FTy = llvm::FunctionType::get(
3319 CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3320
3321 return CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
3322}
3323
3324namespace {
3325 /// A cleanup to call __cxa_end_catch. In many cases, the caught
3326 /// exception type lets us state definitively that the thrown exception
3327 /// type does not have a destructor. In particular:
3328 /// - Catch-alls tell us nothing, so we have to conservatively
3329 /// assume that the thrown exception might have a destructor.
3330 /// - Catches by reference behave according to their base types.
3331 /// - Catches of non-record types will only trigger for exceptions
3332 /// of non-record types, which never have destructors.
3333 /// - Catches of record types can trigger for arbitrary subclasses
3334 /// of the caught type, so we have to assume the actual thrown
3335 /// exception type might have a throwing destructor, even if the
3336 /// caught type's destructor is trivial or nothrow.
3337 struct CallEndCatch : EHScopeStack::Cleanup {
3338 CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
3339 bool MightThrow;
3340
3341 void Emit(CodeGenFunction &CGF, Flags flags) override {
3342 if (!MightThrow) {
3343 CGF.EmitNounwindRuntimeCall(getEndCatchFn(CGF.CGM));
3344 return;
3345 }
3346
3347 CGF.EmitRuntimeCallOrInvoke(getEndCatchFn(CGF.CGM));
3348 }
3349 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003350}
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003351
3352/// Emits a call to __cxa_begin_catch and enters a cleanup to call
3353/// __cxa_end_catch.
3354///
3355/// \param EndMightThrow - true if __cxa_end_catch might throw
3356static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
3357 llvm::Value *Exn,
3358 bool EndMightThrow) {
3359 llvm::CallInst *call =
3360 CGF.EmitNounwindRuntimeCall(getBeginCatchFn(CGF.CGM), Exn);
3361
3362 CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
3363
3364 return call;
3365}
3366
3367/// A "special initializer" callback for initializing a catch
3368/// parameter during catch initialization.
3369static void InitCatchParam(CodeGenFunction &CGF,
3370 const VarDecl &CatchParam,
3371 llvm::Value *ParamAddr,
3372 SourceLocation Loc) {
3373 // Load the exception from where the landing pad saved it.
3374 llvm::Value *Exn = CGF.getExceptionFromSlot();
3375
3376 CanQualType CatchType =
3377 CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
3378 llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
3379
3380 // If we're catching by reference, we can just cast the object
3381 // pointer to the appropriate pointer.
3382 if (isa<ReferenceType>(CatchType)) {
3383 QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
3384 bool EndCatchMightThrow = CaughtType->isRecordType();
3385
3386 // __cxa_begin_catch returns the adjusted object pointer.
3387 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
3388
3389 // We have no way to tell the personality function that we're
3390 // catching by reference, so if we're catching a pointer,
3391 // __cxa_begin_catch will actually return that pointer by value.
3392 if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
3393 QualType PointeeType = PT->getPointeeType();
3394
3395 // When catching by reference, generally we should just ignore
3396 // this by-value pointer and use the exception object instead.
3397 if (!PointeeType->isRecordType()) {
3398
3399 // Exn points to the struct _Unwind_Exception header, which
3400 // we have to skip past in order to reach the exception data.
3401 unsigned HeaderSize =
3402 CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
3403 AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
3404
3405 // However, if we're catching a pointer-to-record type that won't
3406 // work, because the personality function might have adjusted
3407 // the pointer. There's actually no way for us to fully satisfy
3408 // the language/ABI contract here: we can't use Exn because it
3409 // might have the wrong adjustment, but we can't use the by-value
3410 // pointer because it's off by a level of abstraction.
3411 //
3412 // The current solution is to dump the adjusted pointer into an
3413 // alloca, which breaks language semantics (because changing the
3414 // pointer doesn't change the exception) but at least works.
3415 // The better solution would be to filter out non-exact matches
3416 // and rethrow them, but this is tricky because the rethrow
3417 // really needs to be catchable by other sites at this landing
3418 // pad. The best solution is to fix the personality function.
3419 } else {
3420 // Pull the pointer for the reference type off.
3421 llvm::Type *PtrTy =
3422 cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
3423
3424 // Create the temporary and write the adjusted pointer into it.
3425 llvm::Value *ExnPtrTmp = CGF.CreateTempAlloca(PtrTy, "exn.byref.tmp");
3426 llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
3427 CGF.Builder.CreateStore(Casted, ExnPtrTmp);
3428
3429 // Bind the reference to the temporary.
3430 AdjustedExn = ExnPtrTmp;
3431 }
3432 }
3433
3434 llvm::Value *ExnCast =
3435 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
3436 CGF.Builder.CreateStore(ExnCast, ParamAddr);
3437 return;
3438 }
3439
3440 // Scalars and complexes.
3441 TypeEvaluationKind TEK = CGF.getEvaluationKind(CatchType);
3442 if (TEK != TEK_Aggregate) {
3443 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
3444
3445 // If the catch type is a pointer type, __cxa_begin_catch returns
3446 // the pointer by value.
3447 if (CatchType->hasPointerRepresentation()) {
3448 llvm::Value *CastExn =
3449 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
3450
3451 switch (CatchType.getQualifiers().getObjCLifetime()) {
3452 case Qualifiers::OCL_Strong:
3453 CastExn = CGF.EmitARCRetainNonBlock(CastExn);
3454 // fallthrough
3455
3456 case Qualifiers::OCL_None:
3457 case Qualifiers::OCL_ExplicitNone:
3458 case Qualifiers::OCL_Autoreleasing:
3459 CGF.Builder.CreateStore(CastExn, ParamAddr);
3460 return;
3461
3462 case Qualifiers::OCL_Weak:
3463 CGF.EmitARCInitWeak(ParamAddr, CastExn);
3464 return;
3465 }
3466 llvm_unreachable("bad ownership qualifier!");
3467 }
3468
3469 // Otherwise, it returns a pointer into the exception object.
3470
3471 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
3472 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
3473
3474 LValue srcLV = CGF.MakeNaturalAlignAddrLValue(Cast, CatchType);
3475 LValue destLV = CGF.MakeAddrLValue(ParamAddr, CatchType,
3476 CGF.getContext().getDeclAlign(&CatchParam));
3477 switch (TEK) {
3478 case TEK_Complex:
3479 CGF.EmitStoreOfComplex(CGF.EmitLoadOfComplex(srcLV, Loc), destLV,
3480 /*init*/ true);
3481 return;
3482 case TEK_Scalar: {
3483 llvm::Value *ExnLoad = CGF.EmitLoadOfScalar(srcLV, Loc);
3484 CGF.EmitStoreOfScalar(ExnLoad, destLV, /*init*/ true);
3485 return;
3486 }
3487 case TEK_Aggregate:
3488 llvm_unreachable("evaluation kind filtered out!");
3489 }
3490 llvm_unreachable("bad evaluation kind");
3491 }
3492
3493 assert(isa<RecordType>(CatchType) && "unexpected catch type!");
3494
3495 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
3496
3497 // Check for a copy expression. If we don't have a copy expression,
3498 // that means a trivial copy is okay.
3499 const Expr *copyExpr = CatchParam.getInit();
3500 if (!copyExpr) {
3501 llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true);
3502 llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
3503 CGF.EmitAggregateCopy(ParamAddr, adjustedExn, CatchType);
3504 return;
3505 }
3506
3507 // We have to call __cxa_get_exception_ptr to get the adjusted
3508 // pointer before copying.
3509 llvm::CallInst *rawAdjustedExn =
3510 CGF.EmitNounwindRuntimeCall(getGetExceptionPtrFn(CGF.CGM), Exn);
3511
3512 // Cast that to the appropriate type.
3513 llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
3514
3515 // The copy expression is defined in terms of an OpaqueValueExpr.
3516 // Find it and map it to the adjusted expression.
3517 CodeGenFunction::OpaqueValueMapping
3518 opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr),
3519 CGF.MakeAddrLValue(adjustedExn, CatchParam.getType()));
3520
3521 // Call the copy ctor in a terminate scope.
3522 CGF.EHStack.pushTerminate();
3523
3524 // Perform the copy construction.
3525 CharUnits Alignment = CGF.getContext().getDeclAlign(&CatchParam);
3526 CGF.EmitAggExpr(copyExpr,
3527 AggValueSlot::forAddr(ParamAddr, Alignment, Qualifiers(),
3528 AggValueSlot::IsNotDestructed,
3529 AggValueSlot::DoesNotNeedGCBarriers,
3530 AggValueSlot::IsNotAliased));
3531
3532 // Leave the terminate scope.
3533 CGF.EHStack.popTerminate();
3534
3535 // Undo the opaque value mapping.
3536 opaque.pop();
3537
3538 // Finally we can call __cxa_begin_catch.
3539 CallBeginCatch(CGF, Exn, true);
3540}
3541
3542/// Begins a catch statement by initializing the catch variable and
3543/// calling __cxa_begin_catch.
3544void ItaniumCXXABI::emitBeginCatch(CodeGenFunction &CGF,
3545 const CXXCatchStmt *S) {
3546 // We have to be very careful with the ordering of cleanups here:
3547 // C++ [except.throw]p4:
3548 // The destruction [of the exception temporary] occurs
3549 // immediately after the destruction of the object declared in
3550 // the exception-declaration in the handler.
3551 //
3552 // So the precise ordering is:
3553 // 1. Construct catch variable.
3554 // 2. __cxa_begin_catch
3555 // 3. Enter __cxa_end_catch cleanup
3556 // 4. Enter dtor cleanup
3557 //
3558 // We do this by using a slightly abnormal initialization process.
3559 // Delegation sequence:
3560 // - ExitCXXTryStmt opens a RunCleanupsScope
3561 // - EmitAutoVarAlloca creates the variable and debug info
3562 // - InitCatchParam initializes the variable from the exception
3563 // - CallBeginCatch calls __cxa_begin_catch
3564 // - CallBeginCatch enters the __cxa_end_catch cleanup
3565 // - EmitAutoVarCleanups enters the variable destructor cleanup
3566 // - EmitCXXTryStmt emits the code for the catch body
3567 // - EmitCXXTryStmt close the RunCleanupsScope
3568
3569 VarDecl *CatchParam = S->getExceptionDecl();
3570 if (!CatchParam) {
3571 llvm::Value *Exn = CGF.getExceptionFromSlot();
3572 CallBeginCatch(CGF, Exn, true);
3573 return;
3574 }
3575
3576 // Emit the local.
3577 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
3578 InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF), S->getLocStart());
3579 CGF.EmitAutoVarCleanups(var);
3580}
3581
3582/// Get or define the following function:
3583/// void @__clang_call_terminate(i8* %exn) nounwind noreturn
3584/// This code is used only in C++.
3585static llvm::Constant *getClangCallTerminateFn(CodeGenModule &CGM) {
3586 llvm::FunctionType *fnTy =
3587 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3588 llvm::Constant *fnRef =
3589 CGM.CreateRuntimeFunction(fnTy, "__clang_call_terminate");
3590
3591 llvm::Function *fn = dyn_cast<llvm::Function>(fnRef);
3592 if (fn && fn->empty()) {
3593 fn->setDoesNotThrow();
3594 fn->setDoesNotReturn();
3595
3596 // What we really want is to massively penalize inlining without
3597 // forbidding it completely. The difference between that and
3598 // 'noinline' is negligible.
3599 fn->addFnAttr(llvm::Attribute::NoInline);
3600
3601 // Allow this function to be shared across translation units, but
3602 // we don't want it to turn into an exported symbol.
3603 fn->setLinkage(llvm::Function::LinkOnceODRLinkage);
3604 fn->setVisibility(llvm::Function::HiddenVisibility);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00003605 if (CGM.supportsCOMDAT())
3606 fn->setComdat(CGM.getModule().getOrInsertComdat(fn->getName()));
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003607
3608 // Set up the function.
3609 llvm::BasicBlock *entry =
3610 llvm::BasicBlock::Create(CGM.getLLVMContext(), "", fn);
3611 CGBuilderTy builder(entry);
3612
3613 // Pull the exception pointer out of the parameter list.
3614 llvm::Value *exn = &*fn->arg_begin();
3615
3616 // Call __cxa_begin_catch(exn).
3617 llvm::CallInst *catchCall = builder.CreateCall(getBeginCatchFn(CGM), exn);
3618 catchCall->setDoesNotThrow();
3619 catchCall->setCallingConv(CGM.getRuntimeCC());
3620
3621 // Call std::terminate().
David Blaikie43f9bb72015-05-18 22:14:03 +00003622 llvm::CallInst *termCall = builder.CreateCall(CGM.getTerminateFn(), {});
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003623 termCall->setDoesNotThrow();
3624 termCall->setDoesNotReturn();
3625 termCall->setCallingConv(CGM.getRuntimeCC());
3626
3627 // std::terminate cannot return.
3628 builder.CreateUnreachable();
3629 }
3630
3631 return fnRef;
3632}
3633
3634llvm::CallInst *
3635ItaniumCXXABI::emitTerminateForUnexpectedException(CodeGenFunction &CGF,
3636 llvm::Value *Exn) {
3637 // In C++, we want to call __cxa_begin_catch() before terminating.
3638 if (Exn) {
3639 assert(CGF.CGM.getLangOpts().CPlusPlus);
3640 return CGF.EmitNounwindRuntimeCall(getClangCallTerminateFn(CGF.CGM), Exn);
3641 }
3642 return CGF.EmitNounwindRuntimeCall(CGF.CGM.getTerminateFn());
3643}