blob: d91eb43ca32227de4769ae7ba1e204d9216c7421 [file] [log] [blame]
Daniel Dunbar303e2c22008-08-11 02:45:11 +00001//===------- CGObjCMac.cpp - Interface to Apple Objective-C Runtime -------===//
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 Objective-C code generation targeting the Apple runtime.
Daniel Dunbar303e2c22008-08-11 02:45:11 +000011//
12//===----------------------------------------------------------------------===//
13
John McCallad7c5c12011-02-08 08:22:06 +000014#include "CGBlocks.h"
John McCalled1ae862011-01-28 11:13:47 +000015#include "CGCleanup.h"
Justin Lebar5e83dfe2016-10-21 21:45:01 +000016#include "CGObjCRuntime.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000017#include "CGRecordLayout.h"
18#include "CodeGenFunction.h"
19#include "CodeGenModule.h"
John McCall5ad74072017-03-02 20:04:19 +000020#include "clang/CodeGen/ConstantInitBuilder.h"
Daniel Dunbar8b8683f2008-08-12 00:12:39 +000021#include "clang/AST/ASTContext.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000022#include "clang/AST/Decl.h"
Daniel Dunbarb036db82008-08-13 03:21:16 +000023#include "clang/AST/DeclObjC.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000024#include "clang/AST/RecordLayout.h"
Chris Lattnerf0b64d72009-04-26 01:32:48 +000025#include "clang/AST/StmtObjC.h"
Richard Trieu63688182018-12-11 03:18:39 +000026#include "clang/Basic/CodeGenOptions.h"
Daniel Dunbar3ad53482008-08-11 21:35:06 +000027#include "clang/Basic/LangOptions.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000028#include "clang/CodeGen/CGFunctionInfo.h"
Justin Lebar5e83dfe2016-10-21 21:45:01 +000029#include "llvm/ADT/CachedHashString.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000030#include "llvm/ADT/DenseSet.h"
31#include "llvm/ADT/SetVector.h"
32#include "llvm/ADT/SmallPtrSet.h"
33#include "llvm/ADT/SmallString.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000034#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000035#include "llvm/IR/DataLayout.h"
36#include "llvm/IR/InlineAsm.h"
37#include "llvm/IR/IntrinsicInst.h"
38#include "llvm/IR/LLVMContext.h"
39#include "llvm/IR/Module.h"
Akira Hatanaka2ec36f02018-08-17 15:46:07 +000040#include "llvm/Support/ScopedPrinter.h"
Daniel Dunbard027a922009-09-07 00:20:42 +000041#include "llvm/Support/raw_ostream.h"
Torok Edwindb714922009-08-24 13:25:12 +000042#include <cstdio>
Daniel Dunbar303e2c22008-08-11 02:45:11 +000043
44using namespace clang;
Daniel Dunbar41cf9de2008-09-09 01:06:48 +000045using namespace CodeGen;
Daniel Dunbar303e2c22008-08-11 02:45:11 +000046
47namespace {
Daniel Dunbar8b8683f2008-08-12 00:12:39 +000048
Daniel Dunbar59e476b2009-08-03 17:06:42 +000049// FIXME: We should find a nicer way to make the labels for metadata, string
50// concatenation is lame.
Daniel Dunbarb036db82008-08-13 03:21:16 +000051
Fariborz Jahanian279eda62009-01-21 22:04:16 +000052class ObjCCommonTypesHelper {
Owen Anderson170229f2009-07-14 23:10:40 +000053protected:
54 llvm::LLVMContext &VMContext;
Daniel Dunbar59e476b2009-08-03 17:06:42 +000055
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +000056private:
John McCall9dc0db22011-05-15 01:53:33 +000057 // The types of these functions don't really matter because we
58 // should always bitcast before calling them.
59
60 /// id objc_msgSend (id, SEL, ...)
Fangrui Song6907ce22018-07-30 19:24:48 +000061 ///
John McCall9dc0db22011-05-15 01:53:33 +000062 /// The default messenger, used for sends whose ABI is unchanged from
63 /// the all-integer/pointer case.
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +000064 llvm::Constant *getMessageSendFn() const {
John McCall31168b02011-06-15 23:02:42 +000065 // Add the non-lazy-bind attribute, since objc_msgSend is likely to
66 // be called a lot.
Chris Lattnera5f58b02011-07-09 17:41:47 +000067 llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy };
Reid Klecknerde864822017-03-21 16:57:30 +000068 return CGM.CreateRuntimeFunction(
69 llvm::FunctionType::get(ObjectPtrTy, params, true), "objc_msgSend",
70 llvm::AttributeList::get(CGM.getLLVMContext(),
71 llvm::AttributeList::FunctionIndex,
72 llvm::Attribute::NonLazyBind));
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +000073 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +000074
John McCall9dc0db22011-05-15 01:53:33 +000075 /// void objc_msgSend_stret (id, SEL, ...)
76 ///
77 /// The messenger used when the return value is an aggregate returned
78 /// by indirect reference in the first argument, and therefore the
79 /// self and selector parameters are shifted over by one.
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +000080 llvm::Constant *getMessageSendStretFn() const {
Chris Lattnera5f58b02011-07-09 17:41:47 +000081 llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy };
John McCall9dc0db22011-05-15 01:53:33 +000082 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.VoidTy,
83 params, true),
84 "objc_msgSend_stret");
Daniel Dunbar59e476b2009-08-03 17:06:42 +000085
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +000086 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +000087
John McCall9dc0db22011-05-15 01:53:33 +000088 /// [double | long double] objc_msgSend_fpret(id self, SEL op, ...)
89 ///
90 /// The messenger used when the return value is returned on the x87
91 /// floating-point stack; without a special entrypoint, the nil case
92 /// would be unbalanced.
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +000093 llvm::Constant *getMessageSendFpretFn() const {
Chris Lattnera5f58b02011-07-09 17:41:47 +000094 llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy };
Chris Lattnerece04092012-02-07 00:39:47 +000095 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.DoubleTy,
96 params, true),
John McCall9dc0db22011-05-15 01:53:33 +000097 "objc_msgSend_fpret");
Daniel Dunbar59e476b2009-08-03 17:06:42 +000098
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +000099 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000100
Anders Carlsson2f1a6c32011-10-31 16:27:11 +0000101 /// _Complex long double objc_msgSend_fp2ret(id self, SEL op, ...)
102 ///
103 /// The messenger used when the return value is returned in two values on the
104 /// x87 floating point stack; without a special entrypoint, the nil case
105 /// would be unbalanced. Only used on 64-bit X86.
106 llvm::Constant *getMessageSendFp2retFn() const {
107 llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy };
108 llvm::Type *longDoubleType = llvm::Type::getX86_FP80Ty(VMContext);
Serge Guelton1d993272017-05-09 19:31:30 +0000109 llvm::Type *resultType =
110 llvm::StructType::get(longDoubleType, longDoubleType);
Anders Carlsson2f1a6c32011-10-31 16:27:11 +0000111
112 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(resultType,
113 params, true),
114 "objc_msgSend_fp2ret");
115 }
116
John McCall9dc0db22011-05-15 01:53:33 +0000117 /// id objc_msgSendSuper(struct objc_super *super, SEL op, ...)
118 ///
119 /// The messenger used for super calls, which have different dispatch
120 /// semantics. The class passed is the superclass of the current
121 /// class.
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +0000122 llvm::Constant *getMessageSendSuperFn() const {
Chris Lattnera5f58b02011-07-09 17:41:47 +0000123 llvm::Type *params[] = { SuperPtrTy, SelectorPtrTy };
Owen Anderson9793f0e2009-07-29 22:16:19 +0000124 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
John McCall9dc0db22011-05-15 01:53:33 +0000125 params, true),
126 "objc_msgSendSuper");
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +0000127 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000128
John McCall9dc0db22011-05-15 01:53:33 +0000129 /// id objc_msgSendSuper2(struct objc_super *super, SEL op, ...)
130 ///
131 /// A slightly different messenger used for super calls. The class
132 /// passed is the current class.
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +0000133 llvm::Constant *getMessageSendSuperFn2() const {
Chris Lattnera5f58b02011-07-09 17:41:47 +0000134 llvm::Type *params[] = { SuperPtrTy, SelectorPtrTy };
Owen Anderson9793f0e2009-07-29 22:16:19 +0000135 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
John McCall9dc0db22011-05-15 01:53:33 +0000136 params, true),
137 "objc_msgSendSuper2");
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +0000138 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000139
John McCall9dc0db22011-05-15 01:53:33 +0000140 /// void objc_msgSendSuper_stret(void *stretAddr, struct objc_super *super,
141 /// SEL op, ...)
142 ///
143 /// The messenger used for super calls which return an aggregate indirectly.
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +0000144 llvm::Constant *getMessageSendSuperStretFn() const {
Chris Lattnera5f58b02011-07-09 17:41:47 +0000145 llvm::Type *params[] = { Int8PtrTy, SuperPtrTy, SelectorPtrTy };
Owen Anderson170229f2009-07-14 23:10:40 +0000146 return CGM.CreateRuntimeFunction(
John McCall9dc0db22011-05-15 01:53:33 +0000147 llvm::FunctionType::get(CGM.VoidTy, params, true),
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000148 "objc_msgSendSuper_stret");
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +0000149 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000150
John McCall9dc0db22011-05-15 01:53:33 +0000151 /// void objc_msgSendSuper2_stret(void * stretAddr, struct objc_super *super,
152 /// SEL op, ...)
153 ///
154 /// objc_msgSendSuper_stret with the super2 semantics.
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +0000155 llvm::Constant *getMessageSendSuperStretFn2() const {
Chris Lattnera5f58b02011-07-09 17:41:47 +0000156 llvm::Type *params[] = { Int8PtrTy, SuperPtrTy, SelectorPtrTy };
Owen Anderson170229f2009-07-14 23:10:40 +0000157 return CGM.CreateRuntimeFunction(
John McCall9dc0db22011-05-15 01:53:33 +0000158 llvm::FunctionType::get(CGM.VoidTy, params, true),
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000159 "objc_msgSendSuper2_stret");
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +0000160 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000161
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +0000162 llvm::Constant *getMessageSendSuperFpretFn() const {
163 // There is no objc_msgSendSuper_fpret? How can that work?
164 return getMessageSendSuperFn();
165 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000166
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +0000167 llvm::Constant *getMessageSendSuperFpretFn2() const {
168 // There is no objc_msgSendSuper_fpret? How can that work?
169 return getMessageSendSuperFn2();
170 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000171
Fariborz Jahanian279eda62009-01-21 22:04:16 +0000172protected:
173 CodeGen::CodeGenModule &CGM;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000174
Daniel Dunbar8b8683f2008-08-12 00:12:39 +0000175public:
John McCall176f8922016-11-30 02:39:18 +0000176 llvm::IntegerType *ShortTy, *IntTy, *LongTy;
177 llvm::PointerType *Int8PtrTy, *Int8PtrPtrTy;
Tim Northover238b5082014-03-29 13:42:40 +0000178 llvm::Type *IvarOffsetVarTy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000179
Daniel Dunbar5d715592008-08-12 05:28:47 +0000180 /// ObjectPtrTy - LLVM type for object handles (typeof(id))
John McCall176f8922016-11-30 02:39:18 +0000181 llvm::PointerType *ObjectPtrTy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000182
Fariborz Jahanian406b1172008-11-18 20:18:11 +0000183 /// PtrObjectPtrTy - LLVM type for id *
John McCall176f8922016-11-30 02:39:18 +0000184 llvm::PointerType *PtrObjectPtrTy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000185
Daniel Dunbar7bd00bd2008-08-12 06:48:42 +0000186 /// SelectorPtrTy - LLVM type for selector handles (typeof(SEL))
John McCall176f8922016-11-30 02:39:18 +0000187 llvm::PointerType *SelectorPtrTy;
Fangrui Song6907ce22018-07-30 19:24:48 +0000188
Douglas Gregor020de322012-01-17 18:36:30 +0000189private:
Daniel Dunbarb036db82008-08-13 03:21:16 +0000190 /// ProtocolPtrTy - LLVM type for external protocol handles
191 /// (typeof(Protocol))
Chris Lattnera5f58b02011-07-09 17:41:47 +0000192 llvm::Type *ExternalProtocolPtrTy;
Fangrui Song6907ce22018-07-30 19:24:48 +0000193
Douglas Gregor020de322012-01-17 18:36:30 +0000194public:
195 llvm::Type *getExternalProtocolPtrTy() {
196 if (!ExternalProtocolPtrTy) {
197 // FIXME: It would be nice to unify this with the opaque type, so that the
198 // IR comes out a bit cleaner.
199 CodeGen::CodeGenTypes &Types = CGM.getTypes();
200 ASTContext &Ctx = CGM.getContext();
201 llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
202 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
203 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000204
Douglas Gregor020de322012-01-17 18:36:30 +0000205 return ExternalProtocolPtrTy;
206 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000207
Daniel Dunbarc722b852008-08-30 03:02:31 +0000208 // SuperCTy - clang type for struct objc_super.
209 QualType SuperCTy;
210 // SuperPtrCTy - clang type for struct objc_super *.
211 QualType SuperPtrCTy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000212
Daniel Dunbarf6397fe2008-08-23 04:28:29 +0000213 /// SuperTy - LLVM type for struct objc_super.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000214 llvm::StructType *SuperTy;
Daniel Dunbar97ff50d2008-08-23 09:25:55 +0000215 /// SuperPtrTy - LLVM type for struct objc_super *.
John McCall176f8922016-11-30 02:39:18 +0000216 llvm::PointerType *SuperPtrTy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000217
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +0000218 /// PropertyTy - LLVM type for struct objc_property (struct _prop_t
219 /// in GCC parlance).
Chris Lattnera5f58b02011-07-09 17:41:47 +0000220 llvm::StructType *PropertyTy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000221
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +0000222 /// PropertyListTy - LLVM type for struct objc_property_list
223 /// (_prop_list_t in GCC parlance).
Chris Lattnera5f58b02011-07-09 17:41:47 +0000224 llvm::StructType *PropertyListTy;
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +0000225 /// PropertyListPtrTy - LLVM type for struct objc_property_list*.
John McCall176f8922016-11-30 02:39:18 +0000226 llvm::PointerType *PropertyListPtrTy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000227
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +0000228 // MethodTy - LLVM type for struct objc_method.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000229 llvm::StructType *MethodTy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000230
Fariborz Jahanian0232c052009-01-23 01:46:23 +0000231 /// CacheTy - LLVM type for struct objc_cache.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000232 llvm::Type *CacheTy;
Fariborz Jahanian0232c052009-01-23 01:46:23 +0000233 /// CachePtrTy - LLVM type for struct objc_cache *.
John McCall176f8922016-11-30 02:39:18 +0000234 llvm::PointerType *CachePtrTy;
Fangrui Song6907ce22018-07-30 19:24:48 +0000235
Chris Lattnerce8754e2009-04-22 02:44:54 +0000236 llvm::Constant *getGetPropertyFn() {
237 CodeGen::CodeGenTypes &Types = CGM.getTypes();
238 ASTContext &Ctx = CGM.getContext();
239 // id objc_getProperty (id, SEL, ptrdiff_t, bool)
John McCall2da83a32010-02-26 00:48:12 +0000240 CanQualType IdType = Ctx.getCanonicalParamType(Ctx.getObjCIdType());
241 CanQualType SelType = Ctx.getCanonicalParamType(Ctx.getObjCSelType());
Benjamin Kramer30934732016-07-02 11:41:41 +0000242 CanQualType Params[] = {
243 IdType, SelType,
244 Ctx.getPointerDiffType()->getCanonicalTypeUnqualified(), Ctx.BoolTy};
Chris Lattner2192fe52011-07-18 04:24:23 +0000245 llvm::FunctionType *FTy =
John McCallc56a8b32016-03-11 04:30:31 +0000246 Types.GetFunctionType(
247 Types.arrangeBuiltinFunctionDeclaration(IdType, Params));
Chris Lattnerce8754e2009-04-22 02:44:54 +0000248 return CGM.CreateRuntimeFunction(FTy, "objc_getProperty");
249 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000250
Chris Lattnerce8754e2009-04-22 02:44:54 +0000251 llvm::Constant *getSetPropertyFn() {
252 CodeGen::CodeGenTypes &Types = CGM.getTypes();
253 ASTContext &Ctx = CGM.getContext();
254 // void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool)
John McCall2da83a32010-02-26 00:48:12 +0000255 CanQualType IdType = Ctx.getCanonicalParamType(Ctx.getObjCIdType());
256 CanQualType SelType = Ctx.getCanonicalParamType(Ctx.getObjCSelType());
Benjamin Kramer30934732016-07-02 11:41:41 +0000257 CanQualType Params[] = {
258 IdType,
259 SelType,
260 Ctx.getPointerDiffType()->getCanonicalTypeUnqualified(),
261 IdType,
262 Ctx.BoolTy,
263 Ctx.BoolTy};
Chris Lattner2192fe52011-07-18 04:24:23 +0000264 llvm::FunctionType *FTy =
John McCallc56a8b32016-03-11 04:30:31 +0000265 Types.GetFunctionType(
266 Types.arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, Params));
Chris Lattnerce8754e2009-04-22 02:44:54 +0000267 return CGM.CreateRuntimeFunction(FTy, "objc_setProperty");
268 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000269
Ted Kremeneke65b0862012-03-06 20:05:56 +0000270 llvm::Constant *getOptimizedSetPropertyFn(bool atomic, bool copy) {
271 CodeGen::CodeGenTypes &Types = CGM.getTypes();
272 ASTContext &Ctx = CGM.getContext();
Fangrui Song6907ce22018-07-30 19:24:48 +0000273 // void objc_setProperty_atomic(id self, SEL _cmd,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000274 // id newValue, ptrdiff_t offset);
Fangrui Song6907ce22018-07-30 19:24:48 +0000275 // void objc_setProperty_nonatomic(id self, SEL _cmd,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000276 // id newValue, ptrdiff_t offset);
Fangrui Song6907ce22018-07-30 19:24:48 +0000277 // void objc_setProperty_atomic_copy(id self, SEL _cmd,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000278 // id newValue, ptrdiff_t offset);
Fangrui Song6907ce22018-07-30 19:24:48 +0000279 // void objc_setProperty_nonatomic_copy(id self, SEL _cmd,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000280 // id newValue, ptrdiff_t offset);
Fangrui Song6907ce22018-07-30 19:24:48 +0000281
Ted Kremeneke65b0862012-03-06 20:05:56 +0000282 SmallVector<CanQualType,4> Params;
283 CanQualType IdType = Ctx.getCanonicalParamType(Ctx.getObjCIdType());
284 CanQualType SelType = Ctx.getCanonicalParamType(Ctx.getObjCSelType());
285 Params.push_back(IdType);
286 Params.push_back(SelType);
287 Params.push_back(IdType);
288 Params.push_back(Ctx.getPointerDiffType()->getCanonicalTypeUnqualified());
289 llvm::FunctionType *FTy =
John McCallc56a8b32016-03-11 04:30:31 +0000290 Types.GetFunctionType(
291 Types.arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, Params));
Ted Kremeneke65b0862012-03-06 20:05:56 +0000292 const char *name;
293 if (atomic && copy)
294 name = "objc_setProperty_atomic_copy";
295 else if (atomic && !copy)
296 name = "objc_setProperty_atomic";
297 else if (!atomic && copy)
298 name = "objc_setProperty_nonatomic_copy";
299 else
300 name = "objc_setProperty_nonatomic";
Fangrui Song6907ce22018-07-30 19:24:48 +0000301
Ted Kremeneke65b0862012-03-06 20:05:56 +0000302 return CGM.CreateRuntimeFunction(FTy, name);
303 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000304
Fariborz Jahanian5a8c2032010-04-12 18:18:10 +0000305 llvm::Constant *getCopyStructFn() {
306 CodeGen::CodeGenTypes &Types = CGM.getTypes();
307 ASTContext &Ctx = CGM.getContext();
308 // void objc_copyStruct (void *, const void *, size_t, bool, bool)
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000309 SmallVector<CanQualType,5> Params;
Fariborz Jahanian5a8c2032010-04-12 18:18:10 +0000310 Params.push_back(Ctx.VoidPtrTy);
311 Params.push_back(Ctx.VoidPtrTy);
Saleem Abdulrasool91d9bfc2017-06-17 17:30:31 +0000312 Params.push_back(Ctx.getSizeType());
Fariborz Jahanian5a8c2032010-04-12 18:18:10 +0000313 Params.push_back(Ctx.BoolTy);
314 Params.push_back(Ctx.BoolTy);
Chris Lattner2192fe52011-07-18 04:24:23 +0000315 llvm::FunctionType *FTy =
John McCallc56a8b32016-03-11 04:30:31 +0000316 Types.GetFunctionType(
317 Types.arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, Params));
Fariborz Jahanian5a8c2032010-04-12 18:18:10 +0000318 return CGM.CreateRuntimeFunction(FTy, "objc_copyStruct");
319 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000320
Fariborz Jahanian1e1b5492012-01-06 18:07:23 +0000321 /// This routine declares and returns address of:
322 /// void objc_copyCppObjectAtomic(
Fangrui Song6907ce22018-07-30 19:24:48 +0000323 /// void *dest, const void *src,
Fariborz Jahanian1e1b5492012-01-06 18:07:23 +0000324 /// void (*copyHelper) (void *dest, const void *source));
325 llvm::Constant *getCppAtomicObjectFunction() {
326 CodeGen::CodeGenTypes &Types = CGM.getTypes();
327 ASTContext &Ctx = CGM.getContext();
328 /// void objc_copyCppObjectAtomic(void *dest, const void *src, void *helper);
329 SmallVector<CanQualType,3> Params;
330 Params.push_back(Ctx.VoidPtrTy);
331 Params.push_back(Ctx.VoidPtrTy);
332 Params.push_back(Ctx.VoidPtrTy);
333 llvm::FunctionType *FTy =
John McCallc56a8b32016-03-11 04:30:31 +0000334 Types.GetFunctionType(
335 Types.arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, Params));
Fariborz Jahanian1e1b5492012-01-06 18:07:23 +0000336 return CGM.CreateRuntimeFunction(FTy, "objc_copyCppObjectAtomic");
337 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000338
Chris Lattnerce8754e2009-04-22 02:44:54 +0000339 llvm::Constant *getEnumerationMutationFn() {
Daniel Dunbar9d82da42009-07-11 20:32:50 +0000340 CodeGen::CodeGenTypes &Types = CGM.getTypes();
341 ASTContext &Ctx = CGM.getContext();
Chris Lattnerce8754e2009-04-22 02:44:54 +0000342 // void objc_enumerationMutation (id)
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000343 SmallVector<CanQualType,1> Params;
John McCall2da83a32010-02-26 00:48:12 +0000344 Params.push_back(Ctx.getCanonicalParamType(Ctx.getObjCIdType()));
Chris Lattner2192fe52011-07-18 04:24:23 +0000345 llvm::FunctionType *FTy =
John McCallc56a8b32016-03-11 04:30:31 +0000346 Types.GetFunctionType(
347 Types.arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, Params));
Chris Lattnerce8754e2009-04-22 02:44:54 +0000348 return CGM.CreateRuntimeFunction(FTy, "objc_enumerationMutation");
349 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000350
Douglas Gregor24ae22c2016-04-01 23:23:52 +0000351 llvm::Constant *getLookUpClassFn() {
352 CodeGen::CodeGenTypes &Types = CGM.getTypes();
353 ASTContext &Ctx = CGM.getContext();
354 // Class objc_lookUpClass (const char *)
355 SmallVector<CanQualType,1> Params;
356 Params.push_back(
357 Ctx.getCanonicalType(Ctx.getPointerType(Ctx.CharTy.withConst())));
358 llvm::FunctionType *FTy =
359 Types.GetFunctionType(Types.arrangeBuiltinFunctionDeclaration(
360 Ctx.getCanonicalType(Ctx.getObjCClassType()),
361 Params));
362 return CGM.CreateRuntimeFunction(FTy, "objc_lookUpClass");
363 }
364
Fariborz Jahanianeee54df2009-01-22 00:37:21 +0000365 /// GcReadWeakFn -- LLVM objc_read_weak (id *src) function.
Chris Lattnerce8754e2009-04-22 02:44:54 +0000366 llvm::Constant *getGcReadWeakFn() {
367 // id objc_read_weak (id *)
Chris Lattnera5f58b02011-07-09 17:41:47 +0000368 llvm::Type *args[] = { ObjectPtrTy->getPointerTo() };
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000369 llvm::FunctionType *FTy =
John McCall9dc0db22011-05-15 01:53:33 +0000370 llvm::FunctionType::get(ObjectPtrTy, args, false);
Chris Lattnerce8754e2009-04-22 02:44:54 +0000371 return CGM.CreateRuntimeFunction(FTy, "objc_read_weak");
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000372 }
373
Fariborz Jahanianeee54df2009-01-22 00:37:21 +0000374 /// GcAssignWeakFn -- LLVM objc_assign_weak function.
Chris Lattner6fdd57c2009-04-17 22:12:36 +0000375 llvm::Constant *getGcAssignWeakFn() {
376 // id objc_assign_weak (id, id *)
Chris Lattnera5f58b02011-07-09 17:41:47 +0000377 llvm::Type *args[] = { ObjectPtrTy, ObjectPtrTy->getPointerTo() };
Chris Lattner6fdd57c2009-04-17 22:12:36 +0000378 llvm::FunctionType *FTy =
John McCall9dc0db22011-05-15 01:53:33 +0000379 llvm::FunctionType::get(ObjectPtrTy, args, false);
Chris Lattner6fdd57c2009-04-17 22:12:36 +0000380 return CGM.CreateRuntimeFunction(FTy, "objc_assign_weak");
381 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000382
Fariborz Jahanianeee54df2009-01-22 00:37:21 +0000383 /// GcAssignGlobalFn -- LLVM objc_assign_global function.
Chris Lattner0a696a422009-04-22 02:38:11 +0000384 llvm::Constant *getGcAssignGlobalFn() {
385 // id objc_assign_global(id, id *)
Chris Lattnera5f58b02011-07-09 17:41:47 +0000386 llvm::Type *args[] = { ObjectPtrTy, ObjectPtrTy->getPointerTo() };
Owen Anderson170229f2009-07-14 23:10:40 +0000387 llvm::FunctionType *FTy =
John McCall9dc0db22011-05-15 01:53:33 +0000388 llvm::FunctionType::get(ObjectPtrTy, args, false);
Chris Lattner0a696a422009-04-22 02:38:11 +0000389 return CGM.CreateRuntimeFunction(FTy, "objc_assign_global");
390 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000391
Fariborz Jahanian217af242010-07-20 20:30:03 +0000392 /// GcAssignThreadLocalFn -- LLVM objc_assign_threadlocal function.
393 llvm::Constant *getGcAssignThreadLocalFn() {
394 // id objc_assign_threadlocal(id src, id * dest)
Chris Lattnera5f58b02011-07-09 17:41:47 +0000395 llvm::Type *args[] = { ObjectPtrTy, ObjectPtrTy->getPointerTo() };
Fariborz Jahanian217af242010-07-20 20:30:03 +0000396 llvm::FunctionType *FTy =
John McCall9dc0db22011-05-15 01:53:33 +0000397 llvm::FunctionType::get(ObjectPtrTy, args, false);
Fariborz Jahanian217af242010-07-20 20:30:03 +0000398 return CGM.CreateRuntimeFunction(FTy, "objc_assign_threadlocal");
399 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000400
Fariborz Jahanianeee54df2009-01-22 00:37:21 +0000401 /// GcAssignIvarFn -- LLVM objc_assign_ivar function.
Chris Lattner0a696a422009-04-22 02:38:11 +0000402 llvm::Constant *getGcAssignIvarFn() {
Fariborz Jahanian7a95d722009-09-24 22:25:38 +0000403 // id objc_assign_ivar(id, id *, ptrdiff_t)
Chris Lattnera5f58b02011-07-09 17:41:47 +0000404 llvm::Type *args[] = { ObjectPtrTy, ObjectPtrTy->getPointerTo(),
405 CGM.PtrDiffTy };
Owen Anderson170229f2009-07-14 23:10:40 +0000406 llvm::FunctionType *FTy =
John McCall9dc0db22011-05-15 01:53:33 +0000407 llvm::FunctionType::get(ObjectPtrTy, args, false);
Chris Lattner0a696a422009-04-22 02:38:11 +0000408 return CGM.CreateRuntimeFunction(FTy, "objc_assign_ivar");
409 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000410
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +0000411 /// GcMemmoveCollectableFn -- LLVM objc_memmove_collectable function.
412 llvm::Constant *GcMemmoveCollectableFn() {
413 // void *objc_memmove_collectable(void *dst, const void *src, size_t size)
Chris Lattnera5f58b02011-07-09 17:41:47 +0000414 llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, LongTy };
John McCall9dc0db22011-05-15 01:53:33 +0000415 llvm::FunctionType *FTy = llvm::FunctionType::get(Int8PtrTy, args, false);
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +0000416 return CGM.CreateRuntimeFunction(FTy, "objc_memmove_collectable");
417 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000418
Fariborz Jahanianeee54df2009-01-22 00:37:21 +0000419 /// GcAssignStrongCastFn -- LLVM objc_assign_strongCast function.
Chris Lattner0a696a422009-04-22 02:38:11 +0000420 llvm::Constant *getGcAssignStrongCastFn() {
Fariborz Jahanian217af242010-07-20 20:30:03 +0000421 // id objc_assign_strongCast(id, id *)
Chris Lattnera5f58b02011-07-09 17:41:47 +0000422 llvm::Type *args[] = { ObjectPtrTy, ObjectPtrTy->getPointerTo() };
Owen Anderson170229f2009-07-14 23:10:40 +0000423 llvm::FunctionType *FTy =
John McCall9dc0db22011-05-15 01:53:33 +0000424 llvm::FunctionType::get(ObjectPtrTy, args, false);
Chris Lattner0a696a422009-04-22 02:38:11 +0000425 return CGM.CreateRuntimeFunction(FTy, "objc_assign_strongCast");
426 }
Anders Carlsson9ab53d12009-02-16 22:59:18 +0000427
428 /// ExceptionThrowFn - LLVM objc_exception_throw function.
Chris Lattner0a696a422009-04-22 02:38:11 +0000429 llvm::Constant *getExceptionThrowFn() {
430 // void objc_exception_throw(id)
Chris Lattnera5f58b02011-07-09 17:41:47 +0000431 llvm::Type *args[] = { ObjectPtrTy };
Chris Lattner0a696a422009-04-22 02:38:11 +0000432 llvm::FunctionType *FTy =
John McCall9dc0db22011-05-15 01:53:33 +0000433 llvm::FunctionType::get(CGM.VoidTy, args, false);
Chris Lattner0a696a422009-04-22 02:38:11 +0000434 return CGM.CreateRuntimeFunction(FTy, "objc_exception_throw");
435 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000436
Fariborz Jahanian3336de12010-05-28 17:34:43 +0000437 /// ExceptionRethrowFn - LLVM objc_exception_rethrow function.
438 llvm::Constant *getExceptionRethrowFn() {
439 // void objc_exception_rethrow(void)
John McCall9dc0db22011-05-15 01:53:33 +0000440 llvm::FunctionType *FTy = llvm::FunctionType::get(CGM.VoidTy, false);
Fariborz Jahanian3336de12010-05-28 17:34:43 +0000441 return CGM.CreateRuntimeFunction(FTy, "objc_exception_rethrow");
442 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000443
Daniel Dunbar94ceb612009-02-24 01:43:46 +0000444 /// SyncEnterFn - LLVM object_sync_enter function.
Chris Lattnerdcceee72009-04-06 16:53:45 +0000445 llvm::Constant *getSyncEnterFn() {
Aaron Ballman9c004462012-09-06 16:44:16 +0000446 // int objc_sync_enter (id)
Chris Lattnera5f58b02011-07-09 17:41:47 +0000447 llvm::Type *args[] = { ObjectPtrTy };
Chris Lattnerdcceee72009-04-06 16:53:45 +0000448 llvm::FunctionType *FTy =
Aaron Ballman9c004462012-09-06 16:44:16 +0000449 llvm::FunctionType::get(CGM.IntTy, args, false);
Chris Lattnerdcceee72009-04-06 16:53:45 +0000450 return CGM.CreateRuntimeFunction(FTy, "objc_sync_enter");
451 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000452
Daniel Dunbar94ceb612009-02-24 01:43:46 +0000453 /// SyncExitFn - LLVM object_sync_exit function.
Chris Lattner0a696a422009-04-22 02:38:11 +0000454 llvm::Constant *getSyncExitFn() {
Aaron Ballman9c004462012-09-06 16:44:16 +0000455 // int objc_sync_exit (id)
Chris Lattnera5f58b02011-07-09 17:41:47 +0000456 llvm::Type *args[] = { ObjectPtrTy };
Chris Lattner0a696a422009-04-22 02:38:11 +0000457 llvm::FunctionType *FTy =
Aaron Ballman9c004462012-09-06 16:44:16 +0000458 llvm::FunctionType::get(CGM.IntTy, args, false);
Chris Lattner0a696a422009-04-22 02:38:11 +0000459 return CGM.CreateRuntimeFunction(FTy, "objc_sync_exit");
460 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000461
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +0000462 llvm::Constant *getSendFn(bool IsSuper) const {
463 return IsSuper ? getMessageSendSuperFn() : getMessageSendFn();
464 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000465
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +0000466 llvm::Constant *getSendFn2(bool IsSuper) const {
467 return IsSuper ? getMessageSendSuperFn2() : getMessageSendFn();
468 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000469
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +0000470 llvm::Constant *getSendStretFn(bool IsSuper) const {
471 return IsSuper ? getMessageSendSuperStretFn() : getMessageSendStretFn();
472 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000473
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +0000474 llvm::Constant *getSendStretFn2(bool IsSuper) const {
475 return IsSuper ? getMessageSendSuperStretFn2() : getMessageSendStretFn();
476 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000477
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +0000478 llvm::Constant *getSendFpretFn(bool IsSuper) const {
479 return IsSuper ? getMessageSendSuperFpretFn() : getMessageSendFpretFn();
480 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000481
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +0000482 llvm::Constant *getSendFpretFn2(bool IsSuper) const {
483 return IsSuper ? getMessageSendSuperFpretFn2() : getMessageSendFpretFn();
484 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000485
Anders Carlsson2f1a6c32011-10-31 16:27:11 +0000486 llvm::Constant *getSendFp2retFn(bool IsSuper) const {
487 return IsSuper ? getMessageSendSuperFn() : getMessageSendFp2retFn();
488 }
489
490 llvm::Constant *getSendFp2RetFn2(bool IsSuper) const {
491 return IsSuper ? getMessageSendSuperFn2() : getMessageSendFp2retFn();
492 }
493
Fariborz Jahanian279eda62009-01-21 22:04:16 +0000494 ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm);
Fariborz Jahanian279eda62009-01-21 22:04:16 +0000495};
Daniel Dunbarf6397fe2008-08-23 04:28:29 +0000496
Fariborz Jahanian279eda62009-01-21 22:04:16 +0000497/// ObjCTypesHelper - Helper class that encapsulates lazy
498/// construction of varies types used during ObjC generation.
499class ObjCTypesHelper : public ObjCCommonTypesHelper {
Fariborz Jahanian279eda62009-01-21 22:04:16 +0000500public:
Daniel Dunbar7bd00bd2008-08-12 06:48:42 +0000501 /// SymtabTy - LLVM type for struct objc_symtab.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000502 llvm::StructType *SymtabTy;
Daniel Dunbar22d82ed2008-08-21 04:36:09 +0000503 /// SymtabPtrTy - LLVM type for struct objc_symtab *.
John McCall176f8922016-11-30 02:39:18 +0000504 llvm::PointerType *SymtabPtrTy;
Daniel Dunbar7bd00bd2008-08-12 06:48:42 +0000505 /// ModuleTy - LLVM type for struct objc_module.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000506 llvm::StructType *ModuleTy;
Daniel Dunbarcb515c82008-08-12 03:39:23 +0000507
Daniel Dunbarb036db82008-08-13 03:21:16 +0000508 /// ProtocolTy - LLVM type for struct objc_protocol.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000509 llvm::StructType *ProtocolTy;
Daniel Dunbarb036db82008-08-13 03:21:16 +0000510 /// ProtocolPtrTy - LLVM type for struct objc_protocol *.
John McCall176f8922016-11-30 02:39:18 +0000511 llvm::PointerType *ProtocolPtrTy;
Daniel Dunbarb036db82008-08-13 03:21:16 +0000512 /// ProtocolExtensionTy - LLVM type for struct
513 /// objc_protocol_extension.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000514 llvm::StructType *ProtocolExtensionTy;
Daniel Dunbarb036db82008-08-13 03:21:16 +0000515 /// ProtocolExtensionTy - LLVM type for struct
516 /// objc_protocol_extension *.
John McCall176f8922016-11-30 02:39:18 +0000517 llvm::PointerType *ProtocolExtensionPtrTy;
Daniel Dunbarb036db82008-08-13 03:21:16 +0000518 /// MethodDescriptionTy - LLVM type for struct
519 /// objc_method_description.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000520 llvm::StructType *MethodDescriptionTy;
Daniel Dunbarb036db82008-08-13 03:21:16 +0000521 /// MethodDescriptionListTy - LLVM type for struct
522 /// objc_method_description_list.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000523 llvm::StructType *MethodDescriptionListTy;
Daniel Dunbarb036db82008-08-13 03:21:16 +0000524 /// MethodDescriptionListPtrTy - LLVM type for struct
525 /// objc_method_description_list *.
John McCall176f8922016-11-30 02:39:18 +0000526 llvm::PointerType *MethodDescriptionListPtrTy;
Daniel Dunbarb036db82008-08-13 03:21:16 +0000527 /// ProtocolListTy - LLVM type for struct objc_property_list.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000528 llvm::StructType *ProtocolListTy;
Daniel Dunbarb036db82008-08-13 03:21:16 +0000529 /// ProtocolListPtrTy - LLVM type for struct objc_property_list*.
John McCall176f8922016-11-30 02:39:18 +0000530 llvm::PointerType *ProtocolListPtrTy;
Daniel Dunbar938a77f2008-08-22 20:34:54 +0000531 /// CategoryTy - LLVM type for struct objc_category.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000532 llvm::StructType *CategoryTy;
Daniel Dunbar22d82ed2008-08-21 04:36:09 +0000533 /// ClassTy - LLVM type for struct objc_class.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000534 llvm::StructType *ClassTy;
Daniel Dunbar22d82ed2008-08-21 04:36:09 +0000535 /// ClassPtrTy - LLVM type for struct objc_class *.
John McCall176f8922016-11-30 02:39:18 +0000536 llvm::PointerType *ClassPtrTy;
Daniel Dunbar22d82ed2008-08-21 04:36:09 +0000537 /// ClassExtensionTy - LLVM type for struct objc_class_ext.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000538 llvm::StructType *ClassExtensionTy;
Daniel Dunbar22d82ed2008-08-21 04:36:09 +0000539 /// ClassExtensionPtrTy - LLVM type for struct objc_class_ext *.
John McCall176f8922016-11-30 02:39:18 +0000540 llvm::PointerType *ClassExtensionPtrTy;
Daniel Dunbar22d82ed2008-08-21 04:36:09 +0000541 // IvarTy - LLVM type for struct objc_ivar.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000542 llvm::StructType *IvarTy;
Daniel Dunbar22d82ed2008-08-21 04:36:09 +0000543 /// IvarListTy - LLVM type for struct objc_ivar_list.
John McCall176f8922016-11-30 02:39:18 +0000544 llvm::StructType *IvarListTy;
Daniel Dunbar22d82ed2008-08-21 04:36:09 +0000545 /// IvarListPtrTy - LLVM type for struct objc_ivar_list *.
John McCall176f8922016-11-30 02:39:18 +0000546 llvm::PointerType *IvarListPtrTy;
Daniel Dunbar22d82ed2008-08-21 04:36:09 +0000547 /// MethodListTy - LLVM type for struct objc_method_list.
John McCall176f8922016-11-30 02:39:18 +0000548 llvm::StructType *MethodListTy;
Daniel Dunbar22d82ed2008-08-21 04:36:09 +0000549 /// MethodListPtrTy - LLVM type for struct objc_method_list *.
John McCall176f8922016-11-30 02:39:18 +0000550 llvm::PointerType *MethodListPtrTy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000551
Anders Carlsson9ff22482008-09-09 10:10:21 +0000552 /// ExceptionDataTy - LLVM type for struct _objc_exception_data.
John McCall176f8922016-11-30 02:39:18 +0000553 llvm::StructType *ExceptionDataTy;
Fangrui Song6907ce22018-07-30 19:24:48 +0000554
Anders Carlsson9ff22482008-09-09 10:10:21 +0000555 /// ExceptionTryEnterFn - LLVM objc_exception_try_enter function.
Chris Lattnerc6406db2009-04-22 02:26:14 +0000556 llvm::Constant *getExceptionTryEnterFn() {
Chris Lattnera5f58b02011-07-09 17:41:47 +0000557 llvm::Type *params[] = { ExceptionDataTy->getPointerTo() };
Owen Anderson170229f2009-07-14 23:10:40 +0000558 return CGM.CreateRuntimeFunction(
John McCall9dc0db22011-05-15 01:53:33 +0000559 llvm::FunctionType::get(CGM.VoidTy, params, false),
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000560 "objc_exception_try_enter");
Chris Lattnerc6406db2009-04-22 02:26:14 +0000561 }
Anders Carlsson9ff22482008-09-09 10:10:21 +0000562
563 /// ExceptionTryExitFn - LLVM objc_exception_try_exit function.
Chris Lattnerc6406db2009-04-22 02:26:14 +0000564 llvm::Constant *getExceptionTryExitFn() {
Chris Lattnera5f58b02011-07-09 17:41:47 +0000565 llvm::Type *params[] = { ExceptionDataTy->getPointerTo() };
Owen Anderson170229f2009-07-14 23:10:40 +0000566 return CGM.CreateRuntimeFunction(
John McCall9dc0db22011-05-15 01:53:33 +0000567 llvm::FunctionType::get(CGM.VoidTy, params, false),
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000568 "objc_exception_try_exit");
Chris Lattnerc6406db2009-04-22 02:26:14 +0000569 }
Anders Carlsson9ff22482008-09-09 10:10:21 +0000570
571 /// ExceptionExtractFn - LLVM objc_exception_extract function.
Chris Lattnerc6406db2009-04-22 02:26:14 +0000572 llvm::Constant *getExceptionExtractFn() {
Chris Lattnera5f58b02011-07-09 17:41:47 +0000573 llvm::Type *params[] = { ExceptionDataTy->getPointerTo() };
Owen Anderson9793f0e2009-07-29 22:16:19 +0000574 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
John McCall9dc0db22011-05-15 01:53:33 +0000575 params, false),
Chris Lattnerc6406db2009-04-22 02:26:14 +0000576 "objc_exception_extract");
Chris Lattnerc6406db2009-04-22 02:26:14 +0000577 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000578
Anders Carlsson9ff22482008-09-09 10:10:21 +0000579 /// ExceptionMatchFn - LLVM objc_exception_match function.
Chris Lattnerc6406db2009-04-22 02:26:14 +0000580 llvm::Constant *getExceptionMatchFn() {
Chris Lattnera5f58b02011-07-09 17:41:47 +0000581 llvm::Type *params[] = { ClassPtrTy, ObjectPtrTy };
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000582 return CGM.CreateRuntimeFunction(
John McCall9dc0db22011-05-15 01:53:33 +0000583 llvm::FunctionType::get(CGM.Int32Ty, params, false),
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000584 "objc_exception_match");
Chris Lattnerc6406db2009-04-22 02:26:14 +0000585 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000586
Anders Carlsson9ff22482008-09-09 10:10:21 +0000587 /// SetJmpFn - LLVM _setjmp function.
Chris Lattnerc6406db2009-04-22 02:26:14 +0000588 llvm::Constant *getSetJmpFn() {
John McCall9dc0db22011-05-15 01:53:33 +0000589 // This is specifically the prototype for x86.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000590 llvm::Type *params[] = { CGM.Int32Ty->getPointerTo() };
Reid Klecknerde864822017-03-21 16:57:30 +0000591 return CGM.CreateRuntimeFunction(
592 llvm::FunctionType::get(CGM.Int32Ty, params, false), "_setjmp",
593 llvm::AttributeList::get(CGM.getLLVMContext(),
594 llvm::AttributeList::FunctionIndex,
595 llvm::Attribute::NonLazyBind));
Chris Lattnerc6406db2009-04-22 02:26:14 +0000596 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000597
Daniel Dunbar8b8683f2008-08-12 00:12:39 +0000598public:
599 ObjCTypesHelper(CodeGen::CodeGenModule &cgm);
Daniel Dunbar8b8683f2008-08-12 00:12:39 +0000600};
601
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +0000602/// ObjCNonFragileABITypesHelper - will have all types needed by objective-c's
Fariborz Jahanian279eda62009-01-21 22:04:16 +0000603/// modern abi
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +0000604class ObjCNonFragileABITypesHelper : public ObjCCommonTypesHelper {
Fariborz Jahaniane4dc35d2009-02-04 20:42:28 +0000605public:
Fariborz Jahanian0232c052009-01-23 01:46:23 +0000606 // MethodListnfABITy - LLVM for struct _method_list_t
Chris Lattnera5f58b02011-07-09 17:41:47 +0000607 llvm::StructType *MethodListnfABITy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000608
Fariborz Jahanian0232c052009-01-23 01:46:23 +0000609 // MethodListnfABIPtrTy - LLVM for struct _method_list_t*
John McCall176f8922016-11-30 02:39:18 +0000610 llvm::PointerType *MethodListnfABIPtrTy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000611
Fariborz Jahanian0232c052009-01-23 01:46:23 +0000612 // ProtocolnfABITy = LLVM for struct _protocol_t
Chris Lattnera5f58b02011-07-09 17:41:47 +0000613 llvm::StructType *ProtocolnfABITy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000614
Daniel Dunbar8de90f02009-02-15 07:36:20 +0000615 // ProtocolnfABIPtrTy = LLVM for struct _protocol_t*
John McCall176f8922016-11-30 02:39:18 +0000616 llvm::PointerType *ProtocolnfABIPtrTy;
Daniel Dunbar8de90f02009-02-15 07:36:20 +0000617
Fariborz Jahanian0232c052009-01-23 01:46:23 +0000618 // ProtocolListnfABITy - LLVM for struct _objc_protocol_list
Chris Lattnera5f58b02011-07-09 17:41:47 +0000619 llvm::StructType *ProtocolListnfABITy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000620
Fariborz Jahanian0232c052009-01-23 01:46:23 +0000621 // ProtocolListnfABIPtrTy - LLVM for struct _objc_protocol_list*
John McCall176f8922016-11-30 02:39:18 +0000622 llvm::PointerType *ProtocolListnfABIPtrTy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000623
Fariborz Jahanian0232c052009-01-23 01:46:23 +0000624 // ClassnfABITy - LLVM for struct _class_t
Chris Lattnera5f58b02011-07-09 17:41:47 +0000625 llvm::StructType *ClassnfABITy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000626
Fariborz Jahanian71394042009-01-23 23:53:38 +0000627 // ClassnfABIPtrTy - LLVM for struct _class_t*
John McCall176f8922016-11-30 02:39:18 +0000628 llvm::PointerType *ClassnfABIPtrTy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000629
Fariborz Jahanian0232c052009-01-23 01:46:23 +0000630 // IvarnfABITy - LLVM for struct _ivar_t
Chris Lattnera5f58b02011-07-09 17:41:47 +0000631 llvm::StructType *IvarnfABITy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000632
Fariborz Jahanian0232c052009-01-23 01:46:23 +0000633 // IvarListnfABITy - LLVM for struct _ivar_list_t
Chris Lattnera5f58b02011-07-09 17:41:47 +0000634 llvm::StructType *IvarListnfABITy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000635
Fariborz Jahanian0232c052009-01-23 01:46:23 +0000636 // IvarListnfABIPtrTy = LLVM for struct _ivar_list_t*
John McCall176f8922016-11-30 02:39:18 +0000637 llvm::PointerType *IvarListnfABIPtrTy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000638
Fariborz Jahanian0232c052009-01-23 01:46:23 +0000639 // ClassRonfABITy - LLVM for struct _class_ro_t
Chris Lattnera5f58b02011-07-09 17:41:47 +0000640 llvm::StructType *ClassRonfABITy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000641
Fariborz Jahanian0232c052009-01-23 01:46:23 +0000642 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
John McCall176f8922016-11-30 02:39:18 +0000643 llvm::PointerType *ImpnfABITy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000644
Fariborz Jahanian0232c052009-01-23 01:46:23 +0000645 // CategorynfABITy - LLVM for struct _category_t
Chris Lattnera5f58b02011-07-09 17:41:47 +0000646 llvm::StructType *CategorynfABITy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000647
Fariborz Jahanian82c72e12009-02-03 23:49:23 +0000648 // New types for nonfragile abi messaging.
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000649
Fariborz Jahanian82c72e12009-02-03 23:49:23 +0000650 // MessageRefTy - LLVM for:
651 // struct _message_ref_t {
652 // IMP messenger;
653 // SEL name;
654 // };
Chris Lattnera5f58b02011-07-09 17:41:47 +0000655 llvm::StructType *MessageRefTy;
Fariborz Jahaniane4dc35d2009-02-04 20:42:28 +0000656 // MessageRefCTy - clang type for struct _message_ref_t
657 QualType MessageRefCTy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000658
Fariborz Jahanian82c72e12009-02-03 23:49:23 +0000659 // MessageRefPtrTy - LLVM for struct _message_ref_t*
Chris Lattnera5f58b02011-07-09 17:41:47 +0000660 llvm::Type *MessageRefPtrTy;
Fariborz Jahaniane4dc35d2009-02-04 20:42:28 +0000661 // MessageRefCPtrTy - clang type for struct _message_ref_t*
662 QualType MessageRefCPtrTy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000663
Fariborz Jahanian82c72e12009-02-03 23:49:23 +0000664 // SuperMessageRefTy - LLVM for:
665 // struct _super_message_ref_t {
666 // SUPER_IMP messenger;
667 // SEL name;
668 // };
Chris Lattnera5f58b02011-07-09 17:41:47 +0000669 llvm::StructType *SuperMessageRefTy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000670
Fariborz Jahanian82c72e12009-02-03 23:49:23 +0000671 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
John McCall176f8922016-11-30 02:39:18 +0000672 llvm::PointerType *SuperMessageRefPtrTy;
Daniel Dunbar0b0dcd92009-02-24 07:47:38 +0000673
Chris Lattner2dfdb3e2009-04-22 02:53:24 +0000674 llvm::Constant *getMessageSendFixupFn() {
675 // id objc_msgSend_fixup(id, struct message_ref_t*, ...)
Chris Lattnera5f58b02011-07-09 17:41:47 +0000676 llvm::Type *params[] = { ObjectPtrTy, MessageRefPtrTy };
Owen Anderson9793f0e2009-07-29 22:16:19 +0000677 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
John McCall9dc0db22011-05-15 01:53:33 +0000678 params, true),
Chris Lattner2dfdb3e2009-04-22 02:53:24 +0000679 "objc_msgSend_fixup");
680 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000681
Chris Lattner2dfdb3e2009-04-22 02:53:24 +0000682 llvm::Constant *getMessageSendFpretFixupFn() {
683 // id objc_msgSend_fpret_fixup(id, struct message_ref_t*, ...)
Chris Lattnera5f58b02011-07-09 17:41:47 +0000684 llvm::Type *params[] = { ObjectPtrTy, MessageRefPtrTy };
Owen Anderson9793f0e2009-07-29 22:16:19 +0000685 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
John McCall9dc0db22011-05-15 01:53:33 +0000686 params, true),
Chris Lattner2dfdb3e2009-04-22 02:53:24 +0000687 "objc_msgSend_fpret_fixup");
688 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000689
Chris Lattner2dfdb3e2009-04-22 02:53:24 +0000690 llvm::Constant *getMessageSendStretFixupFn() {
691 // id objc_msgSend_stret_fixup(id, struct message_ref_t*, ...)
Chris Lattnera5f58b02011-07-09 17:41:47 +0000692 llvm::Type *params[] = { ObjectPtrTy, MessageRefPtrTy };
Owen Anderson9793f0e2009-07-29 22:16:19 +0000693 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
John McCall9dc0db22011-05-15 01:53:33 +0000694 params, true),
Chris Lattner2dfdb3e2009-04-22 02:53:24 +0000695 "objc_msgSend_stret_fixup");
696 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000697
Chris Lattner2dfdb3e2009-04-22 02:53:24 +0000698 llvm::Constant *getMessageSendSuper2FixupFn() {
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000699 // id objc_msgSendSuper2_fixup (struct objc_super *,
Chris Lattner2dfdb3e2009-04-22 02:53:24 +0000700 // struct _super_message_ref_t*, ...)
Chris Lattnera5f58b02011-07-09 17:41:47 +0000701 llvm::Type *params[] = { SuperPtrTy, SuperMessageRefPtrTy };
Owen Anderson9793f0e2009-07-29 22:16:19 +0000702 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
John McCall9dc0db22011-05-15 01:53:33 +0000703 params, true),
Chris Lattner2dfdb3e2009-04-22 02:53:24 +0000704 "objc_msgSendSuper2_fixup");
705 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000706
Chris Lattner2dfdb3e2009-04-22 02:53:24 +0000707 llvm::Constant *getMessageSendSuper2StretFixupFn() {
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000708 // id objc_msgSendSuper2_stret_fixup(struct objc_super *,
Chris Lattner2dfdb3e2009-04-22 02:53:24 +0000709 // struct _super_message_ref_t*, ...)
Chris Lattnera5f58b02011-07-09 17:41:47 +0000710 llvm::Type *params[] = { SuperPtrTy, SuperMessageRefPtrTy };
Owen Anderson9793f0e2009-07-29 22:16:19 +0000711 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
John McCall9dc0db22011-05-15 01:53:33 +0000712 params, true),
Chris Lattner2dfdb3e2009-04-22 02:53:24 +0000713 "objc_msgSendSuper2_stret_fixup");
714 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000715
Chris Lattnera7c00b42009-04-22 02:15:23 +0000716 llvm::Constant *getObjCEndCatchFn() {
John McCall9dc0db22011-05-15 01:53:33 +0000717 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.VoidTy, false),
Chris Lattnera7c00b42009-04-22 02:15:23 +0000718 "objc_end_catch");
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000719
Chris Lattnera7c00b42009-04-22 02:15:23 +0000720 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000721
Chris Lattnera7c00b42009-04-22 02:15:23 +0000722 llvm::Constant *getObjCBeginCatchFn() {
Chris Lattnera5f58b02011-07-09 17:41:47 +0000723 llvm::Type *params[] = { Int8PtrTy };
Owen Anderson9793f0e2009-07-29 22:16:19 +0000724 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(Int8PtrTy,
John McCall9dc0db22011-05-15 01:53:33 +0000725 params, false),
Chris Lattnera7c00b42009-04-22 02:15:23 +0000726 "objc_begin_catch");
727 }
Daniel Dunbarb1559a42009-03-01 04:46:24 +0000728
Chris Lattnera5f58b02011-07-09 17:41:47 +0000729 llvm::StructType *EHTypeTy;
730 llvm::Type *EHTypePtrTy;
Fangrui Song6907ce22018-07-30 19:24:48 +0000731
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +0000732 ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm);
Fariborz Jahanian279eda62009-01-21 22:04:16 +0000733};
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000734
Saleem Abdulrasool271106c2016-09-16 23:41:13 +0000735enum class ObjCLabelType {
736 ClassName,
737 MethodVarName,
738 MethodVarType,
739 PropertyName,
740};
741
Fariborz Jahanian279eda62009-01-21 22:04:16 +0000742class CGObjCCommonMac : public CodeGen::CGObjCRuntime {
Fariborz Jahaniancbaf73c2009-03-11 20:59:05 +0000743public:
Fariborz Jahaniancbaf73c2009-03-11 20:59:05 +0000744 class SKIP_SCAN {
Daniel Dunbar7b89ace2009-05-03 13:44:42 +0000745 public:
746 unsigned skip;
747 unsigned scan;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000748 SKIP_SCAN(unsigned _skip = 0, unsigned _scan = 0)
Daniel Dunbar7b89ace2009-05-03 13:44:42 +0000749 : skip(_skip), scan(_scan) {}
Fariborz Jahaniancbaf73c2009-03-11 20:59:05 +0000750 };
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000751
Fariborz Jahanian196f9382012-10-25 21:15:04 +0000752 /// opcode for captured block variables layout 'instructions'.
753 /// In the following descriptions, 'I' is the value of the immediate field.
754 /// (field following the opcode).
755 ///
756 enum BLOCK_LAYOUT_OPCODE {
757 /// An operator which affects how the following layout should be
758 /// interpreted.
759 /// I == 0: Halt interpretation and treat everything else as
760 /// a non-pointer. Note that this instruction is equal
761 /// to '\0'.
762 /// I != 0: Currently unused.
763 BLOCK_LAYOUT_OPERATOR = 0,
Fangrui Song6907ce22018-07-30 19:24:48 +0000764
Fariborz Jahanian196f9382012-10-25 21:15:04 +0000765 /// The next I+1 bytes do not contain a value of object pointer type.
766 /// Note that this can leave the stream unaligned, meaning that
767 /// subsequent word-size instructions do not begin at a multiple of
768 /// the pointer size.
769 BLOCK_LAYOUT_NON_OBJECT_BYTES = 1,
Fangrui Song6907ce22018-07-30 19:24:48 +0000770
Fariborz Jahanian196f9382012-10-25 21:15:04 +0000771 /// The next I+1 words do not contain a value of object pointer type.
772 /// This is simply an optimized version of BLOCK_LAYOUT_BYTES for
773 /// when the required skip quantity is a multiple of the pointer size.
774 BLOCK_LAYOUT_NON_OBJECT_WORDS = 2,
Fangrui Song6907ce22018-07-30 19:24:48 +0000775
Fariborz Jahanian196f9382012-10-25 21:15:04 +0000776 /// The next I+1 words are __strong pointers to Objective-C
777 /// objects or blocks.
778 BLOCK_LAYOUT_STRONG = 3,
Fangrui Song6907ce22018-07-30 19:24:48 +0000779
Fariborz Jahanian196f9382012-10-25 21:15:04 +0000780 /// The next I+1 words are pointers to __block variables.
781 BLOCK_LAYOUT_BYREF = 4,
Fangrui Song6907ce22018-07-30 19:24:48 +0000782
Fariborz Jahanian196f9382012-10-25 21:15:04 +0000783 /// The next I+1 words are __weak pointers to Objective-C
784 /// objects or blocks.
785 BLOCK_LAYOUT_WEAK = 5,
Fangrui Song6907ce22018-07-30 19:24:48 +0000786
Fariborz Jahanian196f9382012-10-25 21:15:04 +0000787 /// The next I+1 words are __unsafe_unretained pointers to
788 /// Objective-C objects or blocks.
789 BLOCK_LAYOUT_UNRETAINED = 6
Fangrui Song6907ce22018-07-30 19:24:48 +0000790
Fariborz Jahanian196f9382012-10-25 21:15:04 +0000791 /// The next I+1 words are block or object pointers with some
792 /// as-yet-unspecified ownership semantics. If we add more
793 /// flavors of ownership semantics, values will be taken from
794 /// this range.
795 ///
796 /// This is included so that older tools can at least continue
797 /// processing the layout past such things.
798 //BLOCK_LAYOUT_OWNERSHIP_UNKNOWN = 7..10,
Fangrui Song6907ce22018-07-30 19:24:48 +0000799
Fariborz Jahanian196f9382012-10-25 21:15:04 +0000800 /// All other opcodes are reserved. Halt interpretation and
801 /// treat everything else as opaque.
802 };
Fangrui Song6907ce22018-07-30 19:24:48 +0000803
Fariborz Jahanian196f9382012-10-25 21:15:04 +0000804 class RUN_SKIP {
805 public:
806 enum BLOCK_LAYOUT_OPCODE opcode;
Fariborz Jahanian7778d612012-11-07 20:00:32 +0000807 CharUnits block_var_bytepos;
808 CharUnits block_var_size;
Fariborz Jahanian196f9382012-10-25 21:15:04 +0000809 RUN_SKIP(enum BLOCK_LAYOUT_OPCODE Opcode = BLOCK_LAYOUT_OPERATOR,
Fariborz Jahanian7778d612012-11-07 20:00:32 +0000810 CharUnits BytePos = CharUnits::Zero(),
811 CharUnits Size = CharUnits::Zero())
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +0000812 : opcode(Opcode), block_var_bytepos(BytePos), block_var_size(Size) {}
Fangrui Song6907ce22018-07-30 19:24:48 +0000813
Fariborz Jahanian196f9382012-10-25 21:15:04 +0000814 // Allow sorting based on byte pos.
815 bool operator<(const RUN_SKIP &b) const {
816 return block_var_bytepos < b.block_var_bytepos;
817 }
818 };
Fangrui Song6907ce22018-07-30 19:24:48 +0000819
Fariborz Jahanian279eda62009-01-21 22:04:16 +0000820protected:
Owen Andersonae86c192009-07-13 04:10:07 +0000821 llvm::LLVMContext &VMContext;
Fariborz Jahanian279eda62009-01-21 22:04:16 +0000822 // FIXME! May not be needing this after all.
Daniel Dunbar8b8683f2008-08-12 00:12:39 +0000823 unsigned ObjCABI;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000824
Fariborz Jahanian196f9382012-10-25 21:15:04 +0000825 // arc/mrr layout of captured block literal variables.
826 SmallVector<RUN_SKIP, 16> RunSkipBlockVars;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000827
Daniel Dunbarc61d0e92008-08-25 06:02:07 +0000828 /// LazySymbols - Symbols to generate a lazy reference for. See
829 /// DefinedSymbols and FinishModule().
Daniel Dunbard027a922009-09-07 00:20:42 +0000830 llvm::SetVector<IdentifierInfo*> LazySymbols;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000831
Daniel Dunbarc61d0e92008-08-25 06:02:07 +0000832 /// DefinedSymbols - External symbols which are defined by this
833 /// module. The symbols in this list and LazySymbols are used to add
834 /// special linker symbols which ensure that Objective-C modules are
835 /// linked properly.
Daniel Dunbard027a922009-09-07 00:20:42 +0000836 llvm::SetVector<IdentifierInfo*> DefinedSymbols;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000837
Daniel Dunbar7bd00bd2008-08-12 06:48:42 +0000838 /// ClassNames - uniqued class names.
Fariborz Jahanian451b92a2014-07-16 16:16:04 +0000839 llvm::StringMap<llvm::GlobalVariable*> ClassNames;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000840
Daniel Dunbarcb515c82008-08-12 03:39:23 +0000841 /// MethodVarNames - uniqued method variable names.
842 llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000843
Fariborz Jahanian9adb2e62010-06-21 22:05:18 +0000844 /// DefinedCategoryNames - list of category names in form Class_Category.
Justin Lebar5e83dfe2016-10-21 21:45:01 +0000845 llvm::SmallSetVector<llvm::CachedHashString, 16> DefinedCategoryNames;
Fariborz Jahanian9adb2e62010-06-21 22:05:18 +0000846
Daniel Dunbarb036db82008-08-13 03:21:16 +0000847 /// MethodVarTypes - uniqued method type signatures. We have to use
848 /// a StringMap here because have no other unique reference.
849 llvm::StringMap<llvm::GlobalVariable*> MethodVarTypes;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000850
Daniel Dunbar3c76cb52008-08-26 21:51:14 +0000851 /// MethodDefinitions - map of methods which have been defined in
852 /// this translation unit.
853 llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> MethodDefinitions;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000854
Daniel Dunbar80a840b2008-08-23 00:19:03 +0000855 /// PropertyNames - uniqued method variable names.
856 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000857
Daniel Dunbar22d82ed2008-08-21 04:36:09 +0000858 /// ClassReferences - uniqued class references.
859 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000860
Daniel Dunbarcb515c82008-08-12 03:39:23 +0000861 /// SelectorReferences - uniqued selector references.
862 llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000863
Daniel Dunbarb036db82008-08-13 03:21:16 +0000864 /// Protocols - Protocols for which an objc_protocol structure has
865 /// been emitted. Forward declarations are handled by creating an
866 /// empty structure whose initializer is filled in when/if defined.
867 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> Protocols;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000868
Daniel Dunbarc475d422008-10-29 22:36:39 +0000869 /// DefinedProtocols - Protocols which have actually been
870 /// defined. We should not need this, see FIXME in GenerateProtocol.
871 llvm::DenseSet<IdentifierInfo*> DefinedProtocols;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000872
Daniel Dunbar22d82ed2008-08-21 04:36:09 +0000873 /// DefinedClasses - List of defined classes.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000874 SmallVector<llvm::GlobalValue*, 16> DefinedClasses;
Fangrui Song6907ce22018-07-30 19:24:48 +0000875
Fariborz Jahanianf322f2f2014-03-11 00:25:05 +0000876 /// ImplementedClasses - List of @implemented classes.
877 SmallVector<const ObjCInterfaceDecl*, 16> ImplementedClasses;
Daniel Dunbar9a017d72009-05-15 22:33:15 +0000878
879 /// DefinedNonLazyClasses - List of defined "non-lazy" classes.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000880 SmallVector<llvm::GlobalValue*, 16> DefinedNonLazyClasses;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000881
Daniel Dunbar22d82ed2008-08-21 04:36:09 +0000882 /// DefinedCategories - List of defined categories.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000883 SmallVector<llvm::GlobalValue*, 16> DefinedCategories;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000884
Daniel Dunbar9a017d72009-05-15 22:33:15 +0000885 /// DefinedNonLazyCategories - List of defined "non-lazy" categories.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000886 SmallVector<llvm::GlobalValue*, 16> DefinedNonLazyCategories;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000887
John McCallcd21d542016-11-30 23:15:55 +0000888 /// Cached reference to the class for constant strings. This value has type
889 /// int * but is actually an Obj-C class pointer.
Sanjoy Dase369bd92017-05-01 17:08:00 +0000890 llvm::WeakTrackingVH ConstantStringClassRef;
John McCallcd21d542016-11-30 23:15:55 +0000891
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000892 /// The LLVM type corresponding to NSConstantString.
John McCallcd21d542016-11-30 23:15:55 +0000893 llvm::StructType *NSConstantStringType = nullptr;
894
895 llvm::StringMap<llvm::GlobalVariable *> NSConstantStringMap;
896
Fariborz Jahanian0b1ccdc2009-01-21 23:34:32 +0000897 /// GetNameForMethod - Return a name for the given method.
898 /// \param[out] NameOut - The return value.
899 void GetNameForMethod(const ObjCMethodDecl *OMD,
900 const ObjCContainerDecl *CD,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000901 SmallVectorImpl<char> &NameOut);
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000902
Fariborz Jahanian0b1ccdc2009-01-21 23:34:32 +0000903 /// GetMethodVarName - Return a unique constant for the given
904 /// selector's name. The return value has type char *.
905 llvm::Constant *GetMethodVarName(Selector Sel);
906 llvm::Constant *GetMethodVarName(IdentifierInfo *Ident);
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000907
Fariborz Jahanian0b1ccdc2009-01-21 23:34:32 +0000908 /// GetMethodVarType - Return a unique constant for the given
Bob Wilson5f4e3a72011-11-30 01:57:58 +0000909 /// method's type encoding string. The return value has type char *.
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000910
Fariborz Jahanian0b1ccdc2009-01-21 23:34:32 +0000911 // FIXME: This is a horrible name.
Bob Wilson5f4e3a72011-11-30 01:57:58 +0000912 llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D,
913 bool Extended = false);
Daniel Dunbarf5c18462009-04-20 06:54:31 +0000914 llvm::Constant *GetMethodVarType(const FieldDecl *D);
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000915
Fariborz Jahanian0b1ccdc2009-01-21 23:34:32 +0000916 /// GetPropertyName - Return a unique constant for the given
917 /// name. The return value has type char *.
918 llvm::Constant *GetPropertyName(IdentifierInfo *Ident);
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000919
Fariborz Jahanian0b1ccdc2009-01-21 23:34:32 +0000920 // FIXME: This can be dropped once string functions are unified.
921 llvm::Constant *GetPropertyTypeString(const ObjCPropertyDecl *PD,
922 const Decl *Container);
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000923
Fariborz Jahanian9e3ad522009-01-24 20:21:50 +0000924 /// GetClassName - Return a unique constant for the given selector's
Fariborz Jahanian451b92a2014-07-16 16:16:04 +0000925 /// runtime name (which may change via use of objc_runtime_name attribute on
926 /// class or protocol definition. The return value has type char *.
927 llvm::Constant *GetClassName(StringRef RuntimeName);
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000928
Argyrios Kyrtzidis13257c52010-08-09 10:54:20 +0000929 llvm::Function *GetMethodDefinition(const ObjCMethodDecl *MD);
930
Fariborz Jahanianc559f3f2009-03-05 22:39:55 +0000931 /// BuildIvarLayout - Builds ivar layout bitmap for the class
932 /// implementation for the __strong or __weak case.
933 ///
John McCall460ce582015-10-22 18:38:17 +0000934 /// \param hasMRCWeakIvars - Whether we are compiling in MRC and there
935 /// are any weak ivars defined directly in the class. Meaningless unless
936 /// building a weak layout. Does not guarantee that the layout will
937 /// actually have any entries, because the ivar might be under-aligned.
Fariborz Jahanian1bf72882009-03-12 22:50:49 +0000938 llvm::Constant *BuildIvarLayout(const ObjCImplementationDecl *OI,
John McCall3fd13f062015-10-21 18:06:47 +0000939 CharUnits beginOffset,
940 CharUnits endOffset,
John McCall460ce582015-10-22 18:38:17 +0000941 bool forStrongLayout,
942 bool hasMRCWeakIvars);
943
944 llvm::Constant *BuildStrongIvarLayout(const ObjCImplementationDecl *OI,
945 CharUnits beginOffset,
946 CharUnits endOffset) {
947 return BuildIvarLayout(OI, beginOffset, endOffset, true, false);
948 }
949
950 llvm::Constant *BuildWeakIvarLayout(const ObjCImplementationDecl *OI,
951 CharUnits beginOffset,
952 CharUnits endOffset,
953 bool hasMRCWeakIvars) {
954 return BuildIvarLayout(OI, beginOffset, endOffset, false, hasMRCWeakIvars);
955 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000956
Fariborz Jahaniana9d44642012-11-14 17:15:51 +0000957 Qualifiers::ObjCLifetime getBlockCaptureLifetime(QualType QT, bool ByrefLayout);
Fangrui Song6907ce22018-07-30 19:24:48 +0000958
Fariborz Jahanian39319c42012-10-30 20:05:29 +0000959 void UpdateRunSkipBlockVars(bool IsByref,
960 Qualifiers::ObjCLifetime LifeTime,
Fariborz Jahanian7778d612012-11-07 20:00:32 +0000961 CharUnits FieldOffset,
962 CharUnits FieldSize);
Fangrui Song6907ce22018-07-30 19:24:48 +0000963
Fariborz Jahanian39319c42012-10-30 20:05:29 +0000964 void BuildRCBlockVarRecordLayout(const RecordType *RT,
Fariborz Jahaniana9d44642012-11-14 17:15:51 +0000965 CharUnits BytePos, bool &HasUnion,
966 bool ByrefLayout=false);
Fangrui Song6907ce22018-07-30 19:24:48 +0000967
Fariborz Jahanian39319c42012-10-30 20:05:29 +0000968 void BuildRCRecordLayout(const llvm::StructLayout *RecLayout,
969 const RecordDecl *RD,
970 ArrayRef<const FieldDecl*> RecFields,
Fariborz Jahaniana9d44642012-11-14 17:15:51 +0000971 CharUnits BytePos, bool &HasUnion,
972 bool ByrefLayout);
Fangrui Song6907ce22018-07-30 19:24:48 +0000973
Fariborz Jahanian23290b02012-11-01 18:32:55 +0000974 uint64_t InlineLayoutInstruction(SmallVectorImpl<unsigned char> &Layout);
Fangrui Song6907ce22018-07-30 19:24:48 +0000975
Fariborz Jahaniana9d44642012-11-14 17:15:51 +0000976 llvm::Constant *getBitmapBlockLayout(bool ComputeByrefLayout);
Fangrui Song6907ce22018-07-30 19:24:48 +0000977
Fariborz Jahanian01dff422009-03-05 19:17:31 +0000978 /// GetIvarLayoutName - Returns a unique constant for the given
979 /// ivar layout bitmap.
980 llvm::Constant *GetIvarLayoutName(IdentifierInfo *Ident,
981 const ObjCCommonTypesHelper &ObjCTypes);
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000982
Fariborz Jahanian066347e2009-01-28 22:18:42 +0000983 /// EmitPropertyList - Emit the given property list. The return
984 /// value has type PropertyListPtrTy.
Zachary Turner41a9ee92017-10-11 23:54:34 +0000985 llvm::Constant *EmitPropertyList(Twine Name,
986 const Decl *Container,
Fariborz Jahanian066347e2009-01-28 22:18:42 +0000987 const ObjCContainerDecl *OCD,
Manman Renad0e7912016-01-29 19:22:54 +0000988 const ObjCCommonTypesHelper &ObjCTypes,
989 bool IsClassProperty);
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000990
Fangrui Song6907ce22018-07-30 19:24:48 +0000991 /// EmitProtocolMethodTypes - Generate the array of extended method type
Bob Wilson5f4e3a72011-11-30 01:57:58 +0000992 /// strings. The return value has type Int8PtrPtrTy.
Fangrui Song6907ce22018-07-30 19:24:48 +0000993 llvm::Constant *EmitProtocolMethodTypes(Twine Name,
Zachary Turner41a9ee92017-10-11 23:54:34 +0000994 ArrayRef<llvm::Constant*> MethodTypes,
995 const ObjCCommonTypesHelper &ObjCTypes);
Bob Wilson5f4e3a72011-11-30 01:57:58 +0000996
Fariborz Jahanian56b3b772009-01-29 19:24:30 +0000997 /// GetProtocolRef - Return a reference to the internal protocol
998 /// description, creating an empty one if it has not been
999 /// defined. The return value has type ProtocolPtrTy.
1000 llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD);
Fariborz Jahanian67726212009-03-08 20:18:37 +00001001
Douglas Gregor24ae22c2016-04-01 23:23:52 +00001002 /// Return a reference to the given Class using runtime calls rather than
1003 /// by a symbol reference.
1004 llvm::Value *EmitClassRefViaRuntime(CodeGenFunction &CGF,
1005 const ObjCInterfaceDecl *ID,
1006 ObjCCommonTypesHelper &ObjCTypes);
1007
Saleem Abdulrasool13d73d52017-06-03 16:18:09 +00001008 std::string GetSectionName(StringRef Section, StringRef MachOAttributes);
1009
John McCall3fd13f062015-10-21 18:06:47 +00001010public:
Daniel Dunbar30c65362009-03-09 20:09:19 +00001011 /// CreateMetadataVar - Create a global variable with internal
1012 /// linkage for use by the Objective-C runtime.
1013 ///
1014 /// This is a convenience wrapper which not only creates the
1015 /// variable, but also sets the section and alignment and adds the
Chris Lattnerf56501c2009-07-17 23:57:13 +00001016 /// global to the "llvm.used" list.
Daniel Dunbar463cc8a2009-03-09 20:50:13 +00001017 ///
1018 /// \param Name - The variable name.
1019 /// \param Init - The variable initializer; this is also used to
John McCall176f8922016-11-30 02:39:18 +00001020 /// define the type of the variable.
Alp Toker541d5072014-06-07 23:30:53 +00001021 /// \param Section - The section the variable should go into, or empty.
Daniel Dunbar463cc8a2009-03-09 20:50:13 +00001022 /// \param Align - The alignment for the variable, or 0.
1023 /// \param AddToUsed - Whether the variable should be added to
John McCall176f8922016-11-30 02:39:18 +00001024 /// "llvm.used".
Zachary Turner41a9ee92017-10-11 23:54:34 +00001025 llvm::GlobalVariable *CreateMetadataVar(Twine Name,
John McCall176f8922016-11-30 02:39:18 +00001026 ConstantStructBuilder &Init,
1027 StringRef Section, CharUnits Align,
1028 bool AddToUsed);
Zachary Turner41a9ee92017-10-11 23:54:34 +00001029 llvm::GlobalVariable *CreateMetadataVar(Twine Name,
John McCall176f8922016-11-30 02:39:18 +00001030 llvm::Constant *Init,
John McCall7f416cc2015-09-08 08:05:57 +00001031 StringRef Section, CharUnits Align,
Daniel Dunbar463cc8a2009-03-09 20:50:13 +00001032 bool AddToUsed);
Daniel Dunbar30c65362009-03-09 20:09:19 +00001033
Saleem Abdulrasool271106c2016-09-16 23:41:13 +00001034 llvm::GlobalVariable *CreateCStringLiteral(StringRef Name,
Saleem Abdulrasool82f6add2016-09-20 18:38:54 +00001035 ObjCLabelType LabelType,
1036 bool ForceNonFragileABI = false,
1037 bool NullTerminate = true);
Saleem Abdulrasool271106c2016-09-16 23:41:13 +00001038
John McCall3fd13f062015-10-21 18:06:47 +00001039protected:
John McCall9e8bb002011-05-14 03:10:52 +00001040 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
1041 ReturnValueSlot Return,
1042 QualType ResultType,
1043 llvm::Value *Sel,
1044 llvm::Value *Arg0,
1045 QualType Arg0Ty,
1046 bool IsSuper,
1047 const CallArgList &CallArgs,
1048 const ObjCMethodDecl *OMD,
John McCall1e3157b2015-09-10 22:27:50 +00001049 const ObjCInterfaceDecl *ClassReceiver,
John McCall9e8bb002011-05-14 03:10:52 +00001050 const ObjCCommonTypesHelper &ObjCTypes);
Daniel Dunbarf5c18462009-04-20 06:54:31 +00001051
Daniel Dunbar5e639272010-04-25 20:39:01 +00001052 /// EmitImageInfo - Emit the image info marker used to encode some module
1053 /// level information.
1054 void EmitImageInfo();
1055
Fariborz Jahanian279eda62009-01-21 22:04:16 +00001056public:
Owen Andersonae86c192009-07-13 04:10:07 +00001057 CGObjCCommonMac(CodeGen::CodeGenModule &cgm) :
John McCalla729c622012-02-17 03:33:10 +00001058 CGObjCRuntime(cgm), VMContext(cgm.getLLVMContext()) { }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001059
John McCall3fd13f062015-10-21 18:06:47 +00001060 bool isNonFragileABI() const {
1061 return ObjCABI == 2;
1062 }
1063
John McCall7f416cc2015-09-08 08:05:57 +00001064 ConstantAddress GenerateConstantString(const StringLiteral *SL) override;
John McCallcd21d542016-11-30 23:15:55 +00001065 ConstantAddress GenerateConstantNSString(const StringLiteral *SL);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001066
Craig Topper4f12f102014-03-12 06:41:41 +00001067 llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
Craig Topper8a13c412014-05-21 05:09:00 +00001068 const ObjCContainerDecl *CD=nullptr) override;
Craig Topper4f12f102014-03-12 06:41:41 +00001069
1070 void GenerateProtocol(const ObjCProtocolDecl *PD) override;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001071
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00001072 /// GetOrEmitProtocol - Get the protocol object for the given
1073 /// declaration, emitting it if necessary. The return value has type
1074 /// ProtocolPtrTy.
1075 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD)=0;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001076
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00001077 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
1078 /// object for the given declaration, emitting it if needed. These
1079 /// forward references will be filled in with empty bodies if no
1080 /// definition is seen. The return value has type ProtocolPtrTy.
1081 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD)=0;
John McCallcd21d542016-11-30 23:15:55 +00001082
1083 virtual llvm::Constant *getNSConstantStringClassRef() = 0;
1084
Craig Topper4f12f102014-03-12 06:41:41 +00001085 llvm::Constant *BuildGCBlockLayout(CodeGen::CodeGenModule &CGM,
1086 const CGBlockInfo &blockInfo) override;
1087 llvm::Constant *BuildRCBlockLayout(CodeGen::CodeGenModule &CGM,
1088 const CGBlockInfo &blockInfo) override;
Akira Hatanaka2ec36f02018-08-17 15:46:07 +00001089 std::string getRCBlockLayoutStr(CodeGen::CodeGenModule &CGM,
1090 const CGBlockInfo &blockInfo) override;
Craig Topper4f12f102014-03-12 06:41:41 +00001091
1092 llvm::Constant *BuildByrefLayout(CodeGen::CodeGenModule &CGM,
1093 QualType T) override;
Akira Hatanaka2ec36f02018-08-17 15:46:07 +00001094
1095private:
1096 void fillRunSkipBlockVars(CodeGenModule &CGM, const CGBlockInfo &blockInfo);
Fariborz Jahanian279eda62009-01-21 22:04:16 +00001097};
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001098
John McCall176f8922016-11-30 02:39:18 +00001099namespace {
1100
Saleem Abdulrasoold48b0a32016-10-24 20:47:58 +00001101enum class MethodListType {
1102 CategoryInstanceMethods,
1103 CategoryClassMethods,
1104 InstanceMethods,
1105 ClassMethods,
1106 ProtocolInstanceMethods,
1107 ProtocolClassMethods,
1108 OptionalProtocolInstanceMethods,
1109 OptionalProtocolClassMethods,
1110};
1111
John McCall176f8922016-11-30 02:39:18 +00001112/// A convenience class for splitting the methods of a protocol into
1113/// the four interesting groups.
1114class ProtocolMethodLists {
1115public:
1116 enum Kind {
1117 RequiredInstanceMethods,
1118 RequiredClassMethods,
1119 OptionalInstanceMethods,
1120 OptionalClassMethods
1121 };
1122 enum {
1123 NumProtocolMethodLists = 4
1124 };
1125
1126 static MethodListType getMethodListKind(Kind kind) {
1127 switch (kind) {
1128 case RequiredInstanceMethods:
1129 return MethodListType::ProtocolInstanceMethods;
1130 case RequiredClassMethods:
1131 return MethodListType::ProtocolClassMethods;
1132 case OptionalInstanceMethods:
1133 return MethodListType::OptionalProtocolInstanceMethods;
1134 case OptionalClassMethods:
1135 return MethodListType::OptionalProtocolClassMethods;
1136 }
1137 llvm_unreachable("bad kind");
1138 }
1139
1140 SmallVector<const ObjCMethodDecl *, 4> Methods[NumProtocolMethodLists];
1141
1142 static ProtocolMethodLists get(const ObjCProtocolDecl *PD) {
1143 ProtocolMethodLists result;
1144
1145 for (auto MD : PD->methods()) {
1146 size_t index = (2 * size_t(MD->isOptional()))
1147 + (size_t(MD->isClassMethod()));
1148 result.Methods[index].push_back(MD);
1149 }
1150
1151 return result;
1152 }
1153
1154 template <class Self>
1155 SmallVector<llvm::Constant*, 8> emitExtendedTypesArray(Self *self) const {
1156 // In both ABIs, the method types list is parallel with the
1157 // concatenation of the methods arrays in the following order:
1158 // instance methods
1159 // class methods
1160 // optional instance methods
1161 // optional class methods
1162 SmallVector<llvm::Constant*, 8> result;
1163
1164 // Methods is already in the correct order for both ABIs.
1165 for (auto &list : Methods) {
1166 for (auto MD : list) {
1167 result.push_back(self->GetMethodVarType(MD, true));
1168 }
1169 }
1170
1171 return result;
1172 }
1173
1174 template <class Self>
1175 llvm::Constant *emitMethodList(Self *self, const ObjCProtocolDecl *PD,
1176 Kind kind) const {
1177 return self->emitMethodList(PD->getObjCRuntimeNameAsString(),
1178 getMethodListKind(kind), Methods[kind]);
1179 }
1180};
1181
1182} // end anonymous namespace
1183
Fariborz Jahanian279eda62009-01-21 22:04:16 +00001184class CGObjCMac : public CGObjCCommonMac {
1185private:
John McCallc4ae1dd2016-11-30 04:18:19 +00001186 friend ProtocolMethodLists;
John McCall176f8922016-11-30 02:39:18 +00001187
Fariborz Jahanian279eda62009-01-21 22:04:16 +00001188 ObjCTypesHelper ObjCTypes;
Daniel Dunbar3ad53482008-08-11 21:35:06 +00001189
Daniel Dunbar7bd00bd2008-08-12 06:48:42 +00001190 /// EmitModuleInfo - Another marker encoding module level
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001191 /// information.
Daniel Dunbar7bd00bd2008-08-12 06:48:42 +00001192 void EmitModuleInfo();
1193
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00001194 /// EmitModuleSymols - Emit module symbols, the list of defined
1195 /// classes and categories. The result has type SymtabPtrTy.
Daniel Dunbar7bd00bd2008-08-12 06:48:42 +00001196 llvm::Constant *EmitModuleSymbols();
1197
Daniel Dunbar3ad53482008-08-11 21:35:06 +00001198 /// FinishModule - Write out global data structures at the end of
1199 /// processing a translation unit.
1200 void FinishModule();
Daniel Dunbarb036db82008-08-13 03:21:16 +00001201
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00001202 /// EmitClassExtension - Generate the class extension structure used
1203 /// to store the weak ivar layout and properties. The return value
1204 /// has type ClassExtensionPtrTy.
John McCall3fd13f062015-10-21 18:06:47 +00001205 llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID,
John McCall460ce582015-10-22 18:38:17 +00001206 CharUnits instanceSize,
Manman Renad0e7912016-01-29 19:22:54 +00001207 bool hasMRCWeakIvars,
John McCall176f8922016-11-30 02:39:18 +00001208 bool isMetaclass);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00001209
1210 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
1211 /// for the given class.
John McCall882987f2013-02-28 19:01:20 +00001212 llvm::Value *EmitClassRef(CodeGenFunction &CGF,
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00001213 const ObjCInterfaceDecl *ID);
Fangrui Song6907ce22018-07-30 19:24:48 +00001214
John McCall882987f2013-02-28 19:01:20 +00001215 llvm::Value *EmitClassRefFromId(CodeGenFunction &CGF,
John McCall31168b02011-06-15 23:02:42 +00001216 IdentifierInfo *II);
Craig Topper4f12f102014-03-12 06:41:41 +00001217
1218 llvm::Value *EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) override;
1219
Fariborz Jahanianeb80c982009-11-12 20:14:24 +00001220 /// EmitSuperClassRef - Emits reference to class's main metadata class.
1221 llvm::Value *EmitSuperClassRef(const ObjCInterfaceDecl *ID);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00001222
1223 /// EmitIvarList - Emit the ivar list for the given
1224 /// implementation. If ForClass is true the list of class ivars
1225 /// (i.e. metaclass ivars) is emitted, otherwise the list of
1226 /// interface ivars will be emitted. The return value has type
1227 /// IvarListPtrTy.
1228 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanianb042a592009-01-28 19:12:34 +00001229 bool ForClass);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001230
Daniel Dunbarca8531a2008-08-25 08:19:24 +00001231 /// EmitMetaClass - Emit a forward reference to the class structure
1232 /// for the metaclass of the given interface. The return value has
1233 /// type ClassPtrTy.
1234 llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
1235
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00001236 /// EmitMetaClass - Emit a class structure for the metaclass of the
Daniel Dunbarca8531a2008-08-25 08:19:24 +00001237 /// given implementation. The return value has type ClassPtrTy.
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00001238 llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
1239 llvm::Constant *Protocols,
John McCall176f8922016-11-30 02:39:18 +00001240 ArrayRef<const ObjCMethodDecl *> Methods);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001241
John McCall176f8922016-11-30 02:39:18 +00001242 void emitMethodConstant(ConstantArrayBuilder &builder,
1243 const ObjCMethodDecl *MD);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001244
John McCall176f8922016-11-30 02:39:18 +00001245 void emitMethodDescriptionConstant(ConstantArrayBuilder &builder,
1246 const ObjCMethodDecl *MD);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00001247
1248 /// EmitMethodList - Emit the method list for the given
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001249 /// implementation. The return value has type MethodListPtrTy.
Zachary Turner41a9ee92017-10-11 23:54:34 +00001250 llvm::Constant *emitMethodList(Twine Name, MethodListType MLT,
John McCall176f8922016-11-30 02:39:18 +00001251 ArrayRef<const ObjCMethodDecl *> Methods);
Daniel Dunbarb036db82008-08-13 03:21:16 +00001252
Daniel Dunbarc475d422008-10-29 22:36:39 +00001253 /// GetOrEmitProtocol - Get the protocol object for the given
1254 /// declaration, emitting it if necessary. The return value has type
1255 /// ProtocolPtrTy.
Craig Topper4f12f102014-03-12 06:41:41 +00001256 llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD) override;
Daniel Dunbarc475d422008-10-29 22:36:39 +00001257
1258 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
1259 /// object for the given declaration, emitting it if needed. These
1260 /// forward references will be filled in with empty bodies if no
1261 /// definition is seen. The return value has type ProtocolPtrTy.
Craig Topper4f12f102014-03-12 06:41:41 +00001262 llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) override;
Daniel Dunbarc475d422008-10-29 22:36:39 +00001263
Daniel Dunbarb036db82008-08-13 03:21:16 +00001264 /// EmitProtocolExtension - Generate the protocol extension
1265 /// structure used to store optional instance and class methods, and
1266 /// protocol properties. The return value has type
1267 /// ProtocolExtensionPtrTy.
Daniel Dunbareb1f9a22008-08-27 02:31:56 +00001268 llvm::Constant *
1269 EmitProtocolExtension(const ObjCProtocolDecl *PD,
John McCall176f8922016-11-30 02:39:18 +00001270 const ProtocolMethodLists &methodLists);
Daniel Dunbarb036db82008-08-13 03:21:16 +00001271
1272 /// EmitProtocolList - Generate the list of referenced
1273 /// protocols. The return value has type ProtocolListPtrTy.
Zachary Turner41a9ee92017-10-11 23:54:34 +00001274 llvm::Constant *EmitProtocolList(Twine Name,
Daniel Dunbardec75f82008-08-21 21:57:41 +00001275 ObjCProtocolDecl::protocol_iterator begin,
1276 ObjCProtocolDecl::protocol_iterator end);
Daniel Dunbarb036db82008-08-13 03:21:16 +00001277
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00001278 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
1279 /// for the given selector.
John McCall7f416cc2015-09-08 08:05:57 +00001280 llvm::Value *EmitSelector(CodeGenFunction &CGF, Selector Sel);
1281 Address EmitSelectorAddr(CodeGenFunction &CGF, Selector Sel);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001282
1283public:
Daniel Dunbar303e2c22008-08-11 02:45:11 +00001284 CGObjCMac(CodeGen::CodeGenModule &cgm);
Daniel Dunbar303e2c22008-08-11 02:45:11 +00001285
John McCallcd21d542016-11-30 23:15:55 +00001286 llvm::Constant *getNSConstantStringClassRef() override;
1287
Craig Topper4f12f102014-03-12 06:41:41 +00001288 llvm::Function *ModuleInitFunction() override;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001289
Craig Topper4f12f102014-03-12 06:41:41 +00001290 CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
1291 ReturnValueSlot Return,
1292 QualType ResultType,
1293 Selector Sel, llvm::Value *Receiver,
1294 const CallArgList &CallArgs,
1295 const ObjCInterfaceDecl *Class,
1296 const ObjCMethodDecl *Method) override;
Daniel Dunbar303e2c22008-08-11 02:45:11 +00001297
Craig Topper4f12f102014-03-12 06:41:41 +00001298 CodeGen::RValue
Daniel Dunbar97db84c2008-08-23 03:46:30 +00001299 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00001300 ReturnValueSlot Return, QualType ResultType,
1301 Selector Sel, const ObjCInterfaceDecl *Class,
1302 bool isCategoryImpl, llvm::Value *Receiver,
1303 bool IsClassMessage, const CallArgList &CallArgs,
1304 const ObjCMethodDecl *Method) override;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001305
Craig Topper4f12f102014-03-12 06:41:41 +00001306 llvm::Value *GetClass(CodeGenFunction &CGF,
1307 const ObjCInterfaceDecl *ID) override;
Daniel Dunbar303e2c22008-08-11 02:45:11 +00001308
John McCall7f416cc2015-09-08 08:05:57 +00001309 llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel) override;
1310 Address GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) override;
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001311
1312 /// The NeXT/Apple runtimes do not support typed selectors; just emit an
1313 /// untyped one.
Craig Topper4f12f102014-03-12 06:41:41 +00001314 llvm::Value *GetSelector(CodeGenFunction &CGF,
1315 const ObjCMethodDecl *Method) override;
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001316
Craig Topper4f12f102014-03-12 06:41:41 +00001317 llvm::Constant *GetEHType(QualType T) override;
John McCall2ca705e2010-07-24 00:37:23 +00001318
Craig Topper4f12f102014-03-12 06:41:41 +00001319 void GenerateCategory(const ObjCCategoryImplDecl *CMD) override;
Daniel Dunbar303e2c22008-08-11 02:45:11 +00001320
Craig Topper4f12f102014-03-12 06:41:41 +00001321 void GenerateClass(const ObjCImplementationDecl *ClassDecl) override;
Daniel Dunbar303e2c22008-08-11 02:45:11 +00001322
Craig Topper4f12f102014-03-12 06:41:41 +00001323 void RegisterAlias(const ObjCCompatibleAliasDecl *OAD) override {}
David Chisnall92d436b2012-01-31 18:59:20 +00001324
Craig Topper4f12f102014-03-12 06:41:41 +00001325 llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,
1326 const ObjCProtocolDecl *PD) override;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001327
Craig Topper4f12f102014-03-12 06:41:41 +00001328 llvm::Constant *GetPropertyGetFunction() override;
1329 llvm::Constant *GetPropertySetFunction() override;
1330 llvm::Constant *GetOptimizedPropertySetFunction(bool atomic,
1331 bool copy) override;
1332 llvm::Constant *GetGetStructFunction() override;
1333 llvm::Constant *GetSetStructFunction() override;
1334 llvm::Constant *GetCppAtomicObjectGetFunction() override;
1335 llvm::Constant *GetCppAtomicObjectSetFunction() override;
1336 llvm::Constant *EnumerationMutationFunction() override;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001337
Craig Topper4f12f102014-03-12 06:41:41 +00001338 void EmitTryStmt(CodeGen::CodeGenFunction &CGF,
1339 const ObjCAtTryStmt &S) override;
1340 void EmitSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
1341 const ObjCAtSynchronizedStmt &S) override;
John McCallbd309292010-07-06 01:34:17 +00001342 void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF, const Stmt &S);
Craig Topper4f12f102014-03-12 06:41:41 +00001343 void EmitThrowStmt(CodeGen::CodeGenFunction &CGF, const ObjCAtThrowStmt &S,
1344 bool ClearInsertionPoint=true) override;
1345 llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001346 Address AddrWeakObj) override;
Craig Topper4f12f102014-03-12 06:41:41 +00001347 void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001348 llvm::Value *src, Address dst) override;
Craig Topper4f12f102014-03-12 06:41:41 +00001349 void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001350 llvm::Value *src, Address dest,
Craig Topper4f12f102014-03-12 06:41:41 +00001351 bool threadlocal = false) override;
1352 void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001353 llvm::Value *src, Address dest,
Craig Topper4f12f102014-03-12 06:41:41 +00001354 llvm::Value *ivarOffset) override;
1355 void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001356 llvm::Value *src, Address dest) override;
Craig Topper4f12f102014-03-12 06:41:41 +00001357 void EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001358 Address dest, Address src,
Craig Topper4f12f102014-03-12 06:41:41 +00001359 llvm::Value *size) override;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001360
Craig Topper4f12f102014-03-12 06:41:41 +00001361 LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF, QualType ObjectTy,
1362 llvm::Value *BaseValue, const ObjCIvarDecl *Ivar,
1363 unsigned CVRQualifiers) override;
1364 llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
1365 const ObjCInterfaceDecl *Interface,
1366 const ObjCIvarDecl *Ivar) override;
Daniel Dunbar303e2c22008-08-11 02:45:11 +00001367};
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001368
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00001369class CGObjCNonFragileABIMac : public CGObjCCommonMac {
Fariborz Jahanian279eda62009-01-21 22:04:16 +00001370private:
John McCallc4ae1dd2016-11-30 04:18:19 +00001371 friend ProtocolMethodLists;
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00001372 ObjCNonFragileABITypesHelper ObjCTypes;
Fariborz Jahanian71394042009-01-23 23:53:38 +00001373 llvm::GlobalVariable* ObjCEmptyCacheVar;
John McCall176f8922016-11-30 02:39:18 +00001374 llvm::Constant* ObjCEmptyVtableVar;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001375
Daniel Dunbar508a7dd2009-04-18 08:51:00 +00001376 /// SuperClassReferences - uniqued super class references.
1377 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> SuperClassReferences;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001378
Fariborz Jahanian6b7cd6e2009-02-06 20:09:23 +00001379 /// MetaClassReferences - uniqued meta class references.
1380 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> MetaClassReferences;
Daniel Dunbarb1559a42009-03-01 04:46:24 +00001381
1382 /// EHTypeReferences - uniqued class ehtype references.
1383 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> EHTypeReferences;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001384
John McCall9e8bb002011-05-14 03:10:52 +00001385 /// VTableDispatchMethods - List of methods for which we generate
1386 /// vtable-based message dispatch.
1387 llvm::DenseSet<Selector> VTableDispatchMethods;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001388
Fariborz Jahanian67260552009-11-17 21:37:35 +00001389 /// DefinedMetaClasses - List of defined meta-classes.
1390 std::vector<llvm::GlobalValue*> DefinedMetaClasses;
Fangrui Song6907ce22018-07-30 19:24:48 +00001391
John McCall9e8bb002011-05-14 03:10:52 +00001392 /// isVTableDispatchedSelector - Returns true if SEL is a
1393 /// vtable-based selector.
1394 bool isVTableDispatchedSelector(Selector Sel);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001395
Fariborz Jahanian71394042009-01-23 23:53:38 +00001396 /// FinishNonFragileABIModule - Write out global data structures at the end of
1397 /// processing a translation unit.
1398 void FinishNonFragileABIModule();
Daniel Dunbar8f28d012009-04-08 04:21:03 +00001399
Daniel Dunbar19573e72009-05-15 21:48:48 +00001400 /// AddModuleClassList - Add the given list of class pointers to the
1401 /// module with the provided symbol and section names.
Saleem Abdulrasool1e6c4062016-05-16 05:06:49 +00001402 void AddModuleClassList(ArrayRef<llvm::GlobalValue *> Container,
1403 StringRef SymbolName, StringRef SectionName);
Daniel Dunbar19573e72009-05-15 21:48:48 +00001404
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001405 llvm::GlobalVariable * BuildClassRoTInitializer(unsigned flags,
1406 unsigned InstanceStart,
1407 unsigned InstanceSize,
1408 const ObjCImplementationDecl *ID);
John McCalldba63a72016-11-30 23:54:50 +00001409 llvm::GlobalVariable *BuildClassObject(const ObjCInterfaceDecl *CI,
1410 bool isMetaclass,
1411 llvm::Constant *IsAGV,
1412 llvm::Constant *SuperClassGV,
1413 llvm::Constant *ClassRoGV,
1414 bool HiddenVisibility);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001415
John McCall176f8922016-11-30 02:39:18 +00001416 void emitMethodConstant(ConstantArrayBuilder &builder,
1417 const ObjCMethodDecl *MD,
1418 bool forProtocol);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001419
John McCall176f8922016-11-30 02:39:18 +00001420 /// Emit the method list for the given implementation. The return value
1421 /// has type MethodListnfABITy.
Zachary Turner41a9ee92017-10-11 23:54:34 +00001422 llvm::Constant *emitMethodList(Twine Name, MethodListType MLT,
John McCall176f8922016-11-30 02:39:18 +00001423 ArrayRef<const ObjCMethodDecl *> Methods);
Saleem Abdulrasoold48b0a32016-10-24 20:47:58 +00001424
Fariborz Jahanian7415caa2009-01-27 19:38:51 +00001425 /// EmitIvarList - Emit the ivar list for the given
1426 /// implementation. If ForClass is true the list of class ivars
1427 /// (i.e. metaclass ivars) is emitted, otherwise the list of
1428 /// interface ivars will be emitted. The return value has type
1429 /// IvarListnfABIPtrTy.
1430 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001431
Fariborz Jahanian4e7ae062009-02-10 20:21:06 +00001432 llvm::Constant *EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,
Fariborz Jahanian3d3426f2009-01-28 01:36:42 +00001433 const ObjCIvarDecl *Ivar,
Eli Friedman8cbca202012-11-06 22:15:52 +00001434 unsigned long int offset);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001435
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00001436 /// GetOrEmitProtocol - Get the protocol object for the given
1437 /// declaration, emitting it if necessary. The return value has type
1438 /// ProtocolPtrTy.
Craig Topper4f12f102014-03-12 06:41:41 +00001439 llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD) override;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001440
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00001441 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
1442 /// object for the given declaration, emitting it if needed. These
1443 /// forward references will be filled in with empty bodies if no
1444 /// definition is seen. The return value has type ProtocolPtrTy.
Craig Topper4f12f102014-03-12 06:41:41 +00001445 llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) override;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001446
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00001447 /// EmitProtocolList - Generate the list of referenced
1448 /// protocols. The return value has type ProtocolListPtrTy.
Zachary Turner41a9ee92017-10-11 23:54:34 +00001449 llvm::Constant *EmitProtocolList(Twine Name,
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00001450 ObjCProtocolDecl::protocol_iterator begin,
Fariborz Jahanian3d9296e2009-02-04 00:22:57 +00001451 ObjCProtocolDecl::protocol_iterator end);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001452
John McCall9e8bb002011-05-14 03:10:52 +00001453 CodeGen::RValue EmitVTableMessageSend(CodeGen::CodeGenFunction &CGF,
1454 ReturnValueSlot Return,
1455 QualType ResultType,
1456 Selector Sel,
1457 llvm::Value *Receiver,
1458 QualType Arg0Ty,
1459 bool IsSuper,
1460 const CallArgList &CallArgs,
1461 const ObjCMethodDecl *Method);
Fangrui Song6907ce22018-07-30 19:24:48 +00001462
Daniel Dunbarc6928bb2009-03-01 04:40:10 +00001463 /// GetClassGlobal - Return the global variable for the Objective-C
1464 /// class of the given name.
John McCalldba63a72016-11-30 23:54:50 +00001465 llvm::Constant *GetClassGlobal(StringRef Name,
1466 ForDefinition_t IsForDefinition,
1467 bool Weak = false, bool DLLImport = false);
1468 llvm::Constant *GetClassGlobal(const ObjCInterfaceDecl *ID,
1469 bool isMetaclass,
1470 ForDefinition_t isForDefinition);
Rafael Espindola554256c2014-02-26 22:25:45 +00001471
Fariborz Jahanian33f66e62009-02-05 20:41:40 +00001472 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
Daniel Dunbar508a7dd2009-04-18 08:51:00 +00001473 /// for the given class reference.
John McCall882987f2013-02-28 19:01:20 +00001474 llvm::Value *EmitClassRef(CodeGenFunction &CGF,
Daniel Dunbar508a7dd2009-04-18 08:51:00 +00001475 const ObjCInterfaceDecl *ID);
Fangrui Song6907ce22018-07-30 19:24:48 +00001476
John McCall882987f2013-02-28 19:01:20 +00001477 llvm::Value *EmitClassRefFromId(CodeGenFunction &CGF,
John McCalldba63a72016-11-30 23:54:50 +00001478 IdentifierInfo *II,
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00001479 const ObjCInterfaceDecl *ID);
Craig Topper4f12f102014-03-12 06:41:41 +00001480
1481 llvm::Value *EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) override;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001482
Daniel Dunbar508a7dd2009-04-18 08:51:00 +00001483 /// EmitSuperClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
1484 /// for the given super class reference.
John McCall882987f2013-02-28 19:01:20 +00001485 llvm::Value *EmitSuperClassRef(CodeGenFunction &CGF,
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001486 const ObjCInterfaceDecl *ID);
1487
Fariborz Jahanian6b7cd6e2009-02-06 20:09:23 +00001488 /// EmitMetaClassRef - Return a Value * of the address of _class_t
1489 /// meta-data
John McCall882987f2013-02-28 19:01:20 +00001490 llvm::Value *EmitMetaClassRef(CodeGenFunction &CGF,
Fariborz Jahanian0b3bc242014-06-10 17:08:04 +00001491 const ObjCInterfaceDecl *ID, bool Weak);
Fariborz Jahanian6b7cd6e2009-02-06 20:09:23 +00001492
Fariborz Jahanian4e7ae062009-02-10 20:21:06 +00001493 /// ObjCIvarOffsetVariable - Returns the ivar offset variable for
1494 /// the given ivar.
1495 ///
Daniel Dunbara1060522009-04-19 00:31:15 +00001496 llvm::GlobalVariable * ObjCIvarOffsetVariable(
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001497 const ObjCInterfaceDecl *ID,
1498 const ObjCIvarDecl *Ivar);
1499
Fariborz Jahanian74b77222009-02-11 20:51:17 +00001500 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
1501 /// for the given selector.
John McCall7f416cc2015-09-08 08:05:57 +00001502 llvm::Value *EmitSelector(CodeGenFunction &CGF, Selector Sel);
1503 Address EmitSelectorAddr(CodeGenFunction &CGF, Selector Sel);
Daniel Dunbarb1559a42009-03-01 04:46:24 +00001504
Daniel Dunbar8f28d012009-04-08 04:21:03 +00001505 /// GetInterfaceEHType - Get the cached ehtype for the given Objective-C
Daniel Dunbarb1559a42009-03-01 04:46:24 +00001506 /// interface. The return value has type EHTypePtrTy.
John McCall2ca705e2010-07-24 00:37:23 +00001507 llvm::Constant *GetInterfaceEHType(const ObjCInterfaceDecl *ID,
John McCalldba63a72016-11-30 23:54:50 +00001508 ForDefinition_t IsForDefinition);
Daniel Dunbar15894b72009-04-07 05:48:37 +00001509
Saleem Abdulrasool1e6c4062016-05-16 05:06:49 +00001510 StringRef getMetaclassSymbolPrefix() const { return "OBJC_METACLASS_$_"; }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001511
Saleem Abdulrasool1e6c4062016-05-16 05:06:49 +00001512 StringRef getClassSymbolPrefix() const { return "OBJC_CLASS_$_"; }
Daniel Dunbar15894b72009-04-07 05:48:37 +00001513
Daniel Dunbar961202372009-05-03 12:57:56 +00001514 void GetClassSizeInfo(const ObjCImplementationDecl *OID,
Daniel Dunbar554fd792009-04-19 23:41:48 +00001515 uint32_t &InstanceStart,
1516 uint32_t &InstanceSize);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001517
Fariborz Jahaniane4128642009-05-12 20:06:41 +00001518 // Shamelessly stolen from Analysis/CFRefCount.cpp
Daniel Dunbar9a017d72009-05-15 22:33:15 +00001519 Selector GetNullarySelector(const char* name) const {
Fariborz Jahaniane4128642009-05-12 20:06:41 +00001520 IdentifierInfo* II = &CGM.getContext().Idents.get(name);
1521 return CGM.getContext().Selectors.getSelector(0, &II);
1522 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001523
Daniel Dunbar9a017d72009-05-15 22:33:15 +00001524 Selector GetUnarySelector(const char* name) const {
Fariborz Jahaniane4128642009-05-12 20:06:41 +00001525 IdentifierInfo* II = &CGM.getContext().Idents.get(name);
1526 return CGM.getContext().Selectors.getSelector(1, &II);
1527 }
Daniel Dunbar554fd792009-04-19 23:41:48 +00001528
Daniel Dunbar9a017d72009-05-15 22:33:15 +00001529 /// ImplementationIsNonLazy - Check whether the given category or
1530 /// class implementation is "non-lazy".
Fariborz Jahaniana6bed832009-05-21 01:03:45 +00001531 bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const;
Daniel Dunbar9a017d72009-05-15 22:33:15 +00001532
Saleem Abdulrasool5f25bc32013-02-17 04:03:34 +00001533 bool IsIvarOffsetKnownIdempotent(const CodeGen::CodeGenFunction &CGF,
Saleem Abdulrasool5f25bc32013-02-17 04:03:34 +00001534 const ObjCIvarDecl *IV) {
Fariborz Jahaniandafffbe2014-03-04 18:34:52 +00001535 // Annotate the load as an invariant load iff inside an instance method
1536 // and ivar belongs to instance method's class and one of its super class.
1537 // This check is needed because the ivar offset is a lazily
Saleem Abdulrasool5f25bc32013-02-17 04:03:34 +00001538 // initialised value that may depend on objc_msgSend to perform a fixup on
1539 // the first message dispatch.
1540 //
1541 // An additional opportunity to mark the load as invariant arises when the
1542 // base of the ivar access is a parameter to an Objective C method.
1543 // However, because the parameters are not available in the current
1544 // interface, we cannot perform this check.
Fariborz Jahaniandafffbe2014-03-04 18:34:52 +00001545 if (const ObjCMethodDecl *MD =
1546 dyn_cast_or_null<ObjCMethodDecl>(CGF.CurFuncDecl))
Fariborz Jahanian7a583022014-03-04 22:57:32 +00001547 if (MD->isInstanceMethod())
Fariborz Jahaniandafffbe2014-03-04 18:34:52 +00001548 if (const ObjCInterfaceDecl *ID = MD->getClassInterface())
1549 return IV->getContainingInterface()->isSuperClassOf(ID);
Saleem Abdulrasool5f25bc32013-02-17 04:03:34 +00001550 return false;
1551 }
1552
Fariborz Jahanian279eda62009-01-21 22:04:16 +00001553public:
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00001554 CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm);
John McCallcd21d542016-11-30 23:15:55 +00001555
1556 llvm::Constant *getNSConstantStringClassRef() override;
1557
Craig Topper4f12f102014-03-12 06:41:41 +00001558 llvm::Function *ModuleInitFunction() override;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001559
Craig Topper4f12f102014-03-12 06:41:41 +00001560 CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
1561 ReturnValueSlot Return,
1562 QualType ResultType, Selector Sel,
1563 llvm::Value *Receiver,
1564 const CallArgList &CallArgs,
1565 const ObjCInterfaceDecl *Class,
1566 const ObjCMethodDecl *Method) override;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001567
Craig Topper4f12f102014-03-12 06:41:41 +00001568 CodeGen::RValue
Fariborz Jahanian71394042009-01-23 23:53:38 +00001569 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00001570 ReturnValueSlot Return, QualType ResultType,
1571 Selector Sel, const ObjCInterfaceDecl *Class,
1572 bool isCategoryImpl, llvm::Value *Receiver,
1573 bool IsClassMessage, const CallArgList &CallArgs,
1574 const ObjCMethodDecl *Method) override;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001575
Craig Topper4f12f102014-03-12 06:41:41 +00001576 llvm::Value *GetClass(CodeGenFunction &CGF,
1577 const ObjCInterfaceDecl *ID) override;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001578
John McCall7f416cc2015-09-08 08:05:57 +00001579 llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel) override
1580 { return EmitSelector(CGF, Sel); }
1581 Address GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) override
1582 { return EmitSelectorAddr(CGF, Sel); }
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001583
1584 /// The NeXT/Apple runtimes do not support typed selectors; just emit an
1585 /// untyped one.
Craig Topper4f12f102014-03-12 06:41:41 +00001586 llvm::Value *GetSelector(CodeGenFunction &CGF,
1587 const ObjCMethodDecl *Method) override
John McCall882987f2013-02-28 19:01:20 +00001588 { return EmitSelector(CGF, Method->getSelector()); }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001589
Craig Topper4f12f102014-03-12 06:41:41 +00001590 void GenerateCategory(const ObjCCategoryImplDecl *CMD) override;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001591
Craig Topper4f12f102014-03-12 06:41:41 +00001592 void GenerateClass(const ObjCImplementationDecl *ClassDecl) override;
David Chisnall92d436b2012-01-31 18:59:20 +00001593
Craig Topper4f12f102014-03-12 06:41:41 +00001594 void RegisterAlias(const ObjCCompatibleAliasDecl *OAD) override {}
David Chisnall92d436b2012-01-31 18:59:20 +00001595
Craig Topper4f12f102014-03-12 06:41:41 +00001596 llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,
1597 const ObjCProtocolDecl *PD) override;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001598
Craig Topper4f12f102014-03-12 06:41:41 +00001599 llvm::Constant *GetEHType(QualType T) override;
John McCall2ca705e2010-07-24 00:37:23 +00001600
Craig Topper4f12f102014-03-12 06:41:41 +00001601 llvm::Constant *GetPropertyGetFunction() override {
Chris Lattnerce8754e2009-04-22 02:44:54 +00001602 return ObjCTypes.getGetPropertyFn();
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00001603 }
Craig Topper4f12f102014-03-12 06:41:41 +00001604 llvm::Constant *GetPropertySetFunction() override {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001605 return ObjCTypes.getSetPropertyFn();
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00001606 }
Craig Topper4f12f102014-03-12 06:41:41 +00001607
1608 llvm::Constant *GetOptimizedPropertySetFunction(bool atomic,
1609 bool copy) override {
Ted Kremeneke65b0862012-03-06 20:05:56 +00001610 return ObjCTypes.getOptimizedSetPropertyFn(atomic, copy);
1611 }
Craig Topper4f12f102014-03-12 06:41:41 +00001612
1613 llvm::Constant *GetSetStructFunction() override {
David Chisnall168b80f2010-12-26 22:13:16 +00001614 return ObjCTypes.getCopyStructFn();
1615 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001616
Craig Topper4f12f102014-03-12 06:41:41 +00001617 llvm::Constant *GetGetStructFunction() override {
Fariborz Jahanian5a8c2032010-04-12 18:18:10 +00001618 return ObjCTypes.getCopyStructFn();
1619 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001620
Craig Topper4f12f102014-03-12 06:41:41 +00001621 llvm::Constant *GetCppAtomicObjectSetFunction() override {
David Chisnall0d75e062012-12-17 18:54:24 +00001622 return ObjCTypes.getCppAtomicObjectFunction();
1623 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001624
Craig Topper4f12f102014-03-12 06:41:41 +00001625 llvm::Constant *GetCppAtomicObjectGetFunction() override {
Fariborz Jahanian1e1b5492012-01-06 18:07:23 +00001626 return ObjCTypes.getCppAtomicObjectFunction();
1627 }
Craig Topper4f12f102014-03-12 06:41:41 +00001628
1629 llvm::Constant *EnumerationMutationFunction() override {
Chris Lattnerce8754e2009-04-22 02:44:54 +00001630 return ObjCTypes.getEnumerationMutationFn();
Daniel Dunbard73ea8162009-02-16 18:48:45 +00001631 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001632
Craig Topper4f12f102014-03-12 06:41:41 +00001633 void EmitTryStmt(CodeGen::CodeGenFunction &CGF,
1634 const ObjCAtTryStmt &S) override;
1635 void EmitSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
1636 const ObjCAtSynchronizedStmt &S) override;
1637 void EmitThrowStmt(CodeGen::CodeGenFunction &CGF, const ObjCAtThrowStmt &S,
1638 bool ClearInsertionPoint=true) override;
1639 llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001640 Address AddrWeakObj) override;
Craig Topper4f12f102014-03-12 06:41:41 +00001641 void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001642 llvm::Value *src, Address edst) override;
Craig Topper4f12f102014-03-12 06:41:41 +00001643 void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001644 llvm::Value *src, Address dest,
Craig Topper4f12f102014-03-12 06:41:41 +00001645 bool threadlocal = false) override;
1646 void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001647 llvm::Value *src, Address dest,
Craig Topper4f12f102014-03-12 06:41:41 +00001648 llvm::Value *ivarOffset) override;
1649 void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001650 llvm::Value *src, Address dest) override;
Craig Topper4f12f102014-03-12 06:41:41 +00001651 void EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001652 Address dest, Address src,
Craig Topper4f12f102014-03-12 06:41:41 +00001653 llvm::Value *size) override;
1654 LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF, QualType ObjectTy,
1655 llvm::Value *BaseValue, const ObjCIvarDecl *Ivar,
1656 unsigned CVRQualifiers) override;
1657 llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
1658 const ObjCInterfaceDecl *Interface,
1659 const ObjCIvarDecl *Ivar) override;
Fariborz Jahanian279eda62009-01-21 22:04:16 +00001660};
Fariborz Jahanian715fdd52012-01-29 20:27:13 +00001661
1662/// A helper class for performing the null-initialization of a return
1663/// value.
1664struct NullReturnState {
1665 llvm::BasicBlock *NullBB;
Craig Topper8a13c412014-05-21 05:09:00 +00001666 NullReturnState() : NullBB(nullptr) {}
Fariborz Jahanian715fdd52012-01-29 20:27:13 +00001667
John McCall3d1e2c92013-02-12 05:53:35 +00001668 /// Perform a null-check of the given receiver.
Fariborz Jahanian715fdd52012-01-29 20:27:13 +00001669 void init(CodeGenFunction &CGF, llvm::Value *receiver) {
John McCall3d1e2c92013-02-12 05:53:35 +00001670 // Make blocks for the null-receiver and call edges.
1671 NullBB = CGF.createBasicBlock("msgSend.null-receiver");
1672 llvm::BasicBlock *callBB = CGF.createBasicBlock("msgSend.call");
Fariborz Jahanian715fdd52012-01-29 20:27:13 +00001673
1674 // Check for a null receiver and, if there is one, jump to the
John McCall3d1e2c92013-02-12 05:53:35 +00001675 // null-receiver block. There's no point in trying to avoid it:
1676 // we're always going to put *something* there, because otherwise
1677 // we shouldn't have done this null-check in the first place.
Fariborz Jahanian715fdd52012-01-29 20:27:13 +00001678 llvm::Value *isNull = CGF.Builder.CreateIsNull(receiver);
1679 CGF.Builder.CreateCondBr(isNull, NullBB, callBB);
1680
1681 // Otherwise, start performing the call.
1682 CGF.EmitBlock(callBB);
1683 }
1684
John McCall3d1e2c92013-02-12 05:53:35 +00001685 /// Complete the null-return operation. It is valid to call this
1686 /// regardless of whether 'init' has been called.
Kuba Mracekbce5cea2017-06-30 16:28:15 +00001687 RValue complete(CodeGenFunction &CGF,
1688 ReturnValueSlot returnSlot,
1689 RValue result,
1690 QualType resultType,
Fariborz Jahanianf2bda692012-01-30 21:40:37 +00001691 const CallArgList &CallArgs,
1692 const ObjCMethodDecl *Method) {
John McCall3d1e2c92013-02-12 05:53:35 +00001693 // If we never had to do a null-check, just use the raw result.
Fariborz Jahanian715fdd52012-01-29 20:27:13 +00001694 if (!NullBB) return result;
John McCall3d1e2c92013-02-12 05:53:35 +00001695
1696 // The continuation block. This will be left null if we don't have an
1697 // IP, which can happen if the method we're calling is marked noreturn.
Craig Topper8a13c412014-05-21 05:09:00 +00001698 llvm::BasicBlock *contBB = nullptr;
1699
John McCall3d1e2c92013-02-12 05:53:35 +00001700 // Finish the call path.
1701 llvm::BasicBlock *callBB = CGF.Builder.GetInsertBlock();
1702 if (callBB) {
1703 contBB = CGF.createBasicBlock("msgSend.cont");
1704 CGF.Builder.CreateBr(contBB);
Fariborz Jahanianf2bda692012-01-30 21:40:37 +00001705 }
Fariborz Jahanian715fdd52012-01-29 20:27:13 +00001706
John McCall3d1e2c92013-02-12 05:53:35 +00001707 // Okay, start emitting the null-receiver block.
Fariborz Jahanian715fdd52012-01-29 20:27:13 +00001708 CGF.EmitBlock(NullBB);
Fangrui Song6907ce22018-07-30 19:24:48 +00001709
John McCall3d1e2c92013-02-12 05:53:35 +00001710 // Release any consumed arguments we've got.
Fariborz Jahanianf2bda692012-01-30 21:40:37 +00001711 if (Method) {
1712 CallArgList::const_iterator I = CallArgs.begin();
1713 for (ObjCMethodDecl::param_const_iterator i = Method->param_begin(),
1714 e = Method->param_end(); i != e; ++i, ++I) {
1715 const ParmVarDecl *ParamDecl = (*i);
1716 if (ParamDecl->hasAttr<NSConsumedAttr>()) {
Yaxun Liu5b330e82018-03-15 15:25:19 +00001717 RValue RV = I->getRValue(CGF);
Fangrui Song6907ce22018-07-30 19:24:48 +00001718 assert(RV.isScalar() &&
Fariborz Jahanianf2bda692012-01-30 21:40:37 +00001719 "NullReturnState::complete - arg not on object");
John McCallcdda29c2013-03-13 03:10:54 +00001720 CGF.EmitARCRelease(RV.getScalarVal(), ARCImpreciseLifetime);
Fariborz Jahanianf2bda692012-01-30 21:40:37 +00001721 }
1722 }
1723 }
John McCall3d1e2c92013-02-12 05:53:35 +00001724
1725 // The phi code below assumes that we haven't needed any control flow yet.
1726 assert(CGF.Builder.GetInsertBlock() == NullBB);
1727
1728 // If we've got a void return, just jump to the continuation block.
1729 if (result.isScalar() && resultType->isVoidType()) {
1730 // No jumps required if the message-send was noreturn.
1731 if (contBB) CGF.EmitBlock(contBB);
Fariborz Jahanian715fdd52012-01-29 20:27:13 +00001732 return result;
1733 }
1734
John McCall3d1e2c92013-02-12 05:53:35 +00001735 // If we've got a scalar return, build a phi.
1736 if (result.isScalar()) {
1737 // Derive the null-initialization value.
1738 llvm::Constant *null = CGF.CGM.EmitNullConstant(resultType);
1739
1740 // If no join is necessary, just flow out.
1741 if (!contBB) return RValue::get(null);
1742
1743 // Otherwise, build a phi.
1744 CGF.EmitBlock(contBB);
1745 llvm::PHINode *phi = CGF.Builder.CreatePHI(null->getType(), 2);
1746 phi->addIncoming(result.getScalarVal(), callBB);
1747 phi->addIncoming(null, NullBB);
1748 return RValue::get(phi);
1749 }
1750
1751 // If we've got an aggregate return, null the buffer out.
1752 // FIXME: maybe we should be doing things differently for all the
1753 // cases where the ABI has us returning (1) non-agg values in
1754 // memory or (2) agg values in registers.
1755 if (result.isAggregate()) {
1756 assert(result.isAggregate() && "null init of non-aggregate result?");
Kuba Mracekbce5cea2017-06-30 16:28:15 +00001757 if (!returnSlot.isUnused())
1758 CGF.EmitNullInitialization(result.getAggregateAddress(), resultType);
John McCall3d1e2c92013-02-12 05:53:35 +00001759 if (contBB) CGF.EmitBlock(contBB);
1760 return result;
1761 }
1762
1763 // Complex types.
Fariborz Jahanian715fdd52012-01-29 20:27:13 +00001764 CGF.EmitBlock(contBB);
John McCall3d1e2c92013-02-12 05:53:35 +00001765 CodeGenFunction::ComplexPairTy callResult = result.getComplexVal();
1766
1767 // Find the scalar type and its zero value.
1768 llvm::Type *scalarTy = callResult.first->getType();
1769 llvm::Constant *scalarZero = llvm::Constant::getNullValue(scalarTy);
1770
1771 // Build phis for both coordinates.
1772 llvm::PHINode *real = CGF.Builder.CreatePHI(scalarTy, 2);
1773 real->addIncoming(callResult.first, callBB);
1774 real->addIncoming(scalarZero, NullBB);
1775 llvm::PHINode *imag = CGF.Builder.CreatePHI(scalarTy, 2);
1776 imag->addIncoming(callResult.second, callBB);
1777 imag->addIncoming(scalarZero, NullBB);
1778 return RValue::getComplex(real, imag);
Fariborz Jahanian715fdd52012-01-29 20:27:13 +00001779 }
1780};
1781
Daniel Dunbar303e2c22008-08-11 02:45:11 +00001782} // end anonymous namespace
Daniel Dunbar8b8683f2008-08-12 00:12:39 +00001783
1784/* *** Helper Functions *** */
1785
1786/// getConstantGEP() - Help routine to construct simple GEPs.
Owen Anderson170229f2009-07-14 23:10:40 +00001787static llvm::Constant *getConstantGEP(llvm::LLVMContext &VMContext,
David Blaikiee3b172a2015-04-02 18:55:21 +00001788 llvm::GlobalVariable *C, unsigned idx0,
Daniel Dunbar8b8683f2008-08-12 00:12:39 +00001789 unsigned idx1) {
1790 llvm::Value *Idxs[] = {
Owen Anderson41a75022009-08-13 21:57:51 +00001791 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), idx0),
1792 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), idx1)
Daniel Dunbar8b8683f2008-08-12 00:12:39 +00001793 };
David Blaikiee3b172a2015-04-02 18:55:21 +00001794 return llvm::ConstantExpr::getGetElementPtr(C->getValueType(), C, Idxs);
Daniel Dunbar8b8683f2008-08-12 00:12:39 +00001795}
1796
Daniel Dunbar8f28d012009-04-08 04:21:03 +00001797/// hasObjCExceptionAttribute - Return true if this class or any super
1798/// class has the __objc_exception__ attribute.
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001799static bool hasObjCExceptionAttribute(ASTContext &Context,
Douglas Gregor78bd61f2009-06-18 16:11:24 +00001800 const ObjCInterfaceDecl *OID) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001801 if (OID->hasAttr<ObjCExceptionAttr>())
Daniel Dunbar8f28d012009-04-08 04:21:03 +00001802 return true;
1803 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
Douglas Gregor78bd61f2009-06-18 16:11:24 +00001804 return hasObjCExceptionAttribute(Context, Super);
Daniel Dunbar8f28d012009-04-08 04:21:03 +00001805 return false;
1806}
1807
Daniel Dunbar8b8683f2008-08-12 00:12:39 +00001808/* *** CGObjCMac Public Interface *** */
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001809
Fariborz Jahanian279eda62009-01-21 22:04:16 +00001810CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm),
Mike Stump11289f42009-09-09 15:08:12 +00001811 ObjCTypes(cgm) {
Fariborz Jahanian279eda62009-01-21 22:04:16 +00001812 ObjCABI = 1;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001813 EmitImageInfo();
Daniel Dunbar303e2c22008-08-11 02:45:11 +00001814}
1815
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +00001816/// GetClass - Return a reference to the class for the given interface
1817/// decl.
John McCall882987f2013-02-28 19:01:20 +00001818llvm::Value *CGObjCMac::GetClass(CodeGenFunction &CGF,
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00001819 const ObjCInterfaceDecl *ID) {
John McCall882987f2013-02-28 19:01:20 +00001820 return EmitClassRef(CGF, ID);
Daniel Dunbar303e2c22008-08-11 02:45:11 +00001821}
1822
1823/// GetSelector - Return the pointer to the unique'd string for this selector.
John McCall7f416cc2015-09-08 08:05:57 +00001824llvm::Value *CGObjCMac::GetSelector(CodeGenFunction &CGF, Selector Sel) {
1825 return EmitSelector(CGF, Sel);
1826}
1827Address CGObjCMac::GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) {
1828 return EmitSelectorAddr(CGF, Sel);
Daniel Dunbar303e2c22008-08-11 02:45:11 +00001829}
John McCall882987f2013-02-28 19:01:20 +00001830llvm::Value *CGObjCMac::GetSelector(CodeGenFunction &CGF, const ObjCMethodDecl
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001831 *Method) {
John McCall882987f2013-02-28 19:01:20 +00001832 return EmitSelector(CGF, Method->getSelector());
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001833}
Daniel Dunbar303e2c22008-08-11 02:45:11 +00001834
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +00001835llvm::Constant *CGObjCMac::GetEHType(QualType T) {
Fariborz Jahanian0a3cfcc2011-06-22 20:21:51 +00001836 if (T->isObjCIdType() ||
1837 T->isObjCQualifiedIdType()) {
1838 return CGM.GetAddrOfRTTIDescriptor(
Douglas Gregor97673472011-08-11 20:58:55 +00001839 CGM.getContext().getObjCIdRedefinitionType(), /*ForEH=*/true);
Fariborz Jahanian0a3cfcc2011-06-22 20:21:51 +00001840 }
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +00001841 if (T->isObjCClassType() ||
1842 T->isObjCQualifiedClassType()) {
1843 return CGM.GetAddrOfRTTIDescriptor(
Douglas Gregor97673472011-08-11 20:58:55 +00001844 CGM.getContext().getObjCClassRedefinitionType(), /*ForEH=*/true);
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +00001845 }
1846 if (T->isObjCObjectPointerType())
1847 return CGM.GetAddrOfRTTIDescriptor(T, /*ForEH=*/true);
Fangrui Song6907ce22018-07-30 19:24:48 +00001848
John McCall2ca705e2010-07-24 00:37:23 +00001849 llvm_unreachable("asking for catch type for ObjC type in fragile runtime");
John McCall2ca705e2010-07-24 00:37:23 +00001850}
1851
Daniel Dunbar8b8683f2008-08-12 00:12:39 +00001852/// Generate a constant CFString object.
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001853/*
1854 struct __builtin_CFString {
1855 const int *isa; // point to __CFConstantStringClassReference
1856 int flags;
1857 const char *str;
1858 long length;
1859 };
Daniel Dunbar8b8683f2008-08-12 00:12:39 +00001860*/
1861
Fariborz Jahanian63408e82010-04-22 20:26:39 +00001862/// or Generate a constant NSString object.
1863/*
1864 struct __builtin_NSString {
1865 const int *isa; // point to __NSConstantStringClassReference
1866 const char *str;
1867 unsigned int length;
1868 };
1869*/
1870
John McCallcd21d542016-11-30 23:15:55 +00001871ConstantAddress
1872CGObjCCommonMac::GenerateConstantString(const StringLiteral *SL) {
1873 return (!CGM.getLangOpts().NoConstantCFStrings
1874 ? CGM.GetAddrOfConstantCFString(SL)
1875 : GenerateConstantNSString(SL));
1876}
1877
1878static llvm::StringMapEntry<llvm::GlobalVariable *> &
1879GetConstantStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
1880 const StringLiteral *Literal, unsigned &StringLength) {
1881 StringRef String = Literal->getString();
1882 StringLength = String.size();
1883 return *Map.insert(std::make_pair(String, nullptr)).first;
1884}
1885
1886llvm::Constant *CGObjCMac::getNSConstantStringClassRef() {
1887 if (llvm::Value *V = ConstantStringClassRef)
1888 return cast<llvm::Constant>(V);
1889
1890 auto &StringClass = CGM.getLangOpts().ObjCConstantStringClass;
1891 std::string str =
1892 StringClass.empty() ? "_NSConstantStringClassReference"
1893 : "_" + StringClass + "ClassReference";
1894
1895 llvm::Type *PTy = llvm::ArrayType::get(CGM.IntTy, 0);
1896 auto GV = CGM.CreateRuntimeVariable(PTy, str);
1897 auto V = llvm::ConstantExpr::getBitCast(GV, CGM.IntTy->getPointerTo());
1898 ConstantStringClassRef = V;
1899 return V;
1900}
1901
1902llvm::Constant *CGObjCNonFragileABIMac::getNSConstantStringClassRef() {
1903 if (llvm::Value *V = ConstantStringClassRef)
1904 return cast<llvm::Constant>(V);
1905
1906 auto &StringClass = CGM.getLangOpts().ObjCConstantStringClass;
Fangrui Song6907ce22018-07-30 19:24:48 +00001907 std::string str =
1908 StringClass.empty() ? "OBJC_CLASS_$_NSConstantString"
John McCallcd21d542016-11-30 23:15:55 +00001909 : "OBJC_CLASS_$_" + StringClass;
John McCalldba63a72016-11-30 23:54:50 +00001910 auto GV = GetClassGlobal(str, NotForDefinition);
John McCallcd21d542016-11-30 23:15:55 +00001911
1912 // Make sure the result is of the correct type.
1913 auto V = llvm::ConstantExpr::getBitCast(GV, CGM.IntTy->getPointerTo());
1914
1915 ConstantStringClassRef = V;
1916 return V;
1917}
1918
1919ConstantAddress
1920CGObjCCommonMac::GenerateConstantNSString(const StringLiteral *Literal) {
1921 unsigned StringLength = 0;
1922 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
1923 GetConstantStringEntry(NSConstantStringMap, Literal, StringLength);
1924
1925 if (auto *C = Entry.second)
1926 return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment()));
1927
1928 // If we don't already have it, get _NSConstantStringClassReference.
1929 llvm::Constant *Class = getNSConstantStringClassRef();
1930
1931 // If we don't already have it, construct the type for a constant NSString.
1932 if (!NSConstantStringType) {
1933 NSConstantStringType =
1934 llvm::StructType::create({
1935 CGM.Int32Ty->getPointerTo(),
1936 CGM.Int8PtrTy,
1937 CGM.IntTy
1938 }, "struct.__builtin_NSString");
1939 }
1940
1941 ConstantInitBuilder Builder(CGM);
1942 auto Fields = Builder.beginStruct(NSConstantStringType);
1943
1944 // Class pointer.
1945 Fields.add(Class);
1946
1947 // String pointer.
1948 llvm::Constant *C =
1949 llvm::ConstantDataArray::getString(VMContext, Entry.first());
1950
1951 llvm::GlobalValue::LinkageTypes Linkage = llvm::GlobalValue::PrivateLinkage;
1952 bool isConstant = !CGM.getLangOpts().WritableStrings;
1953
1954 auto *GV = new llvm::GlobalVariable(CGM.getModule(), C->getType(), isConstant,
1955 Linkage, C, ".str");
1956 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1957 // Don't enforce the target's minimum global alignment, since the only use
1958 // of the string is via this class initializer.
1959 GV->setAlignment(1);
1960 Fields.addBitCast(GV, CGM.Int8PtrTy);
1961
1962 // String length.
1963 Fields.addInt(CGM.IntTy, StringLength);
1964
1965 // The struct.
1966 CharUnits Alignment = CGM.getPointerAlign();
1967 GV = Fields.finishAndCreateGlobal("_unnamed_nsstring_", Alignment,
1968 /*constant*/ true,
1969 llvm::GlobalVariable::PrivateLinkage);
1970 const char *NSStringSection = "__OBJC,__cstring_object,regular,no_dead_strip";
1971 const char *NSStringNonFragileABISection =
1972 "__DATA,__objc_stringobj,regular,no_dead_strip";
1973 // FIXME. Fix section.
1974 GV->setSection(CGM.getLangOpts().ObjCRuntime.isNonFragile()
1975 ? NSStringNonFragileABISection
1976 : NSStringSection);
1977 Entry.second = GV;
1978
1979 return ConstantAddress(GV, Alignment);
Daniel Dunbar303e2c22008-08-11 02:45:11 +00001980}
1981
Ted Kremeneke65b0862012-03-06 20:05:56 +00001982enum {
1983 kCFTaggedObjectID_Integer = (1 << 1) + 1
1984};
1985
Daniel Dunbar303e2c22008-08-11 02:45:11 +00001986/// Generates a message send where the super is the receiver. This is
1987/// a message send to self with special delivery semantics indicating
1988/// which class's method should be called.
Daniel Dunbar97db84c2008-08-23 03:46:30 +00001989CodeGen::RValue
1990CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +00001991 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +00001992 QualType ResultType,
1993 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +00001994 const ObjCInterfaceDecl *Class,
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +00001995 bool isCategoryImpl,
Daniel Dunbarca8531a2008-08-25 08:19:24 +00001996 llvm::Value *Receiver,
Daniel Dunbarc722b852008-08-30 03:02:31 +00001997 bool IsClassMessage,
Daniel Dunbaraff9fca2009-09-17 04:01:22 +00001998 const CodeGen::CallArgList &CallArgs,
1999 const ObjCMethodDecl *Method) {
Daniel Dunbarf6397fe2008-08-23 04:28:29 +00002000 // Create and init a super structure; this is a (receiver, class)
2001 // pair we will pass to objc_msgSendSuper.
John McCall7f416cc2015-09-08 08:05:57 +00002002 Address ObjCSuper =
2003 CGF.CreateTempAlloca(ObjCTypes.SuperTy, CGF.getPointerAlign(),
2004 "objc_super");
Daniel Dunbar59e476b2009-08-03 17:06:42 +00002005 llvm::Value *ReceiverAsObject =
Daniel Dunbarf6397fe2008-08-23 04:28:29 +00002006 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
David Blaikie1ed728c2015-04-05 22:45:47 +00002007 CGF.Builder.CreateStore(
2008 ReceiverAsObject,
John McCall7f416cc2015-09-08 08:05:57 +00002009 CGF.Builder.CreateStructGEP(ObjCSuper, 0, CharUnits::Zero()));
Daniel Dunbarf6397fe2008-08-23 04:28:29 +00002010
Daniel Dunbarca8531a2008-08-25 08:19:24 +00002011 // If this is a class message the metaclass is passed as the target.
2012 llvm::Value *Target;
2013 if (IsClassMessage) {
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +00002014 if (isCategoryImpl) {
2015 // Message sent to 'super' in a class method defined in a category
2016 // implementation requires an odd treatment.
2017 // If we are in a class method, we must retrieve the
2018 // _metaclass_ for the current class, pointed at by
2019 // the class's "isa" pointer. The following assumes that
2020 // isa" is the first ivar in a class (which it must be).
John McCall882987f2013-02-28 19:01:20 +00002021 Target = EmitClassRef(CGF, Class->getSuperClass());
David Blaikie1ed728c2015-04-05 22:45:47 +00002022 Target = CGF.Builder.CreateStructGEP(ObjCTypes.ClassTy, Target, 0);
John McCall7f416cc2015-09-08 08:05:57 +00002023 Target = CGF.Builder.CreateAlignedLoad(Target, CGF.getPointerAlign());
Mike Stump658fe022009-07-30 22:28:39 +00002024 } else {
David Blaikie1ed728c2015-04-05 22:45:47 +00002025 llvm::Constant *MetaClassPtr = EmitMetaClassRef(Class);
2026 llvm::Value *SuperPtr =
2027 CGF.Builder.CreateStructGEP(ObjCTypes.ClassTy, MetaClassPtr, 1);
John McCall7f416cc2015-09-08 08:05:57 +00002028 llvm::Value *Super =
2029 CGF.Builder.CreateAlignedLoad(SuperPtr, CGF.getPointerAlign());
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +00002030 Target = Super;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00002031 }
David Blaikie1ed728c2015-04-05 22:45:47 +00002032 } else if (isCategoryImpl)
John McCall882987f2013-02-28 19:01:20 +00002033 Target = EmitClassRef(CGF, Class->getSuperClass());
Fariborz Jahanianda2efb02009-11-14 02:18:31 +00002034 else {
Fariborz Jahanianeb80c982009-11-12 20:14:24 +00002035 llvm::Value *ClassPtr = EmitSuperClassRef(Class);
David Blaikie1ed728c2015-04-05 22:45:47 +00002036 ClassPtr = CGF.Builder.CreateStructGEP(ObjCTypes.ClassTy, ClassPtr, 1);
John McCall7f416cc2015-09-08 08:05:57 +00002037 Target = CGF.Builder.CreateAlignedLoad(ClassPtr, CGF.getPointerAlign());
Daniel Dunbarca8531a2008-08-25 08:19:24 +00002038 }
Mike Stump18bb9282009-05-16 07:57:57 +00002039 // FIXME: We shouldn't need to do this cast, rectify the ASTContext and
2040 // ObjCTypes types.
Chris Lattner2192fe52011-07-18 04:24:23 +00002041 llvm::Type *ClassTy =
Daniel Dunbarc722b852008-08-30 03:02:31 +00002042 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
Daniel Dunbarc475d422008-10-29 22:36:39 +00002043 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
John McCall7f416cc2015-09-08 08:05:57 +00002044 CGF.Builder.CreateStore(Target,
2045 CGF.Builder.CreateStructGEP(ObjCSuper, 1, CGF.getPointerSize()));
John McCall9e8bb002011-05-14 03:10:52 +00002046 return EmitMessageSend(CGF, Return, ResultType,
John McCall882987f2013-02-28 19:01:20 +00002047 EmitSelector(CGF, Sel),
John McCall7f416cc2015-09-08 08:05:57 +00002048 ObjCSuper.getPointer(), ObjCTypes.SuperPtrCTy,
John McCall1e3157b2015-09-10 22:27:50 +00002049 true, CallArgs, Method, Class, ObjCTypes);
Daniel Dunbar303e2c22008-08-11 02:45:11 +00002050}
Daniel Dunbar59e476b2009-08-03 17:06:42 +00002051
2052/// Generate code for a message send expression.
Daniel Dunbar97db84c2008-08-23 03:46:30 +00002053CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +00002054 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +00002055 QualType ResultType,
2056 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +00002057 llvm::Value *Receiver,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00002058 const CallArgList &CallArgs,
David Chisnall01aa4672010-04-28 19:33:36 +00002059 const ObjCInterfaceDecl *Class,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00002060 const ObjCMethodDecl *Method) {
John McCall9e8bb002011-05-14 03:10:52 +00002061 return EmitMessageSend(CGF, Return, ResultType,
John McCall882987f2013-02-28 19:01:20 +00002062 EmitSelector(CGF, Sel),
John McCall9e8bb002011-05-14 03:10:52 +00002063 Receiver, CGF.getContext().getObjCIdType(),
John McCall1e3157b2015-09-10 22:27:50 +00002064 false, CallArgs, Method, Class, ObjCTypes);
2065}
2066
2067static bool isWeakLinkedClass(const ObjCInterfaceDecl *ID) {
2068 do {
2069 if (ID->isWeakImported())
2070 return true;
2071 } while ((ID = ID->getSuperClass()));
2072
2073 return false;
Daniel Dunbar97ff50d2008-08-23 09:25:55 +00002074}
2075
Daniel Dunbaraff9fca2009-09-17 04:01:22 +00002076CodeGen::RValue
John McCall9e8bb002011-05-14 03:10:52 +00002077CGObjCCommonMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
2078 ReturnValueSlot Return,
2079 QualType ResultType,
2080 llvm::Value *Sel,
2081 llvm::Value *Arg0,
2082 QualType Arg0Ty,
2083 bool IsSuper,
2084 const CallArgList &CallArgs,
2085 const ObjCMethodDecl *Method,
John McCall1e3157b2015-09-10 22:27:50 +00002086 const ObjCInterfaceDecl *ClassReceiver,
John McCall9e8bb002011-05-14 03:10:52 +00002087 const ObjCCommonTypesHelper &ObjCTypes) {
Daniel Dunbarc722b852008-08-30 03:02:31 +00002088 CallArgList ActualArgs;
Fariborz Jahanian969bc682009-04-24 21:07:43 +00002089 if (!IsSuper)
Benjamin Kramer76399eb2011-09-27 21:06:10 +00002090 Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy);
Eli Friedman43dca6a2011-05-02 17:57:46 +00002091 ActualArgs.add(RValue::get(Arg0), Arg0Ty);
2092 ActualArgs.add(RValue::get(Sel), CGF.getContext().getObjCSelType());
John McCall31168b02011-06-15 23:02:42 +00002093 ActualArgs.addFrom(CallArgs);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00002094
John McCalla729c622012-02-17 03:33:10 +00002095 // If we're calling a method, use the formal signature.
2096 MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00002097
Anders Carlsson280e61f12010-06-21 20:59:55 +00002098 if (Method)
Alp Toker314cc812014-01-25 16:55:45 +00002099 assert(CGM.getContext().getCanonicalType(Method->getReturnType()) ==
2100 CGM.getContext().getCanonicalType(ResultType) &&
Anders Carlsson280e61f12010-06-21 20:59:55 +00002101 "Result type mismatch!");
2102
John McCall1e3157b2015-09-10 22:27:50 +00002103 bool ReceiverCanBeNull = true;
2104
2105 // Super dispatch assumes that self is non-null; even the messenger
2106 // doesn't have a null check internally.
2107 if (IsSuper) {
2108 ReceiverCanBeNull = false;
2109
2110 // If this is a direct dispatch of a class method, check whether the class,
2111 // or anything in its hierarchy, was weak-linked.
2112 } else if (ClassReceiver && Method && Method->isClassMethod()) {
2113 ReceiverCanBeNull = isWeakLinkedClass(ClassReceiver);
2114
2115 // If we're emitting a method, and self is const (meaning just ARC, for now),
2116 // and the receiver is a load of self, then self is a valid object.
2117 } else if (auto CurMethod =
2118 dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl)) {
2119 auto Self = CurMethod->getSelfDecl();
2120 if (Self->getType().isConstQualified()) {
2121 if (auto LI = dyn_cast<llvm::LoadInst>(Arg0->stripPointerCasts())) {
2122 llvm::Value *SelfAddr = CGF.GetAddrOfLocalVar(Self).getPointer();
2123 if (SelfAddr == LI->getPointerOperand()) {
2124 ReceiverCanBeNull = false;
2125 }
2126 }
2127 }
2128 }
2129
Kuba Mracekbce5cea2017-06-30 16:28:15 +00002130 bool RequiresNullCheck = false;
John McCall5880fb82011-05-14 21:12:11 +00002131
Craig Topper8a13c412014-05-21 05:09:00 +00002132 llvm::Constant *Fn = nullptr;
Tim Northovere77cc392014-03-29 13:28:05 +00002133 if (CGM.ReturnSlotInterferesWithArgs(MSI.CallInfo)) {
Kuba Mracekbce5cea2017-06-30 16:28:15 +00002134 if (ReceiverCanBeNull) RequiresNullCheck = true;
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +00002135 Fn = (ObjCABI == 2) ? ObjCTypes.getSendStretFn2(IsSuper)
Daniel Dunbar59e476b2009-08-03 17:06:42 +00002136 : ObjCTypes.getSendStretFn(IsSuper);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00002137 } else if (CGM.ReturnTypeUsesFPRet(ResultType)) {
2138 Fn = (ObjCABI == 2) ? ObjCTypes.getSendFpretFn2(IsSuper)
2139 : ObjCTypes.getSendFpretFn(IsSuper);
Anders Carlsson2f1a6c32011-10-31 16:27:11 +00002140 } else if (CGM.ReturnTypeUsesFP2Ret(ResultType)) {
2141 Fn = (ObjCABI == 2) ? ObjCTypes.getSendFp2RetFn2(IsSuper)
2142 : ObjCTypes.getSendFp2retFn(IsSuper);
Daniel Dunbar3c683f5b2008-10-17 03:24:53 +00002143 } else {
Tim Northovere77cc392014-03-29 13:28:05 +00002144 // arm64 uses objc_msgSend for stret methods and yet null receiver check
2145 // must be made for it.
Ahmed Bougachaa3df87b2015-10-02 22:41:59 +00002146 if (ReceiverCanBeNull && CGM.ReturnTypeUsesSRet(MSI.CallInfo))
Kuba Mracekbce5cea2017-06-30 16:28:15 +00002147 RequiresNullCheck = true;
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +00002148 Fn = (ObjCABI == 2) ? ObjCTypes.getSendFn2(IsSuper)
Daniel Dunbar59e476b2009-08-03 17:06:42 +00002149 : ObjCTypes.getSendFn(IsSuper);
Daniel Dunbar3c683f5b2008-10-17 03:24:53 +00002150 }
John McCall1e3157b2015-09-10 22:27:50 +00002151
Kuba Mracekbce5cea2017-06-30 16:28:15 +00002152 // We don't need to emit a null check to zero out an indirect result if the
2153 // result is ignored.
2154 if (Return.isUnused())
2155 RequiresNullCheck = false;
2156
John McCall1e3157b2015-09-10 22:27:50 +00002157 // Emit a null-check if there's a consumed argument other than the receiver.
Kuba Mracekbce5cea2017-06-30 16:28:15 +00002158 if (!RequiresNullCheck && CGM.getLangOpts().ObjCAutoRefCount && Method) {
David Majnemer59f77922016-06-24 04:05:48 +00002159 for (const auto *ParamDecl : Method->parameters()) {
Fariborz Jahanianf2bda692012-01-30 21:40:37 +00002160 if (ParamDecl->hasAttr<NSConsumedAttr>()) {
John McCall1e3157b2015-09-10 22:27:50 +00002161 RequiresNullCheck = true;
Fariborz Jahanianf2bda692012-01-30 21:40:37 +00002162 break;
2163 }
2164 }
John McCall1e3157b2015-09-10 22:27:50 +00002165 }
Kuba Mracekbce5cea2017-06-30 16:28:15 +00002166
2167 NullReturnState nullReturn;
2168 if (RequiresNullCheck) {
2169 nullReturn.init(CGF, Arg0);
2170 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002171
John McCall1e3157b2015-09-10 22:27:50 +00002172 llvm::Instruction *CallSite;
John McCalla729c622012-02-17 03:33:10 +00002173 Fn = llvm::ConstantExpr::getBitCast(Fn, MSI.MessengerType);
John McCallb92ab1a2016-10-26 23:46:34 +00002174 CGCallee Callee = CGCallee::forDirect(Fn);
2175 RValue rvalue = CGF.EmitCall(MSI.CallInfo, Callee, Return, ActualArgs,
2176 &CallSite);
John McCall1e3157b2015-09-10 22:27:50 +00002177
2178 // Mark the call as noreturn if the method is marked noreturn and the
2179 // receiver cannot be null.
2180 if (Method && Method->hasAttr<NoReturnAttr>() && !ReceiverCanBeNull) {
2181 llvm::CallSite(CallSite).setDoesNotReturn();
2182 }
2183
Kuba Mracekbce5cea2017-06-30 16:28:15 +00002184 return nullReturn.complete(CGF, Return, rvalue, ResultType, CallArgs,
John McCall1e3157b2015-09-10 22:27:50 +00002185 RequiresNullCheck ? Method : nullptr);
Daniel Dunbar303e2c22008-08-11 02:45:11 +00002186}
2187
John McCall3fd13f062015-10-21 18:06:47 +00002188static Qualifiers::GC GetGCAttrTypeForType(ASTContext &Ctx, QualType FQT,
2189 bool pointee = false) {
2190 // Note that GC qualification applies recursively to C pointer types
2191 // that aren't otherwise decorated. This is weird, but it's probably
2192 // an intentional workaround to the unreliable placement of GC qualifiers.
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00002193 if (FQT.isObjCGCStrong())
2194 return Qualifiers::Strong;
John McCall3fd13f062015-10-21 18:06:47 +00002195
2196 if (FQT.isObjCGCWeak())
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00002197 return Qualifiers::Weak;
John McCall3fd13f062015-10-21 18:06:47 +00002198
2199 if (auto ownership = FQT.getObjCLifetime()) {
2200 // Ownership does not apply recursively to C pointer types.
2201 if (pointee) return Qualifiers::GCNone;
2202 switch (ownership) {
2203 case Qualifiers::OCL_Weak: return Qualifiers::Weak;
2204 case Qualifiers::OCL_Strong: return Qualifiers::Strong;
2205 case Qualifiers::OCL_ExplicitNone: return Qualifiers::GCNone;
2206 case Qualifiers::OCL_Autoreleasing: llvm_unreachable("autoreleasing ivar?");
2207 case Qualifiers::OCL_None: llvm_unreachable("known nonzero");
2208 }
2209 llvm_unreachable("bad objc ownership");
2210 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002211
John McCall3fd13f062015-10-21 18:06:47 +00002212 // Treat unqualified retainable pointers as strong.
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00002213 if (FQT->isObjCObjectPointerType() || FQT->isBlockPointerType())
2214 return Qualifiers::Strong;
Fangrui Song6907ce22018-07-30 19:24:48 +00002215
John McCall3fd13f062015-10-21 18:06:47 +00002216 // Walk into C pointer types, but only in GC.
2217 if (Ctx.getLangOpts().getGC() != LangOptions::NonGC) {
2218 if (const PointerType *PT = FQT->getAs<PointerType>())
2219 return GetGCAttrTypeForType(Ctx, PT->getPointeeType(), /*pointee*/ true);
2220 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002221
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00002222 return Qualifiers::GCNone;
2223}
2224
John McCall3fd13f062015-10-21 18:06:47 +00002225namespace {
2226 struct IvarInfo {
2227 CharUnits Offset;
2228 uint64_t SizeInWords;
2229 IvarInfo(CharUnits offset, uint64_t sizeInWords)
2230 : Offset(offset), SizeInWords(sizeInWords) {}
2231
2232 // Allow sorting based on byte pos.
2233 bool operator<(const IvarInfo &other) const {
2234 return Offset < other.Offset;
2235 }
2236 };
2237
2238 /// A helper class for building GC layout strings.
2239 class IvarLayoutBuilder {
2240 CodeGenModule &CGM;
2241
2242 /// The start of the layout. Offsets will be relative to this value,
2243 /// and entries less than this value will be silently discarded.
2244 CharUnits InstanceBegin;
2245
2246 /// The end of the layout. Offsets will never exceed this value.
2247 CharUnits InstanceEnd;
2248
2249 /// Whether we're generating the strong layout or the weak layout.
2250 bool ForStrongLayout;
2251
2252 /// Whether the offsets in IvarsInfo might be out-of-order.
2253 bool IsDisordered = false;
2254
2255 llvm::SmallVector<IvarInfo, 8> IvarsInfo;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00002256
John McCall3fd13f062015-10-21 18:06:47 +00002257 public:
2258 IvarLayoutBuilder(CodeGenModule &CGM, CharUnits instanceBegin,
2259 CharUnits instanceEnd, bool forStrongLayout)
2260 : CGM(CGM), InstanceBegin(instanceBegin), InstanceEnd(instanceEnd),
2261 ForStrongLayout(forStrongLayout) {
2262 }
2263
2264 void visitRecord(const RecordType *RT, CharUnits offset);
2265
2266 template <class Iterator, class GetOffsetFn>
Fangrui Song6907ce22018-07-30 19:24:48 +00002267 void visitAggregate(Iterator begin, Iterator end,
John McCall3fd13f062015-10-21 18:06:47 +00002268 CharUnits aggrOffset,
2269 const GetOffsetFn &getOffset);
2270
2271 void visitField(const FieldDecl *field, CharUnits offset);
2272
2273 /// Add the layout of a block implementation.
2274 void visitBlock(const CGBlockInfo &blockInfo);
2275
2276 /// Is there any information for an interesting bitmap?
2277 bool hasBitmapData() const { return !IvarsInfo.empty(); }
2278
2279 llvm::Constant *buildBitmap(CGObjCCommonMac &CGObjC,
2280 llvm::SmallVectorImpl<unsigned char> &buffer);
2281
2282 static void dump(ArrayRef<unsigned char> buffer) {
2283 const unsigned char *s = buffer.data();
2284 for (unsigned i = 0, e = buffer.size(); i < e; i++)
2285 if (!(s[i] & 0xf0))
2286 printf("0x0%x%s", s[i], s[i] != 0 ? ", " : "");
2287 else
2288 printf("0x%x%s", s[i], s[i] != 0 ? ", " : "");
2289 printf("\n");
2290 }
2291 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00002292} // end anonymous namespace
John McCall3fd13f062015-10-21 18:06:47 +00002293
John McCall351762c2011-02-07 10:33:21 +00002294llvm::Constant *CGObjCCommonMac::BuildGCBlockLayout(CodeGenModule &CGM,
2295 const CGBlockInfo &blockInfo) {
Fangrui Song6907ce22018-07-30 19:24:48 +00002296
Chris Lattnerece04092012-02-07 00:39:47 +00002297 llvm::Constant *nullPtr = llvm::Constant::getNullValue(CGM.Int8PtrTy);
John McCall460ce582015-10-22 18:38:17 +00002298 if (CGM.getLangOpts().getGC() == LangOptions::NonGC)
John McCall351762c2011-02-07 10:33:21 +00002299 return nullPtr;
2300
John McCall3fd13f062015-10-21 18:06:47 +00002301 IvarLayoutBuilder builder(CGM, CharUnits::Zero(), blockInfo.BlockSize,
2302 /*for strong layout*/ true);
2303
2304 builder.visitBlock(blockInfo);
2305
2306 if (!builder.hasBitmapData())
2307 return nullPtr;
2308
2309 llvm::SmallVector<unsigned char, 32> buffer;
2310 llvm::Constant *C = builder.buildBitmap(*this, buffer);
John McCallf5ea0722015-10-29 23:36:14 +00002311 if (CGM.getLangOpts().ObjCGCBitmapPrint && !buffer.empty()) {
John McCall3fd13f062015-10-21 18:06:47 +00002312 printf("\n block variable layout for block: ");
2313 builder.dump(buffer);
2314 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002315
John McCall3fd13f062015-10-21 18:06:47 +00002316 return C;
2317}
2318
2319void IvarLayoutBuilder::visitBlock(const CGBlockInfo &blockInfo) {
Fariborz Jahaniancfddabf2010-09-09 00:21:45 +00002320 // __isa is the first field in block descriptor and must assume by runtime's
2321 // convention that it is GC'able.
John McCall3fd13f062015-10-21 18:06:47 +00002322 IvarsInfo.push_back(IvarInfo(CharUnits::Zero(), 1));
John McCall351762c2011-02-07 10:33:21 +00002323
2324 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
2325
John McCall351762c2011-02-07 10:33:21 +00002326 // Ignore the optional 'this' capture: C++ objects are not assumed
2327 // to be GC'ed.
2328
John McCall3fd13f062015-10-21 18:06:47 +00002329 CharUnits lastFieldOffset;
2330
John McCall351762c2011-02-07 10:33:21 +00002331 // Walk the captured variables.
Aaron Ballman9371dd22014-03-14 18:34:04 +00002332 for (const auto &CI : blockDecl->captures()) {
2333 const VarDecl *variable = CI.getVariable();
John McCall351762c2011-02-07 10:33:21 +00002334 QualType type = variable->getType();
2335
2336 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
2337
2338 // Ignore constant captures.
2339 if (capture.isConstant()) continue;
2340
John McCall3fd13f062015-10-21 18:06:47 +00002341 CharUnits fieldOffset = capture.getOffset();
2342
2343 // Block fields are not necessarily ordered; if we detect that we're
2344 // adding them out-of-order, make sure we sort later.
2345 if (fieldOffset < lastFieldOffset)
2346 IsDisordered = true;
2347 lastFieldOffset = fieldOffset;
John McCall351762c2011-02-07 10:33:21 +00002348
2349 // __block variables are passed by their descriptor address.
Aaron Ballman9371dd22014-03-14 18:34:04 +00002350 if (CI.isByRef()) {
John McCall3fd13f062015-10-21 18:06:47 +00002351 IvarsInfo.push_back(IvarInfo(fieldOffset, /*size in words*/ 1));
Fariborz Jahanian933c6722010-09-11 01:27:29 +00002352 continue;
John McCall351762c2011-02-07 10:33:21 +00002353 }
2354
2355 assert(!type->isArrayType() && "array variable should not be caught");
2356 if (const RecordType *record = type->getAs<RecordType>()) {
John McCall3fd13f062015-10-21 18:06:47 +00002357 visitRecord(record, fieldOffset);
Fariborz Jahanian903aba32010-08-05 21:00:25 +00002358 continue;
2359 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002360
John McCall351762c2011-02-07 10:33:21 +00002361 Qualifiers::GC GCAttr = GetGCAttrTypeForType(CGM.getContext(), type);
John McCall351762c2011-02-07 10:33:21 +00002362
John McCall3fd13f062015-10-21 18:06:47 +00002363 if (GCAttr == Qualifiers::Strong) {
2364 assert(CGM.getContext().getTypeSize(type)
2365 == CGM.getTarget().getPointerWidth(0));
2366 IvarsInfo.push_back(IvarInfo(fieldOffset, /*size in words*/ 1));
2367 }
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00002368 }
Fariborz Jahanianc05349e2010-08-04 16:57:49 +00002369}
2370
Fariborz Jahanian2c96d302012-11-04 18:19:40 +00002371/// getBlockCaptureLifetime - This routine returns life time of the captured
2372/// block variable for the purpose of block layout meta-data generation. FQT is
2373/// the type of the variable captured in the block.
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002374Qualifiers::ObjCLifetime CGObjCCommonMac::getBlockCaptureLifetime(QualType FQT,
2375 bool ByrefLayout) {
John McCall460ce582015-10-22 18:38:17 +00002376 // If it has an ownership qualifier, we're done.
2377 if (auto lifetime = FQT.getObjCLifetime())
2378 return lifetime;
2379
2380 // If it doesn't, and this is ARC, it has no ownership.
Fariborz Jahanian2dd78192012-11-02 22:51:18 +00002381 if (CGM.getLangOpts().ObjCAutoRefCount)
John McCall460ce582015-10-22 18:38:17 +00002382 return Qualifiers::OCL_None;
Fangrui Song6907ce22018-07-30 19:24:48 +00002383
John McCall460ce582015-10-22 18:38:17 +00002384 // In MRC, retainable pointers are owned by non-__block variables.
Fariborz Jahanian2dd78192012-11-02 22:51:18 +00002385 if (FQT->isObjCObjectPointerType() || FQT->isBlockPointerType())
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002386 return ByrefLayout ? Qualifiers::OCL_ExplicitNone : Qualifiers::OCL_Strong;
Fangrui Song6907ce22018-07-30 19:24:48 +00002387
Fariborz Jahanian2dd78192012-11-02 22:51:18 +00002388 return Qualifiers::OCL_None;
2389}
2390
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002391void CGObjCCommonMac::UpdateRunSkipBlockVars(bool IsByref,
2392 Qualifiers::ObjCLifetime LifeTime,
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002393 CharUnits FieldOffset,
2394 CharUnits FieldSize) {
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002395 // __block variables are passed by their descriptor address.
2396 if (IsByref)
2397 RunSkipBlockVars.push_back(RUN_SKIP(BLOCK_LAYOUT_BYREF, FieldOffset,
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002398 FieldSize));
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002399 else if (LifeTime == Qualifiers::OCL_Strong)
2400 RunSkipBlockVars.push_back(RUN_SKIP(BLOCK_LAYOUT_STRONG, FieldOffset,
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002401 FieldSize));
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002402 else if (LifeTime == Qualifiers::OCL_Weak)
2403 RunSkipBlockVars.push_back(RUN_SKIP(BLOCK_LAYOUT_WEAK, FieldOffset,
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002404 FieldSize));
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002405 else if (LifeTime == Qualifiers::OCL_ExplicitNone)
2406 RunSkipBlockVars.push_back(RUN_SKIP(BLOCK_LAYOUT_UNRETAINED, FieldOffset,
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002407 FieldSize));
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002408 else
2409 RunSkipBlockVars.push_back(RUN_SKIP(BLOCK_LAYOUT_NON_OBJECT_BYTES,
2410 FieldOffset,
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002411 FieldSize));
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002412}
2413
2414void CGObjCCommonMac::BuildRCRecordLayout(const llvm::StructLayout *RecLayout,
2415 const RecordDecl *RD,
2416 ArrayRef<const FieldDecl*> RecFields,
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002417 CharUnits BytePos, bool &HasUnion,
2418 bool ByrefLayout) {
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002419 bool IsUnion = (RD && RD->isUnion());
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002420 CharUnits MaxUnionSize = CharUnits::Zero();
Craig Topper8a13c412014-05-21 05:09:00 +00002421 const FieldDecl *MaxField = nullptr;
2422 const FieldDecl *LastFieldBitfieldOrUnnamed = nullptr;
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002423 CharUnits MaxFieldOffset = CharUnits::Zero();
2424 CharUnits LastBitfieldOrUnnamedOffset = CharUnits::Zero();
Fangrui Song6907ce22018-07-30 19:24:48 +00002425
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002426 if (RecFields.empty())
2427 return;
John McCallc8e01702013-04-16 22:48:15 +00002428 unsigned ByteSizeInBits = CGM.getTarget().getCharWidth();
Fangrui Song6907ce22018-07-30 19:24:48 +00002429
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002430 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
2431 const FieldDecl *Field = RecFields[i];
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002432 // Note that 'i' here is actually the field index inside RD of Field,
2433 // although this dependency is hidden.
2434 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002435 CharUnits FieldOffset =
2436 CGM.getContext().toCharUnitsFromBits(RL.getFieldOffset(i));
Fangrui Song6907ce22018-07-30 19:24:48 +00002437
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002438 // Skip over unnamed or bitfields
2439 if (!Field->getIdentifier() || Field->isBitField()) {
2440 LastFieldBitfieldOrUnnamed = Field;
2441 LastBitfieldOrUnnamedOffset = FieldOffset;
2442 continue;
2443 }
Craig Topper8a13c412014-05-21 05:09:00 +00002444
2445 LastFieldBitfieldOrUnnamed = nullptr;
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002446 QualType FQT = Field->getType();
2447 if (FQT->isRecordType() || FQT->isUnionType()) {
2448 if (FQT->isUnionType())
2449 HasUnion = true;
Fangrui Song6907ce22018-07-30 19:24:48 +00002450
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002451 BuildRCBlockVarRecordLayout(FQT->getAs<RecordType>(),
2452 BytePos + FieldOffset, HasUnion);
2453 continue;
2454 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002455
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002456 if (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
2457 const ConstantArrayType *CArray =
2458 dyn_cast_or_null<ConstantArrayType>(Array);
2459 uint64_t ElCount = CArray->getSize().getZExtValue();
2460 assert(CArray && "only array with known element size is supported");
2461 FQT = CArray->getElementType();
2462 while (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
2463 const ConstantArrayType *CArray =
2464 dyn_cast_or_null<ConstantArrayType>(Array);
2465 ElCount *= CArray->getSize().getZExtValue();
2466 FQT = CArray->getElementType();
2467 }
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002468 if (FQT->isRecordType() && ElCount) {
2469 int OldIndex = RunSkipBlockVars.size() - 1;
2470 const RecordType *RT = FQT->getAs<RecordType>();
2471 BuildRCBlockVarRecordLayout(RT, BytePos + FieldOffset,
2472 HasUnion);
Fangrui Song6907ce22018-07-30 19:24:48 +00002473
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002474 // Replicate layout information for each array element. Note that
2475 // one element is already done.
2476 uint64_t ElIx = 1;
2477 for (int FirstIndex = RunSkipBlockVars.size() - 1 ;ElIx < ElCount; ElIx++) {
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002478 CharUnits Size = CGM.getContext().getTypeSizeInChars(RT);
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002479 for (int i = OldIndex+1; i <= FirstIndex; ++i)
2480 RunSkipBlockVars.push_back(
2481 RUN_SKIP(RunSkipBlockVars[i].opcode,
2482 RunSkipBlockVars[i].block_var_bytepos + Size*ElIx,
2483 RunSkipBlockVars[i].block_var_size));
2484 }
2485 continue;
2486 }
2487 }
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002488 CharUnits FieldSize = CGM.getContext().getTypeSizeInChars(Field->getType());
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002489 if (IsUnion) {
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002490 CharUnits UnionIvarSize = FieldSize;
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002491 if (UnionIvarSize > MaxUnionSize) {
2492 MaxUnionSize = UnionIvarSize;
2493 MaxField = Field;
2494 MaxFieldOffset = FieldOffset;
2495 }
2496 } else {
2497 UpdateRunSkipBlockVars(false,
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002498 getBlockCaptureLifetime(FQT, ByrefLayout),
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002499 BytePos + FieldOffset,
2500 FieldSize);
2501 }
2502 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002503
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002504 if (LastFieldBitfieldOrUnnamed) {
2505 if (LastFieldBitfieldOrUnnamed->isBitField()) {
2506 // Last field was a bitfield. Must update the info.
2507 uint64_t BitFieldSize
2508 = LastFieldBitfieldOrUnnamed->getBitWidthValue(CGM.getContext());
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002509 unsigned UnsSize = (BitFieldSize / ByteSizeInBits) +
Eli Friedman8cbca202012-11-06 22:15:52 +00002510 ((BitFieldSize % ByteSizeInBits) != 0);
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002511 CharUnits Size = CharUnits::fromQuantity(UnsSize);
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002512 Size += LastBitfieldOrUnnamedOffset;
2513 UpdateRunSkipBlockVars(false,
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002514 getBlockCaptureLifetime(LastFieldBitfieldOrUnnamed->getType(),
2515 ByrefLayout),
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002516 BytePos + LastBitfieldOrUnnamedOffset,
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002517 Size);
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002518 } else {
2519 assert(!LastFieldBitfieldOrUnnamed->getIdentifier() &&"Expected unnamed");
2520 // Last field was unnamed. Must update skip info.
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002521 CharUnits FieldSize
2522 = CGM.getContext().getTypeSizeInChars(LastFieldBitfieldOrUnnamed->getType());
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002523 UpdateRunSkipBlockVars(false,
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002524 getBlockCaptureLifetime(LastFieldBitfieldOrUnnamed->getType(),
2525 ByrefLayout),
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002526 BytePos + LastBitfieldOrUnnamedOffset,
2527 FieldSize);
2528 }
2529 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002530
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002531 if (MaxField)
2532 UpdateRunSkipBlockVars(false,
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002533 getBlockCaptureLifetime(MaxField->getType(), ByrefLayout),
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002534 BytePos + MaxFieldOffset,
2535 MaxUnionSize);
2536}
2537
2538void CGObjCCommonMac::BuildRCBlockVarRecordLayout(const RecordType *RT,
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002539 CharUnits BytePos,
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002540 bool &HasUnion,
2541 bool ByrefLayout) {
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002542 const RecordDecl *RD = RT->getDecl();
Aaron Ballman62e47c42014-03-10 13:43:55 +00002543 SmallVector<const FieldDecl*, 16> Fields(RD->fields());
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002544 llvm::Type *Ty = CGM.getTypes().ConvertType(QualType(RT, 0));
2545 const llvm::StructLayout *RecLayout =
2546 CGM.getDataLayout().getStructLayout(cast<llvm::StructType>(Ty));
Fangrui Song6907ce22018-07-30 19:24:48 +00002547
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002548 BuildRCRecordLayout(RecLayout, RD, Fields, BytePos, HasUnion, ByrefLayout);
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002549}
2550
Fariborz Jahanian23290b02012-11-01 18:32:55 +00002551/// InlineLayoutInstruction - This routine produce an inline instruction for the
2552/// block variable layout if it can. If not, it returns 0. Rules are as follow:
2553/// If ((uintptr_t) layout) < (1 << 12), the layout is inline. In the 64bit world,
2554/// an inline layout of value 0x0000000000000xyz is interpreted as follows:
2555/// x captured object pointers of BLOCK_LAYOUT_STRONG. Followed by
2556/// y captured object of BLOCK_LAYOUT_BYREF. Followed by
2557/// z captured object of BLOCK_LAYOUT_WEAK. If any of the above is missing, zero
2558/// replaces it. For example, 0x00000x00 means x BLOCK_LAYOUT_STRONG and no
2559/// BLOCK_LAYOUT_BYREF and no BLOCK_LAYOUT_WEAK objects are captured.
2560uint64_t CGObjCCommonMac::InlineLayoutInstruction(
2561 SmallVectorImpl<unsigned char> &Layout) {
2562 uint64_t Result = 0;
2563 if (Layout.size() <= 3) {
2564 unsigned size = Layout.size();
2565 unsigned strong_word_count = 0, byref_word_count=0, weak_word_count=0;
2566 unsigned char inst;
2567 enum BLOCK_LAYOUT_OPCODE opcode ;
2568 switch (size) {
2569 case 3:
2570 inst = Layout[0];
2571 opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
2572 if (opcode == BLOCK_LAYOUT_STRONG)
2573 strong_word_count = (inst & 0xF)+1;
2574 else
2575 return 0;
2576 inst = Layout[1];
2577 opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
2578 if (opcode == BLOCK_LAYOUT_BYREF)
2579 byref_word_count = (inst & 0xF)+1;
2580 else
2581 return 0;
2582 inst = Layout[2];
2583 opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
2584 if (opcode == BLOCK_LAYOUT_WEAK)
2585 weak_word_count = (inst & 0xF)+1;
2586 else
2587 return 0;
2588 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00002589
Fariborz Jahanian23290b02012-11-01 18:32:55 +00002590 case 2:
2591 inst = Layout[0];
2592 opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
2593 if (opcode == BLOCK_LAYOUT_STRONG) {
2594 strong_word_count = (inst & 0xF)+1;
2595 inst = Layout[1];
2596 opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
2597 if (opcode == BLOCK_LAYOUT_BYREF)
2598 byref_word_count = (inst & 0xF)+1;
2599 else if (opcode == BLOCK_LAYOUT_WEAK)
2600 weak_word_count = (inst & 0xF)+1;
2601 else
2602 return 0;
2603 }
2604 else if (opcode == BLOCK_LAYOUT_BYREF) {
2605 byref_word_count = (inst & 0xF)+1;
2606 inst = Layout[1];
2607 opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
2608 if (opcode == BLOCK_LAYOUT_WEAK)
2609 weak_word_count = (inst & 0xF)+1;
2610 else
2611 return 0;
2612 }
2613 else
2614 return 0;
2615 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00002616
Fariborz Jahanian23290b02012-11-01 18:32:55 +00002617 case 1:
2618 inst = Layout[0];
2619 opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
2620 if (opcode == BLOCK_LAYOUT_STRONG)
2621 strong_word_count = (inst & 0xF)+1;
2622 else if (opcode == BLOCK_LAYOUT_BYREF)
2623 byref_word_count = (inst & 0xF)+1;
2624 else if (opcode == BLOCK_LAYOUT_WEAK)
2625 weak_word_count = (inst & 0xF)+1;
2626 else
2627 return 0;
2628 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00002629
Fariborz Jahanian23290b02012-11-01 18:32:55 +00002630 default:
2631 return 0;
2632 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002633
Fariborz Jahanian23290b02012-11-01 18:32:55 +00002634 // Cannot inline when any of the word counts is 15. Because this is one less
2635 // than the actual work count (so 15 means 16 actual word counts),
2636 // and we can only display 0 thru 15 word counts.
2637 if (strong_word_count == 16 || byref_word_count == 16 || weak_word_count == 16)
2638 return 0;
Fangrui Song6907ce22018-07-30 19:24:48 +00002639
Fariborz Jahanian23290b02012-11-01 18:32:55 +00002640 unsigned count =
2641 (strong_word_count != 0) + (byref_word_count != 0) + (weak_word_count != 0);
Fangrui Song6907ce22018-07-30 19:24:48 +00002642
Fariborz Jahanian23290b02012-11-01 18:32:55 +00002643 if (size == count) {
2644 if (strong_word_count)
2645 Result = strong_word_count;
2646 Result <<= 4;
2647 if (byref_word_count)
2648 Result += byref_word_count;
2649 Result <<= 4;
2650 if (weak_word_count)
2651 Result += weak_word_count;
2652 }
2653 }
2654 return Result;
2655}
2656
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002657llvm::Constant *CGObjCCommonMac::getBitmapBlockLayout(bool ComputeByrefLayout) {
2658 llvm::Constant *nullPtr = llvm::Constant::getNullValue(CGM.Int8PtrTy);
2659 if (RunSkipBlockVars.empty())
2660 return nullPtr;
John McCallc8e01702013-04-16 22:48:15 +00002661 unsigned WordSizeInBits = CGM.getTarget().getPointerWidth(0);
2662 unsigned ByteSizeInBits = CGM.getTarget().getCharWidth();
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002663 unsigned WordSizeInBytes = WordSizeInBits/ByteSizeInBits;
Fangrui Song6907ce22018-07-30 19:24:48 +00002664
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002665 // Sort on byte position; captures might not be allocated in order,
2666 // and unions can do funny things.
2667 llvm::array_pod_sort(RunSkipBlockVars.begin(), RunSkipBlockVars.end());
2668 SmallVector<unsigned char, 16> Layout;
Fangrui Song6907ce22018-07-30 19:24:48 +00002669
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002670 unsigned size = RunSkipBlockVars.size();
2671 for (unsigned i = 0; i < size; i++) {
2672 enum BLOCK_LAYOUT_OPCODE opcode = RunSkipBlockVars[i].opcode;
2673 CharUnits start_byte_pos = RunSkipBlockVars[i].block_var_bytepos;
2674 CharUnits end_byte_pos = start_byte_pos;
2675 unsigned j = i+1;
2676 while (j < size) {
2677 if (opcode == RunSkipBlockVars[j].opcode) {
2678 end_byte_pos = RunSkipBlockVars[j++].block_var_bytepos;
2679 i++;
2680 }
2681 else
2682 break;
2683 }
2684 CharUnits size_in_bytes =
2685 end_byte_pos - start_byte_pos + RunSkipBlockVars[j-1].block_var_size;
2686 if (j < size) {
2687 CharUnits gap =
2688 RunSkipBlockVars[j].block_var_bytepos -
2689 RunSkipBlockVars[j-1].block_var_bytepos - RunSkipBlockVars[j-1].block_var_size;
2690 size_in_bytes += gap;
2691 }
2692 CharUnits residue_in_bytes = CharUnits::Zero();
2693 if (opcode == BLOCK_LAYOUT_NON_OBJECT_BYTES) {
2694 residue_in_bytes = size_in_bytes % WordSizeInBytes;
2695 size_in_bytes -= residue_in_bytes;
2696 opcode = BLOCK_LAYOUT_NON_OBJECT_WORDS;
2697 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002698
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002699 unsigned size_in_words = size_in_bytes.getQuantity() / WordSizeInBytes;
2700 while (size_in_words >= 16) {
2701 // Note that value in imm. is one less that the actual
2702 // value. So, 0xf means 16 words follow!
2703 unsigned char inst = (opcode << 4) | 0xf;
2704 Layout.push_back(inst);
2705 size_in_words -= 16;
2706 }
2707 if (size_in_words > 0) {
2708 // Note that value in imm. is one less that the actual
2709 // value. So, we subtract 1 away!
2710 unsigned char inst = (opcode << 4) | (size_in_words-1);
2711 Layout.push_back(inst);
2712 }
2713 if (residue_in_bytes > CharUnits::Zero()) {
2714 unsigned char inst =
2715 (BLOCK_LAYOUT_NON_OBJECT_BYTES << 4) | (residue_in_bytes.getQuantity()-1);
2716 Layout.push_back(inst);
2717 }
2718 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002719
John McCall7f416cc2015-09-08 08:05:57 +00002720 while (!Layout.empty()) {
2721 unsigned char inst = Layout.back();
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002722 enum BLOCK_LAYOUT_OPCODE opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
2723 if (opcode == BLOCK_LAYOUT_NON_OBJECT_BYTES || opcode == BLOCK_LAYOUT_NON_OBJECT_WORDS)
2724 Layout.pop_back();
2725 else
2726 break;
2727 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002728
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002729 uint64_t Result = InlineLayoutInstruction(Layout);
2730 if (Result != 0) {
2731 // Block variable layout instruction has been inlined.
2732 if (CGM.getLangOpts().ObjCGCBitmapPrint) {
2733 if (ComputeByrefLayout)
John McCall7f416cc2015-09-08 08:05:57 +00002734 printf("\n Inline BYREF variable layout: ");
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002735 else
John McCall7f416cc2015-09-08 08:05:57 +00002736 printf("\n Inline block variable layout: ");
2737 printf("0x0%" PRIx64 "", Result);
2738 if (auto numStrong = (Result & 0xF00) >> 8)
2739 printf(", BL_STRONG:%d", (int) numStrong);
2740 if (auto numByref = (Result & 0x0F0) >> 4)
2741 printf(", BL_BYREF:%d", (int) numByref);
2742 if (auto numWeak = (Result & 0x00F) >> 0)
2743 printf(", BL_WEAK:%d", (int) numWeak);
2744 printf(", BL_OPERATOR:0\n");
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002745 }
Vedant Kumar3ed0df02015-12-21 19:43:25 +00002746 return llvm::ConstantInt::get(CGM.IntPtrTy, Result);
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002747 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002748
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002749 unsigned char inst = (BLOCK_LAYOUT_OPERATOR << 4) | 0;
2750 Layout.push_back(inst);
2751 std::string BitMap;
2752 for (unsigned i = 0, e = Layout.size(); i != e; i++)
2753 BitMap += Layout[i];
Fangrui Song6907ce22018-07-30 19:24:48 +00002754
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002755 if (CGM.getLangOpts().ObjCGCBitmapPrint) {
2756 if (ComputeByrefLayout)
John McCall7f416cc2015-09-08 08:05:57 +00002757 printf("\n Byref variable layout: ");
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002758 else
John McCall7f416cc2015-09-08 08:05:57 +00002759 printf("\n Block variable layout: ");
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002760 for (unsigned i = 0, e = BitMap.size(); i != e; i++) {
2761 unsigned char inst = BitMap[i];
2762 enum BLOCK_LAYOUT_OPCODE opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
2763 unsigned delta = 1;
2764 switch (opcode) {
2765 case BLOCK_LAYOUT_OPERATOR:
2766 printf("BL_OPERATOR:");
2767 delta = 0;
2768 break;
2769 case BLOCK_LAYOUT_NON_OBJECT_BYTES:
2770 printf("BL_NON_OBJECT_BYTES:");
2771 break;
2772 case BLOCK_LAYOUT_NON_OBJECT_WORDS:
2773 printf("BL_NON_OBJECT_WORD:");
2774 break;
2775 case BLOCK_LAYOUT_STRONG:
2776 printf("BL_STRONG:");
2777 break;
2778 case BLOCK_LAYOUT_BYREF:
2779 printf("BL_BYREF:");
2780 break;
2781 case BLOCK_LAYOUT_WEAK:
2782 printf("BL_WEAK:");
2783 break;
2784 case BLOCK_LAYOUT_UNRETAINED:
2785 printf("BL_UNRETAINED:");
2786 break;
2787 }
2788 // Actual value of word count is one more that what is in the imm.
2789 // field of the instruction
2790 printf("%d", (inst & 0xf) + delta);
2791 if (i < e-1)
2792 printf(", ");
2793 else
2794 printf("\n");
2795 }
2796 }
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00002797
Saleem Abdulrasool82f6add2016-09-20 18:38:54 +00002798 auto *Entry = CreateCStringLiteral(BitMap, ObjCLabelType::ClassName,
2799 /*ForceNonFragileABI=*/true,
2800 /*NullTerminate=*/false);
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002801 return getConstantGEP(VMContext, Entry, 0, 0);
2802}
2803
Akira Hatanaka2ec36f02018-08-17 15:46:07 +00002804static std::string getBlockLayoutInfoString(
2805 const SmallVectorImpl<CGObjCCommonMac::RUN_SKIP> &RunSkipBlockVars,
2806 bool HasCopyDisposeHelpers) {
2807 std::string Str;
2808 for (const CGObjCCommonMac::RUN_SKIP &R : RunSkipBlockVars) {
2809 if (R.opcode == CGObjCCommonMac::BLOCK_LAYOUT_UNRETAINED) {
2810 // Copy/dispose helpers don't have any information about
2811 // __unsafe_unretained captures, so unconditionally concatenate a string.
2812 Str += "u";
2813 } else if (HasCopyDisposeHelpers) {
2814 // Information about __strong, __weak, or byref captures has already been
2815 // encoded into the names of the copy/dispose helpers. We have to add a
2816 // string here only when the copy/dispose helpers aren't generated (which
2817 // happens when the block is non-escaping).
2818 continue;
2819 } else {
2820 switch (R.opcode) {
2821 case CGObjCCommonMac::BLOCK_LAYOUT_STRONG:
2822 Str += "s";
2823 break;
2824 case CGObjCCommonMac::BLOCK_LAYOUT_BYREF:
2825 Str += "r";
2826 break;
2827 case CGObjCCommonMac::BLOCK_LAYOUT_WEAK:
2828 Str += "w";
2829 break;
2830 default:
2831 continue;
2832 }
2833 }
2834 Str += llvm::to_string(R.block_var_bytepos.getQuantity());
2835 Str += "l" + llvm::to_string(R.block_var_size.getQuantity());
2836 }
2837 return Str;
2838}
2839
2840void CGObjCCommonMac::fillRunSkipBlockVars(CodeGenModule &CGM,
2841 const CGBlockInfo &blockInfo) {
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +00002842 assert(CGM.getLangOpts().getGC() == LangOptions::NonGC);
Fangrui Song6907ce22018-07-30 19:24:48 +00002843
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +00002844 RunSkipBlockVars.clear();
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002845 bool hasUnion = false;
Fangrui Song6907ce22018-07-30 19:24:48 +00002846
John McCallc8e01702013-04-16 22:48:15 +00002847 unsigned WordSizeInBits = CGM.getTarget().getPointerWidth(0);
2848 unsigned ByteSizeInBits = CGM.getTarget().getCharWidth();
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +00002849 unsigned WordSizeInBytes = WordSizeInBits/ByteSizeInBits;
Fangrui Song6907ce22018-07-30 19:24:48 +00002850
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +00002851 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +00002852
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +00002853 // Calculate the basic layout of the block structure.
2854 const llvm::StructLayout *layout =
2855 CGM.getDataLayout().getStructLayout(blockInfo.StructureType);
Fangrui Song6907ce22018-07-30 19:24:48 +00002856
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +00002857 // Ignore the optional 'this' capture: C++ objects are not assumed
2858 // to be GC'ed.
Fariborz Jahanian4cf177e2012-12-04 17:20:57 +00002859 if (blockInfo.BlockHeaderForcedGapSize != CharUnits::Zero())
2860 UpdateRunSkipBlockVars(false, Qualifiers::OCL_None,
2861 blockInfo.BlockHeaderForcedGapOffset,
2862 blockInfo.BlockHeaderForcedGapSize);
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +00002863 // Walk the captured variables.
Aaron Ballman9371dd22014-03-14 18:34:04 +00002864 for (const auto &CI : blockDecl->captures()) {
2865 const VarDecl *variable = CI.getVariable();
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +00002866 QualType type = variable->getType();
Fangrui Song6907ce22018-07-30 19:24:48 +00002867
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +00002868 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
Fangrui Song6907ce22018-07-30 19:24:48 +00002869
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +00002870 // Ignore constant captures.
2871 if (capture.isConstant()) continue;
Fangrui Song6907ce22018-07-30 19:24:48 +00002872
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002873 CharUnits fieldOffset =
2874 CharUnits::fromQuantity(layout->getElementOffset(capture.getIndex()));
Fangrui Song6907ce22018-07-30 19:24:48 +00002875
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002876 assert(!type->isArrayType() && "array variable should not be caught");
Aaron Ballman9371dd22014-03-14 18:34:04 +00002877 if (!CI.isByRef())
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002878 if (const RecordType *record = type->getAs<RecordType>()) {
2879 BuildRCBlockVarRecordLayout(record, fieldOffset, hasUnion);
2880 continue;
2881 }
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002882 CharUnits fieldSize;
Aaron Ballman9371dd22014-03-14 18:34:04 +00002883 if (CI.isByRef())
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002884 fieldSize = CharUnits::fromQuantity(WordSizeInBytes);
2885 else
2886 fieldSize = CGM.getContext().getTypeSizeInChars(type);
Aaron Ballman9371dd22014-03-14 18:34:04 +00002887 UpdateRunSkipBlockVars(CI.isByRef(), getBlockCaptureLifetime(type, false),
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002888 fieldOffset, fieldSize);
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +00002889 }
Akira Hatanaka2ec36f02018-08-17 15:46:07 +00002890}
2891
2892llvm::Constant *
2893CGObjCCommonMac::BuildRCBlockLayout(CodeGenModule &CGM,
2894 const CGBlockInfo &blockInfo) {
2895 fillRunSkipBlockVars(CGM, blockInfo);
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002896 return getBitmapBlockLayout(false);
2897}
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +00002898
Akira Hatanaka2ec36f02018-08-17 15:46:07 +00002899std::string CGObjCCommonMac::getRCBlockLayoutStr(CodeGenModule &CGM,
2900 const CGBlockInfo &blockInfo) {
2901 fillRunSkipBlockVars(CGM, blockInfo);
2902 return getBlockLayoutInfoString(RunSkipBlockVars,
2903 blockInfo.needsCopyDisposeHelpers());
2904}
2905
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002906llvm::Constant *CGObjCCommonMac::BuildByrefLayout(CodeGen::CodeGenModule &CGM,
2907 QualType T) {
2908 assert(CGM.getLangOpts().getGC() == LangOptions::NonGC);
2909 assert(!T->isArrayType() && "__block array variable should not be caught");
2910 CharUnits fieldOffset;
2911 RunSkipBlockVars.clear();
2912 bool hasUnion = false;
2913 if (const RecordType *record = T->getAs<RecordType>()) {
2914 BuildRCBlockVarRecordLayout(record, fieldOffset, hasUnion, true /*ByrefLayout */);
2915 llvm::Constant *Result = getBitmapBlockLayout(true);
Vedant Kumar2f5bb1152015-12-21 20:21:15 +00002916 if (isa<llvm::ConstantInt>(Result))
2917 Result = llvm::ConstantExpr::getIntToPtr(Result, CGM.Int8PtrTy);
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002918 return Result;
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +00002919 }
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002920 llvm::Constant *nullPtr = llvm::Constant::getNullValue(CGM.Int8PtrTy);
2921 return nullPtr;
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +00002922}
2923
John McCall882987f2013-02-28 19:01:20 +00002924llvm::Value *CGObjCMac::GenerateProtocolRef(CodeGenFunction &CGF,
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00002925 const ObjCProtocolDecl *PD) {
Daniel Dunbar7050c552008-09-04 04:33:15 +00002926 // FIXME: I don't understand why gcc generates this, or where it is
Mike Stump18bb9282009-05-16 07:57:57 +00002927 // resolved. Investigate. Its also wasteful to look this up over and over.
Daniel Dunbar7050c552008-09-04 04:33:15 +00002928 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
2929
Owen Andersonade90fd2009-07-29 18:54:39 +00002930 return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
Douglas Gregor020de322012-01-17 18:36:30 +00002931 ObjCTypes.getExternalProtocolPtrTy());
Daniel Dunbar303e2c22008-08-11 02:45:11 +00002932}
2933
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00002934void CGObjCCommonMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
Mike Stump18bb9282009-05-16 07:57:57 +00002935 // FIXME: We shouldn't need this, the protocol decl should contain enough
2936 // information to tell us whether this was a declaration or a definition.
Daniel Dunbarc475d422008-10-29 22:36:39 +00002937 DefinedProtocols.insert(PD->getIdentifier());
2938
2939 // If we have generated a forward reference to this protocol, emit
2940 // it now. Otherwise do nothing, the protocol objects are lazily
2941 // emitted.
Daniel Dunbar59e476b2009-08-03 17:06:42 +00002942 if (Protocols.count(PD->getIdentifier()))
Daniel Dunbarc475d422008-10-29 22:36:39 +00002943 GetOrEmitProtocol(PD);
2944}
2945
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00002946llvm::Constant *CGObjCCommonMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbarc475d422008-10-29 22:36:39 +00002947 if (DefinedProtocols.count(PD->getIdentifier()))
2948 return GetOrEmitProtocol(PD);
Fangrui Song6907ce22018-07-30 19:24:48 +00002949
Daniel Dunbarc475d422008-10-29 22:36:39 +00002950 return GetOrEmitProtocolRef(PD);
2951}
2952
Douglas Gregor24ae22c2016-04-01 23:23:52 +00002953llvm::Value *CGObjCCommonMac::EmitClassRefViaRuntime(
2954 CodeGenFunction &CGF,
2955 const ObjCInterfaceDecl *ID,
2956 ObjCCommonTypesHelper &ObjCTypes) {
2957 llvm::Constant *lookUpClassFn = ObjCTypes.getLookUpClassFn();
2958
2959 llvm::Value *className =
2960 CGF.CGM.GetAddrOfConstantCString(ID->getObjCRuntimeNameAsString())
2961 .getPointer();
2962 ASTContext &ctx = CGF.CGM.getContext();
2963 className =
2964 CGF.Builder.CreateBitCast(className,
2965 CGF.ConvertType(
2966 ctx.getPointerType(ctx.CharTy.withConst())));
2967 llvm::CallInst *call = CGF.Builder.CreateCall(lookUpClassFn, className);
2968 call->setDoesNotThrow();
2969 return call;
2970}
2971
Daniel Dunbarb036db82008-08-13 03:21:16 +00002972/*
Rafael Espindolaf9e1e5e2014-02-20 14:09:04 +00002973// Objective-C 1.0 extensions
Daniel Dunbar59e476b2009-08-03 17:06:42 +00002974struct _objc_protocol {
2975struct _objc_protocol_extension *isa;
2976char *protocol_name;
2977struct _objc_protocol_list *protocol_list;
2978struct _objc__method_prototype_list *instance_methods;
2979struct _objc__method_prototype_list *class_methods
2980};
Daniel Dunbarb036db82008-08-13 03:21:16 +00002981
Daniel Dunbar59e476b2009-08-03 17:06:42 +00002982See EmitProtocolExtension().
Daniel Dunbarb036db82008-08-13 03:21:16 +00002983*/
Daniel Dunbarc475d422008-10-29 22:36:39 +00002984llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
John McCallf9582a72012-03-30 21:29:05 +00002985 llvm::GlobalVariable *Entry = Protocols[PD->getIdentifier()];
Daniel Dunbarc475d422008-10-29 22:36:39 +00002986
2987 // Early exit if a defining object has already been generated.
2988 if (Entry && Entry->hasInitializer())
2989 return Entry;
2990
Douglas Gregora715bff2012-01-01 19:51:50 +00002991 // Use the protocol definition, if there is one.
2992 if (const ObjCProtocolDecl *Def = PD->getDefinition())
2993 PD = Def;
2994
Daniel Dunbarc61d0e92008-08-25 06:02:07 +00002995 // FIXME: I don't understand why gcc generates this, or where it is
Mike Stump18bb9282009-05-16 07:57:57 +00002996 // resolved. Investigate. Its also wasteful to look this up over and over.
Daniel Dunbarc61d0e92008-08-25 06:02:07 +00002997 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
2998
Daniel Dunbareb1f9a22008-08-27 02:31:56 +00002999 // Construct method lists.
John McCall176f8922016-11-30 02:39:18 +00003000 auto methodLists = ProtocolMethodLists::get(PD);
Daniel Dunbareb1f9a22008-08-27 02:31:56 +00003001
John McCall176f8922016-11-30 02:39:18 +00003002 ConstantInitBuilder builder(CGM);
3003 auto values = builder.beginStruct(ObjCTypes.ProtocolTy);
3004 values.add(EmitProtocolExtension(PD, methodLists));
3005 values.add(GetClassName(PD->getObjCRuntimeNameAsString()));
3006 values.add(EmitProtocolList("OBJC_PROTOCOL_REFS_" + PD->getName(),
3007 PD->protocol_begin(), PD->protocol_end()));
3008 values.add(methodLists.emitMethodList(this, PD,
3009 ProtocolMethodLists::RequiredInstanceMethods));
3010 values.add(methodLists.emitMethodList(this, PD,
3011 ProtocolMethodLists::RequiredClassMethods));
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003012
Daniel Dunbarb036db82008-08-13 03:21:16 +00003013 if (Entry) {
Rafael Espindola5d117f32014-03-06 01:10:46 +00003014 // Already created, update the initializer.
Rafael Espindolab3262952014-05-09 00:43:37 +00003015 assert(Entry->hasPrivateLinkage());
John McCall176f8922016-11-30 02:39:18 +00003016 values.finishAndSetAsInitializer(Entry);
Daniel Dunbarb036db82008-08-13 03:21:16 +00003017 } else {
John McCall176f8922016-11-30 02:39:18 +00003018 Entry = values.finishAndCreateGlobal("OBJC_PROTOCOL_" + PD->getName(),
3019 CGM.getPointerAlign(),
3020 /*constant*/ false,
3021 llvm::GlobalValue::PrivateLinkage);
Daniel Dunbarb036db82008-08-13 03:21:16 +00003022 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
John McCallf9582a72012-03-30 21:29:05 +00003023
3024 Protocols[PD->getIdentifier()] = Entry;
Daniel Dunbarb036db82008-08-13 03:21:16 +00003025 }
Rafael Espindola060062a2014-03-06 22:15:10 +00003026 CGM.addCompilerUsedGlobal(Entry);
Daniel Dunbarc475d422008-10-29 22:36:39 +00003027
3028 return Entry;
Daniel Dunbarb036db82008-08-13 03:21:16 +00003029}
3030
Daniel Dunbarc475d422008-10-29 22:36:39 +00003031llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbarb036db82008-08-13 03:21:16 +00003032 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
3033
3034 if (!Entry) {
Daniel Dunbarc475d422008-10-29 22:36:39 +00003035 // We use the initializer as a marker of whether this is a forward
3036 // reference or not. At module finalization we add the empty
3037 // contents for protocols which were referenced but never defined.
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00003038 Entry = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ProtocolTy,
3039 false, llvm::GlobalValue::PrivateLinkage,
3040 nullptr, "OBJC_PROTOCOL_" + PD->getName());
Daniel Dunbarb036db82008-08-13 03:21:16 +00003041 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbarb036db82008-08-13 03:21:16 +00003042 // FIXME: Is this necessary? Why only for protocol?
3043 Entry->setAlignment(4);
3044 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003045
Daniel Dunbarb036db82008-08-13 03:21:16 +00003046 return Entry;
3047}
3048
3049/*
3050 struct _objc_protocol_extension {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003051 uint32_t size;
3052 struct objc_method_description_list *optional_instance_methods;
3053 struct objc_method_description_list *optional_class_methods;
3054 struct objc_property_list *instance_properties;
Bob Wilson5f4e3a72011-11-30 01:57:58 +00003055 const char ** extendedMethodTypes;
Manman Rence7bff52016-01-29 23:46:55 +00003056 struct objc_property_list *class_properties;
Daniel Dunbarb036db82008-08-13 03:21:16 +00003057 };
3058*/
Daniel Dunbareb1f9a22008-08-27 02:31:56 +00003059llvm::Constant *
3060CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
John McCall176f8922016-11-30 02:39:18 +00003061 const ProtocolMethodLists &methodLists) {
3062 auto optInstanceMethods =
3063 methodLists.emitMethodList(this, PD,
3064 ProtocolMethodLists::OptionalInstanceMethods);
3065 auto optClassMethods =
3066 methodLists.emitMethodList(this, PD,
3067 ProtocolMethodLists::OptionalClassMethods);
3068
3069 auto extendedMethodTypes =
3070 EmitProtocolMethodTypes("OBJC_PROTOCOL_METHOD_TYPES_" + PD->getName(),
3071 methodLists.emitExtendedTypesArray(this),
3072 ObjCTypes);
3073
3074 auto instanceProperties =
3075 EmitPropertyList("OBJC_$_PROP_PROTO_LIST_" + PD->getName(), nullptr, PD,
3076 ObjCTypes, false);
3077 auto classProperties =
3078 EmitPropertyList("OBJC_$_CLASS_PROP_PROTO_LIST_" + PD->getName(), nullptr,
3079 PD, ObjCTypes, true);
Daniel Dunbarb036db82008-08-13 03:21:16 +00003080
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003081 // Return null if no extension bits are used.
John McCall176f8922016-11-30 02:39:18 +00003082 if (optInstanceMethods->isNullValue() &&
3083 optClassMethods->isNullValue() &&
3084 extendedMethodTypes->isNullValue() &&
3085 instanceProperties->isNullValue() &&
3086 classProperties->isNullValue()) {
Owen Anderson0b75f232009-07-31 20:28:54 +00003087 return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
John McCall176f8922016-11-30 02:39:18 +00003088 }
Daniel Dunbarb036db82008-08-13 03:21:16 +00003089
John McCall176f8922016-11-30 02:39:18 +00003090 uint64_t size =
3091 CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ProtocolExtensionTy);
3092
3093 ConstantInitBuilder builder(CGM);
3094 auto values = builder.beginStruct(ObjCTypes.ProtocolExtensionTy);
3095 values.addInt(ObjCTypes.IntTy, size);
3096 values.add(optInstanceMethods);
3097 values.add(optClassMethods);
3098 values.add(instanceProperties);
3099 values.add(extendedMethodTypes);
3100 values.add(classProperties);
Daniel Dunbarb036db82008-08-13 03:21:16 +00003101
Daniel Dunbarc2d4b622009-03-09 21:49:58 +00003102 // No special section, but goes in llvm.used
John McCall176f8922016-11-30 02:39:18 +00003103 return CreateMetadataVar("\01l_OBJC_PROTOCOLEXT_" + PD->getName(), values,
John McCall7f416cc2015-09-08 08:05:57 +00003104 StringRef(), CGM.getPointerAlign(), true);
Daniel Dunbarb036db82008-08-13 03:21:16 +00003105}
3106
3107/*
3108 struct objc_protocol_list {
Bill Wendlinga515b582012-02-09 22:16:49 +00003109 struct objc_protocol_list *next;
3110 long count;
3111 Protocol *list[];
Daniel Dunbarb036db82008-08-13 03:21:16 +00003112 };
3113*/
Daniel Dunbardec75f82008-08-21 21:57:41 +00003114llvm::Constant *
Zachary Turner41a9ee92017-10-11 23:54:34 +00003115CGObjCMac::EmitProtocolList(Twine name,
Daniel Dunbardec75f82008-08-21 21:57:41 +00003116 ObjCProtocolDecl::protocol_iterator begin,
3117 ObjCProtocolDecl::protocol_iterator end) {
Daniel Dunbarb036db82008-08-13 03:21:16 +00003118 // Just return null for empty protocol lists
John McCall176f8922016-11-30 02:39:18 +00003119 if (begin == end)
Owen Anderson0b75f232009-07-31 20:28:54 +00003120 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
Daniel Dunbarb036db82008-08-13 03:21:16 +00003121
John McCall176f8922016-11-30 02:39:18 +00003122 ConstantInitBuilder builder(CGM);
3123 auto values = builder.beginStruct();
Daniel Dunbarb036db82008-08-13 03:21:16 +00003124
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003125 // This field is only used by the runtime.
John McCall176f8922016-11-30 02:39:18 +00003126 values.addNullPointer(ObjCTypes.ProtocolListPtrTy);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003127
John McCall176f8922016-11-30 02:39:18 +00003128 // Reserve a slot for the count.
3129 auto countSlot = values.addPlaceholder();
3130
3131 auto refsArray = values.beginArray(ObjCTypes.ProtocolPtrTy);
3132 for (; begin != end; ++begin) {
3133 refsArray.add(GetProtocolRef(*begin));
3134 }
3135 auto count = refsArray.size();
3136
3137 // This list is null terminated.
3138 refsArray.addNullPointer(ObjCTypes.ProtocolPtrTy);
3139
3140 refsArray.finishAndAddTo(values);
3141 values.fillPlaceholderWithInt(countSlot, ObjCTypes.LongTy, count);
3142
3143 StringRef section;
Saleem Abdulrasool3c628af2016-10-25 21:43:28 +00003144 if (CGM.getTriple().isOSBinFormatMachO())
John McCall176f8922016-11-30 02:39:18 +00003145 section = "__OBJC,__cat_cls_meth,regular,no_dead_strip";
Saleem Abdulrasool3c628af2016-10-25 21:43:28 +00003146
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003147 llvm::GlobalVariable *GV =
Zachary Turner41a9ee92017-10-11 23:54:34 +00003148 CreateMetadataVar(name, values, section, CGM.getPointerAlign(), false);
Owen Andersonade90fd2009-07-29 18:54:39 +00003149 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
Daniel Dunbarb036db82008-08-13 03:21:16 +00003150}
3151
Fangrui Song6907ce22018-07-30 19:24:48 +00003152static void
Bill Wendlingcb5b5ff2012-02-07 09:25:09 +00003153PushProtocolProperties(llvm::SmallPtrSet<const IdentifierInfo*,16> &PropertySet,
John McCall176f8922016-11-30 02:39:18 +00003154 SmallVectorImpl<const ObjCPropertyDecl *> &Properties,
Aaron Ballmandc4bea42014-03-13 18:47:37 +00003155 const ObjCProtocolDecl *Proto,
Manman Renad0e7912016-01-29 19:22:54 +00003156 bool IsClassProperty) {
Fangrui Song6907ce22018-07-30 19:24:48 +00003157 for (const auto *P : Proto->protocols())
John McCall176f8922016-11-30 02:39:18 +00003158 PushProtocolProperties(PropertySet, Properties, P, IsClassProperty);
Manman Renad0e7912016-01-29 19:22:54 +00003159
3160 for (const auto *PD : Proto->properties()) {
3161 if (IsClassProperty != PD->isClassProperty())
3162 continue;
David Blaikie82e95a32014-11-19 07:49:47 +00003163 if (!PropertySet.insert(PD->getIdentifier()).second)
Fariborz Jahanian751c1e72009-12-12 21:26:21 +00003164 continue;
John McCall176f8922016-11-30 02:39:18 +00003165 Properties.push_back(PD);
Fariborz Jahanian751c1e72009-12-12 21:26:21 +00003166 }
3167}
3168
Daniel Dunbarb036db82008-08-13 03:21:16 +00003169/*
Daniel Dunbar80a840b2008-08-23 00:19:03 +00003170 struct _objc_property {
Bill Wendlinga515b582012-02-09 22:16:49 +00003171 const char * const name;
3172 const char * const attributes;
Daniel Dunbar80a840b2008-08-23 00:19:03 +00003173 };
3174
3175 struct _objc_property_list {
Bill Wendlinga515b582012-02-09 22:16:49 +00003176 uint32_t entsize; // sizeof (struct _objc_property)
3177 uint32_t prop_count;
3178 struct _objc_property[prop_count];
Daniel Dunbar80a840b2008-08-23 00:19:03 +00003179 };
3180*/
Zachary Turner41a9ee92017-10-11 23:54:34 +00003181llvm::Constant *CGObjCCommonMac::EmitPropertyList(Twine Name,
3182 const Decl *Container,
3183 const ObjCContainerDecl *OCD,
3184 const ObjCCommonTypesHelper &ObjCTypes,
3185 bool IsClassProperty) {
Manman Ren01b705e2016-04-19 19:05:03 +00003186 if (IsClassProperty) {
3187 // Make this entry NULL for OS X with deployment target < 10.11, for iOS
3188 // with deployment target < 9.0.
3189 const llvm::Triple &Triple = CGM.getTarget().getTriple();
3190 if ((Triple.isMacOSX() && Triple.isMacOSXVersionLT(10, 11)) ||
3191 (Triple.isiOS() && Triple.isOSVersionLT(9)))
3192 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
3193 }
3194
John McCall176f8922016-11-30 02:39:18 +00003195 SmallVector<const ObjCPropertyDecl *, 16> Properties;
Fariborz Jahanian751c1e72009-12-12 21:26:21 +00003196 llvm::SmallPtrSet<const IdentifierInfo*, 16> PropertySet;
Nico Weber08c93332015-12-03 17:44:51 +00003197
Nico Weber08c93332015-12-03 17:44:51 +00003198 if (const ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(OCD))
3199 for (const ObjCCategoryDecl *ClassExt : OID->known_extensions())
Manman Renad0e7912016-01-29 19:22:54 +00003200 for (auto *PD : ClassExt->properties()) {
3201 if (IsClassProperty != PD->isClassProperty())
3202 continue;
Nico Weber08c93332015-12-03 17:44:51 +00003203 PropertySet.insert(PD->getIdentifier());
John McCall176f8922016-11-30 02:39:18 +00003204 Properties.push_back(PD);
Nico Weber08c93332015-12-03 17:44:51 +00003205 }
Manman Renad0e7912016-01-29 19:22:54 +00003206
3207 for (const auto *PD : OCD->properties()) {
3208 if (IsClassProperty != PD->isClassProperty())
3209 continue;
Nico Weber08c93332015-12-03 17:44:51 +00003210 // Don't emit duplicate metadata for properties that were already in a
3211 // class extension.
3212 if (!PropertySet.insert(PD->getIdentifier()).second)
3213 continue;
John McCall176f8922016-11-30 02:39:18 +00003214 Properties.push_back(PD);
Daniel Dunbar80a840b2008-08-23 00:19:03 +00003215 }
Nico Weber08c93332015-12-03 17:44:51 +00003216
Fariborz Jahanian7966aff2010-06-22 16:33:55 +00003217 if (const ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(OCD)) {
Aaron Ballmana9f49e32014-03-13 20:55:22 +00003218 for (const auto *P : OID->all_referenced_protocols())
John McCall176f8922016-11-30 02:39:18 +00003219 PushProtocolProperties(PropertySet, Properties, P, IsClassProperty);
Fariborz Jahanian7966aff2010-06-22 16:33:55 +00003220 }
3221 else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(OCD)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00003222 for (const auto *P : CD->protocols())
John McCall176f8922016-11-30 02:39:18 +00003223 PushProtocolProperties(PropertySet, Properties, P, IsClassProperty);
Fariborz Jahanian7966aff2010-06-22 16:33:55 +00003224 }
Daniel Dunbar80a840b2008-08-23 00:19:03 +00003225
3226 // Return null for empty list.
3227 if (Properties.empty())
Owen Anderson0b75f232009-07-31 20:28:54 +00003228 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
Daniel Dunbar80a840b2008-08-23 00:19:03 +00003229
John McCall176f8922016-11-30 02:39:18 +00003230 unsigned propertySize =
Micah Villmowdd31ca12012-10-08 16:25:52 +00003231 CGM.getDataLayout().getTypeAllocSize(ObjCTypes.PropertyTy);
John McCall176f8922016-11-30 02:39:18 +00003232
3233 ConstantInitBuilder builder(CGM);
3234 auto values = builder.beginStruct();
3235 values.addInt(ObjCTypes.IntTy, propertySize);
3236 values.addInt(ObjCTypes.IntTy, Properties.size());
3237 auto propertiesArray = values.beginArray(ObjCTypes.PropertyTy);
3238 for (auto PD : Properties) {
3239 auto property = propertiesArray.beginStruct(ObjCTypes.PropertyTy);
3240 property.add(GetPropertyName(PD->getIdentifier()));
3241 property.add(GetPropertyTypeString(PD, Container));
3242 property.finishAndAddTo(propertiesArray);
3243 }
3244 propertiesArray.finishAndAddTo(values);
Daniel Dunbar80a840b2008-08-23 00:19:03 +00003245
Saleem Abdulrasool3c628af2016-10-25 21:43:28 +00003246 StringRef Section;
3247 if (CGM.getTriple().isOSBinFormatMachO())
3248 Section = (ObjCABI == 2) ? "__DATA, __objc_const"
3249 : "__OBJC,__property,regular,no_dead_strip";
3250
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003251 llvm::GlobalVariable *GV =
John McCall176f8922016-11-30 02:39:18 +00003252 CreateMetadataVar(Name, values, Section, CGM.getPointerAlign(), true);
Owen Andersonade90fd2009-07-29 18:54:39 +00003253 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.PropertyListPtrTy);
Daniel Dunbar80a840b2008-08-23 00:19:03 +00003254}
3255
Zachary Turner41a9ee92017-10-11 23:54:34 +00003256llvm::Constant *
3257CGObjCCommonMac::EmitProtocolMethodTypes(Twine Name,
3258 ArrayRef<llvm::Constant*> MethodTypes,
3259 const ObjCCommonTypesHelper &ObjCTypes) {
Bob Wilson5f4e3a72011-11-30 01:57:58 +00003260 // Return null for empty list.
3261 if (MethodTypes.empty())
3262 return llvm::Constant::getNullValue(ObjCTypes.Int8PtrPtrTy);
3263
3264 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
3265 MethodTypes.size());
3266 llvm::Constant *Init = llvm::ConstantArray::get(AT, MethodTypes);
3267
Saleem Abdulrasool3c628af2016-10-25 21:43:28 +00003268 StringRef Section;
3269 if (CGM.getTriple().isOSBinFormatMachO() && ObjCABI == 2)
3270 Section = "__DATA, __objc_const";
3271
3272 llvm::GlobalVariable *GV =
3273 CreateMetadataVar(Name, Init, Section, CGM.getPointerAlign(), true);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00003274 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.Int8PtrPtrTy);
3275}
3276
Daniel Dunbar80a840b2008-08-23 00:19:03 +00003277/*
Daniel Dunbar938a77f2008-08-22 20:34:54 +00003278 struct _objc_category {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003279 char *category_name;
3280 char *class_name;
3281 struct _objc_method_list *instance_methods;
3282 struct _objc_method_list *class_methods;
3283 struct _objc_protocol_list *protocols;
3284 uint32_t size; // <rdar://4585769>
3285 struct _objc_property_list *instance_properties;
Manman Ren96df0b32016-01-29 23:45:01 +00003286 struct _objc_property_list *class_properties;
Daniel Dunbar938a77f2008-08-22 20:34:54 +00003287 };
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003288*/
Daniel Dunbar92992502008-08-15 22:20:32 +00003289void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00003290 unsigned Size = CGM.getDataLayout().getTypeAllocSize(ObjCTypes.CategoryTy);
Daniel Dunbar938a77f2008-08-22 20:34:54 +00003291
Mike Stump18bb9282009-05-16 07:57:57 +00003292 // FIXME: This is poor design, the OCD should have a pointer to the category
3293 // decl. Additionally, note that Category can be null for the @implementation
3294 // w/o an @interface case. Sema should just create one for us as it does for
3295 // @implementation so everyone else can live life under a clear blue sky.
Daniel Dunbar938a77f2008-08-22 20:34:54 +00003296 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003297 const ObjCCategoryDecl *Category =
Daniel Dunbar28e76ca2008-08-26 23:03:11 +00003298 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Daniel Dunbar349e6fb2009-10-18 20:48:59 +00003299
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003300 SmallString<256> ExtName;
Daniel Dunbar349e6fb2009-10-18 20:48:59 +00003301 llvm::raw_svector_ostream(ExtName) << Interface->getName() << '_'
3302 << OCD->getName();
Daniel Dunbar938a77f2008-08-22 20:34:54 +00003303
John McCall176f8922016-11-30 02:39:18 +00003304 ConstantInitBuilder Builder(CGM);
3305 auto Values = Builder.beginStruct(ObjCTypes.CategoryTy);
Aaron Ballmanf26acce2014-03-13 19:50:17 +00003306
John McCall176f8922016-11-30 02:39:18 +00003307 enum {
3308 InstanceMethods,
3309 ClassMethods,
3310 NumMethodLists
3311 };
3312 SmallVector<const ObjCMethodDecl *, 16> Methods[NumMethodLists];
3313 for (const auto *MD : OCD->methods()) {
3314 Methods[unsigned(MD->isClassMethod())].push_back(MD);
3315 }
Daniel Dunbar3c76cb52008-08-26 21:51:14 +00003316
John McCall176f8922016-11-30 02:39:18 +00003317 Values.add(GetClassName(OCD->getName()));
3318 Values.add(GetClassName(Interface->getObjCRuntimeNameAsString()));
Fariborz Jahaniane55f8662009-04-29 20:40:05 +00003319 LazySymbols.insert(Interface->getIdentifier());
Saleem Abdulrasoold48b0a32016-10-24 20:47:58 +00003320
John McCall176f8922016-11-30 02:39:18 +00003321 Values.add(emitMethodList(ExtName, MethodListType::CategoryInstanceMethods,
3322 Methods[InstanceMethods]));
3323 Values.add(emitMethodList(ExtName, MethodListType::CategoryClassMethods,
3324 Methods[ClassMethods]));
Daniel Dunbareb1f9a22008-08-27 02:31:56 +00003325 if (Category) {
John McCall176f8922016-11-30 02:39:18 +00003326 Values.add(
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00003327 EmitProtocolList("OBJC_CATEGORY_PROTOCOLS_" + ExtName.str(),
John McCall176f8922016-11-30 02:39:18 +00003328 Category->protocol_begin(), Category->protocol_end()));
Daniel Dunbareb1f9a22008-08-27 02:31:56 +00003329 } else {
John McCall176f8922016-11-30 02:39:18 +00003330 Values.addNullPointer(ObjCTypes.ProtocolListPtrTy);
Daniel Dunbareb1f9a22008-08-27 02:31:56 +00003331 }
John McCall176f8922016-11-30 02:39:18 +00003332 Values.addInt(ObjCTypes.IntTy, Size);
Daniel Dunbar28e76ca2008-08-26 23:03:11 +00003333
3334 // If there is no category @interface then there can be no properties.
3335 if (Category) {
John McCall176f8922016-11-30 02:39:18 +00003336 Values.add(EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ExtName.str(),
3337 OCD, Category, ObjCTypes, false));
3338 Values.add(EmitPropertyList("\01l_OBJC_$_CLASS_PROP_LIST_" + ExtName.str(),
3339 OCD, Category, ObjCTypes, true));
Daniel Dunbar28e76ca2008-08-26 23:03:11 +00003340 } else {
John McCall176f8922016-11-30 02:39:18 +00003341 Values.addNullPointer(ObjCTypes.PropertyListPtrTy);
3342 Values.addNullPointer(ObjCTypes.PropertyListPtrTy);
Daniel Dunbar28e76ca2008-08-26 23:03:11 +00003343 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003344
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003345 llvm::GlobalVariable *GV =
John McCall176f8922016-11-30 02:39:18 +00003346 CreateMetadataVar("OBJC_CATEGORY_" + ExtName.str(), Values,
John McCall7f416cc2015-09-08 08:05:57 +00003347 "__OBJC,__category,regular,no_dead_strip",
3348 CGM.getPointerAlign(), true);
Daniel Dunbar938a77f2008-08-22 20:34:54 +00003349 DefinedCategories.push_back(GV);
Justin Lebar5e83dfe2016-10-21 21:45:01 +00003350 DefinedCategoryNames.insert(llvm::CachedHashString(ExtName));
Fariborz Jahanianc0577942011-04-22 22:02:28 +00003351 // method definition entries must be clear for next implementation.
3352 MethodDefinitions.clear();
Daniel Dunbar303e2c22008-08-11 02:45:11 +00003353}
3354
John McCallef19dbb2012-10-17 04:53:23 +00003355enum FragileClassFlags {
John McCall460ce582015-10-22 18:38:17 +00003356 /// Apparently: is not a meta-class.
John McCallef19dbb2012-10-17 04:53:23 +00003357 FragileABI_Class_Factory = 0x00001,
John McCall460ce582015-10-22 18:38:17 +00003358
3359 /// Is a meta-class.
John McCallef19dbb2012-10-17 04:53:23 +00003360 FragileABI_Class_Meta = 0x00002,
John McCall460ce582015-10-22 18:38:17 +00003361
3362 /// Has a non-trivial constructor or destructor.
John McCallef19dbb2012-10-17 04:53:23 +00003363 FragileABI_Class_HasCXXStructors = 0x02000,
John McCall460ce582015-10-22 18:38:17 +00003364
3365 /// Has hidden visibility.
John McCall09ec1ec2015-10-21 22:06:03 +00003366 FragileABI_Class_Hidden = 0x20000,
John McCall460ce582015-10-22 18:38:17 +00003367
3368 /// Class implementation was compiled under ARC.
3369 FragileABI_Class_CompiledByARC = 0x04000000,
3370
3371 /// Class implementation was compiled under MRC and has MRC weak ivars.
3372 /// Exclusive with CompiledByARC.
3373 FragileABI_Class_HasMRCWeakIvars = 0x08000000,
John McCallef19dbb2012-10-17 04:53:23 +00003374};
3375
3376enum NonFragileClassFlags {
3377 /// Is a meta-class.
3378 NonFragileABI_Class_Meta = 0x00001,
3379
3380 /// Is a root class.
3381 NonFragileABI_Class_Root = 0x00002,
3382
John McCall460ce582015-10-22 18:38:17 +00003383 /// Has a non-trivial constructor or destructor.
John McCallef19dbb2012-10-17 04:53:23 +00003384 NonFragileABI_Class_HasCXXStructors = 0x00004,
3385
3386 /// Has hidden visibility.
3387 NonFragileABI_Class_Hidden = 0x00010,
3388
3389 /// Has the exception attribute.
3390 NonFragileABI_Class_Exception = 0x00020,
3391
3392 /// (Obsolete) ARC-specific: this class has a .release_ivars method
3393 NonFragileABI_Class_HasIvarReleaser = 0x00040,
3394
3395 /// Class implementation was compiled under ARC.
John McCall0d54a172012-10-17 04:53:31 +00003396 NonFragileABI_Class_CompiledByARC = 0x00080,
3397
3398 /// Class has non-trivial destructors, but zero-initialization is okay.
John McCall460ce582015-10-22 18:38:17 +00003399 NonFragileABI_Class_HasCXXDestructorOnly = 0x00100,
3400
3401 /// Class implementation was compiled under MRC and has MRC weak ivars.
3402 /// Exclusive with CompiledByARC.
3403 NonFragileABI_Class_HasMRCWeakIvars = 0x00200,
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003404};
3405
John McCall460ce582015-10-22 18:38:17 +00003406static bool hasWeakMember(QualType type) {
3407 if (type.getObjCLifetime() == Qualifiers::OCL_Weak) {
3408 return true;
3409 }
3410
3411 if (auto recType = type->getAs<RecordType>()) {
3412 for (auto field : recType->getDecl()->fields()) {
3413 if (hasWeakMember(field->getType()))
3414 return true;
3415 }
3416 }
3417
3418 return false;
3419}
3420
3421/// For compatibility, we only want to set the "HasMRCWeakIvars" flag
3422/// (and actually fill in a layout string) if we really do have any
3423/// __weak ivars.
3424static bool hasMRCWeakIvars(CodeGenModule &CGM,
3425 const ObjCImplementationDecl *ID) {
3426 if (!CGM.getLangOpts().ObjCWeak) return false;
3427 assert(CGM.getLangOpts().getGC() == LangOptions::NonGC);
3428
3429 for (const ObjCIvarDecl *ivar =
3430 ID->getClassInterface()->all_declared_ivar_begin();
3431 ivar; ivar = ivar->getNextIvar()) {
3432 if (hasWeakMember(ivar->getType()))
3433 return true;
3434 }
3435
3436 return false;
3437}
3438
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003439/*
3440 struct _objc_class {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003441 Class isa;
3442 Class super_class;
3443 const char *name;
3444 long version;
3445 long info;
3446 long instance_size;
3447 struct _objc_ivar_list *ivars;
3448 struct _objc_method_list *methods;
3449 struct _objc_cache *cache;
3450 struct _objc_protocol_list *protocols;
3451 // Objective-C 1.0 extensions (<rdr://4585769>)
3452 const char *ivar_layout;
3453 struct _objc_class_ext *ext;
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003454 };
3455
3456 See EmitClassExtension();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003457*/
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003458void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
Akira Hatanaka0c194462018-04-03 22:50:16 +00003459 IdentifierInfo *RuntimeName =
3460 &CGM.getContext().Idents.get(ID->getObjCRuntimeNameAsString());
3461 DefinedSymbols.insert(RuntimeName);
Daniel Dunbarc61d0e92008-08-25 06:02:07 +00003462
Chris Lattner86d7d912008-11-24 03:54:41 +00003463 std::string ClassName = ID->getNameAsString();
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003464 // FIXME: Gross
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003465 ObjCInterfaceDecl *Interface =
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003466 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003467 llvm::Constant *Protocols =
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00003468 EmitProtocolList("OBJC_CLASS_PROTOCOLS_" + ID->getName(),
3469 Interface->all_referenced_protocol_begin(),
3470 Interface->all_referenced_protocol_end());
John McCallef19dbb2012-10-17 04:53:23 +00003471 unsigned Flags = FragileABI_Class_Factory;
John McCall0d54a172012-10-17 04:53:31 +00003472 if (ID->hasNonZeroConstructors() || ID->hasDestructors())
John McCallef19dbb2012-10-17 04:53:23 +00003473 Flags |= FragileABI_Class_HasCXXStructors;
John McCall09ec1ec2015-10-21 22:06:03 +00003474
John McCall460ce582015-10-22 18:38:17 +00003475 bool hasMRCWeak = false;
3476
John McCall09ec1ec2015-10-21 22:06:03 +00003477 if (CGM.getLangOpts().ObjCAutoRefCount)
3478 Flags |= FragileABI_Class_CompiledByARC;
John McCall460ce582015-10-22 18:38:17 +00003479 else if ((hasMRCWeak = hasMRCWeakIvars(CGM, ID)))
3480 Flags |= FragileABI_Class_HasMRCWeakIvars;
John McCall09ec1ec2015-10-21 22:06:03 +00003481
John McCall3fd13f062015-10-21 18:06:47 +00003482 CharUnits Size =
3483 CGM.getContext().getASTObjCImplementationLayout(ID).getSize();
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003484
3485 // FIXME: Set CXX-structors flag.
John McCall457a04e2010-10-22 21:05:15 +00003486 if (ID->getClassInterface()->getVisibility() == HiddenVisibility)
John McCallef19dbb2012-10-17 04:53:23 +00003487 Flags |= FragileABI_Class_Hidden;
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003488
John McCall176f8922016-11-30 02:39:18 +00003489 enum {
3490 InstanceMethods,
3491 ClassMethods,
3492 NumMethodLists
3493 };
3494 SmallVector<const ObjCMethodDecl *, 16> Methods[NumMethodLists];
3495 for (const auto *MD : ID->methods()) {
3496 Methods[unsigned(MD->isClassMethod())].push_back(MD);
3497 }
Daniel Dunbar3c76cb52008-08-26 21:51:14 +00003498
Aaron Ballmand85eff42014-03-14 15:02:45 +00003499 for (const auto *PID : ID->property_impls()) {
Daniel Dunbar3c76cb52008-08-26 21:51:14 +00003500 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
3501 ObjCPropertyDecl *PD = PID->getPropertyDecl();
3502
3503 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
John McCall176f8922016-11-30 02:39:18 +00003504 if (GetMethodDefinition(MD))
3505 Methods[InstanceMethods].push_back(MD);
Daniel Dunbar3c76cb52008-08-26 21:51:14 +00003506 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
John McCall176f8922016-11-30 02:39:18 +00003507 if (GetMethodDefinition(MD))
3508 Methods[InstanceMethods].push_back(MD);
Daniel Dunbar3c76cb52008-08-26 21:51:14 +00003509 }
3510 }
3511
John McCall176f8922016-11-30 02:39:18 +00003512 ConstantInitBuilder builder(CGM);
3513 auto values = builder.beginStruct(ObjCTypes.ClassTy);
3514 values.add(EmitMetaClass(ID, Protocols, Methods[ClassMethods]));
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003515 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
Daniel Dunbarc61d0e92008-08-25 06:02:07 +00003516 // Record a reference to the super class.
3517 LazySymbols.insert(Super->getIdentifier());
3518
John McCall176f8922016-11-30 02:39:18 +00003519 values.addBitCast(GetClassName(Super->getObjCRuntimeNameAsString()),
3520 ObjCTypes.ClassPtrTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003521 } else {
John McCall176f8922016-11-30 02:39:18 +00003522 values.addNullPointer(ObjCTypes.ClassPtrTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003523 }
John McCall176f8922016-11-30 02:39:18 +00003524 values.add(GetClassName(ID->getObjCRuntimeNameAsString()));
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003525 // Version is always 0.
John McCall176f8922016-11-30 02:39:18 +00003526 values.addInt(ObjCTypes.LongTy, 0);
3527 values.addInt(ObjCTypes.LongTy, Flags);
3528 values.addInt(ObjCTypes.LongTy, Size.getQuantity());
3529 values.add(EmitIvarList(ID, false));
3530 values.add(emitMethodList(ID->getName(), MethodListType::InstanceMethods,
3531 Methods[InstanceMethods]));
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003532 // cache is always NULL.
John McCall176f8922016-11-30 02:39:18 +00003533 values.addNullPointer(ObjCTypes.CachePtrTy);
3534 values.add(Protocols);
3535 values.add(BuildStrongIvarLayout(ID, CharUnits::Zero(), Size));
3536 values.add(EmitClassExtension(ID, Size, hasMRCWeak,
3537 /*isMetaclass*/ false));
3538
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00003539 std::string Name("OBJC_CLASS_");
Fariborz Jahanianeb80c982009-11-12 20:14:24 +00003540 Name += ClassName;
3541 const char *Section = "__OBJC,__class,regular,no_dead_strip";
3542 // Check for a forward reference.
Rafael Espindola554256c2014-02-26 22:25:45 +00003543 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
Fariborz Jahanianeb80c982009-11-12 20:14:24 +00003544 if (GV) {
3545 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
3546 "Forward metaclass reference has incorrect type.");
John McCall176f8922016-11-30 02:39:18 +00003547 values.finishAndSetAsInitializer(GV);
Fariborz Jahanianeb80c982009-11-12 20:14:24 +00003548 GV->setSection(Section);
John McCall7f416cc2015-09-08 08:05:57 +00003549 GV->setAlignment(CGM.getPointerAlign().getQuantity());
Rafael Espindola060062a2014-03-06 22:15:10 +00003550 CGM.addCompilerUsedGlobal(GV);
Rafael Espindola21039aa2014-02-27 16:26:32 +00003551 } else
John McCall176f8922016-11-30 02:39:18 +00003552 GV = CreateMetadataVar(Name, values, Section, CGM.getPointerAlign(), true);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003553 DefinedClasses.push_back(GV);
Fariborz Jahanianf322f2f2014-03-11 00:25:05 +00003554 ImplementedClasses.push_back(Interface);
Fariborz Jahanianc0577942011-04-22 22:02:28 +00003555 // method definition entries must be clear for next implementation.
3556 MethodDefinitions.clear();
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003557}
3558
3559llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
3560 llvm::Constant *Protocols,
John McCall176f8922016-11-30 02:39:18 +00003561 ArrayRef<const ObjCMethodDecl*> Methods) {
John McCallef19dbb2012-10-17 04:53:23 +00003562 unsigned Flags = FragileABI_Class_Meta;
Micah Villmowdd31ca12012-10-08 16:25:52 +00003563 unsigned Size = CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ClassTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003564
John McCall457a04e2010-10-22 21:05:15 +00003565 if (ID->getClassInterface()->getVisibility() == HiddenVisibility)
John McCallef19dbb2012-10-17 04:53:23 +00003566 Flags |= FragileABI_Class_Hidden;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003567
John McCall176f8922016-11-30 02:39:18 +00003568 ConstantInitBuilder builder(CGM);
3569 auto values = builder.beginStruct(ObjCTypes.ClassTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003570 // The isa for the metaclass is the root of the hierarchy.
3571 const ObjCInterfaceDecl *Root = ID->getClassInterface();
3572 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
3573 Root = Super;
John McCall176f8922016-11-30 02:39:18 +00003574 values.addBitCast(GetClassName(Root->getObjCRuntimeNameAsString()),
3575 ObjCTypes.ClassPtrTy);
Daniel Dunbar938a77f2008-08-22 20:34:54 +00003576 // The super class for the metaclass is emitted as the name of the
3577 // super class. The runtime fixes this up to point to the
3578 // *metaclass* for the super class.
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003579 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
John McCall176f8922016-11-30 02:39:18 +00003580 values.addBitCast(GetClassName(Super->getObjCRuntimeNameAsString()),
3581 ObjCTypes.ClassPtrTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003582 } else {
John McCall176f8922016-11-30 02:39:18 +00003583 values.addNullPointer(ObjCTypes.ClassPtrTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003584 }
John McCall176f8922016-11-30 02:39:18 +00003585 values.add(GetClassName(ID->getObjCRuntimeNameAsString()));
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003586 // Version is always 0.
John McCall176f8922016-11-30 02:39:18 +00003587 values.addInt(ObjCTypes.LongTy, 0);
3588 values.addInt(ObjCTypes.LongTy, Flags);
3589 values.addInt(ObjCTypes.LongTy, Size);
3590 values.add(EmitIvarList(ID, true));
3591 values.add(emitMethodList(ID->getName(), MethodListType::ClassMethods,
3592 Methods));
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003593 // cache is always NULL.
John McCall176f8922016-11-30 02:39:18 +00003594 values.addNullPointer(ObjCTypes.CachePtrTy);
3595 values.add(Protocols);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003596 // ivar_layout for metaclass is always NULL.
John McCall176f8922016-11-30 02:39:18 +00003597 values.addNullPointer(ObjCTypes.Int8PtrTy);
Manman Renad0e7912016-01-29 19:22:54 +00003598 // The class extension is used to store class properties for metaclasses.
John McCall176f8922016-11-30 02:39:18 +00003599 values.add(EmitClassExtension(ID, CharUnits::Zero(), false/*hasMRCWeak*/,
3600 /*isMetaclass*/true));
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003601
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00003602 std::string Name("OBJC_METACLASS_");
Benjamin Kramer1bbcbd02012-07-31 11:45:39 +00003603 Name += ID->getName();
Daniel Dunbarca8531a2008-08-25 08:19:24 +00003604
3605 // Check for a forward reference.
Rafael Espindola554256c2014-02-26 22:25:45 +00003606 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
Daniel Dunbarca8531a2008-08-25 08:19:24 +00003607 if (GV) {
3608 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
3609 "Forward metaclass reference has incorrect type.");
John McCall176f8922016-11-30 02:39:18 +00003610 values.finishAndSetAsInitializer(GV);
Daniel Dunbarca8531a2008-08-25 08:19:24 +00003611 } else {
John McCall176f8922016-11-30 02:39:18 +00003612 GV = values.finishAndCreateGlobal(Name, CGM.getPointerAlign(),
3613 /*constant*/ false,
3614 llvm::GlobalValue::PrivateLinkage);
Daniel Dunbarca8531a2008-08-25 08:19:24 +00003615 }
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003616 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
Rafael Espindola060062a2014-03-06 22:15:10 +00003617 CGM.addCompilerUsedGlobal(GV);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003618
3619 return GV;
3620}
3621
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003622llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00003623 std::string Name = "OBJC_METACLASS_" + ID->getNameAsString();
Daniel Dunbarca8531a2008-08-25 08:19:24 +00003624
Mike Stump18bb9282009-05-16 07:57:57 +00003625 // FIXME: Should we look these up somewhere other than the module. Its a bit
3626 // silly since we only generate these while processing an implementation, so
3627 // exactly one pointer would work if know when we entered/exitted an
3628 // implementation block.
Daniel Dunbarca8531a2008-08-25 08:19:24 +00003629
3630 // Check for an existing forward reference.
Fariborz Jahanian475831b2009-01-07 20:11:22 +00003631 // Previously, metaclass with internal linkage may have been defined.
3632 // pass 'true' as 2nd argument so it is returned.
Rafael Espindola21039aa2014-02-27 16:26:32 +00003633 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
3634 if (!GV)
3635 GV = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassTy, false,
Craig Topper8a13c412014-05-21 05:09:00 +00003636 llvm::GlobalValue::PrivateLinkage, nullptr,
3637 Name);
Rafael Espindola21039aa2014-02-27 16:26:32 +00003638
3639 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
3640 "Forward metaclass reference has incorrect type.");
Rafael Espindola21039aa2014-02-27 16:26:32 +00003641 return GV;
Daniel Dunbarca8531a2008-08-25 08:19:24 +00003642}
3643
Fariborz Jahanianeb80c982009-11-12 20:14:24 +00003644llvm::Value *CGObjCMac::EmitSuperClassRef(const ObjCInterfaceDecl *ID) {
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00003645 std::string Name = "OBJC_CLASS_" + ID->getNameAsString();
Rafael Espindola21039aa2014-02-27 16:26:32 +00003646 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
3647
3648 if (!GV)
3649 GV = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassTy, false,
Craig Topper8a13c412014-05-21 05:09:00 +00003650 llvm::GlobalValue::PrivateLinkage, nullptr,
3651 Name);
Rafael Espindola21039aa2014-02-27 16:26:32 +00003652
3653 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
3654 "Forward class metadata reference has incorrect type.");
Rafael Espindola21039aa2014-02-27 16:26:32 +00003655 return GV;
Fariborz Jahanianeb80c982009-11-12 20:14:24 +00003656}
3657
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003658/*
John McCall3fd13f062015-10-21 18:06:47 +00003659 Emit a "class extension", which in this specific context means extra
3660 data that doesn't fit in the normal fragile-ABI class structure, and
3661 has nothing to do with the language concept of a class extension.
3662
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003663 struct objc_class_ext {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003664 uint32_t size;
3665 const char *weak_ivar_layout;
3666 struct _objc_property_list *properties;
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003667 };
3668*/
3669llvm::Constant *
John McCall3fd13f062015-10-21 18:06:47 +00003670CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID,
Manman Renad0e7912016-01-29 19:22:54 +00003671 CharUnits InstanceSize, bool hasMRCWeakIvars,
John McCall176f8922016-11-30 02:39:18 +00003672 bool isMetaclass) {
3673 // Weak ivar layout.
3674 llvm::Constant *layout;
3675 if (isMetaclass) {
3676 layout = llvm::ConstantPointerNull::get(CGM.Int8PtrTy);
3677 } else {
3678 layout = BuildWeakIvarLayout(ID, CharUnits::Zero(), InstanceSize,
3679 hasMRCWeakIvars);
3680 }
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003681
John McCall176f8922016-11-30 02:39:18 +00003682 // Properties.
3683 llvm::Constant *propertyList =
3684 EmitPropertyList((isMetaclass ? Twine("\01l_OBJC_$_CLASS_PROP_LIST_")
3685 : Twine("\01l_OBJC_$_PROP_LIST_"))
3686 + ID->getName(),
3687 ID, ID->getClassInterface(), ObjCTypes, isMetaclass);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003688
3689 // Return null if no extension bits are used.
John McCall176f8922016-11-30 02:39:18 +00003690 if (layout->isNullValue() && propertyList->isNullValue()) {
Owen Anderson0b75f232009-07-31 20:28:54 +00003691 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
John McCall176f8922016-11-30 02:39:18 +00003692 }
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003693
John McCall176f8922016-11-30 02:39:18 +00003694 uint64_t size =
3695 CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ClassExtensionTy);
3696
3697 ConstantInitBuilder builder(CGM);
3698 auto values = builder.beginStruct(ObjCTypes.ClassExtensionTy);
3699 values.addInt(ObjCTypes.IntTy, size);
3700 values.add(layout);
3701 values.add(propertyList);
3702
3703 return CreateMetadataVar("OBJC_CLASSEXT_" + ID->getName(), values,
John McCall7f416cc2015-09-08 08:05:57 +00003704 "__OBJC,__class_ext,regular,no_dead_strip",
3705 CGM.getPointerAlign(), true);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003706}
3707
3708/*
3709 struct objc_ivar {
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00003710 char *ivar_name;
3711 char *ivar_type;
3712 int ivar_offset;
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003713 };
3714
3715 struct objc_ivar_list {
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00003716 int ivar_count;
3717 struct objc_ivar list[count];
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003718 };
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003719*/
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003720llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanianb042a592009-01-28 19:12:34 +00003721 bool ForClass) {
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003722 // When emitting the root class GCC emits ivar entries for the
3723 // actual class structure. It is not clear if we need to follow this
3724 // behavior; for now lets try and get away with not doing it. If so,
3725 // the cleanest solution would be to make up an ObjCInterfaceDecl
3726 // for the class.
3727 if (ForClass)
Owen Anderson0b75f232009-07-31 20:28:54 +00003728 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003729
Jordy Rosea91768e2011-07-22 02:08:32 +00003730 const ObjCInterfaceDecl *OID = ID->getClassInterface();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003731
John McCall176f8922016-11-30 02:39:18 +00003732 ConstantInitBuilder builder(CGM);
3733 auto ivarList = builder.beginStruct();
3734 auto countSlot = ivarList.addPlaceholder();
3735 auto ivars = ivarList.beginArray(ObjCTypes.IvarTy);
3736
Fangrui Song6907ce22018-07-30 19:24:48 +00003737 for (const ObjCIvarDecl *IVD = OID->all_declared_ivar_begin();
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00003738 IVD; IVD = IVD->getNextIvar()) {
Fariborz Jahanian7c809592009-06-04 01:19:09 +00003739 // Ignore unnamed bit-fields.
3740 if (!IVD->getDeclName())
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003741 continue;
John McCall176f8922016-11-30 02:39:18 +00003742
3743 auto ivar = ivars.beginStruct(ObjCTypes.IvarTy);
3744 ivar.add(GetMethodVarName(IVD->getIdentifier()));
3745 ivar.add(GetMethodVarType(IVD));
3746 ivar.addInt(ObjCTypes.IntTy, ComputeIvarBaseOffset(CGM, OID, IVD));
3747 ivar.finishAndAddTo(ivars);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003748 }
3749
3750 // Return null for empty list.
John McCall176f8922016-11-30 02:39:18 +00003751 auto count = ivars.size();
3752 if (count == 0) {
3753 ivars.abandon();
3754 ivarList.abandon();
Owen Anderson0b75f232009-07-31 20:28:54 +00003755 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
John McCall176f8922016-11-30 02:39:18 +00003756 }
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003757
John McCall176f8922016-11-30 02:39:18 +00003758 ivars.finishAndAddTo(ivarList);
3759 ivarList.fillPlaceholderWithInt(countSlot, ObjCTypes.IntTy, count);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003760
Daniel Dunbarc2d4b622009-03-09 21:49:58 +00003761 llvm::GlobalVariable *GV;
3762 if (ForClass)
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00003763 GV =
John McCall176f8922016-11-30 02:39:18 +00003764 CreateMetadataVar("OBJC_CLASS_VARIABLES_" + ID->getName(), ivarList,
John McCall7f416cc2015-09-08 08:05:57 +00003765 "__OBJC,__class_vars,regular,no_dead_strip",
3766 CGM.getPointerAlign(), true);
Daniel Dunbarc2d4b622009-03-09 21:49:58 +00003767 else
John McCall176f8922016-11-30 02:39:18 +00003768 GV = CreateMetadataVar("OBJC_INSTANCE_VARIABLES_" + ID->getName(), ivarList,
John McCall7f416cc2015-09-08 08:05:57 +00003769 "__OBJC,__instance_vars,regular,no_dead_strip",
3770 CGM.getPointerAlign(), true);
Owen Andersonade90fd2009-07-29 18:54:39 +00003771 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.IvarListPtrTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003772}
3773
John McCall176f8922016-11-30 02:39:18 +00003774/// Build a struct objc_method_description constant for the given method.
3775///
3776/// struct objc_method_description {
3777/// SEL method_name;
3778/// char *method_types;
3779/// };
3780void CGObjCMac::emitMethodDescriptionConstant(ConstantArrayBuilder &builder,
3781 const ObjCMethodDecl *MD) {
3782 auto description = builder.beginStruct(ObjCTypes.MethodDescriptionTy);
3783 description.addBitCast(GetMethodVarName(MD->getSelector()),
3784 ObjCTypes.SelectorPtrTy);
3785 description.add(GetMethodVarType(MD));
3786 description.finishAndAddTo(builder);
Daniel Dunbar3c76cb52008-08-26 21:51:14 +00003787}
3788
John McCall176f8922016-11-30 02:39:18 +00003789/// Build a struct objc_method constant for the given method.
3790///
3791/// struct objc_method {
3792/// SEL method_name;
3793/// char *method_types;
3794/// void *method;
3795/// };
3796void CGObjCMac::emitMethodConstant(ConstantArrayBuilder &builder,
3797 const ObjCMethodDecl *MD) {
3798 llvm::Function *fn = GetMethodDefinition(MD);
3799 assert(fn && "no definition registered for method");
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003800
John McCall176f8922016-11-30 02:39:18 +00003801 auto method = builder.beginStruct(ObjCTypes.MethodTy);
3802 method.addBitCast(GetMethodVarName(MD->getSelector()),
3803 ObjCTypes.SelectorPtrTy);
3804 method.add(GetMethodVarType(MD));
3805 method.addBitCast(fn, ObjCTypes.Int8PtrTy);
3806 method.finishAndAddTo(builder);
3807}
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003808
John McCall176f8922016-11-30 02:39:18 +00003809/// Build a struct objc_method_list or struct objc_method_description_list,
3810/// as appropriate.
3811///
3812/// struct objc_method_list {
3813/// struct objc_method_list *obsolete;
3814/// int count;
3815/// struct objc_method methods_list[count];
3816/// };
3817///
3818/// struct objc_method_description_list {
3819/// int count;
3820/// struct objc_method_description list[count];
3821/// };
Zachary Turner41a9ee92017-10-11 23:54:34 +00003822llvm::Constant *CGObjCMac::emitMethodList(Twine name, MethodListType MLT,
3823 ArrayRef<const ObjCMethodDecl *> methods) {
John McCall176f8922016-11-30 02:39:18 +00003824 StringRef prefix;
3825 StringRef section;
3826 bool forProtocol = false;
Saleem Abdulrasoold48b0a32016-10-24 20:47:58 +00003827 switch (MLT) {
3828 case MethodListType::CategoryInstanceMethods:
John McCall176f8922016-11-30 02:39:18 +00003829 prefix = "OBJC_CATEGORY_INSTANCE_METHODS_";
3830 section = "__OBJC,__cat_inst_meth,regular,no_dead_strip";
3831 forProtocol = false;
Saleem Abdulrasoold48b0a32016-10-24 20:47:58 +00003832 break;
3833 case MethodListType::CategoryClassMethods:
John McCall176f8922016-11-30 02:39:18 +00003834 prefix = "OBJC_CATEGORY_CLASS_METHODS_";
3835 section = "__OBJC,__cat_cls_meth,regular,no_dead_strip";
3836 forProtocol = false;
Saleem Abdulrasoold48b0a32016-10-24 20:47:58 +00003837 break;
3838 case MethodListType::InstanceMethods:
John McCall176f8922016-11-30 02:39:18 +00003839 prefix = "OBJC_INSTANCE_METHODS_";
3840 section = "__OBJC,__inst_meth,regular,no_dead_strip";
3841 forProtocol = false;
Saleem Abdulrasoold48b0a32016-10-24 20:47:58 +00003842 break;
3843 case MethodListType::ClassMethods:
John McCall176f8922016-11-30 02:39:18 +00003844 prefix = "OBJC_CLASS_METHODS_";
3845 section = "__OBJC,__cls_meth,regular,no_dead_strip";
3846 forProtocol = false;
Saleem Abdulrasoold48b0a32016-10-24 20:47:58 +00003847 break;
Saleem Abdulrasoold48b0a32016-10-24 20:47:58 +00003848 case MethodListType::ProtocolInstanceMethods:
John McCall176f8922016-11-30 02:39:18 +00003849 prefix = "OBJC_PROTOCOL_INSTANCE_METHODS_";
3850 section = "__OBJC,__cat_inst_meth,regular,no_dead_strip";
3851 forProtocol = true;
3852 break;
Saleem Abdulrasoold48b0a32016-10-24 20:47:58 +00003853 case MethodListType::ProtocolClassMethods:
John McCall176f8922016-11-30 02:39:18 +00003854 prefix = "OBJC_PROTOCOL_CLASS_METHODS_";
3855 section = "__OBJC,__cat_cls_meth,regular,no_dead_strip";
3856 forProtocol = true;
3857 break;
Saleem Abdulrasoold48b0a32016-10-24 20:47:58 +00003858 case MethodListType::OptionalProtocolInstanceMethods:
John McCall176f8922016-11-30 02:39:18 +00003859 prefix = "OBJC_PROTOCOL_INSTANCE_METHODS_OPT_";
3860 section = "__OBJC,__cat_inst_meth,regular,no_dead_strip";
3861 forProtocol = true;
3862 break;
Saleem Abdulrasoold48b0a32016-10-24 20:47:58 +00003863 case MethodListType::OptionalProtocolClassMethods:
John McCall176f8922016-11-30 02:39:18 +00003864 prefix = "OBJC_PROTOCOL_CLASS_METHODS_OPT_";
3865 section = "__OBJC,__cat_cls_meth,regular,no_dead_strip";
3866 forProtocol = true;
3867 break;
Saleem Abdulrasoold48b0a32016-10-24 20:47:58 +00003868 }
3869
John McCall176f8922016-11-30 02:39:18 +00003870 // Return null for empty list.
3871 if (methods.empty())
3872 return llvm::Constant::getNullValue(forProtocol
3873 ? ObjCTypes.MethodDescriptionListPtrTy
3874 : ObjCTypes.MethodListPtrTy);
3875
3876 // For protocols, this is an objc_method_description_list, which has
3877 // a slightly different structure.
3878 if (forProtocol) {
3879 ConstantInitBuilder builder(CGM);
3880 auto values = builder.beginStruct();
3881 values.addInt(ObjCTypes.IntTy, methods.size());
3882 auto methodArray = values.beginArray(ObjCTypes.MethodDescriptionTy);
3883 for (auto MD : methods) {
3884 emitMethodDescriptionConstant(methodArray, MD);
3885 }
3886 methodArray.finishAndAddTo(values);
3887
Zachary Turner41a9ee92017-10-11 23:54:34 +00003888 llvm::GlobalVariable *GV = CreateMetadataVar(prefix + name, values, section,
John McCall176f8922016-11-30 02:39:18 +00003889 CGM.getPointerAlign(), true);
3890 return llvm::ConstantExpr::getBitCast(GV,
3891 ObjCTypes.MethodDescriptionListPtrTy);
3892 }
3893
3894 // Otherwise, it's an objc_method_list.
3895 ConstantInitBuilder builder(CGM);
3896 auto values = builder.beginStruct();
3897 values.addNullPointer(ObjCTypes.Int8PtrTy);
3898 values.addInt(ObjCTypes.IntTy, methods.size());
3899 auto methodArray = values.beginArray(ObjCTypes.MethodTy);
3900 for (auto MD : methods) {
3901 emitMethodConstant(methodArray, MD);
3902 }
3903 methodArray.finishAndAddTo(values);
3904
Zachary Turner41a9ee92017-10-11 23:54:34 +00003905 llvm::GlobalVariable *GV = CreateMetadataVar(prefix + name, values, section,
Saleem Abdulrasoold48b0a32016-10-24 20:47:58 +00003906 CGM.getPointerAlign(), true);
Chris Lattnere64d7ba2011-06-20 04:01:35 +00003907 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.MethodListPtrTy);
Daniel Dunbara94ecd22008-08-16 03:19:19 +00003908}
3909
Fariborz Jahanian99113fd2009-01-26 21:38:32 +00003910llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD,
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003911 const ObjCContainerDecl *CD) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003912 SmallString<256> Name;
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +00003913 GetNameForMethod(OMD, CD, Name);
Daniel Dunbara94ecd22008-08-16 03:19:19 +00003914
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +00003915 CodeGenTypes &Types = CGM.getTypes();
Chris Lattner2192fe52011-07-18 04:24:23 +00003916 llvm::FunctionType *MethodTy =
John McCalla729c622012-02-17 03:33:10 +00003917 Types.GetFunctionType(Types.arrangeObjCMethodDeclaration(OMD));
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003918 llvm::Function *Method =
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00003919 llvm::Function::Create(MethodTy,
Daniel Dunbara94ecd22008-08-16 03:19:19 +00003920 llvm::GlobalValue::InternalLinkage,
Daniel Dunbard2386812009-10-19 01:21:19 +00003921 Name.str(),
Daniel Dunbara94ecd22008-08-16 03:19:19 +00003922 &CGM.getModule());
Daniel Dunbar3c76cb52008-08-26 21:51:14 +00003923 MethodDefinitions.insert(std::make_pair(OMD, Method));
Daniel Dunbara94ecd22008-08-16 03:19:19 +00003924
Daniel Dunbara94ecd22008-08-16 03:19:19 +00003925 return Method;
Daniel Dunbar303e2c22008-08-11 02:45:11 +00003926}
3927
Zachary Turner41a9ee92017-10-11 23:54:34 +00003928llvm::GlobalVariable *CGObjCCommonMac::CreateMetadataVar(Twine Name,
3929 ConstantStructBuilder &Init,
3930 StringRef Section,
3931 CharUnits Align,
3932 bool AddToUsed) {
John McCall176f8922016-11-30 02:39:18 +00003933 llvm::GlobalVariable *GV =
3934 Init.finishAndCreateGlobal(Name, Align, /*constant*/ false,
3935 llvm::GlobalValue::PrivateLinkage);
3936 if (!Section.empty())
3937 GV->setSection(Section);
3938 if (AddToUsed)
3939 CGM.addCompilerUsedGlobal(GV);
3940 return GV;
3941}
3942
Zachary Turner41a9ee92017-10-11 23:54:34 +00003943llvm::GlobalVariable *CGObjCCommonMac::CreateMetadataVar(Twine Name,
Alp Toker541d5072014-06-07 23:30:53 +00003944 llvm::Constant *Init,
3945 StringRef Section,
John McCall7f416cc2015-09-08 08:05:57 +00003946 CharUnits Align,
Alp Toker541d5072014-06-07 23:30:53 +00003947 bool AddToUsed) {
Chris Lattner2192fe52011-07-18 04:24:23 +00003948 llvm::Type *Ty = Init->getType();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003949 llvm::GlobalVariable *GV =
Owen Andersonc10c8d32009-07-08 19:05:04 +00003950 new llvm::GlobalVariable(CGM.getModule(), Ty, false,
Rafael Espindola5179a4e2014-02-27 19:01:11 +00003951 llvm::GlobalValue::PrivateLinkage, Init, Name);
Alp Toker541d5072014-06-07 23:30:53 +00003952 if (!Section.empty())
Daniel Dunbar30c65362009-03-09 20:09:19 +00003953 GV->setSection(Section);
John McCall7f416cc2015-09-08 08:05:57 +00003954 GV->setAlignment(Align.getQuantity());
Daniel Dunbar463cc8a2009-03-09 20:50:13 +00003955 if (AddToUsed)
Rafael Espindola060062a2014-03-06 22:15:10 +00003956 CGM.addCompilerUsedGlobal(GV);
Daniel Dunbar30c65362009-03-09 20:09:19 +00003957 return GV;
3958}
3959
Saleem Abdulrasool271106c2016-09-16 23:41:13 +00003960llvm::GlobalVariable *
Saleem Abdulrasool82f6add2016-09-20 18:38:54 +00003961CGObjCCommonMac::CreateCStringLiteral(StringRef Name, ObjCLabelType Type,
3962 bool ForceNonFragileABI,
3963 bool NullTerminate) {
Saleem Abdulrasool271106c2016-09-16 23:41:13 +00003964 StringRef Label;
3965 switch (Type) {
3966 case ObjCLabelType::ClassName: Label = "OBJC_CLASS_NAME_"; break;
3967 case ObjCLabelType::MethodVarName: Label = "OBJC_METH_VAR_NAME_"; break;
3968 case ObjCLabelType::MethodVarType: Label = "OBJC_METH_VAR_TYPE_"; break;
3969 case ObjCLabelType::PropertyName: Label = "OBJC_PROP_NAME_ATTR_"; break;
3970 }
3971
Saleem Abdulrasool82f6add2016-09-20 18:38:54 +00003972 bool NonFragile = ForceNonFragileABI || isNonFragileABI();
3973
Saleem Abdulrasool271106c2016-09-16 23:41:13 +00003974 StringRef Section;
3975 switch (Type) {
3976 case ObjCLabelType::ClassName:
Saleem Abdulrasool82f6add2016-09-20 18:38:54 +00003977 Section = NonFragile ? "__TEXT,__objc_classname,cstring_literals"
3978 : "__TEXT,__cstring,cstring_literals";
Saleem Abdulrasool271106c2016-09-16 23:41:13 +00003979 break;
3980 case ObjCLabelType::MethodVarName:
Saleem Abdulrasool82f6add2016-09-20 18:38:54 +00003981 Section = NonFragile ? "__TEXT,__objc_methname,cstring_literals"
3982 : "__TEXT,__cstring,cstring_literals";
Saleem Abdulrasool271106c2016-09-16 23:41:13 +00003983 break;
3984 case ObjCLabelType::MethodVarType:
Saleem Abdulrasool82f6add2016-09-20 18:38:54 +00003985 Section = NonFragile ? "__TEXT,__objc_methtype,cstring_literals"
3986 : "__TEXT,__cstring,cstring_literals";
Saleem Abdulrasool271106c2016-09-16 23:41:13 +00003987 break;
3988 case ObjCLabelType::PropertyName:
3989 Section = "__TEXT,__cstring,cstring_literals";
3990 break;
3991 }
3992
Saleem Abdulrasool82f6add2016-09-20 18:38:54 +00003993 llvm::Constant *Value =
3994 llvm::ConstantDataArray::getString(VMContext, Name, NullTerminate);
Saleem Abdulrasool271106c2016-09-16 23:41:13 +00003995 llvm::GlobalVariable *GV =
Saleem Abdulrasool0c54dc82016-09-18 16:12:04 +00003996 new llvm::GlobalVariable(CGM.getModule(), Value->getType(),
3997 /*isConstant=*/true,
Saleem Abdulrasool271106c2016-09-16 23:41:13 +00003998 llvm::GlobalValue::PrivateLinkage, Value, Label);
Saleem Abdulrasool3f307512016-09-18 16:12:14 +00003999 if (CGM.getTriple().isOSBinFormatMachO())
4000 GV->setSection(Section);
4001 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Saleem Abdulrasool271106c2016-09-16 23:41:13 +00004002 GV->setAlignment(CharUnits::One().getQuantity());
4003 CGM.addCompilerUsedGlobal(GV);
4004
4005 return GV;
4006}
4007
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004008llvm::Function *CGObjCMac::ModuleInitFunction() {
Daniel Dunbar3ad53482008-08-11 21:35:06 +00004009 // Abuse this interface function as a place to finalize.
4010 FinishModule();
Craig Topper8a13c412014-05-21 05:09:00 +00004011 return nullptr;
Daniel Dunbar303e2c22008-08-11 02:45:11 +00004012}
4013
Chris Lattnerd4808922009-03-22 21:03:39 +00004014llvm::Constant *CGObjCMac::GetPropertyGetFunction() {
Chris Lattnerce8754e2009-04-22 02:44:54 +00004015 return ObjCTypes.getGetPropertyFn();
Daniel Dunbara91c3e02008-09-24 03:38:44 +00004016}
4017
Chris Lattnerd4808922009-03-22 21:03:39 +00004018llvm::Constant *CGObjCMac::GetPropertySetFunction() {
Chris Lattnerce8754e2009-04-22 02:44:54 +00004019 return ObjCTypes.getSetPropertyFn();
Daniel Dunbara91c3e02008-09-24 03:38:44 +00004020}
4021
Fangrui Song6907ce22018-07-30 19:24:48 +00004022llvm::Constant *CGObjCMac::GetOptimizedPropertySetFunction(bool atomic,
Ted Kremeneke65b0862012-03-06 20:05:56 +00004023 bool copy) {
4024 return ObjCTypes.getOptimizedSetPropertyFn(atomic, copy);
4025}
4026
David Chisnall168b80f2010-12-26 22:13:16 +00004027llvm::Constant *CGObjCMac::GetGetStructFunction() {
4028 return ObjCTypes.getCopyStructFn();
4029}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00004030
David Chisnall168b80f2010-12-26 22:13:16 +00004031llvm::Constant *CGObjCMac::GetSetStructFunction() {
Fariborz Jahanian5a8c2032010-04-12 18:18:10 +00004032 return ObjCTypes.getCopyStructFn();
4033}
4034
David Chisnall0d75e062012-12-17 18:54:24 +00004035llvm::Constant *CGObjCMac::GetCppAtomicObjectGetFunction() {
4036 return ObjCTypes.getCppAtomicObjectFunction();
4037}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00004038
David Chisnall0d75e062012-12-17 18:54:24 +00004039llvm::Constant *CGObjCMac::GetCppAtomicObjectSetFunction() {
Fariborz Jahanian1e1b5492012-01-06 18:07:23 +00004040 return ObjCTypes.getCppAtomicObjectFunction();
4041}
4042
Chris Lattnerd4808922009-03-22 21:03:39 +00004043llvm::Constant *CGObjCMac::EnumerationMutationFunction() {
Chris Lattnerce8754e2009-04-22 02:44:54 +00004044 return ObjCTypes.getEnumerationMutationFn();
Anders Carlsson3f35a262008-08-31 04:05:03 +00004045}
4046
John McCallbd309292010-07-06 01:34:17 +00004047void CGObjCMac::EmitTryStmt(CodeGenFunction &CGF, const ObjCAtTryStmt &S) {
4048 return EmitTryOrSynchronizedStmt(CGF, S);
4049}
4050
4051void CGObjCMac::EmitSynchronizedStmt(CodeGenFunction &CGF,
4052 const ObjCAtSynchronizedStmt &S) {
4053 return EmitTryOrSynchronizedStmt(CGF, S);
4054}
4055
John McCall65bea082010-07-21 06:59:36 +00004056namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00004057 struct PerformFragileFinally final : EHScopeStack::Cleanup {
John McCall65bea082010-07-21 06:59:36 +00004058 const Stmt &S;
John McCall7f416cc2015-09-08 08:05:57 +00004059 Address SyncArgSlot;
4060 Address CallTryExitVar;
4061 Address ExceptionData;
John McCall65bea082010-07-21 06:59:36 +00004062 ObjCTypesHelper &ObjCTypes;
4063 PerformFragileFinally(const Stmt *S,
John McCall7f416cc2015-09-08 08:05:57 +00004064 Address SyncArgSlot,
4065 Address CallTryExitVar,
4066 Address ExceptionData,
John McCall65bea082010-07-21 06:59:36 +00004067 ObjCTypesHelper *ObjCTypes)
John McCall2dd7d442010-08-04 05:59:32 +00004068 : S(*S), SyncArgSlot(SyncArgSlot), CallTryExitVar(CallTryExitVar),
John McCall65bea082010-07-21 06:59:36 +00004069 ExceptionData(ExceptionData), ObjCTypes(*ObjCTypes) {}
4070
Craig Topper4f12f102014-03-12 06:41:41 +00004071 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall65bea082010-07-21 06:59:36 +00004072 // Check whether we need to call objc_exception_try_exit.
4073 // In optimized code, this branch will always be folded.
4074 llvm::BasicBlock *FinallyCallExit =
4075 CGF.createBasicBlock("finally.call_exit");
4076 llvm::BasicBlock *FinallyNoCallExit =
4077 CGF.createBasicBlock("finally.no_call_exit");
4078 CGF.Builder.CreateCondBr(CGF.Builder.CreateLoad(CallTryExitVar),
4079 FinallyCallExit, FinallyNoCallExit);
4080
4081 CGF.EmitBlock(FinallyCallExit);
John McCall882987f2013-02-28 19:01:20 +00004082 CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionTryExitFn(),
John McCall7f416cc2015-09-08 08:05:57 +00004083 ExceptionData.getPointer());
John McCall65bea082010-07-21 06:59:36 +00004084
4085 CGF.EmitBlock(FinallyNoCallExit);
4086
4087 if (isa<ObjCAtTryStmt>(S)) {
4088 if (const ObjCAtFinallyStmt* FinallyStmt =
John McCallcebe0ca2010-08-11 00:16:14 +00004089 cast<ObjCAtTryStmt>(S).getFinallyStmt()) {
John McCall638d4f52013-04-03 00:56:07 +00004090 // Don't try to do the @finally if this is an EH cleanup.
4091 if (flags.isForEHCleanup()) return;
4092
John McCallcebe0ca2010-08-11 00:16:14 +00004093 // Save the current cleanup destination in case there's
4094 // control flow inside the finally statement.
4095 llvm::Value *CurCleanupDest =
4096 CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot());
4097
John McCall65bea082010-07-21 06:59:36 +00004098 CGF.EmitStmt(FinallyStmt->getFinallyBody());
4099
John McCallcebe0ca2010-08-11 00:16:14 +00004100 if (CGF.HaveInsertPoint()) {
4101 CGF.Builder.CreateStore(CurCleanupDest,
4102 CGF.getNormalCleanupDestSlot());
4103 } else {
4104 // Currently, the end of the cleanup must always exist.
4105 CGF.EnsureInsertPoint();
4106 }
4107 }
John McCall65bea082010-07-21 06:59:36 +00004108 } else {
4109 // Emit objc_sync_exit(expr); as finally's sole statement for
4110 // @synchronized.
John McCall2dd7d442010-08-04 05:59:32 +00004111 llvm::Value *SyncArg = CGF.Builder.CreateLoad(SyncArgSlot);
John McCall882987f2013-02-28 19:01:20 +00004112 CGF.EmitNounwindRuntimeCall(ObjCTypes.getSyncExitFn(), SyncArg);
John McCall65bea082010-07-21 06:59:36 +00004113 }
4114 }
4115 };
John McCall42227ed2010-07-31 23:20:56 +00004116
4117 class FragileHazards {
4118 CodeGenFunction &CGF;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004119 SmallVector<llvm::Value*, 20> Locals;
John McCall42227ed2010-07-31 23:20:56 +00004120 llvm::DenseSet<llvm::BasicBlock*> BlocksBeforeTry;
4121
4122 llvm::InlineAsm *ReadHazard;
4123 llvm::InlineAsm *WriteHazard;
4124
4125 llvm::FunctionType *GetAsmFnType();
4126
4127 void collectLocals();
4128 void emitReadHazard(CGBuilderTy &Builder);
4129
4130 public:
4131 FragileHazards(CodeGenFunction &CGF);
John McCall2dd7d442010-08-04 05:59:32 +00004132
John McCall42227ed2010-07-31 23:20:56 +00004133 void emitWriteHazard();
John McCall2dd7d442010-08-04 05:59:32 +00004134 void emitHazardsInNewBlocks();
John McCall42227ed2010-07-31 23:20:56 +00004135 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00004136} // end anonymous namespace
John McCall42227ed2010-07-31 23:20:56 +00004137
4138/// Create the fragile-ABI read and write hazards based on the current
4139/// state of the function, which is presumed to be immediately prior
4140/// to a @try block. These hazards are used to maintain correct
4141/// semantics in the face of optimization and the fragile ABI's
4142/// cavalier use of setjmp/longjmp.
4143FragileHazards::FragileHazards(CodeGenFunction &CGF) : CGF(CGF) {
4144 collectLocals();
4145
4146 if (Locals.empty()) return;
4147
4148 // Collect all the blocks in the function.
4149 for (llvm::Function::iterator
4150 I = CGF.CurFn->begin(), E = CGF.CurFn->end(); I != E; ++I)
4151 BlocksBeforeTry.insert(&*I);
4152
4153 llvm::FunctionType *AsmFnTy = GetAsmFnType();
4154
4155 // Create a read hazard for the allocas. This inhibits dead-store
4156 // optimizations and forces the values to memory. This hazard is
4157 // inserted before any 'throwing' calls in the protected scope to
4158 // reflect the possibility that the variables might be read from the
4159 // catch block if the call throws.
4160 {
4161 std::string Constraint;
4162 for (unsigned I = 0, E = Locals.size(); I != E; ++I) {
4163 if (I) Constraint += ',';
4164 Constraint += "*m";
4165 }
4166
4167 ReadHazard = llvm::InlineAsm::get(AsmFnTy, "", Constraint, true, false);
4168 }
4169
4170 // Create a write hazard for the allocas. This inhibits folding
4171 // loads across the hazard. This hazard is inserted at the
4172 // beginning of the catch path to reflect the possibility that the
4173 // variables might have been written within the protected scope.
4174 {
4175 std::string Constraint;
4176 for (unsigned I = 0, E = Locals.size(); I != E; ++I) {
4177 if (I) Constraint += ',';
4178 Constraint += "=*m";
4179 }
4180
4181 WriteHazard = llvm::InlineAsm::get(AsmFnTy, "", Constraint, true, false);
4182 }
4183}
4184
4185/// Emit a write hazard at the current location.
4186void FragileHazards::emitWriteHazard() {
4187 if (Locals.empty()) return;
4188
John McCall882987f2013-02-28 19:01:20 +00004189 CGF.EmitNounwindRuntimeCall(WriteHazard, Locals);
John McCall42227ed2010-07-31 23:20:56 +00004190}
4191
John McCall42227ed2010-07-31 23:20:56 +00004192void FragileHazards::emitReadHazard(CGBuilderTy &Builder) {
4193 assert(!Locals.empty());
John McCall882987f2013-02-28 19:01:20 +00004194 llvm::CallInst *call = Builder.CreateCall(ReadHazard, Locals);
4195 call->setDoesNotThrow();
4196 call->setCallingConv(CGF.getRuntimeCC());
John McCall42227ed2010-07-31 23:20:56 +00004197}
4198
4199/// Emit read hazards in all the protected blocks, i.e. all the blocks
4200/// which have been inserted since the beginning of the try.
John McCall2dd7d442010-08-04 05:59:32 +00004201void FragileHazards::emitHazardsInNewBlocks() {
John McCall42227ed2010-07-31 23:20:56 +00004202 if (Locals.empty()) return;
4203
John McCall7f416cc2015-09-08 08:05:57 +00004204 CGBuilderTy Builder(CGF, CGF.getLLVMContext());
John McCall42227ed2010-07-31 23:20:56 +00004205
4206 // Iterate through all blocks, skipping those prior to the try.
4207 for (llvm::Function::iterator
4208 FI = CGF.CurFn->begin(), FE = CGF.CurFn->end(); FI != FE; ++FI) {
4209 llvm::BasicBlock &BB = *FI;
4210 if (BlocksBeforeTry.count(&BB)) continue;
4211
4212 // Walk through all the calls in the block.
4213 for (llvm::BasicBlock::iterator
4214 BI = BB.begin(), BE = BB.end(); BI != BE; ++BI) {
4215 llvm::Instruction &I = *BI;
4216
4217 // Ignore instructions that aren't non-intrinsic calls.
4218 // These are the only calls that can possibly call longjmp.
4219 if (!isa<llvm::CallInst>(I) && !isa<llvm::InvokeInst>(I)) continue;
4220 if (isa<llvm::IntrinsicInst>(I))
4221 continue;
4222
4223 // Ignore call sites marked nounwind. This may be questionable,
4224 // since 'nounwind' doesn't necessarily mean 'does not call longjmp'.
4225 llvm::CallSite CS(&I);
4226 if (CS.doesNotThrow()) continue;
4227
John McCall2dd7d442010-08-04 05:59:32 +00004228 // Insert a read hazard before the call. This will ensure that
4229 // any writes to the locals are performed before making the
4230 // call. If the call throws, then this is sufficient to
4231 // guarantee correctness as long as it doesn't also write to any
4232 // locals.
John McCall42227ed2010-07-31 23:20:56 +00004233 Builder.SetInsertPoint(&BB, BI);
4234 emitReadHazard(Builder);
4235 }
4236 }
4237}
4238
John McCall7f416cc2015-09-08 08:05:57 +00004239static void addIfPresent(llvm::DenseSet<llvm::Value*> &S, Address V) {
4240 if (V.isValid()) S.insert(V.getPointer());
4241}
4242
John McCall42227ed2010-07-31 23:20:56 +00004243void FragileHazards::collectLocals() {
4244 // Compute a set of allocas to ignore.
4245 llvm::DenseSet<llvm::Value*> AllocasToIgnore;
4246 addIfPresent(AllocasToIgnore, CGF.ReturnValue);
4247 addIfPresent(AllocasToIgnore, CGF.NormalCleanupDest);
John McCall42227ed2010-07-31 23:20:56 +00004248
4249 // Collect all the allocas currently in the function. This is
4250 // probably way too aggressive.
4251 llvm::BasicBlock &Entry = CGF.CurFn->getEntryBlock();
4252 for (llvm::BasicBlock::iterator
4253 I = Entry.begin(), E = Entry.end(); I != E; ++I)
4254 if (isa<llvm::AllocaInst>(*I) && !AllocasToIgnore.count(&*I))
4255 Locals.push_back(&*I);
4256}
4257
4258llvm::FunctionType *FragileHazards::GetAsmFnType() {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004259 SmallVector<llvm::Type *, 16> tys(Locals.size());
John McCall9dc0db22011-05-15 01:53:33 +00004260 for (unsigned i = 0, e = Locals.size(); i != e; ++i)
4261 tys[i] = Locals[i]->getType();
4262 return llvm::FunctionType::get(CGF.VoidTy, tys, false);
John McCall65bea082010-07-21 06:59:36 +00004263}
4264
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004265/*
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004266
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004267 Objective-C setjmp-longjmp (sjlj) Exception Handling
4268 --
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004269
John McCallbd309292010-07-06 01:34:17 +00004270 A catch buffer is a setjmp buffer plus:
4271 - a pointer to the exception that was caught
4272 - a pointer to the previous exception data buffer
4273 - two pointers of reserved storage
4274 Therefore catch buffers form a stack, with a pointer to the top
4275 of the stack kept in thread-local storage.
4276
4277 objc_exception_try_enter pushes a catch buffer onto the EH stack.
4278 objc_exception_try_exit pops the given catch buffer, which is
4279 required to be the top of the EH stack.
4280 objc_exception_throw pops the top of the EH stack, writes the
4281 thrown exception into the appropriate field, and longjmps
4282 to the setjmp buffer. It crashes the process (with a printf
4283 and an abort()) if there are no catch buffers on the stack.
4284 objc_exception_extract just reads the exception pointer out of the
4285 catch buffer.
4286
4287 There's no reason an implementation couldn't use a light-weight
4288 setjmp here --- something like __builtin_setjmp, but API-compatible
4289 with the heavyweight setjmp. This will be more important if we ever
4290 want to implement correct ObjC/C++ exception interactions for the
4291 fragile ABI.
4292
4293 Note that for this use of setjmp/longjmp to be correct, we may need
4294 to mark some local variables volatile: if a non-volatile local
4295 variable is modified between the setjmp and the longjmp, it has
4296 indeterminate value. For the purposes of LLVM IR, it may be
4297 sufficient to make loads and stores within the @try (to variables
4298 declared outside the @try) volatile. This is necessary for
4299 optimized correctness, but is not currently being done; this is
4300 being tracked as rdar://problem/8160285
4301
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004302 The basic framework for a @try-catch-finally is as follows:
4303 {
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004304 objc_exception_data d;
4305 id _rethrow = null;
Anders Carlssonda0e4562009-02-07 21:26:04 +00004306 bool _call_try_exit = true;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004307
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004308 objc_exception_try_enter(&d);
4309 if (!setjmp(d.jmp_buf)) {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004310 ... try body ...
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004311 } else {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004312 // exception path
4313 id _caught = objc_exception_extract(&d);
4314
4315 // enter new try scope for handlers
4316 if (!setjmp(d.jmp_buf)) {
4317 ... match exception and execute catch blocks ...
4318
4319 // fell off end, rethrow.
4320 _rethrow = _caught;
4321 ... jump-through-finally to finally_rethrow ...
4322 } else {
4323 // exception in catch block
4324 _rethrow = objc_exception_extract(&d);
4325 _call_try_exit = false;
4326 ... jump-through-finally to finally_rethrow ...
4327 }
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004328 }
Daniel Dunbar2efd5382008-09-30 01:06:03 +00004329 ... jump-through-finally to finally_end ...
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004330
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004331 finally:
Anders Carlssonda0e4562009-02-07 21:26:04 +00004332 if (_call_try_exit)
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004333 objc_exception_try_exit(&d);
Anders Carlssonda0e4562009-02-07 21:26:04 +00004334
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004335 ... finally block ....
Daniel Dunbar2efd5382008-09-30 01:06:03 +00004336 ... dispatch to finally destination ...
4337
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004338 finally_rethrow:
Daniel Dunbar2efd5382008-09-30 01:06:03 +00004339 objc_exception_throw(_rethrow);
4340
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004341 finally_end:
4342 }
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004343
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004344 This framework differs slightly from the one gcc uses, in that gcc
4345 uses _rethrow to determine if objc_exception_try_exit should be called
4346 and if the object should be rethrown. This breaks in the face of
4347 throwing nil and introduces unnecessary branches.
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004348
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004349 We specialize this framework for a few particular circumstances:
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004350
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004351 - If there are no catch blocks, then we avoid emitting the second
4352 exception handling context.
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004353
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004354 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
4355 e)) we avoid emitting the code to rethrow an uncaught exception.
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004356
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004357 - FIXME: If there is no @finally block we can do a few more
4358 simplifications.
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004359
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004360 Rethrows and Jumps-Through-Finally
4361 --
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004362
John McCallbd309292010-07-06 01:34:17 +00004363 '@throw;' is supported by pushing the currently-caught exception
4364 onto ObjCEHStack while the @catch blocks are emitted.
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004365
John McCallbd309292010-07-06 01:34:17 +00004366 Branches through the @finally block are handled with an ordinary
4367 normal cleanup. We do not register an EH cleanup; fragile-ABI ObjC
4368 exceptions are not compatible with C++ exceptions, and this is
4369 hardly the only place where this will go wrong.
Daniel Dunbar2efd5382008-09-30 01:06:03 +00004370
John McCallbd309292010-07-06 01:34:17 +00004371 @synchronized(expr) { stmt; } is emitted as if it were:
4372 id synch_value = expr;
4373 objc_sync_enter(synch_value);
4374 @try { stmt; } @finally { objc_sync_exit(synch_value); }
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004375*/
4376
Fariborz Jahanianc2ad6dc2008-11-21 00:49:24 +00004377void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
4378 const Stmt &S) {
4379 bool isTry = isa<ObjCAtTryStmt>(S);
John McCallbd309292010-07-06 01:34:17 +00004380
4381 // A destination for the fall-through edges of the catch handlers to
4382 // jump to.
4383 CodeGenFunction::JumpDest FinallyEnd =
4384 CGF.getJumpDestInCurrentScope("finally.end");
4385
4386 // A destination for the rethrow edge of the catch handlers to jump
4387 // to.
4388 CodeGenFunction::JumpDest FinallyRethrow =
4389 CGF.getJumpDestInCurrentScope("finally.rethrow");
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004390
Daniel Dunbar94ceb612009-02-24 01:43:46 +00004391 // For @synchronized, call objc_sync_enter(sync.expr). The
4392 // evaluation of the expression must occur before we enter the
John McCall2dd7d442010-08-04 05:59:32 +00004393 // @synchronized. We can't avoid a temp here because we need the
4394 // value to be preserved. If the backend ever does liveness
4395 // correctly after setjmp, this will be unnecessary.
John McCall7f416cc2015-09-08 08:05:57 +00004396 Address SyncArgSlot = Address::invalid();
Daniel Dunbar94ceb612009-02-24 01:43:46 +00004397 if (!isTry) {
John McCall2dd7d442010-08-04 05:59:32 +00004398 llvm::Value *SyncArg =
Daniel Dunbar94ceb612009-02-24 01:43:46 +00004399 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
4400 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
John McCall882987f2013-02-28 19:01:20 +00004401 CGF.EmitNounwindRuntimeCall(ObjCTypes.getSyncEnterFn(), SyncArg);
John McCall2dd7d442010-08-04 05:59:32 +00004402
John McCall7f416cc2015-09-08 08:05:57 +00004403 SyncArgSlot = CGF.CreateTempAlloca(SyncArg->getType(),
4404 CGF.getPointerAlign(), "sync.arg");
John McCall2dd7d442010-08-04 05:59:32 +00004405 CGF.Builder.CreateStore(SyncArg, SyncArgSlot);
Daniel Dunbar94ceb612009-02-24 01:43:46 +00004406 }
Daniel Dunbar2efd5382008-09-30 01:06:03 +00004407
John McCall2dd7d442010-08-04 05:59:32 +00004408 // Allocate memory for the setjmp buffer. This needs to be kept
4409 // live throughout the try and catch blocks.
John McCall7f416cc2015-09-08 08:05:57 +00004410 Address ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
4411 CGF.getPointerAlign(),
4412 "exceptiondata.ptr");
John McCall2dd7d442010-08-04 05:59:32 +00004413
John McCall42227ed2010-07-31 23:20:56 +00004414 // Create the fragile hazards. Note that this will not capture any
4415 // of the allocas required for exception processing, but will
4416 // capture the current basic block (which extends all the way to the
4417 // setjmp call) as "before the @try".
4418 FragileHazards Hazards(CGF);
4419
John McCallbd309292010-07-06 01:34:17 +00004420 // Create a flag indicating whether the cleanup needs to call
4421 // objc_exception_try_exit. This is true except when
4422 // - no catches match and we're branching through the cleanup
4423 // just to rethrow the exception, or
4424 // - a catch matched and we're falling out of the catch handler.
John McCall2dd7d442010-08-04 05:59:32 +00004425 // The setjmp-safety rule here is that we should always store to this
4426 // variable in a place that dominates the branch through the cleanup
4427 // without passing through any setjmps.
John McCall7f416cc2015-09-08 08:05:57 +00004428 Address CallTryExitVar = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(),
4429 CharUnits::One(),
4430 "_call_try_exit");
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004431
John McCall9916e3f2010-10-04 23:42:51 +00004432 // A slot containing the exception to rethrow. Only needed when we
4433 // have both a @catch and a @finally.
John McCall7f416cc2015-09-08 08:05:57 +00004434 Address PropagatingExnVar = Address::invalid();
John McCall9916e3f2010-10-04 23:42:51 +00004435
John McCallbd309292010-07-06 01:34:17 +00004436 // Push a normal cleanup to leave the try scope.
John McCall638d4f52013-04-03 00:56:07 +00004437 CGF.EHStack.pushCleanup<PerformFragileFinally>(NormalAndEHCleanup, &S,
John McCall2dd7d442010-08-04 05:59:32 +00004438 SyncArgSlot,
John McCallcda666c2010-07-21 07:22:38 +00004439 CallTryExitVar,
4440 ExceptionData,
4441 &ObjCTypes);
John McCallbd309292010-07-06 01:34:17 +00004442
4443 // Enter a try block:
4444 // - Call objc_exception_try_enter to push ExceptionData on top of
4445 // the EH stack.
Nico Weber6307cf02015-02-26 20:43:00 +00004446 CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionTryEnterFn(),
John McCall7f416cc2015-09-08 08:05:57 +00004447 ExceptionData.getPointer());
John McCallbd309292010-07-06 01:34:17 +00004448
4449 // - Call setjmp on the exception data buffer.
4450 llvm::Constant *Zero = llvm::ConstantInt::get(CGF.Builder.getInt32Ty(), 0);
4451 llvm::Value *GEPIndexes[] = { Zero, Zero, Zero };
David Blaikie6b2a8302015-04-03 17:47:16 +00004452 llvm::Value *SetJmpBuffer = CGF.Builder.CreateGEP(
John McCall7f416cc2015-09-08 08:05:57 +00004453 ObjCTypes.ExceptionDataTy, ExceptionData.getPointer(), GEPIndexes,
4454 "setjmp_buffer");
Nico Weber6307cf02015-02-26 20:43:00 +00004455 llvm::CallInst *SetJmpResult = CGF.EmitNounwindRuntimeCall(
4456 ObjCTypes.getSetJmpFn(), SetJmpBuffer, "setjmp_result");
Bill Wendlingbd26cf92011-12-19 23:53:28 +00004457 SetJmpResult->setCanReturnTwice();
John McCallbd309292010-07-06 01:34:17 +00004458
4459 // If setjmp returned 0, enter the protected block; otherwise,
4460 // branch to the handler.
Daniel Dunbar75283ff2008-11-11 02:29:29 +00004461 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
4462 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
John McCallbd309292010-07-06 01:34:17 +00004463 llvm::Value *DidCatch =
John McCallcebe0ca2010-08-11 00:16:14 +00004464 CGF.Builder.CreateIsNotNull(SetJmpResult, "did_catch_exception");
4465 CGF.Builder.CreateCondBr(DidCatch, TryHandler, TryBlock);
Anders Carlsson4f1c7c32008-09-09 17:59:25 +00004466
John McCallbd309292010-07-06 01:34:17 +00004467 // Emit the protected block.
Anders Carlsson4f1c7c32008-09-09 17:59:25 +00004468 CGF.EmitBlock(TryBlock);
John McCall2dd7d442010-08-04 05:59:32 +00004469 CGF.Builder.CreateStore(CGF.Builder.getTrue(), CallTryExitVar);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004470 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
John McCallbd309292010-07-06 01:34:17 +00004471 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
John McCall2dd7d442010-08-04 05:59:32 +00004472
4473 CGBuilderTy::InsertPoint TryFallthroughIP = CGF.Builder.saveAndClearIP();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004474
John McCallbd309292010-07-06 01:34:17 +00004475 // Emit the exception handler block.
Daniel Dunbar7f086782008-09-27 23:30:04 +00004476 CGF.EmitBlock(TryHandler);
Daniel Dunbarb22ff592008-09-27 07:03:52 +00004477
John McCall42227ed2010-07-31 23:20:56 +00004478 // Don't optimize loads of the in-scope locals across this point.
4479 Hazards.emitWriteHazard();
4480
John McCallbd309292010-07-06 01:34:17 +00004481 // For a @synchronized (or a @try with no catches), just branch
4482 // through the cleanup to the rethrow block.
4483 if (!isTry || !cast<ObjCAtTryStmt>(S).getNumCatchStmts()) {
4484 // Tell the cleanup not to re-pop the exit.
John McCall2dd7d442010-08-04 05:59:32 +00004485 CGF.Builder.CreateStore(CGF.Builder.getFalse(), CallTryExitVar);
Anders Carlssonbfee7e92009-02-09 20:38:58 +00004486 CGF.EmitBranchThroughCleanup(FinallyRethrow);
John McCallbd309292010-07-06 01:34:17 +00004487
4488 // Otherwise, we have to match against the caught exceptions.
4489 } else {
John McCall2dd7d442010-08-04 05:59:32 +00004490 // Retrieve the exception object. We may emit multiple blocks but
4491 // nothing can cross this so the value is already in SSA form.
4492 llvm::CallInst *Caught =
John McCall882987f2013-02-28 19:01:20 +00004493 CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionExtractFn(),
John McCall7f416cc2015-09-08 08:05:57 +00004494 ExceptionData.getPointer(), "caught");
John McCall2dd7d442010-08-04 05:59:32 +00004495
John McCallbd309292010-07-06 01:34:17 +00004496 // Push the exception to rethrow onto the EH value stack for the
4497 // benefit of any @throws in the handlers.
4498 CGF.ObjCEHValueStack.push_back(Caught);
4499
Douglas Gregor96c79492010-04-23 22:50:49 +00004500 const ObjCAtTryStmt* AtTryStmt = cast<ObjCAtTryStmt>(&S);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004501
Craig Topper8a13c412014-05-21 05:09:00 +00004502 bool HasFinally = (AtTryStmt->getFinallyStmt() != nullptr);
John McCallbd309292010-07-06 01:34:17 +00004503
Craig Topper8a13c412014-05-21 05:09:00 +00004504 llvm::BasicBlock *CatchBlock = nullptr;
4505 llvm::BasicBlock *CatchHandler = nullptr;
John McCall2dd7d442010-08-04 05:59:32 +00004506 if (HasFinally) {
John McCall9916e3f2010-10-04 23:42:51 +00004507 // Save the currently-propagating exception before
4508 // objc_exception_try_enter clears the exception slot.
4509 PropagatingExnVar = CGF.CreateTempAlloca(Caught->getType(),
John McCall7f416cc2015-09-08 08:05:57 +00004510 CGF.getPointerAlign(),
John McCall9916e3f2010-10-04 23:42:51 +00004511 "propagating_exception");
4512 CGF.Builder.CreateStore(Caught, PropagatingExnVar);
4513
John McCall2dd7d442010-08-04 05:59:32 +00004514 // Enter a new exception try block (in case a @catch block
4515 // throws an exception).
John McCall882987f2013-02-28 19:01:20 +00004516 CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionTryEnterFn(),
John McCall7f416cc2015-09-08 08:05:57 +00004517 ExceptionData.getPointer());
Anders Carlsson4f1c7c32008-09-09 17:59:25 +00004518
John McCall2dd7d442010-08-04 05:59:32 +00004519 llvm::CallInst *SetJmpResult =
John McCall882987f2013-02-28 19:01:20 +00004520 CGF.EmitNounwindRuntimeCall(ObjCTypes.getSetJmpFn(),
4521 SetJmpBuffer, "setjmp.result");
Bill Wendlingbd26cf92011-12-19 23:53:28 +00004522 SetJmpResult->setCanReturnTwice();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004523
John McCall2dd7d442010-08-04 05:59:32 +00004524 llvm::Value *Threw =
4525 CGF.Builder.CreateIsNotNull(SetJmpResult, "did_catch_exception");
4526
4527 CatchBlock = CGF.createBasicBlock("catch");
4528 CatchHandler = CGF.createBasicBlock("catch_for_catch");
4529 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
4530
4531 CGF.EmitBlock(CatchBlock);
4532 }
4533
4534 CGF.Builder.CreateStore(CGF.Builder.getInt1(HasFinally), CallTryExitVar);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004535
Daniel Dunbarb22ff592008-09-27 07:03:52 +00004536 // Handle catch list. As a special case we check if everything is
4537 // matched and avoid generating code for falling off the end if
4538 // so.
4539 bool AllMatched = false;
Douglas Gregor96c79492010-04-23 22:50:49 +00004540 for (unsigned I = 0, N = AtTryStmt->getNumCatchStmts(); I != N; ++I) {
4541 const ObjCAtCatchStmt *CatchStmt = AtTryStmt->getCatchStmt(I);
Anders Carlsson4f1c7c32008-09-09 17:59:25 +00004542
Douglas Gregor46a572b2010-04-26 16:46:50 +00004543 const VarDecl *CatchParam = CatchStmt->getCatchParamDecl();
Craig Topper8a13c412014-05-21 05:09:00 +00004544 const ObjCObjectPointerType *OPT = nullptr;
Daniel Dunbar523208f2008-09-27 07:36:24 +00004545
Anders Carlsson4f1c7c32008-09-09 17:59:25 +00004546 // catch(...) always matches.
Daniel Dunbarb22ff592008-09-27 07:03:52 +00004547 if (!CatchParam) {
4548 AllMatched = true;
4549 } else {
John McCall9dd450b2009-09-21 23:43:11 +00004550 OPT = CatchParam->getType()->getAs<ObjCObjectPointerType>();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004551
John McCallbd309292010-07-06 01:34:17 +00004552 // catch(id e) always matches under this ABI, since only
4553 // ObjC exceptions end up here in the first place.
Daniel Dunbar86919f42008-09-27 22:21:14 +00004554 // FIXME: For the time being we also match id<X>; this should
4555 // be rejected by Sema instead.
Eli Friedman55179ca2009-07-11 00:57:02 +00004556 if (OPT && (OPT->isObjCIdType() || OPT->isObjCQualifiedIdType()))
Daniel Dunbarb22ff592008-09-27 07:03:52 +00004557 AllMatched = true;
Anders Carlsson4f1c7c32008-09-09 17:59:25 +00004558 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004559
John McCallbd309292010-07-06 01:34:17 +00004560 // If this is a catch-all, we don't need to test anything.
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004561 if (AllMatched) {
John McCallbd309292010-07-06 01:34:17 +00004562 CodeGenFunction::RunCleanupsScope CatchVarCleanups(CGF);
4563
Anders Carlsson9396a892008-09-11 09:15:33 +00004564 if (CatchParam) {
John McCall1c9c3fd2010-10-15 04:57:14 +00004565 CGF.EmitAutoVarDecl(*CatchParam);
Daniel Dunbar5c7e3932008-11-11 23:11:34 +00004566 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
John McCallbd309292010-07-06 01:34:17 +00004567
4568 // These types work out because ConvertType(id) == i8*.
John McCall17f02752015-10-30 00:56:02 +00004569 EmitInitOfCatchParam(CGF, Caught, CatchParam);
Anders Carlsson9396a892008-09-11 09:15:33 +00004570 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004571
Anders Carlsson9396a892008-09-11 09:15:33 +00004572 CGF.EmitStmt(CatchStmt->getCatchBody());
John McCallbd309292010-07-06 01:34:17 +00004573
4574 // The scope of the catch variable ends right here.
4575 CatchVarCleanups.ForceCleanup();
4576
Anders Carlssonbfee7e92009-02-09 20:38:58 +00004577 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson4f1c7c32008-09-09 17:59:25 +00004578 break;
4579 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004580
Steve Naroff7cae42b2009-07-10 23:34:53 +00004581 assert(OPT && "Unexpected non-object pointer type in @catch");
John McCall96fa4842010-05-17 21:00:27 +00004582 const ObjCObjectType *ObjTy = OPT->getObjectType();
John McCallbd309292010-07-06 01:34:17 +00004583
4584 // FIXME: @catch (Class c) ?
John McCall96fa4842010-05-17 21:00:27 +00004585 ObjCInterfaceDecl *IDecl = ObjTy->getInterface();
4586 assert(IDecl && "Catch parameter must have Objective-C type!");
Anders Carlsson4f1c7c32008-09-09 17:59:25 +00004587
4588 // Check if the @catch block matches the exception object.
John McCall882987f2013-02-28 19:01:20 +00004589 llvm::Value *Class = EmitClassRef(CGF, IDecl);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004590
John McCall882987f2013-02-28 19:01:20 +00004591 llvm::Value *matchArgs[] = { Class, Caught };
John McCallbd309292010-07-06 01:34:17 +00004592 llvm::CallInst *Match =
John McCall882987f2013-02-28 19:01:20 +00004593 CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionMatchFn(),
4594 matchArgs, "match");
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004595
John McCallbd309292010-07-06 01:34:17 +00004596 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("match");
4597 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch.next");
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004598
4599 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
Daniel Dunbar7f086782008-09-27 23:30:04 +00004600 MatchedBlock, NextCatchBlock);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004601
Anders Carlsson4f1c7c32008-09-09 17:59:25 +00004602 // Emit the @catch block.
4603 CGF.EmitBlock(MatchedBlock);
John McCallbd309292010-07-06 01:34:17 +00004604
4605 // Collect any cleanups for the catch variable. The scope lasts until
4606 // the end of the catch body.
John McCall2dd7d442010-08-04 05:59:32 +00004607 CodeGenFunction::RunCleanupsScope CatchVarCleanups(CGF);
John McCallbd309292010-07-06 01:34:17 +00004608
John McCall1c9c3fd2010-10-15 04:57:14 +00004609 CGF.EmitAutoVarDecl(*CatchParam);
Daniel Dunbar5c7e3932008-11-11 23:11:34 +00004610 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004611
John McCallbd309292010-07-06 01:34:17 +00004612 // Initialize the catch variable.
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004613 llvm::Value *Tmp =
4614 CGF.Builder.CreateBitCast(Caught,
Benjamin Kramer76399eb2011-09-27 21:06:10 +00004615 CGF.ConvertType(CatchParam->getType()));
John McCall17f02752015-10-30 00:56:02 +00004616 EmitInitOfCatchParam(CGF, Tmp, CatchParam);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004617
Anders Carlsson9396a892008-09-11 09:15:33 +00004618 CGF.EmitStmt(CatchStmt->getCatchBody());
John McCallbd309292010-07-06 01:34:17 +00004619
4620 // We're done with the catch variable.
4621 CatchVarCleanups.ForceCleanup();
4622
Anders Carlssonbfee7e92009-02-09 20:38:58 +00004623 CGF.EmitBranchThroughCleanup(FinallyEnd);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004624
Anders Carlsson4f1c7c32008-09-09 17:59:25 +00004625 CGF.EmitBlock(NextCatchBlock);
4626 }
4627
John McCallbd309292010-07-06 01:34:17 +00004628 CGF.ObjCEHValueStack.pop_back();
4629
John McCall2dd7d442010-08-04 05:59:32 +00004630 // If nothing wanted anything to do with the caught exception,
4631 // kill the extract call.
4632 if (Caught->use_empty())
4633 Caught->eraseFromParent();
4634
4635 if (!AllMatched)
4636 CGF.EmitBranchThroughCleanup(FinallyRethrow);
4637
4638 if (HasFinally) {
4639 // Emit the exception handler for the @catch blocks.
4640 CGF.EmitBlock(CatchHandler);
4641
4642 // In theory we might now need a write hazard, but actually it's
4643 // unnecessary because there's no local-accessing code between
4644 // the try's write hazard and here.
4645 //Hazards.emitWriteHazard();
4646
John McCall9916e3f2010-10-04 23:42:51 +00004647 // Extract the new exception and save it to the
4648 // propagating-exception slot.
John McCall7f416cc2015-09-08 08:05:57 +00004649 assert(PropagatingExnVar.isValid());
John McCall9916e3f2010-10-04 23:42:51 +00004650 llvm::CallInst *NewCaught =
John McCall882987f2013-02-28 19:01:20 +00004651 CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionExtractFn(),
John McCall7f416cc2015-09-08 08:05:57 +00004652 ExceptionData.getPointer(), "caught");
John McCall9916e3f2010-10-04 23:42:51 +00004653 CGF.Builder.CreateStore(NewCaught, PropagatingExnVar);
4654
John McCall2dd7d442010-08-04 05:59:32 +00004655 // Don't pop the catch handler; the throw already did.
4656 CGF.Builder.CreateStore(CGF.Builder.getFalse(), CallTryExitVar);
Anders Carlssonbfee7e92009-02-09 20:38:58 +00004657 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbarb22ff592008-09-27 07:03:52 +00004658 }
Anders Carlsson4f1c7c32008-09-09 17:59:25 +00004659 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004660
John McCall42227ed2010-07-31 23:20:56 +00004661 // Insert read hazards as required in the new blocks.
John McCall2dd7d442010-08-04 05:59:32 +00004662 Hazards.emitHazardsInNewBlocks();
John McCall42227ed2010-07-31 23:20:56 +00004663
John McCallbd309292010-07-06 01:34:17 +00004664 // Pop the cleanup.
John McCall2dd7d442010-08-04 05:59:32 +00004665 CGF.Builder.restoreIP(TryFallthroughIP);
4666 if (CGF.HaveInsertPoint())
4667 CGF.Builder.CreateStore(CGF.Builder.getTrue(), CallTryExitVar);
John McCallbd309292010-07-06 01:34:17 +00004668 CGF.PopCleanupBlock();
John McCall2dd7d442010-08-04 05:59:32 +00004669 CGF.EmitBlock(FinallyEnd.getBlock(), true);
Anders Carlssonbfee7e92009-02-09 20:38:58 +00004670
John McCallbd309292010-07-06 01:34:17 +00004671 // Emit the rethrow block.
John McCall42227ed2010-07-31 23:20:56 +00004672 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
John McCallad5d61e2010-07-23 21:56:41 +00004673 CGF.EmitBlock(FinallyRethrow.getBlock(), true);
John McCallbd309292010-07-06 01:34:17 +00004674 if (CGF.HaveInsertPoint()) {
John McCall9916e3f2010-10-04 23:42:51 +00004675 // If we have a propagating-exception variable, check it.
4676 llvm::Value *PropagatingExn;
John McCall7f416cc2015-09-08 08:05:57 +00004677 if (PropagatingExnVar.isValid()) {
John McCall9916e3f2010-10-04 23:42:51 +00004678 PropagatingExn = CGF.Builder.CreateLoad(PropagatingExnVar);
John McCall2dd7d442010-08-04 05:59:32 +00004679
John McCall9916e3f2010-10-04 23:42:51 +00004680 // Otherwise, just look in the buffer for the exception to throw.
4681 } else {
4682 llvm::CallInst *Caught =
John McCall882987f2013-02-28 19:01:20 +00004683 CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionExtractFn(),
John McCall7f416cc2015-09-08 08:05:57 +00004684 ExceptionData.getPointer());
John McCall9916e3f2010-10-04 23:42:51 +00004685 PropagatingExn = Caught;
4686 }
4687
John McCall882987f2013-02-28 19:01:20 +00004688 CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionThrowFn(),
4689 PropagatingExn);
John McCallbd309292010-07-06 01:34:17 +00004690 CGF.Builder.CreateUnreachable();
Fariborz Jahaniane2caaaa2008-11-21 19:21:53 +00004691 }
Anders Carlsson4f1c7c32008-09-09 17:59:25 +00004692
John McCall42227ed2010-07-31 23:20:56 +00004693 CGF.Builder.restoreIP(SavedIP);
Anders Carlsson1963b0c2008-09-09 10:04:29 +00004694}
4695
4696void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian1eab0522013-01-10 19:02:56 +00004697 const ObjCAtThrowStmt &S,
4698 bool ClearInsertionPoint) {
Anders Carlssone005aa12008-09-09 16:16:55 +00004699 llvm::Value *ExceptionAsObject;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004700
Anders Carlssone005aa12008-09-09 16:16:55 +00004701 if (const Expr *ThrowExpr = S.getThrowExpr()) {
John McCall248512a2011-10-01 10:32:24 +00004702 llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004703 ExceptionAsObject =
Benjamin Kramer76399eb2011-09-27 21:06:10 +00004704 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy);
Anders Carlssone005aa12008-09-09 16:16:55 +00004705 } else {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004706 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004707 "Unexpected rethrow outside @catch block.");
Anders Carlssonbf8a1be2009-02-07 21:37:21 +00004708 ExceptionAsObject = CGF.ObjCEHValueStack.back();
Anders Carlssone005aa12008-09-09 16:16:55 +00004709 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004710
John McCall882987f2013-02-28 19:01:20 +00004711 CGF.EmitRuntimeCall(ObjCTypes.getExceptionThrowFn(), ExceptionAsObject)
John McCallbd309292010-07-06 01:34:17 +00004712 ->setDoesNotReturn();
Anders Carlsson4f1c7c32008-09-09 17:59:25 +00004713 CGF.Builder.CreateUnreachable();
Daniel Dunbar5c7e3932008-11-11 23:11:34 +00004714
4715 // Clear the insertion point to indicate we are in unreachable code.
Fariborz Jahanian1eab0522013-01-10 19:02:56 +00004716 if (ClearInsertionPoint)
4717 CGF.Builder.ClearInsertionPoint();
Anders Carlsson1963b0c2008-09-09 10:04:29 +00004718}
4719
Fariborz Jahanian83f45b552008-11-18 22:37:34 +00004720/// EmitObjCWeakRead - Code gen for loading value of a __weak
Fariborz Jahanianf5125d12008-11-18 21:45:40 +00004721/// object: objc_read_weak (id *src)
4722///
Fariborz Jahanian83f45b552008-11-18 22:37:34 +00004723llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00004724 Address AddrWeakObj) {
4725 llvm::Type* DestTy = AddrWeakObj.getElementType();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004726 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj,
4727 ObjCTypes.PtrObjectPtrTy);
John McCall882987f2013-02-28 19:01:20 +00004728 llvm::Value *read_weak =
4729 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcReadWeakFn(),
John McCall7f416cc2015-09-08 08:05:57 +00004730 AddrWeakObj.getPointer(), "weakread");
Eli Friedmana374b682009-03-07 03:57:15 +00004731 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanianf5125d12008-11-18 21:45:40 +00004732 return read_weak;
4733}
4734
Fariborz Jahanian83f45b552008-11-18 22:37:34 +00004735/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
4736/// objc_assign_weak (id src, id *dst)
4737///
4738void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00004739 llvm::Value *src, Address dst) {
Chris Lattner2192fe52011-07-18 04:24:23 +00004740 llvm::Type * SrcTy = src->getType();
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00004741 if (!isa<llvm::PointerType>(SrcTy)) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00004742 unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00004743 assert(Size <= 8 && "does not support size > 8");
John McCall176f8922016-11-30 02:39:18 +00004744 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, CGM.Int32Ty)
4745 : CGF.Builder.CreateBitCast(src, CGM.Int64Ty);
Fariborz Jahanian1b074a32009-03-13 00:42:52 +00004746 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
4747 }
Fariborz Jahanian50a12702008-11-19 17:34:06 +00004748 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
4749 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00004750 llvm::Value *args[] = { src, dst.getPointer() };
John McCall882987f2013-02-28 19:01:20 +00004751 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignWeakFn(),
4752 args, "weakassign");
Fariborz Jahanian83f45b552008-11-18 22:37:34 +00004753}
4754
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00004755/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
4756/// objc_assign_global (id src, id *dst)
4757///
4758void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00004759 llvm::Value *src, Address dst,
Fariborz Jahanian217af242010-07-20 20:30:03 +00004760 bool threadlocal) {
Chris Lattner2192fe52011-07-18 04:24:23 +00004761 llvm::Type * SrcTy = src->getType();
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00004762 if (!isa<llvm::PointerType>(SrcTy)) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00004763 unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00004764 assert(Size <= 8 && "does not support size > 8");
John McCall176f8922016-11-30 02:39:18 +00004765 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, CGM.Int32Ty)
4766 : CGF.Builder.CreateBitCast(src, CGM.Int64Ty);
Fariborz Jahanian1b074a32009-03-13 00:42:52 +00004767 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
4768 }
Fariborz Jahanian50a12702008-11-19 17:34:06 +00004769 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
4770 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00004771 llvm::Value *args[] = { src, dst.getPointer() };
Fariborz Jahanian217af242010-07-20 20:30:03 +00004772 if (!threadlocal)
John McCall882987f2013-02-28 19:01:20 +00004773 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignGlobalFn(),
4774 args, "globalassign");
Fariborz Jahanian217af242010-07-20 20:30:03 +00004775 else
John McCall882987f2013-02-28 19:01:20 +00004776 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignThreadLocalFn(),
4777 args, "threadlocalassign");
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00004778}
4779
Fariborz Jahaniane881b532008-11-20 19:23:36 +00004780/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00004781/// objc_assign_ivar (id src, id *dst, ptrdiff_t ivaroffset)
Fariborz Jahaniane881b532008-11-20 19:23:36 +00004782///
4783void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00004784 llvm::Value *src, Address dst,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00004785 llvm::Value *ivarOffset) {
4786 assert(ivarOffset && "EmitObjCIvarAssign - ivarOffset is NULL");
Chris Lattner2192fe52011-07-18 04:24:23 +00004787 llvm::Type * SrcTy = src->getType();
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00004788 if (!isa<llvm::PointerType>(SrcTy)) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00004789 unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00004790 assert(Size <= 8 && "does not support size > 8");
John McCall176f8922016-11-30 02:39:18 +00004791 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, CGM.Int32Ty)
4792 : CGF.Builder.CreateBitCast(src, CGM.Int64Ty);
Fariborz Jahanian1b074a32009-03-13 00:42:52 +00004793 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
4794 }
Fariborz Jahaniane881b532008-11-20 19:23:36 +00004795 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
4796 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00004797 llvm::Value *args[] = { src, dst.getPointer(), ivarOffset };
John McCall882987f2013-02-28 19:01:20 +00004798 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignIvarFn(), args);
Fariborz Jahaniane881b532008-11-20 19:23:36 +00004799}
4800
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00004801/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
4802/// objc_assign_strongCast (id src, id *dst)
4803///
4804void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00004805 llvm::Value *src, Address dst) {
Chris Lattner2192fe52011-07-18 04:24:23 +00004806 llvm::Type * SrcTy = src->getType();
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00004807 if (!isa<llvm::PointerType>(SrcTy)) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00004808 unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00004809 assert(Size <= 8 && "does not support size > 8");
John McCall176f8922016-11-30 02:39:18 +00004810 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, CGM.Int32Ty)
4811 : CGF.Builder.CreateBitCast(src, CGM.Int64Ty);
Fariborz Jahanian1b074a32009-03-13 00:42:52 +00004812 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
4813 }
Fariborz Jahanian50a12702008-11-19 17:34:06 +00004814 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
4815 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00004816 llvm::Value *args[] = { src, dst.getPointer() };
John McCall882987f2013-02-28 19:01:20 +00004817 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignStrongCastFn(),
John McCall7f416cc2015-09-08 08:05:57 +00004818 args, "strongassign");
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00004819}
4820
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00004821void CGObjCMac::EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00004822 Address DestPtr,
4823 Address SrcPtr,
Fariborz Jahanian021510e2010-06-15 22:44:06 +00004824 llvm::Value *size) {
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00004825 SrcPtr = CGF.Builder.CreateBitCast(SrcPtr, ObjCTypes.Int8PtrTy);
4826 DestPtr = CGF.Builder.CreateBitCast(DestPtr, ObjCTypes.Int8PtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00004827 llvm::Value *args[] = { DestPtr.getPointer(), SrcPtr.getPointer(), size };
John McCall882987f2013-02-28 19:01:20 +00004828 CGF.EmitNounwindRuntimeCall(ObjCTypes.GcMemmoveCollectableFn(), args);
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00004829}
4830
Fariborz Jahanian9f84b782009-02-02 20:02:29 +00004831/// EmitObjCValueForIvar - Code Gen for ivar reference.
4832///
Fariborz Jahanian712bfa62009-02-03 19:03:09 +00004833LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
4834 QualType ObjectTy,
4835 llvm::Value *BaseValue,
4836 const ObjCIvarDecl *Ivar,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +00004837 unsigned CVRQualifiers) {
John McCall8b07ec22010-05-15 11:32:37 +00004838 const ObjCInterfaceDecl *ID =
4839 ObjectTy->getAs<ObjCObjectType>()->getInterface();
Daniel Dunbar9fd114d2009-04-22 07:32:20 +00004840 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
4841 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian9f84b782009-02-02 20:02:29 +00004842}
4843
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00004844llvm::Value *CGObjCMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar722f4242009-04-22 05:08:15 +00004845 const ObjCInterfaceDecl *Interface,
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00004846 const ObjCIvarDecl *Ivar) {
Eli Friedman8cbca202012-11-06 22:15:52 +00004847 uint64_t Offset = ComputeIvarBaseOffset(CGM, Interface, Ivar);
4848 return llvm::ConstantInt::get(
4849 CGM.getTypes().ConvertType(CGM.getContext().LongTy),
4850 Offset);
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00004851}
4852
Daniel Dunbar3ad53482008-08-11 21:35:06 +00004853/* *** Private Interface *** */
4854
Saleem Abdulrasool13d73d52017-06-03 16:18:09 +00004855std::string CGObjCCommonMac::GetSectionName(StringRef Section,
4856 StringRef MachOAttributes) {
4857 switch (CGM.getTriple().getObjectFormat()) {
4858 default:
4859 llvm_unreachable("unexpected object file format");
4860 case llvm::Triple::MachO: {
4861 if (MachOAttributes.empty())
4862 return ("__DATA," + Section).str();
4863 return ("__DATA," + Section + "," + MachOAttributes).str();
4864 }
4865 case llvm::Triple::ELF:
4866 assert(Section.substr(0, 2) == "__" &&
4867 "expected the name to begin with __");
4868 return Section.substr(2).str();
4869 case llvm::Triple::COFF:
4870 assert(Section.substr(0, 2) == "__" &&
4871 "expected the name to begin with __");
4872 return ("." + Section.substr(2) + "$B").str();
4873 }
4874}
4875
Daniel Dunbar3ad53482008-08-11 21:35:06 +00004876/// EmitImageInfo - Emit the image info marker used to encode some module
4877/// level information.
4878///
4879/// See: <rdr://4810609&4810587&4810587>
4880/// struct IMAGE_INFO {
4881/// unsigned version;
4882/// unsigned flags;
4883/// };
4884enum ImageInfoFlags {
Fariborz Jahanian39c17a82014-01-14 22:01:08 +00004885 eImageInfo_FixAndContinue = (1 << 0), // This flag is no longer set by clang.
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004886 eImageInfo_GarbageCollected = (1 << 1),
4887 eImageInfo_GCOnly = (1 << 2),
Fariborz Jahanian39c17a82014-01-14 22:01:08 +00004888 eImageInfo_OptimizedByDyld = (1 << 3), // This flag is set by the dyld shared cache.
Daniel Dunbar75e909f2009-04-20 07:11:47 +00004889
Daniel Dunbar5e639272010-04-25 20:39:01 +00004890 // A flag indicating that the module has no instances of a @synthesize of a
4891 // superclass variable. <rdar://problem/6803242>
Fariborz Jahanian39c17a82014-01-14 22:01:08 +00004892 eImageInfo_CorrectedSynthesize = (1 << 4), // This flag is no longer set by clang.
Manman Ren96df0b32016-01-29 23:45:01 +00004893 eImageInfo_ImageIsSimulated = (1 << 5),
4894 eImageInfo_ClassProperties = (1 << 6)
Daniel Dunbar3ad53482008-08-11 21:35:06 +00004895};
4896
Daniel Dunbar5e639272010-04-25 20:39:01 +00004897void CGObjCCommonMac::EmitImageInfo() {
Daniel Dunbar3ad53482008-08-11 21:35:06 +00004898 unsigned version = 0; // Version is unused?
Saleem Abdulrasool13d73d52017-06-03 16:18:09 +00004899 std::string Section =
4900 (ObjCABI == 1)
4901 ? "__OBJC,__image_info,regular"
4902 : GetSectionName("__objc_imageinfo", "regular,no_dead_strip");
Daniel Dunbar3ad53482008-08-11 21:35:06 +00004903
Bill Wendlingb6f795e2012-02-16 01:13:30 +00004904 // Generate module-level named metadata to convey this information to the
4905 // linker and code-gen.
4906 llvm::Module &Mod = CGM.getModule();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004907
Bill Wendlingb6f795e2012-02-16 01:13:30 +00004908 // Add the ObjC ABI version to the module flags.
4909 Mod.addModuleFlag(llvm::Module::Error, "Objective-C Version", ObjCABI);
4910 Mod.addModuleFlag(llvm::Module::Error, "Objective-C Image Info Version",
4911 version);
4912 Mod.addModuleFlag(llvm::Module::Error, "Objective-C Image Info Section",
Saleem Abdulrasool13d73d52017-06-03 16:18:09 +00004913 llvm::MDString::get(VMContext, Section));
Daniel Dunbar3ad53482008-08-11 21:35:06 +00004914
David Blaikiebbafb8a2012-03-11 07:00:24 +00004915 if (CGM.getLangOpts().getGC() == LangOptions::NonGC) {
Bill Wendlingb6f795e2012-02-16 01:13:30 +00004916 // Non-GC overrides those files which specify GC.
4917 Mod.addModuleFlag(llvm::Module::Override,
4918 "Objective-C Garbage Collection", (uint32_t)0);
4919 } else {
4920 // Add the ObjC garbage collection value.
4921 Mod.addModuleFlag(llvm::Module::Error,
4922 "Objective-C Garbage Collection",
4923 eImageInfo_GarbageCollected);
Daniel Dunbarc2d4b622009-03-09 21:49:58 +00004924
David Blaikiebbafb8a2012-03-11 07:00:24 +00004925 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
Bill Wendlingb6f795e2012-02-16 01:13:30 +00004926 // Add the ObjC GC Only value.
4927 Mod.addModuleFlag(llvm::Module::Error, "Objective-C GC Only",
4928 eImageInfo_GCOnly);
4929
4930 // Require that GC be specified and set to eImageInfo_GarbageCollected.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00004931 llvm::Metadata *Ops[2] = {
4932 llvm::MDString::get(VMContext, "Objective-C Garbage Collection"),
4933 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
4934 llvm::Type::getInt32Ty(VMContext), eImageInfo_GarbageCollected))};
Bill Wendlingb6f795e2012-02-16 01:13:30 +00004935 Mod.addModuleFlag(llvm::Module::Require, "Objective-C GC Only",
4936 llvm::MDNode::get(VMContext, Ops));
4937 }
4938 }
Bill Wendling1e60a2c2012-04-24 11:04:57 +00004939
4940 // Indicate whether we're compiling this to run on a simulator.
Alex Lorenz6cdef0e2017-12-07 19:04:10 +00004941 if (CGM.getTarget().getTriple().isSimulatorEnvironment())
Bill Wendling1e60a2c2012-04-24 11:04:57 +00004942 Mod.addModuleFlag(llvm::Module::Error, "Objective-C Is Simulated",
4943 eImageInfo_ImageIsSimulated);
Manman Ren96df0b32016-01-29 23:45:01 +00004944
4945 // Indicate whether we are generating class properties.
4946 Mod.addModuleFlag(llvm::Module::Error, "Objective-C Class Properties",
4947 eImageInfo_ClassProperties);
Daniel Dunbar3ad53482008-08-11 21:35:06 +00004948}
4949
Daniel Dunbar7bd00bd2008-08-12 06:48:42 +00004950// struct objc_module {
4951// unsigned long version;
4952// unsigned long size;
4953// const char *name;
4954// Symtab symtab;
4955// };
4956
4957// FIXME: Get from somewhere
4958static const int ModuleVersion = 7;
4959
4960void CGObjCMac::EmitModuleInfo() {
Micah Villmowdd31ca12012-10-08 16:25:52 +00004961 uint64_t Size = CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ModuleTy);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004962
John McCall176f8922016-11-30 02:39:18 +00004963 ConstantInitBuilder builder(CGM);
4964 auto values = builder.beginStruct(ObjCTypes.ModuleTy);
4965 values.addInt(ObjCTypes.LongTy, ModuleVersion);
4966 values.addInt(ObjCTypes.LongTy, Size);
4967 // This used to be the filename, now it is unused. <rdr://4327263>
4968 values.add(GetClassName(StringRef("")));
4969 values.add(EmitModuleSymbols());
4970 CreateMetadataVar("OBJC_MODULES", values,
John McCall7f416cc2015-09-08 08:05:57 +00004971 "__OBJC,__module_info,regular,no_dead_strip",
4972 CGM.getPointerAlign(), true);
Daniel Dunbar7bd00bd2008-08-12 06:48:42 +00004973}
4974
4975llvm::Constant *CGObjCMac::EmitModuleSymbols() {
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00004976 unsigned NumClasses = DefinedClasses.size();
4977 unsigned NumCategories = DefinedCategories.size();
4978
Daniel Dunbarc61d0e92008-08-25 06:02:07 +00004979 // Return null if no symbols were defined.
4980 if (!NumClasses && !NumCategories)
Owen Anderson0b75f232009-07-31 20:28:54 +00004981 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
Daniel Dunbarc61d0e92008-08-25 06:02:07 +00004982
John McCall176f8922016-11-30 02:39:18 +00004983 ConstantInitBuilder builder(CGM);
4984 auto values = builder.beginStruct();
4985 values.addInt(ObjCTypes.LongTy, 0);
4986 values.addNullPointer(ObjCTypes.SelectorPtrTy);
4987 values.addInt(ObjCTypes.ShortTy, NumClasses);
4988 values.addInt(ObjCTypes.ShortTy, NumCategories);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00004989
Daniel Dunbar938a77f2008-08-22 20:34:54 +00004990 // The runtime expects exactly the list of defined classes followed
4991 // by the list of defined categories, in a single array.
John McCall176f8922016-11-30 02:39:18 +00004992 auto array = values.beginArray(ObjCTypes.Int8PtrTy);
Fariborz Jahanianf322f2f2014-03-11 00:25:05 +00004993 for (unsigned i=0; i<NumClasses; i++) {
4994 const ObjCInterfaceDecl *ID = ImplementedClasses[i];
4995 assert(ID);
4996 if (ObjCImplementationDecl *IMP = ID->getImplementation())
4997 // We are implementing a weak imported interface. Give it external linkage
4998 if (ID->isWeakImported() && !IMP->isWeakImported())
4999 DefinedClasses[i]->setLinkage(llvm::GlobalVariable::ExternalLinkage);
John McCall176f8922016-11-30 02:39:18 +00005000
5001 array.addBitCast(DefinedClasses[i], ObjCTypes.Int8PtrTy);
Fariborz Jahanianf322f2f2014-03-11 00:25:05 +00005002 }
Daniel Dunbar938a77f2008-08-22 20:34:54 +00005003 for (unsigned i=0; i<NumCategories; i++)
John McCall176f8922016-11-30 02:39:18 +00005004 array.addBitCast(DefinedCategories[i], ObjCTypes.Int8PtrTy);
Daniel Dunbar938a77f2008-08-22 20:34:54 +00005005
John McCall176f8922016-11-30 02:39:18 +00005006 array.finishAndAddTo(values);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00005007
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00005008 llvm::GlobalVariable *GV = CreateMetadataVar(
John McCall176f8922016-11-30 02:39:18 +00005009 "OBJC_SYMBOLS", values, "__OBJC,__symbols,regular,no_dead_strip",
John McCall7f416cc2015-09-08 08:05:57 +00005010 CGM.getPointerAlign(), true);
Owen Andersonade90fd2009-07-29 18:54:39 +00005011 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00005012}
5013
John McCall882987f2013-02-28 19:01:20 +00005014llvm::Value *CGObjCMac::EmitClassRefFromId(CodeGenFunction &CGF,
5015 IdentifierInfo *II) {
John McCall31168b02011-06-15 23:02:42 +00005016 LazySymbols.insert(II);
Fangrui Song6907ce22018-07-30 19:24:48 +00005017
John McCall31168b02011-06-15 23:02:42 +00005018 llvm::GlobalVariable *&Entry = ClassReferences[II];
Fangrui Song6907ce22018-07-30 19:24:48 +00005019
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00005020 if (!Entry) {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005021 llvm::Constant *Casted =
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00005022 llvm::ConstantExpr::getBitCast(GetClassName(II->getName()),
John McCall31168b02011-06-15 23:02:42 +00005023 ObjCTypes.ClassPtrTy);
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00005024 Entry = CreateMetadataVar(
5025 "OBJC_CLASS_REFERENCES_", Casted,
John McCall7f416cc2015-09-08 08:05:57 +00005026 "__OBJC,__cls_refs,literal_pointers,no_dead_strip",
5027 CGM.getPointerAlign(), true);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00005028 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005029
John McCall7f416cc2015-09-08 08:05:57 +00005030 return CGF.Builder.CreateAlignedLoad(Entry, CGF.getPointerAlign());
Daniel Dunbar7bd00bd2008-08-12 06:48:42 +00005031}
5032
John McCall882987f2013-02-28 19:01:20 +00005033llvm::Value *CGObjCMac::EmitClassRef(CodeGenFunction &CGF,
John McCall31168b02011-06-15 23:02:42 +00005034 const ObjCInterfaceDecl *ID) {
Douglas Gregor24ae22c2016-04-01 23:23:52 +00005035 // If the class has the objc_runtime_visible attribute, we need to
5036 // use the Objective-C runtime to get the class.
5037 if (ID->hasAttr<ObjCRuntimeVisibleAttr>())
5038 return EmitClassRefViaRuntime(CGF, ID, ObjCTypes);
5039
Akira Hatanaka0c194462018-04-03 22:50:16 +00005040 IdentifierInfo *RuntimeName =
5041 &CGM.getContext().Idents.get(ID->getObjCRuntimeNameAsString());
5042 return EmitClassRefFromId(CGF, RuntimeName);
John McCall31168b02011-06-15 23:02:42 +00005043}
5044
John McCall882987f2013-02-28 19:01:20 +00005045llvm::Value *CGObjCMac::EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) {
John McCall31168b02011-06-15 23:02:42 +00005046 IdentifierInfo *II = &CGM.getContext().Idents.get("NSAutoreleasePool");
John McCall882987f2013-02-28 19:01:20 +00005047 return EmitClassRefFromId(CGF, II);
John McCall31168b02011-06-15 23:02:42 +00005048}
5049
John McCall7f416cc2015-09-08 08:05:57 +00005050llvm::Value *CGObjCMac::EmitSelector(CodeGenFunction &CGF, Selector Sel) {
5051 return CGF.Builder.CreateLoad(EmitSelectorAddr(CGF, Sel));
5052}
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005053
John McCall7f416cc2015-09-08 08:05:57 +00005054Address CGObjCMac::EmitSelectorAddr(CodeGenFunction &CGF, Selector Sel) {
5055 CharUnits Align = CGF.getPointerAlign();
5056
5057 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
Daniel Dunbarcb515c82008-08-12 03:39:23 +00005058 if (!Entry) {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005059 llvm::Constant *Casted =
Owen Andersonade90fd2009-07-29 18:54:39 +00005060 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
Daniel Dunbarcb515c82008-08-12 03:39:23 +00005061 ObjCTypes.SelectorPtrTy);
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00005062 Entry = CreateMetadataVar(
5063 "OBJC_SELECTOR_REFERENCES_", Casted,
John McCall7f416cc2015-09-08 08:05:57 +00005064 "__OBJC,__message_refs,literal_pointers,no_dead_strip", Align, true);
Michael Gottesman5c205962013-02-05 23:08:45 +00005065 Entry->setExternallyInitialized(true);
Daniel Dunbarcb515c82008-08-12 03:39:23 +00005066 }
5067
John McCall7f416cc2015-09-08 08:05:57 +00005068 return Address(Entry, Align);
Daniel Dunbarcb515c82008-08-12 03:39:23 +00005069}
5070
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00005071llvm::Constant *CGObjCCommonMac::GetClassName(StringRef RuntimeName) {
5072 llvm::GlobalVariable *&Entry = ClassNames[RuntimeName];
5073 if (!Entry)
Saleem Abdulrasool271106c2016-09-16 23:41:13 +00005074 Entry = CreateCStringLiteral(RuntimeName, ObjCLabelType::ClassName);
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00005075 return getConstantGEP(VMContext, Entry, 0, 0);
Daniel Dunbar7bd00bd2008-08-12 06:48:42 +00005076}
5077
Argyrios Kyrtzidis13257c52010-08-09 10:54:20 +00005078llvm::Function *CGObjCCommonMac::GetMethodDefinition(const ObjCMethodDecl *MD) {
5079 llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*>::iterator
5080 I = MethodDefinitions.find(MD);
5081 if (I != MethodDefinitions.end())
5082 return I->second;
5083
Craig Topper8a13c412014-05-21 05:09:00 +00005084 return nullptr;
Argyrios Kyrtzidis13257c52010-08-09 10:54:20 +00005085}
5086
Fariborz Jahanian01dff422009-03-05 19:17:31 +00005087/// GetIvarLayoutName - Returns a unique constant for the given
5088/// ivar layout bitmap.
5089llvm::Constant *CGObjCCommonMac::GetIvarLayoutName(IdentifierInfo *Ident,
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005090 const ObjCCommonTypesHelper &ObjCTypes) {
Owen Anderson0b75f232009-07-31 20:28:54 +00005091 return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Fariborz Jahanian01dff422009-03-05 19:17:31 +00005092}
5093
John McCall3fd13f062015-10-21 18:06:47 +00005094void IvarLayoutBuilder::visitRecord(const RecordType *RT,
5095 CharUnits offset) {
Daniel Dunbar15bd8882009-05-03 14:10:34 +00005096 const RecordDecl *RD = RT->getDecl();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005097
John McCall3fd13f062015-10-21 18:06:47 +00005098 // If this is a union, remember that we had one, because it might mess
5099 // up the ordering of layout entries.
5100 if (RD->isUnion())
5101 IsDisordered = true;
5102
5103 const ASTRecordLayout *recLayout = nullptr;
5104 visitAggregate(RD->field_begin(), RD->field_end(), offset,
5105 [&](const FieldDecl *field) -> CharUnits {
5106 if (!recLayout)
5107 recLayout = &CGM.getContext().getASTRecordLayout(RD);
5108 auto offsetInBits = recLayout->getFieldOffset(field->getFieldIndex());
5109 return CGM.getContext().toCharUnitsFromBits(offsetInBits);
5110 });
Daniel Dunbar15bd8882009-05-03 14:10:34 +00005111}
5112
John McCall3fd13f062015-10-21 18:06:47 +00005113template <class Iterator, class GetOffsetFn>
Fangrui Song6907ce22018-07-30 19:24:48 +00005114void IvarLayoutBuilder::visitAggregate(Iterator begin, Iterator end,
John McCall3fd13f062015-10-21 18:06:47 +00005115 CharUnits aggregateOffset,
5116 const GetOffsetFn &getOffset) {
5117 for (; begin != end; ++begin) {
5118 auto field = *begin;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005119
John McCall3fd13f062015-10-21 18:06:47 +00005120 // Skip over bitfields.
5121 if (field->isBitField()) {
5122 continue;
5123 }
5124
5125 // Compute the offset of the field within the aggregate.
5126 CharUnits fieldOffset = aggregateOffset + getOffset(field);
5127
5128 visitField(field, fieldOffset);
5129 }
5130}
5131
5132/// Collect layout information for the given fields into IvarsInfo.
5133void IvarLayoutBuilder::visitField(const FieldDecl *field,
5134 CharUnits fieldOffset) {
5135 QualType fieldType = field->getType();
5136
5137 // Drill down into arrays.
5138 uint64_t numElts = 1;
Volodymyr Sapsai636ed472017-10-27 00:56:23 +00005139 if (auto arrayType = CGM.getContext().getAsIncompleteArrayType(fieldType)) {
5140 numElts = 0;
5141 fieldType = arrayType->getElementType();
5142 }
5143 // Unlike incomplete arrays, constant arrays can be nested.
John McCall3fd13f062015-10-21 18:06:47 +00005144 while (auto arrayType = CGM.getContext().getAsConstantArrayType(fieldType)) {
5145 numElts *= arrayType->getSize().getZExtValue();
5146 fieldType = arrayType->getElementType();
5147 }
5148
5149 assert(!fieldType->isArrayType() && "ivar of non-constant array type?");
5150
5151 // If we ended up with a zero-sized array, we've done what we can do within
5152 // the limits of this layout encoding.
5153 if (numElts == 0) return;
5154
5155 // Recurse if the base element type is a record type.
5156 if (auto recType = fieldType->getAs<RecordType>()) {
5157 size_t oldEnd = IvarsInfo.size();
5158
5159 visitRecord(recType, fieldOffset);
5160
5161 // If we have an array, replicate the first entry's layout information.
5162 auto numEltEntries = IvarsInfo.size() - oldEnd;
5163 if (numElts != 1 && numEltEntries != 0) {
5164 CharUnits eltSize = CGM.getContext().getTypeSizeInChars(recType);
5165 for (uint64_t eltIndex = 1; eltIndex != numElts; ++eltIndex) {
5166 // Copy the last numEltEntries onto the end of the array, adjusting
5167 // each for the element size.
5168 for (size_t i = 0; i != numEltEntries; ++i) {
5169 auto firstEntry = IvarsInfo[oldEnd + i];
5170 IvarsInfo.push_back(IvarInfo(firstEntry.Offset + eltIndex * eltSize,
5171 firstEntry.SizeInWords));
5172 }
5173 }
5174 }
5175
Fariborz Jahanian524bb202009-03-10 16:22:08 +00005176 return;
Fariborz Jahanian3b0f8862009-03-11 00:07:04 +00005177 }
Daniel Dunbar15bd8882009-05-03 14:10:34 +00005178
John McCall3fd13f062015-10-21 18:06:47 +00005179 // Classify the element type.
5180 Qualifiers::GC GCAttr = GetGCAttrTypeForType(CGM.getContext(), fieldType);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005181
John McCall3fd13f062015-10-21 18:06:47 +00005182 // If it matches what we're looking for, add an entry.
5183 if ((ForStrongLayout && GCAttr == Qualifiers::Strong)
5184 || (!ForStrongLayout && GCAttr == Qualifiers::Weak)) {
5185 assert(CGM.getContext().getTypeSizeInChars(fieldType)
5186 == CGM.getPointerSize());
5187 IvarsInfo.push_back(IvarInfo(fieldOffset, numElts));
5188 }
Fariborz Jahanianc559f3f2009-03-05 22:39:55 +00005189}
5190
John McCall3fd13f062015-10-21 18:06:47 +00005191/// buildBitmap - This routine does the horsework of taking the offsets of
5192/// strong/weak references and creating a bitmap. The bitmap is also
5193/// returned in the given buffer, suitable for being passed to \c dump().
5194llvm::Constant *IvarLayoutBuilder::buildBitmap(CGObjCCommonMac &CGObjC,
5195 llvm::SmallVectorImpl<unsigned char> &buffer) {
5196 // The bitmap is a series of skip/scan instructions, aligned to word
5197 // boundaries. The skip is performed first.
5198 const unsigned char MaxNibble = 0xF;
5199 const unsigned char SkipMask = 0xF0, SkipShift = 4;
5200 const unsigned char ScanMask = 0x0F, ScanShift = 0;
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00005201
John McCall3fd13f062015-10-21 18:06:47 +00005202 assert(!IvarsInfo.empty() && "generating bitmap for no data");
5203
5204 // Sort the ivar info on byte position in case we encounterred a
5205 // union nested in the ivar list.
5206 if (IsDisordered) {
5207 // This isn't a stable sort, but our algorithm should handle it fine.
5208 llvm::array_pod_sort(IvarsInfo.begin(), IvarsInfo.end());
5209 } else {
Craig Toppera3467052016-01-03 19:43:20 +00005210 assert(std::is_sorted(IvarsInfo.begin(), IvarsInfo.end()));
John McCall3fd13f062015-10-21 18:06:47 +00005211 }
5212 assert(IvarsInfo.back().Offset < InstanceEnd);
5213
5214 assert(buffer.empty());
5215
5216 // Skip the next N words.
5217 auto skip = [&](unsigned numWords) {
5218 assert(numWords > 0);
5219
5220 // Try to merge into the previous byte. Since scans happen second, we
5221 // can't do this if it includes a scan.
5222 if (!buffer.empty() && !(buffer.back() & ScanMask)) {
5223 unsigned lastSkip = buffer.back() >> SkipShift;
5224 if (lastSkip < MaxNibble) {
5225 unsigned claimed = std::min(MaxNibble - lastSkip, numWords);
5226 numWords -= claimed;
5227 lastSkip += claimed;
5228 buffer.back() = (lastSkip << SkipShift);
5229 }
5230 }
5231
5232 while (numWords >= MaxNibble) {
5233 buffer.push_back(MaxNibble << SkipShift);
5234 numWords -= MaxNibble;
5235 }
5236 if (numWords) {
5237 buffer.push_back(numWords << SkipShift);
5238 }
5239 };
5240
5241 // Scan the next N words.
5242 auto scan = [&](unsigned numWords) {
5243 assert(numWords > 0);
5244
5245 // Try to merge into the previous byte. Since scans happen second, we can
5246 // do this even if it includes a skip.
5247 if (!buffer.empty()) {
5248 unsigned lastScan = (buffer.back() & ScanMask) >> ScanShift;
5249 if (lastScan < MaxNibble) {
5250 unsigned claimed = std::min(MaxNibble - lastScan, numWords);
5251 numWords -= claimed;
5252 lastScan += claimed;
5253 buffer.back() = (buffer.back() & SkipMask) | (lastScan << ScanShift);
5254 }
5255 }
5256
5257 while (numWords >= MaxNibble) {
5258 buffer.push_back(MaxNibble << ScanShift);
5259 numWords -= MaxNibble;
5260 }
5261 if (numWords) {
5262 buffer.push_back(numWords << ScanShift);
5263 }
5264 };
5265
5266 // One past the end of the last scan.
5267 unsigned endOfLastScanInWords = 0;
5268 const CharUnits WordSize = CGM.getPointerSize();
5269
5270 // Consider all the scan requests.
5271 for (auto &request : IvarsInfo) {
5272 CharUnits beginOfScan = request.Offset - InstanceBegin;
5273
5274 // Ignore scan requests that don't start at an even multiple of the
5275 // word size. We can't encode them.
5276 if ((beginOfScan % WordSize) != 0) continue;
5277
5278 // Ignore scan requests that start before the instance start.
5279 // This assumes that scans never span that boundary. The boundary
5280 // isn't the true start of the ivars, because in the fragile-ARC case
5281 // it's rounded up to word alignment, but the test above should leave
5282 // us ignoring that possibility.
5283 if (beginOfScan.isNegative()) {
5284 assert(request.Offset + request.SizeInWords * WordSize <= InstanceBegin);
5285 continue;
5286 }
5287
5288 unsigned beginOfScanInWords = beginOfScan / WordSize;
5289 unsigned endOfScanInWords = beginOfScanInWords + request.SizeInWords;
5290
5291 // If the scan starts some number of words after the last one ended,
5292 // skip forward.
5293 if (beginOfScanInWords > endOfLastScanInWords) {
5294 skip(beginOfScanInWords - endOfLastScanInWords);
5295
5296 // Otherwise, start scanning where the last left off.
5297 } else {
5298 beginOfScanInWords = endOfLastScanInWords;
5299
5300 // If that leaves us with nothing to scan, ignore this request.
5301 if (beginOfScanInWords >= endOfScanInWords) continue;
5302 }
5303
5304 // Scan to the end of the request.
5305 assert(beginOfScanInWords < endOfScanInWords);
5306 scan(endOfScanInWords - beginOfScanInWords);
5307 endOfLastScanInWords = endOfScanInWords;
5308 }
5309
John McCallf5ea0722015-10-29 23:36:14 +00005310 if (buffer.empty())
5311 return llvm::ConstantPointerNull::get(CGM.Int8PtrTy);
5312
John McCall3fd13f062015-10-21 18:06:47 +00005313 // For GC layouts, emit a skip to the end of the allocation so that we
5314 // have precise information about the entire thing. This isn't useful
5315 // or necessary for the ARC-style layout strings.
5316 if (CGM.getLangOpts().getGC() != LangOptions::NonGC) {
5317 unsigned lastOffsetInWords =
5318 (InstanceEnd - InstanceBegin + WordSize - CharUnits::One()) / WordSize;
5319 if (lastOffsetInWords > endOfLastScanInWords) {
5320 skip(lastOffsetInWords - endOfLastScanInWords);
5321 }
5322 }
5323
5324 // Null terminate the string.
5325 buffer.push_back(0);
5326
Saleem Abdulrasool271106c2016-09-16 23:41:13 +00005327 auto *Entry = CGObjC.CreateCStringLiteral(
5328 reinterpret_cast<char *>(buffer.data()), ObjCLabelType::ClassName);
John McCall3fd13f062015-10-21 18:06:47 +00005329 return getConstantGEP(CGM.getLLVMContext(), Entry, 0, 0);
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00005330}
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005331
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00005332/// BuildIvarLayout - Builds ivar layout bitmap for the class
5333/// implementation for the __strong or __weak case.
5334/// The layout map displays which words in ivar list must be skipped
5335/// and which must be scanned by GC (see below). String is built of bytes.
5336/// Each byte is divided up in two nibbles (4-bit each). Left nibble is count
5337/// of words to skip and right nibble is count of words to scan. So, each
5338/// nibble represents up to 15 workds to skip or scan. Skipping the rest is
5339/// represented by a 0x00 byte which also ends the string.
5340/// 1. when ForStrongLayout is true, following ivars are scanned:
5341/// - id, Class
5342/// - object *
5343/// - __strong anything
5344///
5345/// 2. When ForStrongLayout is false, following ivars are scanned:
5346/// - __weak anything
5347///
John McCall3fd13f062015-10-21 18:06:47 +00005348llvm::Constant *
5349CGObjCCommonMac::BuildIvarLayout(const ObjCImplementationDecl *OMD,
5350 CharUnits beginOffset, CharUnits endOffset,
John McCall460ce582015-10-22 18:38:17 +00005351 bool ForStrongLayout, bool HasMRCWeakIvars) {
5352 // If this is MRC, and we're either building a strong layout or there
5353 // are no weak ivars, bail out early.
Chris Lattnerece04092012-02-07 00:39:47 +00005354 llvm::Type *PtrTy = CGM.Int8PtrTy;
David Blaikiebbafb8a2012-03-11 07:00:24 +00005355 if (CGM.getLangOpts().getGC() == LangOptions::NonGC &&
John McCall460ce582015-10-22 18:38:17 +00005356 !CGM.getLangOpts().ObjCAutoRefCount &&
5357 (ForStrongLayout || !HasMRCWeakIvars))
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00005358 return llvm::Constant::getNullValue(PtrTy);
5359
Jordy Rosea91768e2011-07-22 02:08:32 +00005360 const ObjCInterfaceDecl *OI = OMD->getClassInterface();
John McCall3fd13f062015-10-21 18:06:47 +00005361 SmallVector<const ObjCIvarDecl*, 32> ivars;
5362
5363 // GC layout strings include the complete object layout, possibly
5364 // inaccurately in the non-fragile ABI; the runtime knows how to fix this
5365 // up.
5366 //
5367 // ARC layout strings only include the class's ivars. In non-fragile
John McCallf5ea0722015-10-29 23:36:14 +00005368 // runtimes, that means starting at InstanceStart, rounded up to word
5369 // alignment. In fragile runtimes, there's no InstanceStart, so it means
John McCalld80218f2015-11-19 02:27:55 +00005370 // starting at the offset of the first ivar, rounded up to word alignment.
John McCall460ce582015-10-22 18:38:17 +00005371 //
5372 // MRC weak layout strings follow the ARC style.
John McCall3fd13f062015-10-21 18:06:47 +00005373 CharUnits baseOffset;
John McCall460ce582015-10-22 18:38:17 +00005374 if (CGM.getLangOpts().getGC() == LangOptions::NonGC) {
Fangrui Song6907ce22018-07-30 19:24:48 +00005375 for (const ObjCIvarDecl *IVD = OI->all_declared_ivar_begin();
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00005376 IVD; IVD = IVD->getNextIvar())
John McCall3fd13f062015-10-21 18:06:47 +00005377 ivars.push_back(IVD);
5378
5379 if (isNonFragileABI()) {
5380 baseOffset = beginOffset; // InstanceStart
John McCalld80218f2015-11-19 02:27:55 +00005381 } else if (!ivars.empty()) {
5382 baseOffset =
5383 CharUnits::fromQuantity(ComputeIvarBaseOffset(CGM, OMD, ivars[0]));
John McCall3fd13f062015-10-21 18:06:47 +00005384 } else {
5385 baseOffset = CharUnits::Zero();
5386 }
John McCallf5ea0722015-10-29 23:36:14 +00005387
Rui Ueyama83aa9792016-01-14 21:00:27 +00005388 baseOffset = baseOffset.alignTo(CGM.getPointerAlign());
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00005389 }
5390 else {
John McCall3fd13f062015-10-21 18:06:47 +00005391 CGM.getContext().DeepCollectObjCIvars(OI, true, ivars);
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00005392
John McCall3fd13f062015-10-21 18:06:47 +00005393 baseOffset = CharUnits::Zero();
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00005394 }
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00005395
John McCall3fd13f062015-10-21 18:06:47 +00005396 if (ivars.empty())
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00005397 return llvm::Constant::getNullValue(PtrTy);
5398
John McCall3fd13f062015-10-21 18:06:47 +00005399 IvarLayoutBuilder builder(CGM, baseOffset, endOffset, ForStrongLayout);
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00005400
John McCall3fd13f062015-10-21 18:06:47 +00005401 builder.visitAggregate(ivars.begin(), ivars.end(), CharUnits::Zero(),
5402 [&](const ObjCIvarDecl *ivar) -> CharUnits {
5403 return CharUnits::fromQuantity(ComputeIvarBaseOffset(CGM, OMD, ivar));
5404 });
5405
5406 if (!builder.hasBitmapData())
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00005407 return llvm::Constant::getNullValue(PtrTy);
John McCall3fd13f062015-10-21 18:06:47 +00005408
5409 llvm::SmallVector<unsigned char, 4> buffer;
5410 llvm::Constant *C = builder.buildBitmap(*this, buffer);
Fangrui Song6907ce22018-07-30 19:24:48 +00005411
John McCallf5ea0722015-10-29 23:36:14 +00005412 if (CGM.getLangOpts().ObjCGCBitmapPrint && !buffer.empty()) {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005413 printf("\n%s ivar layout for class '%s': ",
Fariborz Jahanian80c9ce22009-04-20 22:03:45 +00005414 ForStrongLayout ? "strong" : "weak",
Ben Langmuire013bdc2014-07-11 00:43:47 +00005415 OMD->getClassInterface()->getName().str().c_str());
John McCall3fd13f062015-10-21 18:06:47 +00005416 builder.dump(buffer);
Fariborz Jahanian80c9ce22009-04-20 22:03:45 +00005417 }
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00005418 return C;
Fariborz Jahanianc559f3f2009-03-05 22:39:55 +00005419}
5420
Fariborz Jahanian0b1ccdc2009-01-21 23:34:32 +00005421llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) {
Daniel Dunbarcb515c82008-08-12 03:39:23 +00005422 llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
Chris Lattner3def9ae2012-02-06 22:16:34 +00005423 // FIXME: Avoid std::string in "Sel.getAsString()"
Daniel Dunbarc2d4b622009-03-09 21:49:58 +00005424 if (!Entry)
Saleem Abdulrasool271106c2016-09-16 23:41:13 +00005425 Entry = CreateCStringLiteral(Sel.getAsString(), ObjCLabelType::MethodVarName);
Owen Anderson170229f2009-07-14 23:10:40 +00005426 return getConstantGEP(VMContext, Entry, 0, 0);
Daniel Dunbarb036db82008-08-13 03:21:16 +00005427}
5428
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00005429// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian0b1ccdc2009-01-21 23:34:32 +00005430llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) {
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00005431 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
5432}
5433
Daniel Dunbarf5c18462009-04-20 06:54:31 +00005434llvm::Constant *CGObjCCommonMac::GetMethodVarType(const FieldDecl *Field) {
Devang Patel4b6e4bb2009-03-04 18:21:39 +00005435 std::string TypeStr;
5436 CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
5437
5438 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
Daniel Dunbarc2d4b622009-03-09 21:49:58 +00005439 if (!Entry)
Saleem Abdulrasool271106c2016-09-16 23:41:13 +00005440 Entry = CreateCStringLiteral(TypeStr, ObjCLabelType::MethodVarType);
Owen Anderson170229f2009-07-14 23:10:40 +00005441 return getConstantGEP(VMContext, Entry, 0, 0);
Daniel Dunbarcb515c82008-08-12 03:39:23 +00005442}
5443
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005444llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D,
5445 bool Extended) {
John McCall843dfcc2016-11-29 21:57:00 +00005446 std::string TypeStr =
5447 CGM.getContext().getObjCEncodingForMethodDecl(D, Extended);
Devang Patel4b6e4bb2009-03-04 18:21:39 +00005448
5449 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
Daniel Dunbar3241fae2009-04-14 23:14:47 +00005450 if (!Entry)
Saleem Abdulrasool271106c2016-09-16 23:41:13 +00005451 Entry = CreateCStringLiteral(TypeStr, ObjCLabelType::MethodVarType);
Owen Anderson170229f2009-07-14 23:10:40 +00005452 return getConstantGEP(VMContext, Entry, 0, 0);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00005453}
5454
Daniel Dunbar80a840b2008-08-23 00:19:03 +00005455// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian0b1ccdc2009-01-21 23:34:32 +00005456llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) {
Daniel Dunbar80a840b2008-08-23 00:19:03 +00005457 llvm::GlobalVariable *&Entry = PropertyNames[Ident];
Daniel Dunbarc2d4b622009-03-09 21:49:58 +00005458 if (!Entry)
Saleem Abdulrasool271106c2016-09-16 23:41:13 +00005459 Entry = CreateCStringLiteral(Ident->getName(), ObjCLabelType::PropertyName);
Owen Anderson170229f2009-07-14 23:10:40 +00005460 return getConstantGEP(VMContext, Entry, 0, 0);
Daniel Dunbar80a840b2008-08-23 00:19:03 +00005461}
5462
5463// FIXME: Merge into a single cstring creation function.
Daniel Dunbar4932b362008-08-28 04:38:10 +00005464// FIXME: This Decl should be more precise.
Daniel Dunbarc2d4b622009-03-09 21:49:58 +00005465llvm::Constant *
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005466CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
5467 const Decl *Container) {
John McCall843dfcc2016-11-29 21:57:00 +00005468 std::string TypeStr =
5469 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container);
Daniel Dunbar80a840b2008-08-23 00:19:03 +00005470 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
5471}
5472
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005473void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D,
Fariborz Jahanian0b1ccdc2009-01-21 23:34:32 +00005474 const ObjCContainerDecl *CD,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005475 SmallVectorImpl<char> &Name) {
Daniel Dunbard2386812009-10-19 01:21:19 +00005476 llvm::raw_svector_ostream OS(Name);
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +00005477 assert (CD && "Missing container decl in GetNameForMethod");
Daniel Dunbard2386812009-10-19 01:21:19 +00005478 OS << '\01' << (D->isInstanceMethod() ? '-' : '+')
5479 << '[' << CD->getName();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005480 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbard2386812009-10-19 01:21:19 +00005481 dyn_cast<ObjCCategoryImplDecl>(D->getDeclContext()))
Benjamin Kramer2f569922012-02-07 11:57:45 +00005482 OS << '(' << *CID << ')';
Daniel Dunbard2386812009-10-19 01:21:19 +00005483 OS << ' ' << D->getSelector().getAsString() << ']';
Daniel Dunbara94ecd22008-08-16 03:19:19 +00005484}
5485
Daniel Dunbar3ad53482008-08-11 21:35:06 +00005486void CGObjCMac::FinishModule() {
Daniel Dunbar7bd00bd2008-08-12 06:48:42 +00005487 EmitModuleInfo();
5488
Daniel Dunbarc475d422008-10-29 22:36:39 +00005489 // Emit the dummy bodies for any protocols which were referenced but
5490 // never defined.
John McCall176f8922016-11-30 02:39:18 +00005491 for (auto &entry : Protocols) {
5492 llvm::GlobalVariable *global = entry.second;
5493 if (global->hasInitializer())
Daniel Dunbarc475d422008-10-29 22:36:39 +00005494 continue;
Daniel Dunbar7bd00bd2008-08-12 06:48:42 +00005495
John McCall176f8922016-11-30 02:39:18 +00005496 ConstantInitBuilder builder(CGM);
5497 auto values = builder.beginStruct(ObjCTypes.ProtocolTy);
5498 values.addNullPointer(ObjCTypes.ProtocolExtensionPtrTy);
5499 values.add(GetClassName(entry.first->getName()));
5500 values.addNullPointer(ObjCTypes.ProtocolListPtrTy);
5501 values.addNullPointer(ObjCTypes.MethodDescriptionListPtrTy);
5502 values.addNullPointer(ObjCTypes.MethodDescriptionListPtrTy);
5503 values.finishAndSetAsInitializer(global);
5504 CGM.addCompilerUsedGlobal(global);
Daniel Dunbarc475d422008-10-29 22:36:39 +00005505 }
5506
Daniel Dunbarc61d0e92008-08-25 06:02:07 +00005507 // Add assembler directives to add lazy undefined symbol references
5508 // for classes which are referenced but not defined. This is
5509 // important for correct linker interaction.
Daniel Dunbard027a922009-09-07 00:20:42 +00005510 //
5511 // FIXME: It would be nice if we had an LLVM construct for this.
Saleem Abdulrasool62c07eb2016-09-12 21:15:23 +00005512 if ((!LazySymbols.empty() || !DefinedSymbols.empty()) &&
5513 CGM.getTriple().isOSBinFormatMachO()) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00005514 SmallString<256> Asm;
Daniel Dunbard027a922009-09-07 00:20:42 +00005515 Asm += CGM.getModule().getModuleInlineAsm();
5516 if (!Asm.empty() && Asm.back() != '\n')
5517 Asm += '\n';
Daniel Dunbarc61d0e92008-08-25 06:02:07 +00005518
Daniel Dunbard027a922009-09-07 00:20:42 +00005519 llvm::raw_svector_ostream OS(Asm);
Saleem Abdulrasool39217d42016-09-16 14:24:26 +00005520 for (const auto *Sym : DefinedSymbols)
Saleem Abdulrasool62c07eb2016-09-12 21:15:23 +00005521 OS << "\t.objc_class_name_" << Sym->getName() << "=0\n"
5522 << "\t.globl .objc_class_name_" << Sym->getName() << "\n";
Saleem Abdulrasool39217d42016-09-16 14:24:26 +00005523 for (const auto *Sym : LazySymbols)
Saleem Abdulrasool62c07eb2016-09-12 21:15:23 +00005524 OS << "\t.lazy_reference .objc_class_name_" << Sym->getName() << "\n";
5525 for (const auto &Category : DefinedCategoryNames)
5526 OS << "\t.objc_category_name_" << Category << "=0\n"
5527 << "\t.globl .objc_category_name_" << Category << "\n";
Fariborz Jahanian9adb2e62010-06-21 22:05:18 +00005528
Daniel Dunbard027a922009-09-07 00:20:42 +00005529 CGM.getModule().setModuleInlineAsm(OS.str());
Daniel Dunbarc61d0e92008-08-25 06:02:07 +00005530 }
Daniel Dunbar3ad53482008-08-11 21:35:06 +00005531}
5532
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005533CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm)
Saleem Abdulrasool4f515a62016-07-13 02:58:44 +00005534 : CGObjCCommonMac(cgm), ObjCTypes(cgm), ObjCEmptyCacheVar(nullptr),
5535 ObjCEmptyVtableVar(nullptr) {
Fariborz Jahanian279eda62009-01-21 22:04:16 +00005536 ObjCABI = 2;
5537}
5538
Daniel Dunbar3ad53482008-08-11 21:35:06 +00005539/* *** */
5540
Fariborz Jahanian279eda62009-01-21 22:04:16 +00005541ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm)
Craig Topper8a13c412014-05-21 05:09:00 +00005542 : VMContext(cgm.getLLVMContext()), CGM(cgm), ExternalProtocolPtrTy(nullptr)
Douglas Gregora95f9aa2012-01-17 23:38:32 +00005543{
Daniel Dunbar7bd00bd2008-08-12 06:48:42 +00005544 CodeGen::CodeGenTypes &Types = CGM.getTypes();
5545 ASTContext &Ctx = CGM.getContext();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005546
John McCall176f8922016-11-30 02:39:18 +00005547 ShortTy = cast<llvm::IntegerType>(Types.ConvertType(Ctx.ShortTy));
5548 IntTy = CGM.IntTy;
5549 LongTy = cast<llvm::IntegerType>(Types.ConvertType(Ctx.LongTy));
Chris Lattnerece04092012-02-07 00:39:47 +00005550 Int8PtrTy = CGM.Int8PtrTy;
5551 Int8PtrPtrTy = CGM.Int8PtrPtrTy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005552
Tim Northover238b5082014-03-29 13:42:40 +00005553 // arm64 targets use "int" ivar offset variables. All others,
5554 // including OS X x86_64 and Windows x86_64, use "long" ivar offsets.
Tim Northover40956e62014-07-23 12:32:58 +00005555 if (CGM.getTarget().getTriple().getArch() == llvm::Triple::aarch64)
Tim Northover238b5082014-03-29 13:42:40 +00005556 IvarOffsetVarTy = IntTy;
5557 else
5558 IvarOffsetVarTy = LongTy;
5559
John McCall176f8922016-11-30 02:39:18 +00005560 ObjectPtrTy =
5561 cast<llvm::PointerType>(Types.ConvertType(Ctx.getObjCIdType()));
5562 PtrObjectPtrTy =
5563 llvm::PointerType::getUnqual(ObjectPtrTy);
5564 SelectorPtrTy =
5565 cast<llvm::PointerType>(Types.ConvertType(Ctx.getObjCSelType()));
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005566
Fariborz Jahanian279eda62009-01-21 22:04:16 +00005567 // I'm not sure I like this. The implicit coordination is a bit
5568 // gross. We should solve this in a reasonable fashion because this
5569 // is a pretty common task (match some runtime data structure with
5570 // an LLVM data structure).
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005571
Fariborz Jahanian279eda62009-01-21 22:04:16 +00005572 // FIXME: This is leaked.
5573 // FIXME: Merge with rewriter code?
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005574
Fariborz Jahanian279eda62009-01-21 22:04:16 +00005575 // struct _objc_super {
5576 // id self;
5577 // Class cls;
5578 // }
Abramo Bagnara6150c882010-05-11 21:36:43 +00005579 RecordDecl *RD = RecordDecl::Create(Ctx, TTK_Struct,
Daniel Dunbar0c005372010-04-29 16:29:11 +00005580 Ctx.getTranslationUnitDecl(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00005581 SourceLocation(), SourceLocation(),
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005582 &Ctx.Idents.get("_objc_super"));
Craig Topper8a13c412014-05-21 05:09:00 +00005583 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), SourceLocation(),
5584 nullptr, Ctx.getObjCIdType(), nullptr, nullptr,
5585 false, ICIS_NoInit));
5586 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), SourceLocation(),
5587 nullptr, Ctx.getObjCClassType(), nullptr,
5588 nullptr, false, ICIS_NoInit));
Douglas Gregord5058122010-02-11 01:19:42 +00005589 RD->completeDefinition();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005590
Fariborz Jahanian279eda62009-01-21 22:04:16 +00005591 SuperCTy = Ctx.getTagDeclType(RD);
5592 SuperPtrCTy = Ctx.getPointerType(SuperCTy);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005593
Fariborz Jahanian279eda62009-01-21 22:04:16 +00005594 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005595 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
5596
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005597 // struct _prop_t {
5598 // char *name;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005599 // char *attributes;
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005600 // }
Serge Guelton1d993272017-05-09 19:31:30 +00005601 PropertyTy = llvm::StructType::create("struct._prop_t", Int8PtrTy, Int8PtrTy);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005602
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005603 // struct _prop_list_t {
Fariborz Jahanian0232c052009-01-23 01:46:23 +00005604 // uint32_t entsize; // sizeof(struct _prop_t)
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005605 // uint32_t count_of_properties;
Fariborz Jahanian0232c052009-01-23 01:46:23 +00005606 // struct _prop_t prop_list[count_of_properties];
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005607 // }
Serge Guelton1d993272017-05-09 19:31:30 +00005608 PropertyListTy = llvm::StructType::create(
5609 "struct._prop_list_t", IntTy, IntTy, llvm::ArrayType::get(PropertyTy, 0));
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005610 // struct _prop_list_t *
Owen Anderson9793f0e2009-07-29 22:16:19 +00005611 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005612
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005613 // struct _objc_method {
5614 // SEL _cmd;
5615 // char *method_type;
5616 // char *_imp;
5617 // }
Serge Guelton1d993272017-05-09 19:31:30 +00005618 MethodTy = llvm::StructType::create("struct._objc_method", SelectorPtrTy,
5619 Int8PtrTy, Int8PtrTy);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005620
Fariborz Jahanian0232c052009-01-23 01:46:23 +00005621 // struct _objc_cache *
Chris Lattner5ec04a52011-08-12 17:43:31 +00005622 CacheTy = llvm::StructType::create(VMContext, "struct._objc_cache");
Owen Anderson9793f0e2009-07-29 22:16:19 +00005623 CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
Fariborz Jahanian279eda62009-01-21 22:04:16 +00005624}
Daniel Dunbar7bd00bd2008-08-12 06:48:42 +00005625
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005626ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
Mike Stump11289f42009-09-09 15:08:12 +00005627 : ObjCCommonTypesHelper(cgm) {
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005628 // struct _objc_method_description {
5629 // SEL name;
5630 // char *types;
5631 // }
Serge Guelton1d993272017-05-09 19:31:30 +00005632 MethodDescriptionTy = llvm::StructType::create(
5633 "struct._objc_method_description", SelectorPtrTy, Int8PtrTy);
Daniel Dunbarb036db82008-08-13 03:21:16 +00005634
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005635 // struct _objc_method_description_list {
5636 // int count;
5637 // struct _objc_method_description[1];
5638 // }
Serge Guelton1d993272017-05-09 19:31:30 +00005639 MethodDescriptionListTy =
5640 llvm::StructType::create("struct._objc_method_description_list", IntTy,
5641 llvm::ArrayType::get(MethodDescriptionTy, 0));
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005642
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005643 // struct _objc_method_description_list *
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005644 MethodDescriptionListPtrTy =
Owen Anderson9793f0e2009-07-29 22:16:19 +00005645 llvm::PointerType::getUnqual(MethodDescriptionListTy);
Daniel Dunbarb036db82008-08-13 03:21:16 +00005646
Daniel Dunbarb036db82008-08-13 03:21:16 +00005647 // Protocol description structures
5648
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005649 // struct _objc_protocol_extension {
5650 // uint32_t size; // sizeof(struct _objc_protocol_extension)
5651 // struct _objc_method_description_list *optional_instance_methods;
5652 // struct _objc_method_description_list *optional_class_methods;
5653 // struct _objc_property_list *instance_properties;
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005654 // const char ** extendedMethodTypes;
Manman Rence7bff52016-01-29 23:46:55 +00005655 // struct _objc_property_list *class_properties;
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005656 // }
Serge Guelton1d993272017-05-09 19:31:30 +00005657 ProtocolExtensionTy = llvm::StructType::create(
5658 "struct._objc_protocol_extension", IntTy, MethodDescriptionListPtrTy,
5659 MethodDescriptionListPtrTy, PropertyListPtrTy, Int8PtrPtrTy,
5660 PropertyListPtrTy);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005661
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005662 // struct _objc_protocol_extension *
Owen Anderson9793f0e2009-07-29 22:16:19 +00005663 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
Daniel Dunbarb036db82008-08-13 03:21:16 +00005664
Daniel Dunbarc475d422008-10-29 22:36:39 +00005665 // Handle recursive construction of Protocol and ProtocolList types
Daniel Dunbarb036db82008-08-13 03:21:16 +00005666
Chris Lattnera5f58b02011-07-09 17:41:47 +00005667 ProtocolTy =
Chris Lattner5ec04a52011-08-12 17:43:31 +00005668 llvm::StructType::create(VMContext, "struct._objc_protocol");
Daniel Dunbarb036db82008-08-13 03:21:16 +00005669
Chris Lattnera5f58b02011-07-09 17:41:47 +00005670 ProtocolListTy =
Chris Lattner5ec04a52011-08-12 17:43:31 +00005671 llvm::StructType::create(VMContext, "struct._objc_protocol_list");
Serge Guelton1d993272017-05-09 19:31:30 +00005672 ProtocolListTy->setBody(llvm::PointerType::getUnqual(ProtocolListTy), LongTy,
5673 llvm::ArrayType::get(ProtocolTy, 0));
Daniel Dunbarb036db82008-08-13 03:21:16 +00005674
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005675 // struct _objc_protocol {
5676 // struct _objc_protocol_extension *isa;
5677 // char *protocol_name;
5678 // struct _objc_protocol **_objc_protocol_list;
5679 // struct _objc_method_description_list *instance_methods;
5680 // struct _objc_method_description_list *class_methods;
5681 // }
Chris Lattnera5f58b02011-07-09 17:41:47 +00005682 ProtocolTy->setBody(ProtocolExtensionPtrTy, Int8PtrTy,
5683 llvm::PointerType::getUnqual(ProtocolListTy),
Serge Guelton1d993272017-05-09 19:31:30 +00005684 MethodDescriptionListPtrTy, MethodDescriptionListPtrTy);
Daniel Dunbarb036db82008-08-13 03:21:16 +00005685
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005686 // struct _objc_protocol_list *
Owen Anderson9793f0e2009-07-29 22:16:19 +00005687 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
Daniel Dunbarb036db82008-08-13 03:21:16 +00005688
Owen Anderson9793f0e2009-07-29 22:16:19 +00005689 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00005690
5691 // Class description structures
5692
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005693 // struct _objc_ivar {
5694 // char *ivar_name;
5695 // char *ivar_type;
5696 // int ivar_offset;
5697 // }
Serge Guelton1d993272017-05-09 19:31:30 +00005698 IvarTy = llvm::StructType::create("struct._objc_ivar", Int8PtrTy, Int8PtrTy,
5699 IntTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00005700
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005701 // struct _objc_ivar_list *
Chris Lattnera5f58b02011-07-09 17:41:47 +00005702 IvarListTy =
Chris Lattner5ec04a52011-08-12 17:43:31 +00005703 llvm::StructType::create(VMContext, "struct._objc_ivar_list");
Owen Anderson9793f0e2009-07-29 22:16:19 +00005704 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00005705
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005706 // struct _objc_method_list *
Chris Lattnera5f58b02011-07-09 17:41:47 +00005707 MethodListTy =
Chris Lattner5ec04a52011-08-12 17:43:31 +00005708 llvm::StructType::create(VMContext, "struct._objc_method_list");
Owen Anderson9793f0e2009-07-29 22:16:19 +00005709 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00005710
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005711 // struct _objc_class_extension *
Serge Guelton1d993272017-05-09 19:31:30 +00005712 ClassExtensionTy = llvm::StructType::create(
5713 "struct._objc_class_extension", IntTy, Int8PtrTy, PropertyListPtrTy);
Owen Anderson9793f0e2009-07-29 22:16:19 +00005714 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00005715
Chris Lattner5ec04a52011-08-12 17:43:31 +00005716 ClassTy = llvm::StructType::create(VMContext, "struct._objc_class");
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00005717
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005718 // struct _objc_class {
5719 // Class isa;
5720 // Class super_class;
5721 // char *name;
5722 // long version;
5723 // long info;
5724 // long instance_size;
5725 // struct _objc_ivar_list *ivars;
5726 // struct _objc_method_list *methods;
5727 // struct _objc_cache *cache;
5728 // struct _objc_protocol_list *protocols;
5729 // char *ivar_layout;
5730 // struct _objc_class_ext *ext;
5731 // };
Chris Lattnera5f58b02011-07-09 17:41:47 +00005732 ClassTy->setBody(llvm::PointerType::getUnqual(ClassTy),
Serge Guelton1d993272017-05-09 19:31:30 +00005733 llvm::PointerType::getUnqual(ClassTy), Int8PtrTy, LongTy,
5734 LongTy, LongTy, IvarListPtrTy, MethodListPtrTy, CachePtrTy,
5735 ProtocolListPtrTy, Int8PtrTy, ClassExtensionPtrTy);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005736
Owen Anderson9793f0e2009-07-29 22:16:19 +00005737 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00005738
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005739 // struct _objc_category {
5740 // char *category_name;
5741 // char *class_name;
5742 // struct _objc_method_list *instance_method;
5743 // struct _objc_method_list *class_method;
Manman Renb3736772016-01-25 22:37:47 +00005744 // struct _objc_protocol_list *protocols;
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005745 // uint32_t size; // sizeof(struct _objc_category)
5746 // struct _objc_property_list *instance_properties;// category's @property
Manman Ren96df0b32016-01-29 23:45:01 +00005747 // struct _objc_property_list *class_properties;
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005748 // }
Serge Guelton1d993272017-05-09 19:31:30 +00005749 CategoryTy = llvm::StructType::create(
5750 "struct._objc_category", Int8PtrTy, Int8PtrTy, MethodListPtrTy,
5751 MethodListPtrTy, ProtocolListPtrTy, IntTy, PropertyListPtrTy,
5752 PropertyListPtrTy);
Daniel Dunbar938a77f2008-08-22 20:34:54 +00005753
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00005754 // Global metadata structures
5755
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005756 // struct _objc_symtab {
5757 // long sel_ref_cnt;
5758 // SEL *refs;
5759 // short cls_def_cnt;
5760 // short cat_def_cnt;
5761 // char *defs[cls_def_cnt + cat_def_cnt];
5762 // }
Serge Guelton1d993272017-05-09 19:31:30 +00005763 SymtabTy = llvm::StructType::create("struct._objc_symtab", LongTy,
5764 SelectorPtrTy, ShortTy, ShortTy,
5765 llvm::ArrayType::get(Int8PtrTy, 0));
Owen Anderson9793f0e2009-07-29 22:16:19 +00005766 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00005767
Fariborz Jahanianeee54df2009-01-22 00:37:21 +00005768 // struct _objc_module {
5769 // long version;
5770 // long size; // sizeof(struct _objc_module)
5771 // char *name;
5772 // struct _objc_symtab* symtab;
5773 // }
Serge Guelton1d993272017-05-09 19:31:30 +00005774 ModuleTy = llvm::StructType::create("struct._objc_module", LongTy, LongTy,
5775 Int8PtrTy, SymtabPtrTy);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005776
Mike Stump18bb9282009-05-16 07:57:57 +00005777 // FIXME: This is the size of the setjmp buffer and should be target
5778 // specific. 18 is what's used on 32-bit X86.
Anders Carlsson9ff22482008-09-09 10:10:21 +00005779 uint64_t SetJmpBufferSize = 18;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005780
Anders Carlsson9ff22482008-09-09 10:10:21 +00005781 // Exceptions
Chris Lattnerece04092012-02-07 00:39:47 +00005782 llvm::Type *StackPtrTy = llvm::ArrayType::get(CGM.Int8PtrTy, 4);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005783
Serge Guelton1d993272017-05-09 19:31:30 +00005784 ExceptionDataTy = llvm::StructType::create(
5785 "struct._objc_exception_data",
5786 llvm::ArrayType::get(CGM.Int32Ty, SetJmpBufferSize), StackPtrTy);
Daniel Dunbar8b8683f2008-08-12 00:12:39 +00005787}
5788
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005789ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm)
Mike Stump11289f42009-09-09 15:08:12 +00005790 : ObjCCommonTypesHelper(cgm) {
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005791 // struct _method_list_t {
5792 // uint32_t entsize; // sizeof(struct _objc_method)
5793 // uint32_t method_count;
5794 // struct _objc_method method_list[method_count];
5795 // }
Chris Lattnera5f58b02011-07-09 17:41:47 +00005796 MethodListnfABITy =
Serge Guelton1d993272017-05-09 19:31:30 +00005797 llvm::StructType::create("struct.__method_list_t", IntTy, IntTy,
5798 llvm::ArrayType::get(MethodTy, 0));
Fariborz Jahanian0232c052009-01-23 01:46:23 +00005799 // struct method_list_t *
Owen Anderson9793f0e2009-07-29 22:16:19 +00005800 MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005801
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005802 // struct _protocol_t {
5803 // id isa; // NULL
5804 // const char * const protocol_name;
Fariborz Jahanian0232c052009-01-23 01:46:23 +00005805 // const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005806 // const struct method_list_t * const instance_methods;
5807 // const struct method_list_t * const class_methods;
5808 // const struct method_list_t *optionalInstanceMethods;
5809 // const struct method_list_t *optionalClassMethods;
Fariborz Jahanian0232c052009-01-23 01:46:23 +00005810 // const struct _prop_list_t * properties;
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005811 // const uint32_t size; // sizeof(struct _protocol_t)
5812 // const uint32_t flags; // = 0
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005813 // const char ** extendedMethodTypes;
Fariborz Jahanian6a9c46b2015-03-31 22:22:40 +00005814 // const char *demangledName;
Manman Rence7bff52016-01-29 23:46:55 +00005815 // const struct _prop_list_t * class_properties;
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005816 // }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005817
Fariborz Jahanian0232c052009-01-23 01:46:23 +00005818 // Holder for struct _protocol_list_t *
Chris Lattnera5f58b02011-07-09 17:41:47 +00005819 ProtocolListnfABITy =
Chris Lattner5ec04a52011-08-12 17:43:31 +00005820 llvm::StructType::create(VMContext, "struct._objc_protocol_list");
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005821
Serge Guelton1d993272017-05-09 19:31:30 +00005822 ProtocolnfABITy = llvm::StructType::create(
5823 "struct._protocol_t", ObjectPtrTy, Int8PtrTy,
5824 llvm::PointerType::getUnqual(ProtocolListnfABITy), MethodListnfABIPtrTy,
5825 MethodListnfABIPtrTy, MethodListnfABIPtrTy, MethodListnfABIPtrTy,
5826 PropertyListPtrTy, IntTy, IntTy, Int8PtrPtrTy, Int8PtrTy,
5827 PropertyListPtrTy);
Daniel Dunbar8de90f02009-02-15 07:36:20 +00005828
5829 // struct _protocol_t*
Owen Anderson9793f0e2009-07-29 22:16:19 +00005830 ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005831
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00005832 // struct _protocol_list_t {
Fariborz Jahanian0232c052009-01-23 01:46:23 +00005833 // long protocol_count; // Note, this is 32/64 bit
Daniel Dunbar8de90f02009-02-15 07:36:20 +00005834 // struct _protocol_t *[protocol_count];
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005835 // }
Chris Lattnera5f58b02011-07-09 17:41:47 +00005836 ProtocolListnfABITy->setBody(LongTy,
Serge Guelton1d993272017-05-09 19:31:30 +00005837 llvm::ArrayType::get(ProtocolnfABIPtrTy, 0));
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005838
Fariborz Jahanian0232c052009-01-23 01:46:23 +00005839 // struct _objc_protocol_list*
Owen Anderson9793f0e2009-07-29 22:16:19 +00005840 ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005841
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005842 // struct _ivar_t {
Tim Northover238b5082014-03-29 13:42:40 +00005843 // unsigned [long] int *offset; // pointer to ivar offset location
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005844 // char *name;
5845 // char *type;
5846 // uint32_t alignment;
5847 // uint32_t size;
5848 // }
Tim Northover238b5082014-03-29 13:42:40 +00005849 IvarnfABITy = llvm::StructType::create(
5850 "struct._ivar_t", llvm::PointerType::getUnqual(IvarOffsetVarTy),
Serge Guelton1d993272017-05-09 19:31:30 +00005851 Int8PtrTy, Int8PtrTy, IntTy, IntTy);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005852
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005853 // struct _ivar_list_t {
5854 // uint32 entsize; // sizeof(struct _ivar_t)
5855 // uint32 count;
5856 // struct _iver_t list[count];
5857 // }
Chris Lattnera5f58b02011-07-09 17:41:47 +00005858 IvarListnfABITy =
Serge Guelton1d993272017-05-09 19:31:30 +00005859 llvm::StructType::create("struct._ivar_list_t", IntTy, IntTy,
5860 llvm::ArrayType::get(IvarnfABITy, 0));
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005861
Owen Anderson9793f0e2009-07-29 22:16:19 +00005862 IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005863
Fariborz Jahanian0232c052009-01-23 01:46:23 +00005864 // struct _class_ro_t {
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005865 // uint32_t const flags;
5866 // uint32_t const instanceStart;
5867 // uint32_t const instanceSize;
5868 // uint32_t const reserved; // only when building for 64bit targets
5869 // const uint8_t * const ivarLayout;
5870 // const char *const name;
5871 // const struct _method_list_t * const baseMethods;
5872 // const struct _objc_protocol_list *const baseProtocols;
5873 // const struct _ivar_list_t *const ivars;
5874 // const uint8_t * const weakIvarLayout;
5875 // const struct _prop_list_t * const properties;
5876 // }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005877
Fariborz Jahanian0232c052009-01-23 01:46:23 +00005878 // FIXME. Add 'reserved' field in 64bit abi mode!
Serge Guelton1d993272017-05-09 19:31:30 +00005879 ClassRonfABITy = llvm::StructType::create(
5880 "struct._class_ro_t", IntTy, IntTy, IntTy, Int8PtrTy, Int8PtrTy,
5881 MethodListnfABIPtrTy, ProtocolListnfABIPtrTy, IvarListnfABIPtrTy,
5882 Int8PtrTy, PropertyListPtrTy);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005883
Fariborz Jahanian0232c052009-01-23 01:46:23 +00005884 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
Chris Lattnera5f58b02011-07-09 17:41:47 +00005885 llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy };
John McCall9dc0db22011-05-15 01:53:33 +00005886 ImpnfABITy = llvm::FunctionType::get(ObjectPtrTy, params, false)
5887 ->getPointerTo();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005888
Fariborz Jahanian0232c052009-01-23 01:46:23 +00005889 // struct _class_t {
5890 // struct _class_t *isa;
5891 // struct _class_t * const superclass;
5892 // void *cache;
5893 // IMP *vtable;
5894 // struct class_ro_t *ro;
5895 // }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005896
Chris Lattner5ec04a52011-08-12 17:43:31 +00005897 ClassnfABITy = llvm::StructType::create(VMContext, "struct._class_t");
Chris Lattnera5f58b02011-07-09 17:41:47 +00005898 ClassnfABITy->setBody(llvm::PointerType::getUnqual(ClassnfABITy),
Serge Guelton1d993272017-05-09 19:31:30 +00005899 llvm::PointerType::getUnqual(ClassnfABITy), CachePtrTy,
Chris Lattnera5f58b02011-07-09 17:41:47 +00005900 llvm::PointerType::getUnqual(ImpnfABITy),
Serge Guelton1d993272017-05-09 19:31:30 +00005901 llvm::PointerType::getUnqual(ClassRonfABITy));
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005902
Fariborz Jahanian71394042009-01-23 23:53:38 +00005903 // LLVM for struct _class_t *
Owen Anderson9793f0e2009-07-29 22:16:19 +00005904 ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005905
Fariborz Jahanian0232c052009-01-23 01:46:23 +00005906 // struct _category_t {
5907 // const char * const name;
5908 // struct _class_t *const cls;
5909 // const struct _method_list_t * const instance_methods;
5910 // const struct _method_list_t * const class_methods;
5911 // const struct _protocol_list_t * const protocols;
5912 // const struct _prop_list_t * const properties;
Manman Ren96df0b32016-01-29 23:45:01 +00005913 // const struct _prop_list_t * const class_properties;
Manman Ren42ff3902016-02-24 17:49:50 +00005914 // const uint32_t size;
Fariborz Jahanian5a63e4c2009-01-23 17:41:22 +00005915 // }
Serge Guelton1d993272017-05-09 19:31:30 +00005916 CategorynfABITy = llvm::StructType::create(
5917 "struct._category_t", Int8PtrTy, ClassnfABIPtrTy, MethodListnfABIPtrTy,
5918 MethodListnfABIPtrTy, ProtocolListnfABIPtrTy, PropertyListPtrTy,
5919 PropertyListPtrTy, IntTy);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005920
Fariborz Jahanian82c72e12009-02-03 23:49:23 +00005921 // New types for nonfragile abi messaging.
Fariborz Jahaniane4dc35d2009-02-04 20:42:28 +00005922 CodeGen::CodeGenTypes &Types = CGM.getTypes();
5923 ASTContext &Ctx = CGM.getContext();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005924
Fariborz Jahanian82c72e12009-02-03 23:49:23 +00005925 // MessageRefTy - LLVM for:
5926 // struct _message_ref_t {
5927 // IMP messenger;
5928 // SEL name;
5929 // };
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005930
Fariborz Jahaniane4dc35d2009-02-04 20:42:28 +00005931 // First the clang type for struct _message_ref_t
Abramo Bagnara6150c882010-05-11 21:36:43 +00005932 RecordDecl *RD = RecordDecl::Create(Ctx, TTK_Struct,
Daniel Dunbar0c005372010-04-29 16:29:11 +00005933 Ctx.getTranslationUnitDecl(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00005934 SourceLocation(), SourceLocation(),
Fariborz Jahaniane4dc35d2009-02-04 20:42:28 +00005935 &Ctx.Idents.get("_message_ref_t"));
Craig Topper8a13c412014-05-21 05:09:00 +00005936 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), SourceLocation(),
5937 nullptr, Ctx.VoidPtrTy, nullptr, nullptr, false,
Richard Smith2b013182012-06-10 03:12:00 +00005938 ICIS_NoInit));
Craig Topper8a13c412014-05-21 05:09:00 +00005939 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), SourceLocation(),
5940 nullptr, Ctx.getObjCSelType(), nullptr, nullptr,
5941 false, ICIS_NoInit));
Douglas Gregord5058122010-02-11 01:19:42 +00005942 RD->completeDefinition();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005943
Fariborz Jahaniane4dc35d2009-02-04 20:42:28 +00005944 MessageRefCTy = Ctx.getTagDeclType(RD);
5945 MessageRefCPtrTy = Ctx.getPointerType(MessageRefCTy);
5946 MessageRefTy = cast<llvm::StructType>(Types.ConvertType(MessageRefCTy));
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005947
Fariborz Jahanian82c72e12009-02-03 23:49:23 +00005948 // MessageRefPtrTy - LLVM for struct _message_ref_t*
Owen Anderson9793f0e2009-07-29 22:16:19 +00005949 MessageRefPtrTy = llvm::PointerType::getUnqual(MessageRefTy);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005950
Fariborz Jahanian82c72e12009-02-03 23:49:23 +00005951 // SuperMessageRefTy - LLVM for:
5952 // struct _super_message_ref_t {
5953 // SUPER_IMP messenger;
5954 // SEL name;
5955 // };
Serge Guelton1d993272017-05-09 19:31:30 +00005956 SuperMessageRefTy = llvm::StructType::create("struct._super_message_ref_t",
5957 ImpnfABITy, SelectorPtrTy);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005958
Fariborz Jahanian82c72e12009-02-03 23:49:23 +00005959 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005960 SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00005961
Daniel Dunbarb1559a42009-03-01 04:46:24 +00005962
5963 // struct objc_typeinfo {
5964 // const void** vtable; // objc_ehtype_vtable + 2
5965 // const char* name; // c++ typeinfo string
5966 // Class cls;
5967 // };
Serge Guelton1d993272017-05-09 19:31:30 +00005968 EHTypeTy = llvm::StructType::create("struct._objc_typeinfo",
5969 llvm::PointerType::getUnqual(Int8PtrTy),
5970 Int8PtrTy, ClassnfABIPtrTy);
Owen Anderson9793f0e2009-07-29 22:16:19 +00005971 EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy);
Daniel Dunbar8b8683f2008-08-12 00:12:39 +00005972}
5973
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005974llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() {
Fariborz Jahanian71394042009-01-23 23:53:38 +00005975 FinishNonFragileABIModule();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005976
Craig Topper8a13c412014-05-21 05:09:00 +00005977 return nullptr;
Fariborz Jahanian71394042009-01-23 23:53:38 +00005978}
5979
Saleem Abdulrasool1e6c4062016-05-16 05:06:49 +00005980void CGObjCNonFragileABIMac::AddModuleClassList(
5981 ArrayRef<llvm::GlobalValue *> Container, StringRef SymbolName,
5982 StringRef SectionName) {
Daniel Dunbar19573e72009-05-15 21:48:48 +00005983 unsigned NumClasses = Container.size();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005984
Daniel Dunbar19573e72009-05-15 21:48:48 +00005985 if (!NumClasses)
5986 return;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005987
Chris Lattner3def9ae2012-02-06 22:16:34 +00005988 SmallVector<llvm::Constant*, 8> Symbols(NumClasses);
Daniel Dunbar19573e72009-05-15 21:48:48 +00005989 for (unsigned i=0; i<NumClasses; i++)
Owen Andersonade90fd2009-07-29 18:54:39 +00005990 Symbols[i] = llvm::ConstantExpr::getBitCast(Container[i],
Daniel Dunbar19573e72009-05-15 21:48:48 +00005991 ObjCTypes.Int8PtrTy);
Chris Lattner3def9ae2012-02-06 22:16:34 +00005992 llvm::Constant *Init =
Owen Anderson9793f0e2009-07-29 22:16:19 +00005993 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Chris Lattner3def9ae2012-02-06 22:16:34 +00005994 Symbols.size()),
Daniel Dunbar19573e72009-05-15 21:48:48 +00005995 Symbols);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005996
Daniel Dunbar19573e72009-05-15 21:48:48 +00005997 llvm::GlobalVariable *GV =
Owen Andersonc10c8d32009-07-08 19:05:04 +00005998 new llvm::GlobalVariable(CGM.getModule(), Init->getType(), false,
Rafael Espindola5179a4e2014-02-27 19:01:11 +00005999 llvm::GlobalValue::PrivateLinkage,
Daniel Dunbar19573e72009-05-15 21:48:48 +00006000 Init,
Owen Andersonc10c8d32009-07-08 19:05:04 +00006001 SymbolName);
Micah Villmowdd31ca12012-10-08 16:25:52 +00006002 GV->setAlignment(CGM.getDataLayout().getABITypeAlignment(Init->getType()));
Daniel Dunbar19573e72009-05-15 21:48:48 +00006003 GV->setSection(SectionName);
Rafael Espindola060062a2014-03-06 22:15:10 +00006004 CGM.addCompilerUsedGlobal(GV);
Daniel Dunbar19573e72009-05-15 21:48:48 +00006005}
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006006
Fariborz Jahanian71394042009-01-23 23:53:38 +00006007void CGObjCNonFragileABIMac::FinishNonFragileABIModule() {
6008 // nonfragile abi has no module definition.
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006009
Daniel Dunbar19573e72009-05-15 21:48:48 +00006010 // Build list of all implemented class addresses in array
Fariborz Jahanian279abd32009-01-30 20:55:31 +00006011 // L_OBJC_LABEL_CLASS_$.
Fariborz Jahanianf322f2f2014-03-11 00:25:05 +00006012
6013 for (unsigned i=0, NumClasses=ImplementedClasses.size(); i<NumClasses; i++) {
6014 const ObjCInterfaceDecl *ID = ImplementedClasses[i];
6015 assert(ID);
6016 if (ObjCImplementationDecl *IMP = ID->getImplementation())
6017 // We are implementing a weak imported interface. Give it external linkage
Fariborz Jahanianbc94c942014-07-15 17:14:34 +00006018 if (ID->isWeakImported() && !IMP->isWeakImported()) {
Fariborz Jahanianf322f2f2014-03-11 00:25:05 +00006019 DefinedClasses[i]->setLinkage(llvm::GlobalVariable::ExternalLinkage);
Fariborz Jahanianbc94c942014-07-15 17:14:34 +00006020 DefinedMetaClasses[i]->setLinkage(llvm::GlobalVariable::ExternalLinkage);
6021 }
Fariborz Jahanianf322f2f2014-03-11 00:25:05 +00006022 }
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00006023
6024 AddModuleClassList(DefinedClasses, "OBJC_LABEL_CLASS_$",
Saleem Abdulrasool13d73d52017-06-03 16:18:09 +00006025 GetSectionName("__objc_classlist",
6026 "regular,no_dead_strip"));
Rafael Espindola554256c2014-02-26 22:25:45 +00006027
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00006028 AddModuleClassList(DefinedNonLazyClasses, "OBJC_LABEL_NONLAZY_CLASS_$",
Saleem Abdulrasool13d73d52017-06-03 16:18:09 +00006029 GetSectionName("__objc_nlclslist",
6030 "regular,no_dead_strip"));
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006031
Fariborz Jahanian279abd32009-01-30 20:55:31 +00006032 // Build list of all implemented category addresses in array
6033 // L_OBJC_LABEL_CATEGORY_$.
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00006034 AddModuleClassList(DefinedCategories, "OBJC_LABEL_CATEGORY_$",
Saleem Abdulrasool13d73d52017-06-03 16:18:09 +00006035 GetSectionName("__objc_catlist",
6036 "regular,no_dead_strip"));
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00006037 AddModuleClassList(DefinedNonLazyCategories, "OBJC_LABEL_NONLAZY_CATEGORY_$",
Saleem Abdulrasool13d73d52017-06-03 16:18:09 +00006038 GetSectionName("__objc_nlcatlist",
6039 "regular,no_dead_strip"));
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006040
Daniel Dunbar5e639272010-04-25 20:39:01 +00006041 EmitImageInfo();
Fariborz Jahanian71394042009-01-23 23:53:38 +00006042}
6043
John McCall9e8bb002011-05-14 03:10:52 +00006044/// isVTableDispatchedSelector - Returns true if SEL is not in the list of
6045/// VTableDispatchMethods; false otherwise. What this means is that
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006046/// except for the 19 selectors in the list, we generate 32bit-style
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +00006047/// message dispatch call for all the rest.
John McCall9e8bb002011-05-14 03:10:52 +00006048bool CGObjCNonFragileABIMac::isVTableDispatchedSelector(Selector Sel) {
6049 // At various points we've experimented with using vtable-based
6050 // dispatch for all methods.
Daniel Dunbarfca18c1b42010-04-24 17:56:46 +00006051 switch (CGM.getCodeGenOpts().getObjCDispatchMethod()) {
Daniel Dunbarfca18c1b42010-04-24 17:56:46 +00006052 case CodeGenOptions::Legacy:
Fariborz Jahaniandfb39832010-04-19 17:53:30 +00006053 return false;
John McCall9e8bb002011-05-14 03:10:52 +00006054 case CodeGenOptions::NonLegacy:
6055 return true;
Daniel Dunbarfca18c1b42010-04-24 17:56:46 +00006056 case CodeGenOptions::Mixed:
6057 break;
6058 }
6059
6060 // If so, see whether this selector is in the white-list of things which must
6061 // use the new dispatch convention. We lazily build a dense set for this.
John McCall9e8bb002011-05-14 03:10:52 +00006062 if (VTableDispatchMethods.empty()) {
6063 VTableDispatchMethods.insert(GetNullarySelector("alloc"));
6064 VTableDispatchMethods.insert(GetNullarySelector("class"));
6065 VTableDispatchMethods.insert(GetNullarySelector("self"));
6066 VTableDispatchMethods.insert(GetNullarySelector("isFlipped"));
6067 VTableDispatchMethods.insert(GetNullarySelector("length"));
6068 VTableDispatchMethods.insert(GetNullarySelector("count"));
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006069
John McCall9e8bb002011-05-14 03:10:52 +00006070 // These are vtable-based if GC is disabled.
6071 // Optimistically use vtable dispatch for hybrid compiles.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006072 if (CGM.getLangOpts().getGC() != LangOptions::GCOnly) {
John McCall9e8bb002011-05-14 03:10:52 +00006073 VTableDispatchMethods.insert(GetNullarySelector("retain"));
6074 VTableDispatchMethods.insert(GetNullarySelector("release"));
6075 VTableDispatchMethods.insert(GetNullarySelector("autorelease"));
6076 }
6077
6078 VTableDispatchMethods.insert(GetUnarySelector("allocWithZone"));
6079 VTableDispatchMethods.insert(GetUnarySelector("isKindOfClass"));
6080 VTableDispatchMethods.insert(GetUnarySelector("respondsToSelector"));
6081 VTableDispatchMethods.insert(GetUnarySelector("objectForKey"));
6082 VTableDispatchMethods.insert(GetUnarySelector("objectAtIndex"));
6083 VTableDispatchMethods.insert(GetUnarySelector("isEqualToString"));
6084 VTableDispatchMethods.insert(GetUnarySelector("isEqual"));
6085
6086 // These are vtable-based if GC is enabled.
6087 // Optimistically use vtable dispatch for hybrid compiles.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006088 if (CGM.getLangOpts().getGC() != LangOptions::NonGC) {
John McCall9e8bb002011-05-14 03:10:52 +00006089 VTableDispatchMethods.insert(GetNullarySelector("hash"));
6090 VTableDispatchMethods.insert(GetUnarySelector("addObject"));
Fangrui Song6907ce22018-07-30 19:24:48 +00006091
John McCall9e8bb002011-05-14 03:10:52 +00006092 // "countByEnumeratingWithState:objects:count"
6093 IdentifierInfo *KeyIdents[] = {
6094 &CGM.getContext().Idents.get("countByEnumeratingWithState"),
6095 &CGM.getContext().Idents.get("objects"),
6096 &CGM.getContext().Idents.get("count")
6097 };
6098 VTableDispatchMethods.insert(
6099 CGM.getContext().Selectors.getSelector(3, KeyIdents));
6100 }
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +00006101 }
Daniel Dunbarfca18c1b42010-04-24 17:56:46 +00006102
John McCall9e8bb002011-05-14 03:10:52 +00006103 return VTableDispatchMethods.count(Sel);
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +00006104}
6105
Fariborz Jahanian9e3ad522009-01-24 20:21:50 +00006106/// BuildClassRoTInitializer - generate meta-data for:
6107/// struct _class_ro_t {
6108/// uint32_t const flags;
6109/// uint32_t const instanceStart;
6110/// uint32_t const instanceSize;
6111/// uint32_t const reserved; // only when building for 64bit targets
6112/// const uint8_t * const ivarLayout;
6113/// const char *const name;
6114/// const struct _method_list_t * const baseMethods;
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006115/// const struct _protocol_list_t *const baseProtocols;
Fariborz Jahanian9e3ad522009-01-24 20:21:50 +00006116/// const struct _ivar_list_t *const ivars;
6117/// const uint8_t * const weakIvarLayout;
6118/// const struct _prop_list_t * const properties;
6119/// }
6120///
6121llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer(
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006122 unsigned flags,
6123 unsigned InstanceStart,
6124 unsigned InstanceSize,
6125 const ObjCImplementationDecl *ID) {
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006126 std::string ClassName = ID->getObjCRuntimeNameAsString();
John McCall31168b02011-06-15 23:02:42 +00006127
John McCall3fd13f062015-10-21 18:06:47 +00006128 CharUnits beginInstance = CharUnits::fromQuantity(InstanceStart);
6129 CharUnits endInstance = CharUnits::fromQuantity(InstanceSize);
6130
John McCall460ce582015-10-22 18:38:17 +00006131 bool hasMRCWeak = false;
David Blaikiebbafb8a2012-03-11 07:00:24 +00006132 if (CGM.getLangOpts().ObjCAutoRefCount)
John McCallef19dbb2012-10-17 04:53:23 +00006133 flags |= NonFragileABI_Class_CompiledByARC;
John McCall460ce582015-10-22 18:38:17 +00006134 else if ((hasMRCWeak = hasMRCWeakIvars(CGM, ID)))
6135 flags |= NonFragileABI_Class_HasMRCWeakIvars;
John McCall31168b02011-06-15 23:02:42 +00006136
John McCall176f8922016-11-30 02:39:18 +00006137 ConstantInitBuilder builder(CGM);
6138 auto values = builder.beginStruct(ObjCTypes.ClassRonfABITy);
6139
6140 values.addInt(ObjCTypes.IntTy, flags);
6141 values.addInt(ObjCTypes.IntTy, InstanceStart);
6142 values.addInt(ObjCTypes.IntTy, InstanceSize);
6143 values.add((flags & NonFragileABI_Class_Meta)
6144 ? GetIvarLayoutName(nullptr, ObjCTypes)
6145 : BuildStrongIvarLayout(ID, beginInstance, endInstance));
6146 values.add(GetClassName(ID->getObjCRuntimeNameAsString()));
6147
Fariborz Jahanian99113fd2009-01-26 21:38:32 +00006148 // const struct _method_list_t * const baseMethods;
John McCall176f8922016-11-30 02:39:18 +00006149 SmallVector<const ObjCMethodDecl*, 16> methods;
John McCallef19dbb2012-10-17 04:53:23 +00006150 if (flags & NonFragileABI_Class_Meta) {
John McCall176f8922016-11-30 02:39:18 +00006151 for (const auto *MD : ID->class_methods())
6152 methods.push_back(MD);
Fariborz Jahanian99113fd2009-01-26 21:38:32 +00006153 } else {
John McCall176f8922016-11-30 02:39:18 +00006154 for (const auto *MD : ID->instance_methods())
6155 methods.push_back(MD);
Aaron Ballmanf26acce2014-03-13 19:50:17 +00006156
Aaron Ballmand85eff42014-03-14 15:02:45 +00006157 for (const auto *PID : ID->property_impls()) {
Fariborz Jahaniand27a8202009-01-28 22:46:49 +00006158 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize){
6159 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006160
John McCall176f8922016-11-30 02:39:18 +00006161 if (auto MD = PD->getGetterMethodDecl())
6162 if (GetMethodDefinition(MD))
6163 methods.push_back(MD);
6164 if (auto MD = PD->getSetterMethodDecl())
6165 if (GetMethodDefinition(MD))
6166 methods.push_back(MD);
Fariborz Jahaniand27a8202009-01-28 22:46:49 +00006167 }
6168 }
Fariborz Jahanian99113fd2009-01-26 21:38:32 +00006169 }
Saleem Abdulrasoold48b0a32016-10-24 20:47:58 +00006170
John McCall176f8922016-11-30 02:39:18 +00006171 values.add(emitMethodList(ID->getObjCRuntimeNameAsString(),
6172 (flags & NonFragileABI_Class_Meta)
6173 ? MethodListType::ClassMethods
6174 : MethodListType::InstanceMethods,
6175 methods));
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006176
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006177 const ObjCInterfaceDecl *OID = ID->getClassInterface();
6178 assert(OID && "CGObjCNonFragileABIMac::BuildClassRoTInitializer");
John McCall176f8922016-11-30 02:39:18 +00006179 values.add(EmitProtocolList("\01l_OBJC_CLASS_PROTOCOLS_$_"
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006180 + OID->getObjCRuntimeNameAsString(),
John McCall176f8922016-11-30 02:39:18 +00006181 OID->all_referenced_protocol_begin(),
6182 OID->all_referenced_protocol_end()));
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006183
John McCallef19dbb2012-10-17 04:53:23 +00006184 if (flags & NonFragileABI_Class_Meta) {
John McCall176f8922016-11-30 02:39:18 +00006185 values.addNullPointer(ObjCTypes.IvarListnfABIPtrTy);
6186 values.add(GetIvarLayoutName(nullptr, ObjCTypes));
6187 values.add(EmitPropertyList(
Manman Renad0e7912016-01-29 19:22:54 +00006188 "\01l_OBJC_$_CLASS_PROP_LIST_" + ID->getObjCRuntimeNameAsString(),
John McCall176f8922016-11-30 02:39:18 +00006189 ID, ID->getClassInterface(), ObjCTypes, true));
John McCallef19dbb2012-10-17 04:53:23 +00006190 } else {
John McCall176f8922016-11-30 02:39:18 +00006191 values.add(EmitIvarList(ID));
6192 values.add(BuildWeakIvarLayout(ID, beginInstance, endInstance, hasMRCWeak));
6193 values.add(EmitPropertyList(
Manman Renad0e7912016-01-29 19:22:54 +00006194 "\01l_OBJC_$_PROP_LIST_" + ID->getObjCRuntimeNameAsString(),
John McCall176f8922016-11-30 02:39:18 +00006195 ID, ID->getClassInterface(), ObjCTypes, false));
John McCallef19dbb2012-10-17 04:53:23 +00006196 }
Saleem Abdulrasool3c628af2016-10-25 21:43:28 +00006197
John McCall176f8922016-11-30 02:39:18 +00006198 llvm::SmallString<64> roLabel;
6199 llvm::raw_svector_ostream(roLabel)
Saleem Abdulrasool3c628af2016-10-25 21:43:28 +00006200 << ((flags & NonFragileABI_Class_Meta) ? "\01l_OBJC_METACLASS_RO_$_"
6201 : "\01l_OBJC_CLASS_RO_$_")
6202 << ClassName;
6203
Fariborz Jahanian9e3ad522009-01-24 20:21:50 +00006204 llvm::GlobalVariable *CLASS_RO_GV =
John McCall176f8922016-11-30 02:39:18 +00006205 values.finishAndCreateGlobal(roLabel, CGM.getPointerAlign(),
6206 /*constant*/ false,
6207 llvm::GlobalValue::PrivateLinkage);
Saleem Abdulrasool3c628af2016-10-25 21:43:28 +00006208 if (CGM.getTriple().isOSBinFormatMachO())
6209 CLASS_RO_GV->setSection("__DATA, __objc_const");
Fariborz Jahanian9e3ad522009-01-24 20:21:50 +00006210 return CLASS_RO_GV;
6211}
6212
John McCalldba63a72016-11-30 23:54:50 +00006213/// Build the metaclass object for a class.
6214///
Fariborz Jahanian9e3ad522009-01-24 20:21:50 +00006215/// struct _class_t {
6216/// struct _class_t *isa;
6217/// struct _class_t * const superclass;
6218/// void *cache;
6219/// IMP *vtable;
6220/// struct class_ro_t *ro;
6221/// }
6222///
John McCalldba63a72016-11-30 23:54:50 +00006223llvm::GlobalVariable *
6224CGObjCNonFragileABIMac::BuildClassObject(const ObjCInterfaceDecl *CI,
6225 bool isMetaclass,
6226 llvm::Constant *IsAGV,
6227 llvm::Constant *SuperClassGV,
6228 llvm::Constant *ClassRoGV,
6229 bool HiddenVisibility) {
John McCall176f8922016-11-30 02:39:18 +00006230 ConstantInitBuilder builder(CGM);
6231 auto values = builder.beginStruct(ObjCTypes.ClassnfABITy);
6232 values.add(IsAGV);
6233 if (SuperClassGV) {
6234 values.add(SuperClassGV);
6235 } else {
6236 values.addNullPointer(ObjCTypes.ClassnfABIPtrTy);
6237 }
6238 values.add(ObjCEmptyCacheVar);
6239 values.add(ObjCEmptyVtableVar);
6240 values.add(ClassRoGV);
6241
John McCalldba63a72016-11-30 23:54:50 +00006242 llvm::GlobalVariable *GV =
6243 cast<llvm::GlobalVariable>(GetClassGlobal(CI, isMetaclass, ForDefinition));
John McCall176f8922016-11-30 02:39:18 +00006244 values.finishAndSetAsInitializer(GV);
6245
Saleem Abdulrasool3c628af2016-10-25 21:43:28 +00006246 if (CGM.getTriple().isOSBinFormatMachO())
6247 GV->setSection("__DATA, __objc_data");
Fariborz Jahanianc22f2362009-01-31 02:43:27 +00006248 GV->setAlignment(
Saleem Abdulrasool3c628af2016-10-25 21:43:28 +00006249 CGM.getDataLayout().getABITypeAlignment(ObjCTypes.ClassnfABITy));
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00006250 if (!CGM.getTriple().isOSBinFormatCOFF())
6251 if (HiddenVisibility)
6252 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahanian4723fb72009-01-24 21:21:53 +00006253 return GV;
Fariborz Jahanian9e3ad522009-01-24 20:21:50 +00006254}
6255
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006256bool
Fariborz Jahaniana6bed832009-05-21 01:03:45 +00006257CGObjCNonFragileABIMac::ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
Craig Topper8a13c412014-05-21 05:09:00 +00006258 return OD->getClassMethod(GetNullarySelector("load")) != nullptr;
Daniel Dunbar9a017d72009-05-15 22:33:15 +00006259}
6260
Daniel Dunbar961202372009-05-03 12:57:56 +00006261void CGObjCNonFragileABIMac::GetClassSizeInfo(const ObjCImplementationDecl *OID,
Daniel Dunbar554fd792009-04-19 23:41:48 +00006262 uint32_t &InstanceStart,
6263 uint32_t &InstanceSize) {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006264 const ASTRecordLayout &RL =
Daniel Dunbar9252ee12009-05-04 21:26:30 +00006265 CGM.getContext().getASTObjCImplementationLayout(OID);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006266
Daniel Dunbar9b042e02009-05-04 23:23:09 +00006267 // InstanceSize is really instance end.
Ken Dyckd5090c12011-02-11 02:20:09 +00006268 InstanceSize = RL.getDataSize().getQuantity();
Daniel Dunbar9b042e02009-05-04 23:23:09 +00006269
6270 // If there are no fields, the start is the same as the end.
6271 if (!RL.getFieldCount())
6272 InstanceStart = InstanceSize;
6273 else
Ken Dyckc5ca8762011-04-14 00:43:09 +00006274 InstanceStart = RL.getFieldOffset(0) / CGM.getContext().getCharWidth();
Daniel Dunbar554fd792009-04-19 23:41:48 +00006275}
6276
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00006277static llvm::GlobalValue::DLLStorageClassTypes getStorage(CodeGenModule &CGM,
6278 StringRef Name) {
6279 IdentifierInfo &II = CGM.getContext().Idents.get(Name);
6280 TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
6281 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
6282
6283 const VarDecl *VD = nullptr;
6284 for (const auto &Result : DC->lookup(&II))
6285 if ((VD = dyn_cast<VarDecl>(Result)))
6286 break;
6287
6288 if (!VD)
6289 return llvm::GlobalValue::DLLImportStorageClass;
6290 if (VD->hasAttr<DLLExportAttr>())
6291 return llvm::GlobalValue::DLLExportStorageClass;
6292 if (VD->hasAttr<DLLImportAttr>())
6293 return llvm::GlobalValue::DLLImportStorageClass;
6294 return llvm::GlobalValue::DefaultStorageClass;
6295}
6296
Fariborz Jahanian71394042009-01-23 23:53:38 +00006297void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) {
Fariborz Jahanian71394042009-01-23 23:53:38 +00006298 if (!ObjCEmptyCacheVar) {
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00006299 ObjCEmptyCacheVar =
6300 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.CacheTy, false,
6301 llvm::GlobalValue::ExternalLinkage, nullptr,
6302 "_objc_empty_cache");
6303 if (CGM.getTriple().isOSBinFormatCOFF())
6304 ObjCEmptyCacheVar->setDLLStorageClass(getStorage(CGM, "_objc_empty_cache"));
Craig Topper8a13c412014-05-21 05:09:00 +00006305
Saleem Abdulrasool4f515a62016-07-13 02:58:44 +00006306 // Only OS X with deployment version <10.9 use the empty vtable symbol
Fariborz Jahanian42d49552013-10-24 17:40:28 +00006307 const llvm::Triple &Triple = CGM.getTarget().getTriple();
Saleem Abdulrasool4f515a62016-07-13 02:58:44 +00006308 if (Triple.isMacOSX() && Triple.isMacOSXVersionLT(10, 9))
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00006309 ObjCEmptyVtableVar =
6310 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ImpnfABITy, false,
6311 llvm::GlobalValue::ExternalLinkage, nullptr,
6312 "_objc_empty_vtable");
John McCall176f8922016-11-30 02:39:18 +00006313 else
6314 ObjCEmptyVtableVar =
6315 llvm::ConstantPointerNull::get(ObjCTypes.ImpnfABITy->getPointerTo());
Fariborz Jahanian71394042009-01-23 23:53:38 +00006316 }
Saleem Abdulrasoolbc2d9992016-07-16 22:42:04 +00006317
Daniel Dunbare3f5cfc2009-04-20 20:18:54 +00006318 // FIXME: Is this correct (that meta class size is never computed)?
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006319 uint32_t InstanceStart =
Micah Villmowdd31ca12012-10-08 16:25:52 +00006320 CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ClassnfABITy);
Fariborz Jahanian9e3ad522009-01-24 20:21:50 +00006321 uint32_t InstanceSize = InstanceStart;
John McCallef19dbb2012-10-17 04:53:23 +00006322 uint32_t flags = NonFragileABI_Class_Meta;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006323
John McCalldba63a72016-11-30 23:54:50 +00006324 llvm::Constant *SuperClassGV, *IsAGV;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006325
Saleem Abdulrasoolbc2d9992016-07-16 22:42:04 +00006326 const auto *CI = ID->getClassInterface();
6327 assert(CI && "CGObjCNonFragileABIMac::GenerateClass - class is 0");
6328
John McCall0d54a172012-10-17 04:53:31 +00006329 // Build the flags for the metaclass.
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00006330 bool classIsHidden = (CGM.getTriple().isOSBinFormatCOFF())
6331 ? !CI->hasAttr<DLLExportAttr>()
6332 : CI->getVisibility() == HiddenVisibility;
Fariborz Jahanian82208252009-01-31 00:59:10 +00006333 if (classIsHidden)
John McCallef19dbb2012-10-17 04:53:23 +00006334 flags |= NonFragileABI_Class_Hidden;
John McCall0d54a172012-10-17 04:53:31 +00006335
6336 // FIXME: why is this flag set on the metaclass?
6337 // ObjC metaclasses have no fields and don't really get constructed.
6338 if (ID->hasNonZeroConstructors() || ID->hasDestructors()) {
John McCallef19dbb2012-10-17 04:53:23 +00006339 flags |= NonFragileABI_Class_HasCXXStructors;
John McCall0d54a172012-10-17 04:53:31 +00006340 if (!ID->hasNonZeroConstructors())
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00006341 flags |= NonFragileABI_Class_HasCXXDestructorOnly;
John McCall0d54a172012-10-17 04:53:31 +00006342 }
6343
Saleem Abdulrasoolbc2d9992016-07-16 22:42:04 +00006344 if (!CI->getSuperClass()) {
Fariborz Jahanian9e3ad522009-01-24 20:21:50 +00006345 // class is root
John McCallef19dbb2012-10-17 04:53:23 +00006346 flags |= NonFragileABI_Class_Root;
Saleem Abdulrasoolbc2d9992016-07-16 22:42:04 +00006347
John McCalldba63a72016-11-30 23:54:50 +00006348 SuperClassGV = GetClassGlobal(CI, /*metaclass*/ false, NotForDefinition);
6349 IsAGV = GetClassGlobal(CI, /*metaclass*/ true, NotForDefinition);
Fariborz Jahanian9e3ad522009-01-24 20:21:50 +00006350 } else {
Fariborz Jahanian4723fb72009-01-24 21:21:53 +00006351 // Has a root. Current class is not a root.
Fariborz Jahanian03b300b2009-02-26 18:23:47 +00006352 const ObjCInterfaceDecl *Root = ID->getClassInterface();
6353 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
6354 Root = Super;
Saleem Abdulrasoolbc2d9992016-07-16 22:42:04 +00006355
6356 const auto *Super = CI->getSuperClass();
John McCalldba63a72016-11-30 23:54:50 +00006357 IsAGV = GetClassGlobal(Root, /*metaclass*/ true, NotForDefinition);
6358 SuperClassGV = GetClassGlobal(Super, /*metaclass*/ true, NotForDefinition);
Fariborz Jahanian9e3ad522009-01-24 20:21:50 +00006359 }
Saleem Abdulrasoolbc2d9992016-07-16 22:42:04 +00006360
6361 llvm::GlobalVariable *CLASS_RO_GV =
6362 BuildClassRoTInitializer(flags, InstanceStart, InstanceSize, ID);
6363
Saleem Abdulrasoolbc2d9992016-07-16 22:42:04 +00006364 llvm::GlobalVariable *MetaTClass =
John McCalldba63a72016-11-30 23:54:50 +00006365 BuildClassObject(CI, /*metaclass*/ true,
6366 IsAGV, SuperClassGV, CLASS_RO_GV, classIsHidden);
Rafael Espindolab7350042018-03-01 00:35:47 +00006367 CGM.setGVProperties(MetaTClass, CI);
Fariborz Jahanian67260552009-11-17 21:37:35 +00006368 DefinedMetaClasses.push_back(MetaTClass);
Daniel Dunbar15894b72009-04-07 05:48:37 +00006369
Fariborz Jahanian4723fb72009-01-24 21:21:53 +00006370 // Metadata for the class
John McCallef19dbb2012-10-17 04:53:23 +00006371 flags = 0;
Fariborz Jahanian82208252009-01-31 00:59:10 +00006372 if (classIsHidden)
John McCallef19dbb2012-10-17 04:53:23 +00006373 flags |= NonFragileABI_Class_Hidden;
John McCall0d54a172012-10-17 04:53:31 +00006374
6375 if (ID->hasNonZeroConstructors() || ID->hasDestructors()) {
John McCallef19dbb2012-10-17 04:53:23 +00006376 flags |= NonFragileABI_Class_HasCXXStructors;
Daniel Dunbar8f28d012009-04-08 04:21:03 +00006377
John McCall0d54a172012-10-17 04:53:31 +00006378 // Set a flag to enable a runtime optimization when a class has
6379 // fields that require destruction but which don't require
6380 // anything except zero-initialization during construction. This
6381 // is most notably true of __strong and __weak types, but you can
6382 // also imagine there being C++ types with non-trivial default
6383 // constructors that merely set all fields to null.
6384 if (!ID->hasNonZeroConstructors())
6385 flags |= NonFragileABI_Class_HasCXXDestructorOnly;
6386 }
6387
Saleem Abdulrasoolbc2d9992016-07-16 22:42:04 +00006388 if (hasObjCExceptionAttribute(CGM.getContext(), CI))
John McCallef19dbb2012-10-17 04:53:23 +00006389 flags |= NonFragileABI_Class_Exception;
Daniel Dunbar8f28d012009-04-08 04:21:03 +00006390
Saleem Abdulrasoolbc2d9992016-07-16 22:42:04 +00006391 if (!CI->getSuperClass()) {
John McCallef19dbb2012-10-17 04:53:23 +00006392 flags |= NonFragileABI_Class_Root;
Craig Topper8a13c412014-05-21 05:09:00 +00006393 SuperClassGV = nullptr;
Chris Lattnerb433b272009-04-19 06:02:28 +00006394 } else {
Fariborz Jahanian4723fb72009-01-24 21:21:53 +00006395 // Has a root. Current class is not a root.
Saleem Abdulrasoolbc2d9992016-07-16 22:42:04 +00006396 const auto *Super = CI->getSuperClass();
John McCalldba63a72016-11-30 23:54:50 +00006397 SuperClassGV = GetClassGlobal(Super, /*metaclass*/ false, NotForDefinition);
Fariborz Jahanian4723fb72009-01-24 21:21:53 +00006398 }
Saleem Abdulrasoolbc2d9992016-07-16 22:42:04 +00006399
Daniel Dunbar961202372009-05-03 12:57:56 +00006400 GetClassSizeInfo(ID, InstanceStart, InstanceSize);
Saleem Abdulrasoolbc2d9992016-07-16 22:42:04 +00006401 CLASS_RO_GV =
6402 BuildClassRoTInitializer(flags, InstanceStart, InstanceSize, ID);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006403
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006404 llvm::GlobalVariable *ClassMD =
John McCalldba63a72016-11-30 23:54:50 +00006405 BuildClassObject(CI, /*metaclass*/ false,
6406 MetaTClass, SuperClassGV, CLASS_RO_GV, classIsHidden);
Rafael Espindolab7350042018-03-01 00:35:47 +00006407 CGM.setGVProperties(ClassMD, CI);
Fariborz Jahanian279abd32009-01-30 20:55:31 +00006408 DefinedClasses.push_back(ClassMD);
Saleem Abdulrasoolbc2d9992016-07-16 22:42:04 +00006409 ImplementedClasses.push_back(CI);
Daniel Dunbar8f28d012009-04-08 04:21:03 +00006410
Daniel Dunbar9a017d72009-05-15 22:33:15 +00006411 // Determine if this class is also "non-lazy".
6412 if (ImplementationIsNonLazy(ID))
6413 DefinedNonLazyClasses.push_back(ClassMD);
6414
Daniel Dunbar8f28d012009-04-08 04:21:03 +00006415 // Force the definition of the EHType if necessary.
John McCallef19dbb2012-10-17 04:53:23 +00006416 if (flags & NonFragileABI_Class_Exception)
John McCalldba63a72016-11-30 23:54:50 +00006417 (void) GetInterfaceEHType(CI, ForDefinition);
Fariborz Jahanianc0577942011-04-22 22:02:28 +00006418 // Make sure method definition entries are all clear for next implementation.
6419 MethodDefinitions.clear();
Fariborz Jahanian71394042009-01-23 23:53:38 +00006420}
6421
Fariborz Jahanian097feda2009-01-30 18:58:59 +00006422/// GenerateProtocolRef - This routine is called to generate code for
6423/// a protocol reference expression; as in:
6424/// @code
6425/// @protocol(Proto1);
6426/// @endcode
6427/// It generates a weak reference to l_OBJC_PROTOCOL_REFERENCE_$_Proto1
6428/// which will hold address of the protocol meta-data.
6429///
John McCall882987f2013-02-28 19:01:20 +00006430llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CodeGenFunction &CGF,
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006431 const ObjCProtocolDecl *PD) {
6432
Fariborz Jahanian464423d2009-04-10 18:47:34 +00006433 // This routine is called for @protocol only. So, we must build definition
6434 // of protocol's meta-data (not a reference to it!)
6435 //
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006436 llvm::Constant *Init =
6437 llvm::ConstantExpr::getBitCast(GetOrEmitProtocol(PD),
Douglas Gregor020de322012-01-17 18:36:30 +00006438 ObjCTypes.getExternalProtocolPtrTy());
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006439
Fariborz Jahanian097feda2009-01-30 18:58:59 +00006440 std::string ProtocolName("\01l_OBJC_PROTOCOL_REFERENCE_$_");
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006441 ProtocolName += PD->getObjCRuntimeNameAsString();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006442
John McCall7f416cc2015-09-08 08:05:57 +00006443 CharUnits Align = CGF.getPointerAlign();
6444
Fariborz Jahanian097feda2009-01-30 18:58:59 +00006445 llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName);
6446 if (PTGV)
John McCall7f416cc2015-09-08 08:05:57 +00006447 return CGF.Builder.CreateAlignedLoad(PTGV, Align);
Saleem Abdulrasool9f83f3b2017-06-29 00:54:44 +00006448 PTGV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(), false,
6449 llvm::GlobalValue::WeakAnyLinkage, Init,
6450 ProtocolName);
Saleem Abdulrasool13d73d52017-06-03 16:18:09 +00006451 PTGV->setSection(GetSectionName("__objc_protorefs",
6452 "coalesced,no_dead_strip"));
Rafael Espindola70efc5b2014-03-06 18:54:12 +00006453 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
John McCall7f416cc2015-09-08 08:05:57 +00006454 PTGV->setAlignment(Align.getQuantity());
Saleem Abdulrasool9f83f3b2017-06-29 00:54:44 +00006455 if (!CGM.getTriple().isOSBinFormatMachO())
6456 PTGV->setComdat(CGM.getModule().getOrInsertComdat(ProtocolName));
Saleem Abdulrasoolbe2b5cb2018-01-23 19:35:51 +00006457 CGM.addUsedGlobal(PTGV);
John McCall7f416cc2015-09-08 08:05:57 +00006458 return CGF.Builder.CreateAlignedLoad(PTGV, Align);
Fariborz Jahanian097feda2009-01-30 18:58:59 +00006459}
6460
Fariborz Jahanian0c8d0602009-01-26 18:32:24 +00006461/// GenerateCategory - Build metadata for a category implementation.
6462/// struct _category_t {
6463/// const char * const name;
6464/// struct _class_t *const cls;
6465/// const struct _method_list_t * const instance_methods;
6466/// const struct _method_list_t * const class_methods;
6467/// const struct _protocol_list_t * const protocols;
6468/// const struct _prop_list_t * const properties;
Manman Ren96df0b32016-01-29 23:45:01 +00006469/// const struct _prop_list_t * const class_properties;
Manman Ren42ff3902016-02-24 17:49:50 +00006470/// const uint32_t size;
Fariborz Jahanian0c8d0602009-01-26 18:32:24 +00006471/// }
6472///
Daniel Dunbar9a017d72009-05-15 22:33:15 +00006473void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Fariborz Jahanian0c8d0602009-01-26 18:32:24 +00006474 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Fariborz Jahanian2612e142009-01-26 22:58:07 +00006475 const char *Prefix = "\01l_OBJC_$_CATEGORY_";
Fangrui Song6907ce22018-07-30 19:24:48 +00006476
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006477 llvm::SmallString<64> ExtCatName(Prefix);
6478 ExtCatName += Interface->getObjCRuntimeNameAsString();
6479 ExtCatName += "_$_";
6480 ExtCatName += OCD->getNameAsString();
Fangrui Song6907ce22018-07-30 19:24:48 +00006481
John McCall176f8922016-11-30 02:39:18 +00006482 ConstantInitBuilder builder(CGM);
6483 auto values = builder.beginStruct(ObjCTypes.CategorynfABITy);
6484 values.add(GetClassName(OCD->getIdentifier()->getName()));
Fariborz Jahanian0c8d0602009-01-26 18:32:24 +00006485 // meta-class entry symbol
John McCalldba63a72016-11-30 23:54:50 +00006486 values.add(GetClassGlobal(Interface, /*metaclass*/ false, NotForDefinition));
John McCall176f8922016-11-30 02:39:18 +00006487 std::string listName =
Saleem Abdulrasool209150a2016-10-24 21:25:57 +00006488 (Interface->getObjCRuntimeNameAsString() + "_$_" + OCD->getName()).str();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006489
John McCall176f8922016-11-30 02:39:18 +00006490 SmallVector<const ObjCMethodDecl *, 16> instanceMethods;
6491 SmallVector<const ObjCMethodDecl *, 8> classMethods;
6492 for (const auto *MD : OCD->methods()) {
6493 if (MD->isInstanceMethod()) {
6494 instanceMethods.push_back(MD);
6495 } else {
6496 classMethods.push_back(MD);
6497 }
6498 }
Fariborz Jahanian2612e142009-01-26 22:58:07 +00006499
John McCall176f8922016-11-30 02:39:18 +00006500 values.add(emitMethodList(listName, MethodListType::CategoryInstanceMethods,
6501 instanceMethods));
6502 values.add(emitMethodList(listName, MethodListType::CategoryClassMethods,
6503 classMethods));
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006504
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006505 const ObjCCategoryDecl *Category =
Fariborz Jahanian066347e2009-01-28 22:18:42 +00006506 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Fariborz Jahaniand8fc1052009-02-13 17:52:22 +00006507 if (Category) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00006508 SmallString<256> ExtName;
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006509 llvm::raw_svector_ostream(ExtName) << Interface->getObjCRuntimeNameAsString() << "_$_"
Daniel Dunbar349e6fb2009-10-18 20:48:59 +00006510 << OCD->getName();
John McCall176f8922016-11-30 02:39:18 +00006511 values.add(EmitProtocolList("\01l_OBJC_CATEGORY_PROTOCOLS_$_"
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006512 + Interface->getObjCRuntimeNameAsString() + "_$_"
6513 + Category->getName(),
John McCall176f8922016-11-30 02:39:18 +00006514 Category->protocol_begin(),
6515 Category->protocol_end()));
6516 values.add(EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ExtName.str(),
6517 OCD, Category, ObjCTypes, false));
6518 values.add(EmitPropertyList("\01l_OBJC_$_CLASS_PROP_LIST_" + ExtName.str(),
6519 OCD, Category, ObjCTypes, true));
Mike Stump658fe022009-07-30 22:28:39 +00006520 } else {
John McCall176f8922016-11-30 02:39:18 +00006521 values.addNullPointer(ObjCTypes.ProtocolListnfABIPtrTy);
6522 values.addNullPointer(ObjCTypes.PropertyListPtrTy);
6523 values.addNullPointer(ObjCTypes.PropertyListPtrTy);
Fariborz Jahaniand8fc1052009-02-13 17:52:22 +00006524 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006525
Manman Ren42ff3902016-02-24 17:49:50 +00006526 unsigned Size = CGM.getDataLayout().getTypeAllocSize(ObjCTypes.CategorynfABITy);
John McCall176f8922016-11-30 02:39:18 +00006527 values.addInt(ObjCTypes.IntTy, Size);
Manman Ren42ff3902016-02-24 17:49:50 +00006528
John McCall176f8922016-11-30 02:39:18 +00006529 llvm::GlobalVariable *GCATV =
6530 values.finishAndCreateGlobal(ExtCatName.str(), CGM.getPointerAlign(),
6531 /*constant*/ false,
6532 llvm::GlobalValue::PrivateLinkage);
Saleem Abdulrasool3c628af2016-10-25 21:43:28 +00006533 if (CGM.getTriple().isOSBinFormatMachO())
6534 GCATV->setSection("__DATA, __objc_const");
Rafael Espindola060062a2014-03-06 22:15:10 +00006535 CGM.addCompilerUsedGlobal(GCATV);
Fariborz Jahanian0c8d0602009-01-26 18:32:24 +00006536 DefinedCategories.push_back(GCATV);
Daniel Dunbar9a017d72009-05-15 22:33:15 +00006537
6538 // Determine if this category is also "non-lazy".
6539 if (ImplementationIsNonLazy(OCD))
6540 DefinedNonLazyCategories.push_back(GCATV);
Fariborz Jahanianc0577942011-04-22 22:02:28 +00006541 // method definition entries must be clear for next implementation.
6542 MethodDefinitions.clear();
Fariborz Jahanian0c8d0602009-01-26 18:32:24 +00006543}
Fariborz Jahanian99113fd2009-01-26 21:38:32 +00006544
John McCall176f8922016-11-30 02:39:18 +00006545/// emitMethodConstant - Return a struct objc_method constant. If
6546/// forProtocol is true, the implementation will be null; otherwise,
6547/// the method must have a definition registered with the runtime.
6548///
6549/// struct _objc_method {
6550/// SEL _cmd;
6551/// char *method_type;
6552/// char *_imp;
6553/// }
6554void CGObjCNonFragileABIMac::emitMethodConstant(ConstantArrayBuilder &builder,
6555 const ObjCMethodDecl *MD,
6556 bool forProtocol) {
6557 auto method = builder.beginStruct(ObjCTypes.MethodTy);
6558 method.addBitCast(GetMethodVarName(MD->getSelector()),
6559 ObjCTypes.SelectorPtrTy);
6560 method.add(GetMethodVarType(MD));
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006561
John McCall176f8922016-11-30 02:39:18 +00006562 if (forProtocol) {
6563 // Protocol methods have no implementation. So, this entry is always NULL.
6564 method.addNullPointer(ObjCTypes.Int8PtrTy);
6565 } else {
6566 llvm::Function *fn = GetMethodDefinition(MD);
6567 assert(fn && "no definition for method?");
6568 method.addBitCast(fn, ObjCTypes.Int8PtrTy);
6569 }
6570
6571 method.finishAndAddTo(builder);
Fariborz Jahanian99113fd2009-01-26 21:38:32 +00006572}
6573
John McCall176f8922016-11-30 02:39:18 +00006574/// Build meta-data for method declarations.
6575///
Fariborz Jahanian99113fd2009-01-26 21:38:32 +00006576/// struct _method_list_t {
6577/// uint32_t entsize; // sizeof(struct _objc_method)
6578/// uint32_t method_count;
6579/// struct _objc_method method_list[method_count];
6580/// }
6581///
Zachary Turner41a9ee92017-10-11 23:54:34 +00006582llvm::Constant *
6583CGObjCNonFragileABIMac::emitMethodList(Twine name, MethodListType kind,
6584 ArrayRef<const ObjCMethodDecl *> methods) {
Fariborz Jahanian99113fd2009-01-26 21:38:32 +00006585 // Return null for empty list.
John McCall176f8922016-11-30 02:39:18 +00006586 if (methods.empty())
Owen Anderson0b75f232009-07-31 20:28:54 +00006587 return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006588
John McCall176f8922016-11-30 02:39:18 +00006589 StringRef prefix;
6590 bool forProtocol;
6591 switch (kind) {
Saleem Abdulrasoold48b0a32016-10-24 20:47:58 +00006592 case MethodListType::CategoryInstanceMethods:
John McCall176f8922016-11-30 02:39:18 +00006593 prefix = "\01l_OBJC_$_CATEGORY_INSTANCE_METHODS_";
6594 forProtocol = false;
Saleem Abdulrasoold48b0a32016-10-24 20:47:58 +00006595 break;
6596 case MethodListType::CategoryClassMethods:
John McCall176f8922016-11-30 02:39:18 +00006597 prefix = "\01l_OBJC_$_CATEGORY_CLASS_METHODS_";
6598 forProtocol = false;
Saleem Abdulrasoold48b0a32016-10-24 20:47:58 +00006599 break;
6600 case MethodListType::InstanceMethods:
John McCall176f8922016-11-30 02:39:18 +00006601 prefix = "\01l_OBJC_$_INSTANCE_METHODS_";
6602 forProtocol = false;
Saleem Abdulrasoold48b0a32016-10-24 20:47:58 +00006603 break;
6604 case MethodListType::ClassMethods:
John McCall176f8922016-11-30 02:39:18 +00006605 prefix = "\01l_OBJC_$_CLASS_METHODS_";
6606 forProtocol = false;
Saleem Abdulrasoold48b0a32016-10-24 20:47:58 +00006607 break;
6608
6609 case MethodListType::ProtocolInstanceMethods:
John McCall176f8922016-11-30 02:39:18 +00006610 prefix = "\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_";
6611 forProtocol = true;
Saleem Abdulrasoold48b0a32016-10-24 20:47:58 +00006612 break;
6613 case MethodListType::ProtocolClassMethods:
John McCall176f8922016-11-30 02:39:18 +00006614 prefix = "\01l_OBJC_$_PROTOCOL_CLASS_METHODS_";
6615 forProtocol = true;
Saleem Abdulrasoold48b0a32016-10-24 20:47:58 +00006616 break;
6617 case MethodListType::OptionalProtocolInstanceMethods:
John McCall176f8922016-11-30 02:39:18 +00006618 prefix = "\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_";
6619 forProtocol = true;
Saleem Abdulrasoold48b0a32016-10-24 20:47:58 +00006620 break;
6621 case MethodListType::OptionalProtocolClassMethods:
John McCall176f8922016-11-30 02:39:18 +00006622 prefix = "\01l_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_";
6623 forProtocol = true;
Saleem Abdulrasoold48b0a32016-10-24 20:47:58 +00006624 break;
6625 }
6626
John McCall176f8922016-11-30 02:39:18 +00006627 ConstantInitBuilder builder(CGM);
6628 auto values = builder.beginStruct();
6629
6630 // sizeof(struct _objc_method)
6631 unsigned Size = CGM.getDataLayout().getTypeAllocSize(ObjCTypes.MethodTy);
6632 values.addInt(ObjCTypes.IntTy, Size);
6633 // method_count
6634 values.addInt(ObjCTypes.IntTy, methods.size());
6635 auto methodArray = values.beginArray(ObjCTypes.MethodTy);
6636 for (auto MD : methods) {
6637 emitMethodConstant(methodArray, MD, forProtocol);
6638 }
6639 methodArray.finishAndAddTo(values);
6640
Zachary Turner41a9ee92017-10-11 23:54:34 +00006641 auto *GV = values.finishAndCreateGlobal(prefix + name, CGM.getPointerAlign(),
John McCall176f8922016-11-30 02:39:18 +00006642 /*constant*/ false,
6643 llvm::GlobalValue::PrivateLinkage);
Saleem Abdulrasool3c628af2016-10-25 21:43:28 +00006644 if (CGM.getTriple().isOSBinFormatMachO())
6645 GV->setSection("__DATA, __objc_const");
Rafael Espindola060062a2014-03-06 22:15:10 +00006646 CGM.addCompilerUsedGlobal(GV);
Chris Lattnere64d7ba2011-06-20 04:01:35 +00006647 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.MethodListnfABIPtrTy);
Fariborz Jahanian99113fd2009-01-26 21:38:32 +00006648}
Fariborz Jahanian7415caa2009-01-27 19:38:51 +00006649
Fariborz Jahanian4e7ae062009-02-10 20:21:06 +00006650/// ObjCIvarOffsetVariable - Returns the ivar offset variable for
6651/// the given ivar.
Daniel Dunbar8c7f9812010-04-02 21:14:02 +00006652llvm::GlobalVariable *
6653CGObjCNonFragileABIMac::ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
6654 const ObjCIvarDecl *Ivar) {
6655 const ObjCInterfaceDecl *Container = Ivar->getContainingInterface();
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006656 llvm::SmallString<64> Name("OBJC_IVAR_$_");
6657 Name += Container->getObjCRuntimeNameAsString();
6658 Name += ".";
6659 Name += Ivar->getName();
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00006660 llvm::GlobalVariable *IvarOffsetGV = CGM.getModule().getGlobalVariable(Name);
6661 if (!IvarOffsetGV) {
6662 IvarOffsetGV =
6663 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.IvarOffsetVarTy,
6664 false, llvm::GlobalValue::ExternalLinkage,
6665 nullptr, Name.str());
6666 if (CGM.getTriple().isOSBinFormatCOFF()) {
6667 bool IsPrivateOrPackage =
6668 Ivar->getAccessControl() == ObjCIvarDecl::Private ||
6669 Ivar->getAccessControl() == ObjCIvarDecl::Package;
6670
Saleem Abdulrasoolad75c7d2017-10-25 03:58:15 +00006671 const ObjCInterfaceDecl *ContainingID = Ivar->getContainingInterface();
6672
6673 if (ContainingID->hasAttr<DLLImportAttr>())
6674 IvarOffsetGV
6675 ->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
6676 else if (ContainingID->hasAttr<DLLExportAttr>() && !IsPrivateOrPackage)
6677 IvarOffsetGV
6678 ->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00006679 }
6680 }
Fariborz Jahanian4e7ae062009-02-10 20:21:06 +00006681 return IvarOffsetGV;
6682}
6683
Daniel Dunbar8c7f9812010-04-02 21:14:02 +00006684llvm::Constant *
6685CGObjCNonFragileABIMac::EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,
6686 const ObjCIvarDecl *Ivar,
Eli Friedman8cbca202012-11-06 22:15:52 +00006687 unsigned long int Offset) {
Daniel Dunbarbf90b332009-04-19 00:44:02 +00006688 llvm::GlobalVariable *IvarOffsetGV = ObjCIvarOffsetVariable(ID, Ivar);
Tim Northover238b5082014-03-29 13:42:40 +00006689 IvarOffsetGV->setInitializer(
6690 llvm::ConstantInt::get(ObjCTypes.IvarOffsetVarTy, Offset));
Fariborz Jahanianc22f2362009-01-31 02:43:27 +00006691 IvarOffsetGV->setAlignment(
Tim Northover238b5082014-03-29 13:42:40 +00006692 CGM.getDataLayout().getABITypeAlignment(ObjCTypes.IvarOffsetVarTy));
Daniel Dunbarbf90b332009-04-19 00:44:02 +00006693
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00006694 if (!CGM.getTriple().isOSBinFormatCOFF()) {
6695 // FIXME: This matches gcc, but shouldn't the visibility be set on the use
6696 // as well (i.e., in ObjCIvarOffsetVariable).
6697 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
6698 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
6699 ID->getVisibility() == HiddenVisibility)
6700 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
6701 else
6702 IvarOffsetGV->setVisibility(llvm::GlobalValue::DefaultVisibility);
6703 }
6704
Saleem Abdulrasool3c628af2016-10-25 21:43:28 +00006705 if (CGM.getTriple().isOSBinFormatMachO())
6706 IvarOffsetGV->setSection("__DATA, __objc_ivar");
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00006707 return IvarOffsetGV;
Fariborz Jahanian40a4bcd2009-01-28 01:05:23 +00006708}
6709
Fariborz Jahanian7415caa2009-01-27 19:38:51 +00006710/// EmitIvarList - Emit the ivar list for the given
Daniel Dunbar508a7dd2009-04-18 08:51:00 +00006711/// implementation. The return value has type
Fariborz Jahanian7415caa2009-01-27 19:38:51 +00006712/// IvarListnfABIPtrTy.
6713/// struct _ivar_t {
Tim Northover238b5082014-03-29 13:42:40 +00006714/// unsigned [long] int *offset; // pointer to ivar offset location
Fariborz Jahanian7415caa2009-01-27 19:38:51 +00006715/// char *name;
6716/// char *type;
6717/// uint32_t alignment;
6718/// uint32_t size;
6719/// }
6720/// struct _ivar_list_t {
6721/// uint32 entsize; // sizeof(struct _ivar_t)
6722/// uint32 count;
6723/// struct _iver_t list[count];
6724/// }
6725///
Daniel Dunbarf5c18462009-04-20 06:54:31 +00006726
Fariborz Jahanian7415caa2009-01-27 19:38:51 +00006727llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList(
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006728 const ObjCImplementationDecl *ID) {
6729
John McCall176f8922016-11-30 02:39:18 +00006730 ConstantInitBuilder builder(CGM);
6731 auto ivarList = builder.beginStruct();
6732 ivarList.addInt(ObjCTypes.IntTy,
6733 CGM.getDataLayout().getTypeAllocSize(ObjCTypes.IvarnfABITy));
6734 auto ivarCountSlot = ivarList.addPlaceholder();
6735 auto ivars = ivarList.beginArray(ObjCTypes.IvarnfABITy);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006736
Jordy Rosea91768e2011-07-22 02:08:32 +00006737 const ObjCInterfaceDecl *OID = ID->getClassInterface();
Fariborz Jahanian7415caa2009-01-27 19:38:51 +00006738 assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface");
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006739
Fariborz Jahanian40a4bcd2009-01-28 01:05:23 +00006740 // FIXME. Consolidate this with similar code in GenerateClass.
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006741
Fangrui Song6907ce22018-07-30 19:24:48 +00006742 for (const ObjCIvarDecl *IVD = OID->all_declared_ivar_begin();
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00006743 IVD; IVD = IVD->getNextIvar()) {
Fariborz Jahanian7c809592009-06-04 01:19:09 +00006744 // Ignore unnamed bit-fields.
6745 if (!IVD->getDeclName())
6746 continue;
John McCall176f8922016-11-30 02:39:18 +00006747
6748 auto ivar = ivars.beginStruct(ObjCTypes.IvarnfABITy);
6749 ivar.add(EmitIvarOffsetVar(ID->getClassInterface(), IVD,
6750 ComputeIvarBaseOffset(CGM, ID, IVD)));
6751 ivar.add(GetMethodVarName(IVD->getIdentifier()));
6752 ivar.add(GetMethodVarType(IVD));
Chris Lattner2192fe52011-07-18 04:24:23 +00006753 llvm::Type *FieldTy =
Daniel Dunbar725dc2c2009-04-22 08:22:17 +00006754 CGM.getTypes().ConvertTypeForMem(IVD->getType());
Micah Villmowdd31ca12012-10-08 16:25:52 +00006755 unsigned Size = CGM.getDataLayout().getTypeAllocSize(FieldTy);
Fariborz Jahanian7415caa2009-01-27 19:38:51 +00006756 unsigned Align = CGM.getContext().getPreferredTypeAlign(
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006757 IVD->getType().getTypePtr()) >> 3;
Fariborz Jahanian7415caa2009-01-27 19:38:51 +00006758 Align = llvm::Log2_32(Align);
John McCall176f8922016-11-30 02:39:18 +00006759 ivar.addInt(ObjCTypes.IntTy, Align);
Daniel Dunbarae032262009-04-20 00:33:43 +00006760 // NOTE. Size of a bitfield does not match gcc's, because of the
6761 // way bitfields are treated special in each. But I am told that
6762 // 'size' for bitfield ivars is ignored by the runtime so it does
6763 // not matter. If it matters, there is enough info to get the
6764 // bitfield right!
John McCall176f8922016-11-30 02:39:18 +00006765 ivar.addInt(ObjCTypes.IntTy, Size);
6766 ivar.finishAndAddTo(ivars);
Fariborz Jahanian7415caa2009-01-27 19:38:51 +00006767 }
6768 // Return null for empty list.
John McCall176f8922016-11-30 02:39:18 +00006769 if (ivars.empty()) {
6770 ivars.abandon();
6771 ivarList.abandon();
Owen Anderson0b75f232009-07-31 20:28:54 +00006772 return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
John McCall176f8922016-11-30 02:39:18 +00006773 }
Chris Lattnere64d7ba2011-06-20 04:01:35 +00006774
John McCall176f8922016-11-30 02:39:18 +00006775 auto ivarCount = ivars.size();
6776 ivars.finishAndAddTo(ivarList);
6777 ivarList.fillPlaceholderWithInt(ivarCountSlot, ObjCTypes.IntTy, ivarCount);
6778
Fariborz Jahanian7415caa2009-01-27 19:38:51 +00006779 const char *Prefix = "\01l_OBJC_$_INSTANCE_VARIABLES_";
6780 llvm::GlobalVariable *GV =
John McCall176f8922016-11-30 02:39:18 +00006781 ivarList.finishAndCreateGlobal(Prefix + OID->getObjCRuntimeNameAsString(),
6782 CGM.getPointerAlign(), /*constant*/ false,
6783 llvm::GlobalValue::PrivateLinkage);
Saleem Abdulrasool3c628af2016-10-25 21:43:28 +00006784 if (CGM.getTriple().isOSBinFormatMachO())
6785 GV->setSection("__DATA, __objc_const");
Rafael Espindola060062a2014-03-06 22:15:10 +00006786 CGM.addCompilerUsedGlobal(GV);
Owen Andersonade90fd2009-07-29 18:54:39 +00006787 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.IvarListnfABIPtrTy);
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006788}
6789
6790llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef(
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006791 const ObjCProtocolDecl *PD) {
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006792 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006793
Saleem Abdulrasool9ccc7ad2016-10-25 14:50:44 +00006794 if (!Entry) {
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006795 // We use the initializer as a marker of whether this is a forward
6796 // reference or not. At module finalization we add the empty
6797 // contents for protocols which were referenced but never defined.
Saleem Abdulrasool9ccc7ad2016-10-25 14:50:44 +00006798 llvm::SmallString<64> Protocol;
6799 llvm::raw_svector_ostream(Protocol) << "\01l_OBJC_PROTOCOL_$_"
6800 << PD->getObjCRuntimeNameAsString();
6801
6802 Entry = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ProtocolnfABITy,
6803 false, llvm::GlobalValue::ExternalLinkage,
6804 nullptr, Protocol);
6805 if (!CGM.getTriple().isOSBinFormatMachO())
6806 Entry->setComdat(CGM.getModule().getOrInsertComdat(Protocol));
6807 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006808
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006809 return Entry;
6810}
6811
6812/// GetOrEmitProtocol - Generate the protocol meta-data:
6813/// @code
6814/// struct _protocol_t {
6815/// id isa; // NULL
6816/// const char * const protocol_name;
6817/// const struct _protocol_list_t * protocol_list; // super protocols
6818/// const struct method_list_t * const instance_methods;
6819/// const struct method_list_t * const class_methods;
6820/// const struct method_list_t *optionalInstanceMethods;
6821/// const struct method_list_t *optionalClassMethods;
6822/// const struct _prop_list_t * properties;
6823/// const uint32_t size; // sizeof(struct _protocol_t)
6824/// const uint32_t flags; // = 0
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006825/// const char ** extendedMethodTypes;
Fariborz Jahanian6a9c46b2015-03-31 22:22:40 +00006826/// const char *demangledName;
Manman Rence7bff52016-01-29 23:46:55 +00006827/// const struct _prop_list_t * class_properties;
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006828/// }
6829/// @endcode
6830///
6831
6832llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol(
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006833 const ObjCProtocolDecl *PD) {
John McCallf9582a72012-03-30 21:29:05 +00006834 llvm::GlobalVariable *Entry = Protocols[PD->getIdentifier()];
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006835
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006836 // Early exit if a defining object has already been generated.
6837 if (Entry && Entry->hasInitializer())
6838 return Entry;
6839
Douglas Gregora715bff2012-01-01 19:51:50 +00006840 // Use the protocol definition, if there is one.
Alex Lorenzb111da12018-08-17 22:18:08 +00006841 assert(PD->hasDefinition() &&
6842 "emitting protocol metadata without definition");
6843 PD = PD->getDefinition();
Fangrui Song6907ce22018-07-30 19:24:48 +00006844
John McCall176f8922016-11-30 02:39:18 +00006845 auto methodLists = ProtocolMethodLists::get(PD);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006846
John McCall176f8922016-11-30 02:39:18 +00006847 ConstantInitBuilder builder(CGM);
6848 auto values = builder.beginStruct(ObjCTypes.ProtocolnfABITy);
Douglas Gregora9d84932011-05-27 01:19:52 +00006849
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006850 // isa is NULL
John McCall176f8922016-11-30 02:39:18 +00006851 values.addNullPointer(ObjCTypes.ObjectPtrTy);
6852 values.add(GetClassName(PD->getObjCRuntimeNameAsString()));
6853 values.add(EmitProtocolList("\01l_OBJC_$_PROTOCOL_REFS_"
6854 + PD->getObjCRuntimeNameAsString(),
Daniel Dunbar349e6fb2009-10-18 20:48:59 +00006855 PD->protocol_begin(),
John McCall176f8922016-11-30 02:39:18 +00006856 PD->protocol_end()));
6857 values.add(methodLists.emitMethodList(this, PD,
6858 ProtocolMethodLists::RequiredInstanceMethods));
6859 values.add(methodLists.emitMethodList(this, PD,
6860 ProtocolMethodLists::RequiredClassMethods));
6861 values.add(methodLists.emitMethodList(this, PD,
6862 ProtocolMethodLists::OptionalInstanceMethods));
6863 values.add(methodLists.emitMethodList(this, PD,
6864 ProtocolMethodLists::OptionalClassMethods));
6865 values.add(EmitPropertyList(
6866 "\01l_OBJC_$_PROP_LIST_" + PD->getObjCRuntimeNameAsString(),
6867 nullptr, PD, ObjCTypes, false));
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006868 uint32_t Size =
Micah Villmowdd31ca12012-10-08 16:25:52 +00006869 CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ProtocolnfABITy);
John McCall176f8922016-11-30 02:39:18 +00006870 values.addInt(ObjCTypes.IntTy, Size);
6871 values.addInt(ObjCTypes.IntTy, 0);
6872 values.add(EmitProtocolMethodTypes("\01l_OBJC_$_PROTOCOL_METHOD_TYPES_"
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006873 + PD->getObjCRuntimeNameAsString(),
John McCall176f8922016-11-30 02:39:18 +00006874 methodLists.emitExtendedTypesArray(this),
6875 ObjCTypes));
6876
Fariborz Jahanian6a9c46b2015-03-31 22:22:40 +00006877 // const char *demangledName;
John McCall176f8922016-11-30 02:39:18 +00006878 values.addNullPointer(ObjCTypes.Int8PtrTy);
Manman Rence7bff52016-01-29 23:46:55 +00006879
John McCall176f8922016-11-30 02:39:18 +00006880 values.add(EmitPropertyList(
Manman Rence7bff52016-01-29 23:46:55 +00006881 "\01l_OBJC_$_CLASS_PROP_LIST_" + PD->getObjCRuntimeNameAsString(),
John McCall176f8922016-11-30 02:39:18 +00006882 nullptr, PD, ObjCTypes, true));
Fangrui Song6907ce22018-07-30 19:24:48 +00006883
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006884 if (Entry) {
Rafael Espindola24615092014-09-12 20:14:20 +00006885 // Already created, fix the linkage and update the initializer.
6886 Entry->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
John McCall176f8922016-11-30 02:39:18 +00006887 values.finishAndSetAsInitializer(Entry);
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006888 } else {
John McCall176f8922016-11-30 02:39:18 +00006889 llvm::SmallString<64> symbolName;
6890 llvm::raw_svector_ostream(symbolName)
6891 << "\01l_OBJC_PROTOCOL_$_" << PD->getObjCRuntimeNameAsString();
Saleem Abdulrasool9ccc7ad2016-10-25 14:50:44 +00006892
John McCall176f8922016-11-30 02:39:18 +00006893 Entry = values.finishAndCreateGlobal(symbolName, CGM.getPointerAlign(),
6894 /*constant*/ false,
6895 llvm::GlobalValue::WeakAnyLinkage);
Saleem Abdulrasool9ccc7ad2016-10-25 14:50:44 +00006896 if (!CGM.getTriple().isOSBinFormatMachO())
John McCall176f8922016-11-30 02:39:18 +00006897 Entry->setComdat(CGM.getModule().getOrInsertComdat(symbolName));
John McCallf9582a72012-03-30 21:29:05 +00006898
6899 Protocols[PD->getIdentifier()] = Entry;
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006900 }
Rafael Espindola70efc5b2014-03-06 18:54:12 +00006901 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
Saleem Abdulrasoolbe2b5cb2018-01-23 19:35:51 +00006902 CGM.addUsedGlobal(Entry);
Chris Lattnerf56501c2009-07-17 23:57:13 +00006903
Fariborz Jahanian61cd4b52009-01-29 20:10:59 +00006904 // Use this protocol meta-data to build protocol list table in section
6905 // __DATA, __objc_protolist
Saleem Abdulrasool9ccc7ad2016-10-25 14:50:44 +00006906 llvm::SmallString<64> ProtocolRef;
6907 llvm::raw_svector_ostream(ProtocolRef) << "\01l_OBJC_LABEL_PROTOCOL_$_"
6908 << PD->getObjCRuntimeNameAsString();
6909
Daniel Dunbar349e6fb2009-10-18 20:48:59 +00006910 llvm::GlobalVariable *PTGV =
6911 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ProtocolnfABIPtrTy,
Rafael Espindola70efc5b2014-03-06 18:54:12 +00006912 false, llvm::GlobalValue::WeakAnyLinkage, Entry,
Saleem Abdulrasool9ccc7ad2016-10-25 14:50:44 +00006913 ProtocolRef);
6914 if (!CGM.getTriple().isOSBinFormatMachO())
6915 PTGV->setComdat(CGM.getModule().getOrInsertComdat(ProtocolRef));
Fariborz Jahanianc22f2362009-01-31 02:43:27 +00006916 PTGV->setAlignment(
Micah Villmowdd31ca12012-10-08 16:25:52 +00006917 CGM.getDataLayout().getABITypeAlignment(ObjCTypes.ProtocolnfABIPtrTy));
Saleem Abdulrasool13d73d52017-06-03 16:18:09 +00006918 PTGV->setSection(GetSectionName("__objc_protolist",
6919 "coalesced,no_dead_strip"));
Rafael Espindola70efc5b2014-03-06 18:54:12 +00006920 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Saleem Abdulrasoolbe2b5cb2018-01-23 19:35:51 +00006921 CGM.addUsedGlobal(PTGV);
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006922 return Entry;
6923}
6924
6925/// EmitProtocolList - Generate protocol list meta-data:
6926/// @code
6927/// struct _protocol_list_t {
6928/// long protocol_count; // Note, this is 32/64 bit
6929/// struct _protocol_t[protocol_count];
6930/// }
6931/// @endcode
6932///
Zachary Turner41a9ee92017-10-11 23:54:34 +00006933llvm::Constant *
6934CGObjCNonFragileABIMac::EmitProtocolList(Twine Name,
6935 ObjCProtocolDecl::protocol_iterator begin,
6936 ObjCProtocolDecl::protocol_iterator end) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006937 SmallVector<llvm::Constant *, 16> ProtocolRefs;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006938
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006939 // Just return null for empty protocol lists
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006940 if (begin == end)
Owen Anderson0b75f232009-07-31 20:28:54 +00006941 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006942
Daniel Dunbar8de90f02009-02-15 07:36:20 +00006943 // FIXME: We shouldn't need to do this lookup here, should we?
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00006944 SmallString<256> TmpName;
Daniel Dunbar349e6fb2009-10-18 20:48:59 +00006945 Name.toVector(TmpName);
6946 llvm::GlobalVariable *GV =
6947 CGM.getModule().getGlobalVariable(TmpName.str(), true);
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006948 if (GV)
Daniel Dunbar349e6fb2009-10-18 20:48:59 +00006949 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListnfABIPtrTy);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006950
John McCall176f8922016-11-30 02:39:18 +00006951 ConstantInitBuilder builder(CGM);
6952 auto values = builder.beginStruct();
6953 auto countSlot = values.addPlaceholder();
6954
6955 // A null-terminated array of protocols.
6956 auto array = values.beginArray(ObjCTypes.ProtocolnfABIPtrTy);
Daniel Dunbar8de90f02009-02-15 07:36:20 +00006957 for (; begin != end; ++begin)
John McCall176f8922016-11-30 02:39:18 +00006958 array.add(GetProtocolRef(*begin)); // Implemented???
6959 auto count = array.size();
6960 array.addNullPointer(ObjCTypes.ProtocolnfABIPtrTy);
Daniel Dunbar8de90f02009-02-15 07:36:20 +00006961
John McCall176f8922016-11-30 02:39:18 +00006962 array.finishAndAddTo(values);
6963 values.fillPlaceholderWithInt(countSlot, ObjCTypes.LongTy, count);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006964
John McCall176f8922016-11-30 02:39:18 +00006965 GV = values.finishAndCreateGlobal(Name, CGM.getPointerAlign(),
6966 /*constant*/ false,
6967 llvm::GlobalValue::PrivateLinkage);
Saleem Abdulrasool3c628af2016-10-25 21:43:28 +00006968 if (CGM.getTriple().isOSBinFormatMachO())
6969 GV->setSection("__DATA, __objc_const");
Rafael Espindola060062a2014-03-06 22:15:10 +00006970 CGM.addCompilerUsedGlobal(GV);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006971 return llvm::ConstantExpr::getBitCast(GV,
Daniel Dunbar8de90f02009-02-15 07:36:20 +00006972 ObjCTypes.ProtocolListnfABIPtrTy);
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006973}
6974
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00006975/// EmitObjCValueForIvar - Code Gen for nonfragile ivar reference.
6976/// This code gen. amounts to generating code for:
6977/// @code
6978/// (type *)((char *)base + _OBJC_IVAR_$_.ivar;
6979/// @encode
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006980///
Fariborz Jahanian712bfa62009-02-03 19:03:09 +00006981LValue CGObjCNonFragileABIMac::EmitObjCValueForIvar(
John McCall96fa4842010-05-17 21:00:27 +00006982 CodeGen::CodeGenFunction &CGF,
6983 QualType ObjectTy,
6984 llvm::Value *BaseValue,
6985 const ObjCIvarDecl *Ivar,
6986 unsigned CVRQualifiers) {
6987 ObjCInterfaceDecl *ID = ObjectTy->getAs<ObjCObjectType>()->getInterface();
Fariborz Jahaniancaabf1b2012-02-20 22:42:22 +00006988 llvm::Value *Offset = EmitIvarOffset(CGF, ID, Ivar);
Daniel Dunbar9fd114d2009-04-22 07:32:20 +00006989 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
Fariborz Jahaniancaabf1b2012-02-20 22:42:22 +00006990 Offset);
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00006991}
6992
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00006993llvm::Value *CGObjCNonFragileABIMac::EmitIvarOffset(
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006994 CodeGen::CodeGenFunction &CGF,
6995 const ObjCInterfaceDecl *Interface,
6996 const ObjCIvarDecl *Ivar) {
Tim Northover238b5082014-03-29 13:42:40 +00006997 llvm::Value *IvarOffsetValue = ObjCIvarOffsetVariable(Interface, Ivar);
John McCall7f416cc2015-09-08 08:05:57 +00006998 IvarOffsetValue = CGF.Builder.CreateAlignedLoad(IvarOffsetValue,
6999 CGF.getSizeAlign(), "ivar");
Tim Northover238b5082014-03-29 13:42:40 +00007000 if (IsIvarOffsetKnownIdempotent(CGF, Ivar))
7001 cast<llvm::LoadInst>(IvarOffsetValue)
7002 ->setMetadata(CGM.getModule().getMDKindID("invariant.load"),
Craig Topper5fc8fc22014-08-27 06:28:36 +00007003 llvm::MDNode::get(VMContext, None));
Tim Northover238b5082014-03-29 13:42:40 +00007004
7005 // This could be 32bit int or 64bit integer depending on the architecture.
7006 // Cast it to 64bit integer value, if it is a 32bit integer ivar offset value
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00007007 // as this is what caller always expects.
Tim Northover238b5082014-03-29 13:42:40 +00007008 if (ObjCTypes.IvarOffsetVarTy == ObjCTypes.IntTy)
7009 IvarOffsetValue = CGF.Builder.CreateIntCast(
7010 IvarOffsetValue, ObjCTypes.LongTy, true, "ivar.conv");
7011 return IvarOffsetValue;
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00007012}
7013
John McCall234eac82011-05-13 23:16:18 +00007014static void appendSelectorForMessageRefTable(std::string &buffer,
7015 Selector selector) {
7016 if (selector.isUnarySelector()) {
7017 buffer += selector.getNameForSlot(0);
7018 return;
7019 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007020
John McCall234eac82011-05-13 23:16:18 +00007021 for (unsigned i = 0, e = selector.getNumArgs(); i != e; ++i) {
7022 buffer += selector.getNameForSlot(i);
7023 buffer += '_';
7024 }
7025}
7026
Eric Christopherd160c502016-01-29 01:35:53 +00007027/// Emit a "vtable" message send. We emit a weak hidden-visibility
John McCall9e8bb002011-05-14 03:10:52 +00007028/// struct, initially containing the selector pointer and a pointer to
7029/// a "fixup" variant of the appropriate objc_msgSend. To call, we
7030/// load and call the function pointer, passing the address of the
7031/// struct as the second parameter. The runtime determines whether
7032/// the selector is currently emitted using vtable dispatch; if so, it
7033/// substitutes a stub function which simply tail-calls through the
7034/// appropriate vtable slot, and if not, it substitues a stub function
7035/// which tail-calls objc_msgSend. Both stubs adjust the selector
7036/// argument to correctly point to the selector.
7037RValue
7038CGObjCNonFragileABIMac::EmitVTableMessageSend(CodeGenFunction &CGF,
7039 ReturnValueSlot returnSlot,
7040 QualType resultType,
7041 Selector selector,
7042 llvm::Value *arg0,
7043 QualType arg0Type,
7044 bool isSuper,
7045 const CallArgList &formalArgs,
7046 const ObjCMethodDecl *method) {
John McCall234eac82011-05-13 23:16:18 +00007047 // Compute the actual arguments.
7048 CallArgList args;
7049
John McCall9e8bb002011-05-14 03:10:52 +00007050 // First argument: the receiver / super-call structure.
John McCall234eac82011-05-13 23:16:18 +00007051 if (!isSuper)
John McCall9e8bb002011-05-14 03:10:52 +00007052 arg0 = CGF.Builder.CreateBitCast(arg0, ObjCTypes.ObjectPtrTy);
7053 args.add(RValue::get(arg0), arg0Type);
John McCall234eac82011-05-13 23:16:18 +00007054
John McCall9e8bb002011-05-14 03:10:52 +00007055 // Second argument: a pointer to the message ref structure. Leave
7056 // the actual argument value blank for now.
Craig Topper8a13c412014-05-21 05:09:00 +00007057 args.add(RValue::get(nullptr), ObjCTypes.MessageRefCPtrTy);
John McCall234eac82011-05-13 23:16:18 +00007058
7059 args.insert(args.end(), formalArgs.begin(), formalArgs.end());
7060
John McCalla729c622012-02-17 03:33:10 +00007061 MessageSendInfo MSI = getMessageSendInfo(method, resultType, args);
John McCall234eac82011-05-13 23:16:18 +00007062
John McCall5880fb82011-05-14 21:12:11 +00007063 NullReturnState nullReturn;
7064
John McCall9e8bb002011-05-14 03:10:52 +00007065 // Find the function to call and the mangled name for the message
7066 // ref structure. Using a different mangled name wouldn't actually
7067 // be a problem; it would just be a waste.
7068 //
7069 // The runtime currently never uses vtable dispatch for anything
7070 // except normal, non-super message-sends.
7071 // FIXME: don't use this for that.
Craig Topper8a13c412014-05-21 05:09:00 +00007072 llvm::Constant *fn = nullptr;
John McCall234eac82011-05-13 23:16:18 +00007073 std::string messageRefName("\01l_");
Tim Northovere77cc392014-03-29 13:28:05 +00007074 if (CGM.ReturnSlotInterferesWithArgs(MSI.CallInfo)) {
John McCall234eac82011-05-13 23:16:18 +00007075 if (isSuper) {
7076 fn = ObjCTypes.getMessageSendSuper2StretFixupFn();
7077 messageRefName += "objc_msgSendSuper2_stret_fixup";
Chris Lattner396639d2010-08-18 16:09:06 +00007078 } else {
John McCall5880fb82011-05-14 21:12:11 +00007079 nullReturn.init(CGF, arg0);
John McCall234eac82011-05-13 23:16:18 +00007080 fn = ObjCTypes.getMessageSendStretFixupFn();
7081 messageRefName += "objc_msgSend_stret_fixup";
Chris Lattner396639d2010-08-18 16:09:06 +00007082 }
John McCall234eac82011-05-13 23:16:18 +00007083 } else if (!isSuper && CGM.ReturnTypeUsesFPRet(resultType)) {
7084 fn = ObjCTypes.getMessageSendFpretFixupFn();
7085 messageRefName += "objc_msgSend_fpret_fixup";
Mike Stump658fe022009-07-30 22:28:39 +00007086 } else {
John McCall234eac82011-05-13 23:16:18 +00007087 if (isSuper) {
7088 fn = ObjCTypes.getMessageSendSuper2FixupFn();
7089 messageRefName += "objc_msgSendSuper2_fixup";
Chris Lattner396639d2010-08-18 16:09:06 +00007090 } else {
John McCall234eac82011-05-13 23:16:18 +00007091 fn = ObjCTypes.getMessageSendFixupFn();
7092 messageRefName += "objc_msgSend_fixup";
Chris Lattner396639d2010-08-18 16:09:06 +00007093 }
Fariborz Jahaniane4dc35d2009-02-04 20:42:28 +00007094 }
John McCall234eac82011-05-13 23:16:18 +00007095 assert(fn && "CGObjCNonFragileABIMac::EmitMessageSend");
7096 messageRefName += '_';
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007097
John McCall234eac82011-05-13 23:16:18 +00007098 // Append the selector name, except use underscores anywhere we
7099 // would have used colons.
7100 appendSelectorForMessageRefTable(messageRefName, selector);
7101
7102 llvm::GlobalVariable *messageRef
7103 = CGM.getModule().getGlobalVariable(messageRefName);
7104 if (!messageRef) {
John McCall9e8bb002011-05-14 03:10:52 +00007105 // Build the message ref structure.
John McCall176f8922016-11-30 02:39:18 +00007106 ConstantInitBuilder builder(CGM);
7107 auto values = builder.beginStruct();
7108 values.add(fn);
7109 values.add(GetMethodVarName(selector));
7110 messageRef = values.finishAndCreateGlobal(messageRefName,
7111 CharUnits::fromQuantity(16),
7112 /*constant*/ false,
7113 llvm::GlobalValue::WeakAnyLinkage);
Rafael Espindola70efc5b2014-03-06 18:54:12 +00007114 messageRef->setVisibility(llvm::GlobalValue::HiddenVisibility);
Saleem Abdulrasool13d73d52017-06-03 16:18:09 +00007115 messageRef->setSection(GetSectionName("__objc_msgrefs", "coalesced"));
John McCall234eac82011-05-13 23:16:18 +00007116 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007117
Fariborz Jahanianc93fa982012-01-30 23:39:30 +00007118 bool requiresnullCheck = false;
David Blaikiebbafb8a2012-03-11 07:00:24 +00007119 if (CGM.getLangOpts().ObjCAutoRefCount && method)
David Majnemer59f77922016-06-24 04:05:48 +00007120 for (const auto *ParamDecl : method->parameters()) {
Fariborz Jahanianc93fa982012-01-30 23:39:30 +00007121 if (ParamDecl->hasAttr<NSConsumedAttr>()) {
7122 if (!nullReturn.NullBB)
7123 nullReturn.init(CGF, arg0);
7124 requiresnullCheck = true;
7125 break;
7126 }
7127 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007128
John McCall7f416cc2015-09-08 08:05:57 +00007129 Address mref =
7130 Address(CGF.Builder.CreateBitCast(messageRef, ObjCTypes.MessageRefPtrTy),
7131 CGF.getPointerAlign());
John McCall234eac82011-05-13 23:16:18 +00007132
John McCall9e8bb002011-05-14 03:10:52 +00007133 // Update the message ref argument.
Yaxun Liu5b330e82018-03-15 15:25:19 +00007134 args[1].setRValue(RValue::get(mref.getPointer()));
John McCall234eac82011-05-13 23:16:18 +00007135
7136 // Load the function to call from the message ref table.
John McCall7f416cc2015-09-08 08:05:57 +00007137 Address calleeAddr =
7138 CGF.Builder.CreateStructGEP(mref, 0, CharUnits::Zero());
John McCallb92ab1a2016-10-26 23:46:34 +00007139 llvm::Value *calleePtr = CGF.Builder.CreateLoad(calleeAddr, "msgSend_fn");
John McCall234eac82011-05-13 23:16:18 +00007140
John McCallb92ab1a2016-10-26 23:46:34 +00007141 calleePtr = CGF.Builder.CreateBitCast(calleePtr, MSI.MessengerType);
7142 CGCallee callee(CGCalleeInfo(), calleePtr);
John McCall234eac82011-05-13 23:16:18 +00007143
John McCalla729c622012-02-17 03:33:10 +00007144 RValue result = CGF.EmitCall(MSI.CallInfo, callee, returnSlot, args);
Kuba Mracekbce5cea2017-06-30 16:28:15 +00007145 return nullReturn.complete(CGF, returnSlot, result, resultType, formalArgs,
Craig Topper8a13c412014-05-21 05:09:00 +00007146 requiresnullCheck ? method : nullptr);
Fariborz Jahanian3d9296e2009-02-04 00:22:57 +00007147}
7148
7149/// Generate code for a message send expression in the nonfragile abi.
Daniel Dunbaraff9fca2009-09-17 04:01:22 +00007150CodeGen::RValue
7151CGObjCNonFragileABIMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +00007152 ReturnValueSlot Return,
Daniel Dunbaraff9fca2009-09-17 04:01:22 +00007153 QualType ResultType,
7154 Selector Sel,
7155 llvm::Value *Receiver,
Daniel Dunbaraff9fca2009-09-17 04:01:22 +00007156 const CallArgList &CallArgs,
David Chisnall01aa4672010-04-28 19:33:36 +00007157 const ObjCInterfaceDecl *Class,
Daniel Dunbaraff9fca2009-09-17 04:01:22 +00007158 const ObjCMethodDecl *Method) {
John McCall9e8bb002011-05-14 03:10:52 +00007159 return isVTableDispatchedSelector(Sel)
7160 ? EmitVTableMessageSend(CGF, Return, ResultType, Sel,
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007161 Receiver, CGF.getContext().getObjCIdType(),
John McCall9e8bb002011-05-14 03:10:52 +00007162 false, CallArgs, Method)
7163 : EmitMessageSend(CGF, Return, ResultType,
John McCall882987f2013-02-28 19:01:20 +00007164 EmitSelector(CGF, Sel),
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007165 Receiver, CGF.getContext().getObjCIdType(),
John McCall1e3157b2015-09-10 22:27:50 +00007166 false, CallArgs, Method, Class, ObjCTypes);
Fariborz Jahanian3d9296e2009-02-04 00:22:57 +00007167}
7168
John McCalldba63a72016-11-30 23:54:50 +00007169llvm::Constant *
7170CGObjCNonFragileABIMac::GetClassGlobal(const ObjCInterfaceDecl *ID,
7171 bool metaclass,
7172 ForDefinition_t isForDefinition) {
7173 auto prefix =
7174 (metaclass ? getMetaclassSymbolPrefix() : getClassSymbolPrefix());
7175 return GetClassGlobal((prefix + ID->getObjCRuntimeNameAsString()).str(),
7176 isForDefinition,
7177 ID->isWeakImported(),
7178 !isForDefinition
7179 && CGM.getTriple().isOSBinFormatCOFF()
7180 && ID->hasAttr<DLLImportAttr>());
7181}
7182
7183llvm::Constant *
7184CGObjCNonFragileABIMac::GetClassGlobal(StringRef Name,
7185 ForDefinition_t IsForDefinition,
7186 bool Weak, bool DLLImport) {
Rafael Espindola554256c2014-02-26 22:25:45 +00007187 llvm::GlobalValue::LinkageTypes L =
7188 Weak ? llvm::GlobalValue::ExternalWeakLinkage
7189 : llvm::GlobalValue::ExternalLinkage;
7190
John McCalldba63a72016-11-30 23:54:50 +00007191 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
Erik Pilkington92d8a292018-10-12 17:22:10 +00007192 if (!GV || GV->getType() != ObjCTypes.ClassnfABITy->getPointerTo()) {
7193 auto *NewGV = new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false, L,
7194 nullptr, Name);
Daniel Dunbarc6928bb2009-03-01 04:40:10 +00007195
John McCalldba63a72016-11-30 23:54:50 +00007196 if (DLLImport)
Erik Pilkington92d8a292018-10-12 17:22:10 +00007197 NewGV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
7198
7199 if (GV) {
7200 GV->replaceAllUsesWith(
7201 llvm::ConstantExpr::getBitCast(NewGV, GV->getType()));
7202 GV->eraseFromParent();
7203 }
7204 GV = NewGV;
7205 CGM.getModule().getGlobalList().push_back(GV);
John McCalldba63a72016-11-30 23:54:50 +00007206 }
7207
Rafael Espindola554256c2014-02-26 22:25:45 +00007208 assert(GV->getLinkage() == L);
Daniel Dunbarc6928bb2009-03-01 04:40:10 +00007209 return GV;
7210}
7211
John McCalldba63a72016-11-30 23:54:50 +00007212llvm::Value *
7213CGObjCNonFragileABIMac::EmitClassRefFromId(CodeGenFunction &CGF,
7214 IdentifierInfo *II,
7215 const ObjCInterfaceDecl *ID) {
John McCall7f416cc2015-09-08 08:05:57 +00007216 CharUnits Align = CGF.getPointerAlign();
John McCall31168b02011-06-15 23:02:42 +00007217 llvm::GlobalVariable *&Entry = ClassReferences[II];
Fangrui Song6907ce22018-07-30 19:24:48 +00007218
Fariborz Jahanian33f66e62009-02-05 20:41:40 +00007219 if (!Entry) {
John McCalldba63a72016-11-30 23:54:50 +00007220 llvm::Constant *ClassGV;
7221 if (ID) {
7222 ClassGV = GetClassGlobal(ID, /*metaclass*/ false, NotForDefinition);
7223 } else {
7224 ClassGV = GetClassGlobal((getClassSymbolPrefix() + II->getName()).str(),
7225 NotForDefinition);
7226 }
7227
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00007228 Entry = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassnfABIPtrTy,
7229 false, llvm::GlobalValue::PrivateLinkage,
7230 ClassGV, "OBJC_CLASSLIST_REFERENCES_$_");
John McCall7f416cc2015-09-08 08:05:57 +00007231 Entry->setAlignment(Align.getQuantity());
Saleem Abdulrasool13d73d52017-06-03 16:18:09 +00007232 Entry->setSection(GetSectionName("__objc_classrefs",
7233 "regular,no_dead_strip"));
Rafael Espindola060062a2014-03-06 22:15:10 +00007234 CGM.addCompilerUsedGlobal(Entry);
Daniel Dunbar508a7dd2009-04-18 08:51:00 +00007235 }
John McCall7f416cc2015-09-08 08:05:57 +00007236 return CGF.Builder.CreateAlignedLoad(Entry, Align);
Daniel Dunbar508a7dd2009-04-18 08:51:00 +00007237}
Fariborz Jahanian33f66e62009-02-05 20:41:40 +00007238
John McCall882987f2013-02-28 19:01:20 +00007239llvm::Value *CGObjCNonFragileABIMac::EmitClassRef(CodeGenFunction &CGF,
John McCall31168b02011-06-15 23:02:42 +00007240 const ObjCInterfaceDecl *ID) {
Douglas Gregor24ae22c2016-04-01 23:23:52 +00007241 // If the class has the objc_runtime_visible attribute, we need to
7242 // use the Objective-C runtime to get the class.
7243 if (ID->hasAttr<ObjCRuntimeVisibleAttr>())
7244 return EmitClassRefViaRuntime(CGF, ID, ObjCTypes);
7245
John McCalldba63a72016-11-30 23:54:50 +00007246 return EmitClassRefFromId(CGF, ID->getIdentifier(), ID);
John McCall31168b02011-06-15 23:02:42 +00007247}
7248
7249llvm::Value *CGObjCNonFragileABIMac::EmitNSAutoreleasePoolClassRef(
John McCall882987f2013-02-28 19:01:20 +00007250 CodeGenFunction &CGF) {
John McCall31168b02011-06-15 23:02:42 +00007251 IdentifierInfo *II = &CGM.getContext().Idents.get("NSAutoreleasePool");
John McCalldba63a72016-11-30 23:54:50 +00007252 return EmitClassRefFromId(CGF, II, nullptr);
John McCall31168b02011-06-15 23:02:42 +00007253}
7254
Daniel Dunbar508a7dd2009-04-18 08:51:00 +00007255llvm::Value *
John McCall882987f2013-02-28 19:01:20 +00007256CGObjCNonFragileABIMac::EmitSuperClassRef(CodeGenFunction &CGF,
Daniel Dunbar508a7dd2009-04-18 08:51:00 +00007257 const ObjCInterfaceDecl *ID) {
John McCall7f416cc2015-09-08 08:05:57 +00007258 CharUnits Align = CGF.getPointerAlign();
Daniel Dunbar508a7dd2009-04-18 08:51:00 +00007259 llvm::GlobalVariable *&Entry = SuperClassReferences[ID->getIdentifier()];
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007260
Daniel Dunbar508a7dd2009-04-18 08:51:00 +00007261 if (!Entry) {
John McCalldba63a72016-11-30 23:54:50 +00007262 auto ClassGV = GetClassGlobal(ID, /*metaclass*/ false, NotForDefinition);
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00007263 Entry = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassnfABIPtrTy,
7264 false, llvm::GlobalValue::PrivateLinkage,
7265 ClassGV, "OBJC_CLASSLIST_SUP_REFS_$_");
John McCall7f416cc2015-09-08 08:05:57 +00007266 Entry->setAlignment(Align.getQuantity());
Saleem Abdulrasool13d73d52017-06-03 16:18:09 +00007267 Entry->setSection(GetSectionName("__objc_superrefs",
7268 "regular,no_dead_strip"));
Rafael Espindola060062a2014-03-06 22:15:10 +00007269 CGM.addCompilerUsedGlobal(Entry);
Fariborz Jahanian33f66e62009-02-05 20:41:40 +00007270 }
John McCall7f416cc2015-09-08 08:05:57 +00007271 return CGF.Builder.CreateAlignedLoad(Entry, Align);
Fariborz Jahanian33f66e62009-02-05 20:41:40 +00007272}
7273
Fariborz Jahanian6b7cd6e2009-02-06 20:09:23 +00007274/// EmitMetaClassRef - Return a Value * of the address of _class_t
7275/// meta-data
7276///
John McCall882987f2013-02-28 19:01:20 +00007277llvm::Value *CGObjCNonFragileABIMac::EmitMetaClassRef(CodeGenFunction &CGF,
Fariborz Jahanian0b3bc242014-06-10 17:08:04 +00007278 const ObjCInterfaceDecl *ID,
7279 bool Weak) {
John McCall7f416cc2015-09-08 08:05:57 +00007280 CharUnits Align = CGF.getPointerAlign();
Fariborz Jahanian6b7cd6e2009-02-06 20:09:23 +00007281 llvm::GlobalVariable * &Entry = MetaClassReferences[ID->getIdentifier()];
Rafael Espindola21039aa2014-02-27 16:26:32 +00007282 if (!Entry) {
John McCalldba63a72016-11-30 23:54:50 +00007283 auto MetaClassGV = GetClassGlobal(ID, /*metaclass*/ true, NotForDefinition);
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00007284
Rafael Espindola21039aa2014-02-27 16:26:32 +00007285 Entry = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassnfABIPtrTy,
Rafael Espindola5179a4e2014-02-27 19:01:11 +00007286 false, llvm::GlobalValue::PrivateLinkage,
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00007287 MetaClassGV, "OBJC_CLASSLIST_SUP_REFS_$_");
John McCall7f416cc2015-09-08 08:05:57 +00007288 Entry->setAlignment(Align.getQuantity());
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007289
Saleem Abdulrasool13d73d52017-06-03 16:18:09 +00007290 Entry->setSection(GetSectionName("__objc_superrefs",
7291 "regular,no_dead_strip"));
Rafael Espindola060062a2014-03-06 22:15:10 +00007292 CGM.addCompilerUsedGlobal(Entry);
Rafael Espindola21039aa2014-02-27 16:26:32 +00007293 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007294
John McCall7f416cc2015-09-08 08:05:57 +00007295 return CGF.Builder.CreateAlignedLoad(Entry, Align);
Fariborz Jahanian6b7cd6e2009-02-06 20:09:23 +00007296}
7297
Fariborz Jahanian33f66e62009-02-05 20:41:40 +00007298/// GetClass - Return a reference to the class for the given interface
7299/// decl.
John McCall882987f2013-02-28 19:01:20 +00007300llvm::Value *CGObjCNonFragileABIMac::GetClass(CodeGenFunction &CGF,
Fariborz Jahanian33f66e62009-02-05 20:41:40 +00007301 const ObjCInterfaceDecl *ID) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00007302 if (ID->isWeakImported()) {
John McCalldba63a72016-11-30 23:54:50 +00007303 auto ClassGV = GetClassGlobal(ID, /*metaclass*/ false, NotForDefinition);
Nick Lewycky9a441642014-02-27 00:36:00 +00007304 (void)ClassGV;
John McCalldba63a72016-11-30 23:54:50 +00007305 assert(!isa<llvm::GlobalVariable>(ClassGV) ||
7306 cast<llvm::GlobalVariable>(ClassGV)->hasExternalWeakLinkage());
Fariborz Jahanian95ace552009-11-17 22:42:00 +00007307 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007308
John McCall882987f2013-02-28 19:01:20 +00007309 return EmitClassRef(CGF, ID);
Fariborz Jahanian33f66e62009-02-05 20:41:40 +00007310}
7311
Fariborz Jahanian6b7cd6e2009-02-06 20:09:23 +00007312/// Generates a message send where the super is the receiver. This is
7313/// a message send to self with special delivery semantics indicating
7314/// which class's method should be called.
7315CodeGen::RValue
7316CGObjCNonFragileABIMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +00007317 ReturnValueSlot Return,
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007318 QualType ResultType,
7319 Selector Sel,
7320 const ObjCInterfaceDecl *Class,
7321 bool isCategoryImpl,
7322 llvm::Value *Receiver,
7323 bool IsClassMessage,
Daniel Dunbaraff9fca2009-09-17 04:01:22 +00007324 const CodeGen::CallArgList &CallArgs,
7325 const ObjCMethodDecl *Method) {
Fariborz Jahanian6b7cd6e2009-02-06 20:09:23 +00007326 // ...
7327 // Create and init a super structure; this is a (receiver, class)
7328 // pair we will pass to objc_msgSendSuper.
John McCall7f416cc2015-09-08 08:05:57 +00007329 Address ObjCSuper =
7330 CGF.CreateTempAlloca(ObjCTypes.SuperTy, CGF.getPointerAlign(),
7331 "objc_super");
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007332
Fariborz Jahanian6b7cd6e2009-02-06 20:09:23 +00007333 llvm::Value *ReceiverAsObject =
7334 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
David Blaikie1ed728c2015-04-05 22:45:47 +00007335 CGF.Builder.CreateStore(
7336 ReceiverAsObject,
John McCall7f416cc2015-09-08 08:05:57 +00007337 CGF.Builder.CreateStructGEP(ObjCSuper, 0, CharUnits::Zero()));
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007338
Fariborz Jahanian6b7cd6e2009-02-06 20:09:23 +00007339 // If this is a class message the metaclass is passed as the target.
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +00007340 llvm::Value *Target;
Fariborz Jahanian27678b02012-10-10 23:11:18 +00007341 if (IsClassMessage)
Fariborz Jahanian85b99da2014-08-28 17:05:17 +00007342 Target = EmitMetaClassRef(CGF, Class, Class->isWeakImported());
Fariborz Jahanian27678b02012-10-10 23:11:18 +00007343 else
John McCall882987f2013-02-28 19:01:20 +00007344 Target = EmitSuperClassRef(CGF, Class);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007345
Mike Stump18bb9282009-05-16 07:57:57 +00007346 // FIXME: We shouldn't need to do this cast, rectify the ASTContext and
7347 // ObjCTypes types.
Chris Lattner2192fe52011-07-18 04:24:23 +00007348 llvm::Type *ClassTy =
Fariborz Jahanian6b7cd6e2009-02-06 20:09:23 +00007349 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
7350 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
David Blaikie1ed728c2015-04-05 22:45:47 +00007351 CGF.Builder.CreateStore(
John McCall7f416cc2015-09-08 08:05:57 +00007352 Target, CGF.Builder.CreateStructGEP(ObjCSuper, 1, CGF.getPointerSize()));
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007353
John McCall9e8bb002011-05-14 03:10:52 +00007354 return (isVTableDispatchedSelector(Sel))
7355 ? EmitVTableMessageSend(CGF, Return, ResultType, Sel,
John McCall7f416cc2015-09-08 08:05:57 +00007356 ObjCSuper.getPointer(), ObjCTypes.SuperPtrCTy,
John McCall9e8bb002011-05-14 03:10:52 +00007357 true, CallArgs, Method)
7358 : EmitMessageSend(CGF, Return, ResultType,
John McCall882987f2013-02-28 19:01:20 +00007359 EmitSelector(CGF, Sel),
John McCall7f416cc2015-09-08 08:05:57 +00007360 ObjCSuper.getPointer(), ObjCTypes.SuperPtrCTy,
John McCall1e3157b2015-09-10 22:27:50 +00007361 true, CallArgs, Method, Class, ObjCTypes);
Fariborz Jahanian6b7cd6e2009-02-06 20:09:23 +00007362}
Fariborz Jahanian74b77222009-02-11 20:51:17 +00007363
John McCall882987f2013-02-28 19:01:20 +00007364llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00007365 Selector Sel) {
7366 Address Addr = EmitSelectorAddr(CGF, Sel);
7367
7368 llvm::LoadInst* LI = CGF.Builder.CreateLoad(Addr);
Fangrui Song6907ce22018-07-30 19:24:48 +00007369 LI->setMetadata(CGM.getModule().getMDKindID("invariant.load"),
John McCall7f416cc2015-09-08 08:05:57 +00007370 llvm::MDNode::get(VMContext, None));
7371 return LI;
7372}
7373
7374Address CGObjCNonFragileABIMac::EmitSelectorAddr(CodeGenFunction &CGF,
7375 Selector Sel) {
Fariborz Jahanian74b77222009-02-11 20:51:17 +00007376 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007377
John McCall7f416cc2015-09-08 08:05:57 +00007378 CharUnits Align = CGF.getPointerAlign();
Fariborz Jahanian74b77222009-02-11 20:51:17 +00007379 if (!Entry) {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007380 llvm::Constant *Casted =
7381 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
7382 ObjCTypes.SelectorPtrTy);
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00007383 Entry = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.SelectorPtrTy,
7384 false, llvm::GlobalValue::PrivateLinkage,
7385 Casted, "OBJC_SELECTOR_REFERENCES_");
Michael Gottesman5c205962013-02-05 23:08:45 +00007386 Entry->setExternallyInitialized(true);
Saleem Abdulrasool13d73d52017-06-03 16:18:09 +00007387 Entry->setSection(GetSectionName("__objc_selrefs",
7388 "literal_pointers,no_dead_strip"));
John McCall7f416cc2015-09-08 08:05:57 +00007389 Entry->setAlignment(Align.getQuantity());
Rafael Espindola060062a2014-03-06 22:15:10 +00007390 CGM.addCompilerUsedGlobal(Entry);
Fariborz Jahanian74b77222009-02-11 20:51:17 +00007391 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007392
John McCall7f416cc2015-09-08 08:05:57 +00007393 return Address(Entry, Align);
Fariborz Jahanian74b77222009-02-11 20:51:17 +00007394}
John McCall7f416cc2015-09-08 08:05:57 +00007395
Fariborz Jahanian06292952009-02-16 22:52:32 +00007396/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00007397/// objc_assign_ivar (id src, id *dst, ptrdiff_t)
Fariborz Jahanian06292952009-02-16 22:52:32 +00007398///
7399void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +00007400 llvm::Value *src,
John McCall7f416cc2015-09-08 08:05:57 +00007401 Address dst,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00007402 llvm::Value *ivarOffset) {
Chris Lattner2192fe52011-07-18 04:24:23 +00007403 llvm::Type * SrcTy = src->getType();
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00007404 if (!isa<llvm::PointerType>(SrcTy)) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00007405 unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00007406 assert(Size <= 8 && "does not support size > 8");
7407 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
7408 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian1b074a32009-03-13 00:42:52 +00007409 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
7410 }
Fariborz Jahanian06292952009-02-16 22:52:32 +00007411 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
7412 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00007413 llvm::Value *args[] = { src, dst.getPointer(), ivarOffset };
John McCall882987f2013-02-28 19:01:20 +00007414 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignIvarFn(), args);
Fariborz Jahanian06292952009-02-16 22:52:32 +00007415}
7416
7417/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
7418/// objc_assign_strongCast (id src, id *dst)
7419///
7420void CGObjCNonFragileABIMac::EmitObjCStrongCastAssign(
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007421 CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00007422 llvm::Value *src, Address dst) {
Chris Lattner2192fe52011-07-18 04:24:23 +00007423 llvm::Type * SrcTy = src->getType();
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00007424 if (!isa<llvm::PointerType>(SrcTy)) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00007425 unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00007426 assert(Size <= 8 && "does not support size > 8");
7427 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007428 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian1b074a32009-03-13 00:42:52 +00007429 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
7430 }
Fariborz Jahanian06292952009-02-16 22:52:32 +00007431 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
7432 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00007433 llvm::Value *args[] = { src, dst.getPointer() };
John McCall882987f2013-02-28 19:01:20 +00007434 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignStrongCastFn(),
7435 args, "weakassign");
Fariborz Jahanian06292952009-02-16 22:52:32 +00007436}
7437
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00007438void CGObjCNonFragileABIMac::EmitGCMemmoveCollectable(
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007439 CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00007440 Address DestPtr,
7441 Address SrcPtr,
Fariborz Jahanian021510e2010-06-15 22:44:06 +00007442 llvm::Value *Size) {
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00007443 SrcPtr = CGF.Builder.CreateBitCast(SrcPtr, ObjCTypes.Int8PtrTy);
7444 DestPtr = CGF.Builder.CreateBitCast(DestPtr, ObjCTypes.Int8PtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00007445 llvm::Value *args[] = { DestPtr.getPointer(), SrcPtr.getPointer(), Size };
John McCall882987f2013-02-28 19:01:20 +00007446 CGF.EmitNounwindRuntimeCall(ObjCTypes.GcMemmoveCollectableFn(), args);
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00007447}
7448
Fariborz Jahanian06292952009-02-16 22:52:32 +00007449/// EmitObjCWeakRead - Code gen for loading value of a __weak
7450/// object: objc_read_weak (id *src)
7451///
7452llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead(
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007453 CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00007454 Address AddrWeakObj) {
7455 llvm::Type *DestTy = AddrWeakObj.getElementType();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007456 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
John McCall882987f2013-02-28 19:01:20 +00007457 llvm::Value *read_weak =
7458 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcReadWeakFn(),
John McCall7f416cc2015-09-08 08:05:57 +00007459 AddrWeakObj.getPointer(), "weakread");
Eli Friedmana374b682009-03-07 03:57:15 +00007460 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian06292952009-02-16 22:52:32 +00007461 return read_weak;
7462}
7463
7464/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
7465/// objc_assign_weak (id src, id *dst)
7466///
7467void CGObjCNonFragileABIMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00007468 llvm::Value *src, Address dst) {
Chris Lattner2192fe52011-07-18 04:24:23 +00007469 llvm::Type * SrcTy = src->getType();
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00007470 if (!isa<llvm::PointerType>(SrcTy)) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00007471 unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00007472 assert(Size <= 8 && "does not support size > 8");
7473 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
7474 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian1b074a32009-03-13 00:42:52 +00007475 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
7476 }
Fariborz Jahanian06292952009-02-16 22:52:32 +00007477 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
7478 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00007479 llvm::Value *args[] = { src, dst.getPointer() };
John McCall882987f2013-02-28 19:01:20 +00007480 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignWeakFn(),
7481 args, "weakassign");
Fariborz Jahanian06292952009-02-16 22:52:32 +00007482}
7483
7484/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
7485/// objc_assign_global (id src, id *dst)
7486///
7487void CGObjCNonFragileABIMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00007488 llvm::Value *src, Address dst,
Fariborz Jahanian217af242010-07-20 20:30:03 +00007489 bool threadlocal) {
Chris Lattner2192fe52011-07-18 04:24:23 +00007490 llvm::Type * SrcTy = src->getType();
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00007491 if (!isa<llvm::PointerType>(SrcTy)) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00007492 unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00007493 assert(Size <= 8 && "does not support size > 8");
7494 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
7495 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian1b074a32009-03-13 00:42:52 +00007496 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
7497 }
Fariborz Jahanian06292952009-02-16 22:52:32 +00007498 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
7499 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00007500 llvm::Value *args[] = { src, dst.getPointer() };
Fariborz Jahanian217af242010-07-20 20:30:03 +00007501 if (!threadlocal)
John McCall882987f2013-02-28 19:01:20 +00007502 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignGlobalFn(),
7503 args, "globalassign");
Fariborz Jahanian217af242010-07-20 20:30:03 +00007504 else
John McCall882987f2013-02-28 19:01:20 +00007505 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignThreadLocalFn(),
7506 args, "threadlocalassign");
Fariborz Jahanian06292952009-02-16 22:52:32 +00007507}
Fariborz Jahanian74b77222009-02-11 20:51:17 +00007508
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007509void
John McCallbd309292010-07-06 01:34:17 +00007510CGObjCNonFragileABIMac::EmitSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
7511 const ObjCAtSynchronizedStmt &S) {
David Chisnall3e575602011-03-25 17:46:35 +00007512 EmitAtSynchronizedStmt(CGF, S,
7513 cast<llvm::Function>(ObjCTypes.getSyncEnterFn()),
7514 cast<llvm::Function>(ObjCTypes.getSyncExitFn()));
John McCallbd309292010-07-06 01:34:17 +00007515}
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007516
John McCall2ca705e2010-07-24 00:37:23 +00007517llvm::Constant *
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +00007518CGObjCNonFragileABIMac::GetEHType(QualType T) {
John McCall2ca705e2010-07-24 00:37:23 +00007519 // There's a particular fixed type info for 'id'.
Saleem Abdulrasoole5f3eae2016-07-17 22:27:38 +00007520 if (T->isObjCIdType() || T->isObjCQualifiedIdType()) {
7521 auto *IDEHType = CGM.getModule().getGlobalVariable("OBJC_EHTYPE_id");
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00007522 if (!IDEHType) {
John McCall2ca705e2010-07-24 00:37:23 +00007523 IDEHType =
Saleem Abdulrasoole5f3eae2016-07-17 22:27:38 +00007524 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.EHTypeTy, false,
7525 llvm::GlobalValue::ExternalLinkage, nullptr,
7526 "OBJC_EHTYPE_id");
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00007527 if (CGM.getTriple().isOSBinFormatCOFF())
7528 IDEHType->setDLLStorageClass(getStorage(CGM, "OBJC_EHTYPE_id"));
7529 }
John McCall2ca705e2010-07-24 00:37:23 +00007530 return IDEHType;
7531 }
7532
7533 // All other types should be Objective-C interface pointer types.
Saleem Abdulrasoole5f3eae2016-07-17 22:27:38 +00007534 const ObjCObjectPointerType *PT = T->getAs<ObjCObjectPointerType>();
John McCall2ca705e2010-07-24 00:37:23 +00007535 assert(PT && "Invalid @catch type.");
Saleem Abdulrasoole5f3eae2016-07-17 22:27:38 +00007536
John McCall2ca705e2010-07-24 00:37:23 +00007537 const ObjCInterfaceType *IT = PT->getInterfaceType();
7538 assert(IT && "Invalid @catch type.");
Saleem Abdulrasoole5f3eae2016-07-17 22:27:38 +00007539
John McCalldba63a72016-11-30 23:54:50 +00007540 return GetInterfaceEHType(IT->getDecl(), NotForDefinition);
Saleem Abdulrasoole5f3eae2016-07-17 22:27:38 +00007541}
John McCall2ca705e2010-07-24 00:37:23 +00007542
John McCallbd309292010-07-06 01:34:17 +00007543void CGObjCNonFragileABIMac::EmitTryStmt(CodeGen::CodeGenFunction &CGF,
7544 const ObjCAtTryStmt &S) {
David Chisnall3e575602011-03-25 17:46:35 +00007545 EmitTryCatchStmt(CGF, S,
7546 cast<llvm::Function>(ObjCTypes.getObjCBeginCatchFn()),
7547 cast<llvm::Function>(ObjCTypes.getObjCEndCatchFn()),
7548 cast<llvm::Function>(ObjCTypes.getExceptionRethrowFn()));
Daniel Dunbar0b0dcd92009-02-24 07:47:38 +00007549}
7550
Anders Carlsson9ab53d12009-02-16 22:59:18 +00007551/// EmitThrowStmt - Generate code for a throw statement.
7552void CGObjCNonFragileABIMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian1eab0522013-01-10 19:02:56 +00007553 const ObjCAtThrowStmt &S,
7554 bool ClearInsertionPoint) {
Anders Carlsson9ab53d12009-02-16 22:59:18 +00007555 if (const Expr *ThrowExpr = S.getThrowExpr()) {
John McCall248512a2011-10-01 10:32:24 +00007556 llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00007557 Exception = CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy);
John McCall882987f2013-02-28 19:01:20 +00007558 CGF.EmitRuntimeCallOrInvoke(ObjCTypes.getExceptionThrowFn(), Exception)
John McCall17afe452010-10-16 08:21:07 +00007559 .setDoesNotReturn();
Anders Carlsson9ab53d12009-02-16 22:59:18 +00007560 } else {
John McCall882987f2013-02-28 19:01:20 +00007561 CGF.EmitRuntimeCallOrInvoke(ObjCTypes.getExceptionRethrowFn())
John McCall17afe452010-10-16 08:21:07 +00007562 .setDoesNotReturn();
Anders Carlsson9ab53d12009-02-16 22:59:18 +00007563 }
7564
John McCall17afe452010-10-16 08:21:07 +00007565 CGF.Builder.CreateUnreachable();
Fariborz Jahanian1eab0522013-01-10 19:02:56 +00007566 if (ClearInsertionPoint)
7567 CGF.Builder.ClearInsertionPoint();
Anders Carlsson9ab53d12009-02-16 22:59:18 +00007568}
Daniel Dunbarb1559a42009-03-01 04:46:24 +00007569
John McCall2ca705e2010-07-24 00:37:23 +00007570llvm::Constant *
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007571CGObjCNonFragileABIMac::GetInterfaceEHType(const ObjCInterfaceDecl *ID,
John McCalldba63a72016-11-30 23:54:50 +00007572 ForDefinition_t IsForDefinition) {
Daniel Dunbarb1559a42009-03-01 04:46:24 +00007573 llvm::GlobalVariable * &Entry = EHTypeReferences[ID->getIdentifier()];
Saleem Abdulrasoole5f3eae2016-07-17 22:27:38 +00007574 StringRef ClassName = ID->getObjCRuntimeNameAsString();
Daniel Dunbarb1559a42009-03-01 04:46:24 +00007575
Daniel Dunbar8f28d012009-04-08 04:21:03 +00007576 // If we don't need a definition, return the entry if found or check
7577 // if we use an external reference.
John McCalldba63a72016-11-30 23:54:50 +00007578 if (!IsForDefinition) {
Daniel Dunbar8f28d012009-04-08 04:21:03 +00007579 if (Entry)
7580 return Entry;
Daniel Dunbard7beeea2009-04-07 06:43:45 +00007581
Daniel Dunbar8f28d012009-04-08 04:21:03 +00007582 // If this type (or a super class) has the __objc_exception__
7583 // attribute, emit an external reference.
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00007584 if (hasObjCExceptionAttribute(CGM.getContext(), ID)) {
7585 std::string EHTypeName = ("OBJC_EHTYPE_$_" + ClassName).str();
7586 Entry = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.EHTypeTy,
7587 false, llvm::GlobalValue::ExternalLinkage,
7588 nullptr, EHTypeName);
Rafael Espindolab7350042018-03-01 00:35:47 +00007589 CGM.setGVProperties(Entry, ID);
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00007590 return Entry;
7591 }
Daniel Dunbar8f28d012009-04-08 04:21:03 +00007592 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007593
Saleem Abdulrasoole5f3eae2016-07-17 22:27:38 +00007594 // Otherwise we need to either make a new entry or fill in the initializer.
Daniel Dunbar8f28d012009-04-08 04:21:03 +00007595 assert((!Entry || !Entry->hasInitializer()) && "Duplicate EHType definition");
Saleem Abdulrasoole5f3eae2016-07-17 22:27:38 +00007596
Daniel Dunbarb1559a42009-03-01 04:46:24 +00007597 std::string VTableName = "objc_ehtype_vtable";
Saleem Abdulrasoole5f3eae2016-07-17 22:27:38 +00007598 auto *VTableGV = CGM.getModule().getGlobalVariable(VTableName);
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00007599 if (!VTableGV) {
Saleem Abdulrasoole5f3eae2016-07-17 22:27:38 +00007600 VTableGV =
7601 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.Int8PtrTy, false,
7602 llvm::GlobalValue::ExternalLinkage, nullptr,
7603 VTableName);
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00007604 if (CGM.getTriple().isOSBinFormatCOFF())
7605 VTableGV->setDLLStorageClass(getStorage(CGM, VTableName));
7606 }
Daniel Dunbarb1559a42009-03-01 04:46:24 +00007607
Chris Lattnerece04092012-02-07 00:39:47 +00007608 llvm::Value *VTableIdx = llvm::ConstantInt::get(CGM.Int32Ty, 2);
John McCall176f8922016-11-30 02:39:18 +00007609 ConstantInitBuilder builder(CGM);
7610 auto values = builder.beginStruct(ObjCTypes.EHTypeTy);
Ahmed Bougacha5d0199a2017-11-17 19:46:47 +00007611 values.add(
7612 llvm::ConstantExpr::getInBoundsGetElementPtr(VTableGV->getValueType(),
7613 VTableGV, VTableIdx));
John McCalldba63a72016-11-30 23:54:50 +00007614 values.add(GetClassName(ClassName));
7615 values.add(GetClassGlobal(ID, /*metaclass*/ false, NotForDefinition));
Daniel Dunbarb1559a42009-03-01 04:46:24 +00007616
John McCalldba63a72016-11-30 23:54:50 +00007617 llvm::GlobalValue::LinkageTypes L = IsForDefinition
Rafael Espindola554256c2014-02-26 22:25:45 +00007618 ? llvm::GlobalValue::ExternalLinkage
7619 : llvm::GlobalValue::WeakAnyLinkage;
Daniel Dunbar8f28d012009-04-08 04:21:03 +00007620 if (Entry) {
John McCall176f8922016-11-30 02:39:18 +00007621 values.finishAndSetAsInitializer(Entry);
7622 Entry->setAlignment(CGM.getPointerAlign().getQuantity());
Daniel Dunbar8f28d012009-04-08 04:21:03 +00007623 } else {
John McCall176f8922016-11-30 02:39:18 +00007624 Entry = values.finishAndCreateGlobal("OBJC_EHTYPE_$_" + ClassName,
7625 CGM.getPointerAlign(),
7626 /*constant*/ false,
7627 L);
Rafael Espindolab7350042018-03-01 00:35:47 +00007628 if (hasObjCExceptionAttribute(CGM.getContext(), ID))
7629 CGM.setGVProperties(Entry, ID);
Daniel Dunbar8f28d012009-04-08 04:21:03 +00007630 }
Rafael Espindola554256c2014-02-26 22:25:45 +00007631 assert(Entry->getLinkage() == L);
Daniel Dunbar8f28d012009-04-08 04:21:03 +00007632
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00007633 if (!CGM.getTriple().isOSBinFormatCOFF())
7634 if (ID->getVisibility() == HiddenVisibility)
7635 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
Saleem Abdulrasoole5f3eae2016-07-17 22:27:38 +00007636
John McCalldba63a72016-11-30 23:54:50 +00007637 if (IsForDefinition)
Saleem Abdulrasool3c628af2016-10-25 21:43:28 +00007638 if (CGM.getTriple().isOSBinFormatMachO())
7639 Entry->setSection("__DATA,__objc_const");
Daniel Dunbarb1559a42009-03-01 04:46:24 +00007640
7641 return Entry;
7642}
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007643
Daniel Dunbar8b8683f2008-08-12 00:12:39 +00007644/* *** */
7645
Daniel Dunbarb036db82008-08-13 03:21:16 +00007646CodeGen::CGObjCRuntime *
7647CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
John McCall5fb5df92012-06-20 06:18:46 +00007648 switch (CGM.getLangOpts().ObjCRuntime.getKind()) {
7649 case ObjCRuntime::FragileMacOSX:
Daniel Dunbar303e2c22008-08-11 02:45:11 +00007650 return new CGObjCMac(CGM);
John McCall5fb5df92012-06-20 06:18:46 +00007651
7652 case ObjCRuntime::MacOSX:
7653 case ObjCRuntime::iOS:
Tim Northover756447a2015-10-30 16:30:36 +00007654 case ObjCRuntime::WatchOS:
John McCall5fb5df92012-06-20 06:18:46 +00007655 return new CGObjCNonFragileABIMac(CGM);
7656
David Chisnallb601c962012-07-03 20:49:52 +00007657 case ObjCRuntime::GNUstep:
7658 case ObjCRuntime::GCC:
John McCall775086e2012-07-12 02:07:58 +00007659 case ObjCRuntime::ObjFW:
John McCall5fb5df92012-06-20 06:18:46 +00007660 llvm_unreachable("these runtimes are not Mac runtimes");
7661 }
7662 llvm_unreachable("bad runtime");
Daniel Dunbar303e2c22008-08-11 02:45:11 +00007663}