blob: 201bc518f5f85561f8ad698adeb979b77e31288e [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"
Daniel Dunbar8b8683f2008-08-12 00:12:39 +000020#include "clang/AST/ASTContext.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000021#include "clang/AST/Decl.h"
Daniel Dunbarb036db82008-08-13 03:21:16 +000022#include "clang/AST/DeclObjC.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000023#include "clang/AST/RecordLayout.h"
Chris Lattnerf0b64d72009-04-26 01:32:48 +000024#include "clang/AST/StmtObjC.h"
Daniel Dunbar3ad53482008-08-11 21:35:06 +000025#include "clang/Basic/LangOptions.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000026#include "clang/CodeGen/CGFunctionInfo.h"
Saleem Abdulrasool10a49722016-04-08 16:52:00 +000027#include "clang/Frontend/CodeGenOptions.h"
Justin Lebar5e83dfe2016-10-21 21:45:01 +000028#include "llvm/ADT/CachedHashString.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000029#include "llvm/ADT/DenseSet.h"
30#include "llvm/ADT/SetVector.h"
31#include "llvm/ADT/SmallPtrSet.h"
32#include "llvm/ADT/SmallString.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000033#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000034#include "llvm/IR/DataLayout.h"
35#include "llvm/IR/InlineAsm.h"
36#include "llvm/IR/IntrinsicInst.h"
37#include "llvm/IR/LLVMContext.h"
38#include "llvm/IR/Module.h"
Daniel Dunbard027a922009-09-07 00:20:42 +000039#include "llvm/Support/raw_ostream.h"
Torok Edwindb714922009-08-24 13:25:12 +000040#include <cstdio>
Daniel Dunbar303e2c22008-08-11 02:45:11 +000041
42using namespace clang;
Daniel Dunbar41cf9de2008-09-09 01:06:48 +000043using namespace CodeGen;
Daniel Dunbar303e2c22008-08-11 02:45:11 +000044
45namespace {
Daniel Dunbar8b8683f2008-08-12 00:12:39 +000046
Daniel Dunbar59e476b2009-08-03 17:06:42 +000047// FIXME: We should find a nicer way to make the labels for metadata, string
48// concatenation is lame.
Daniel Dunbarb036db82008-08-13 03:21:16 +000049
Fariborz Jahanian279eda62009-01-21 22:04:16 +000050class ObjCCommonTypesHelper {
Owen Anderson170229f2009-07-14 23:10:40 +000051protected:
52 llvm::LLVMContext &VMContext;
Daniel Dunbar59e476b2009-08-03 17:06:42 +000053
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +000054private:
John McCall9dc0db22011-05-15 01:53:33 +000055 // The types of these functions don't really matter because we
56 // should always bitcast before calling them.
57
58 /// id objc_msgSend (id, SEL, ...)
59 ///
60 /// The default messenger, used for sends whose ABI is unchanged from
61 /// the all-integer/pointer case.
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +000062 llvm::Constant *getMessageSendFn() const {
John McCall31168b02011-06-15 23:02:42 +000063 // Add the non-lazy-bind attribute, since objc_msgSend is likely to
64 // be called a lot.
Chris Lattnera5f58b02011-07-09 17:41:47 +000065 llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy };
Bill Wendling8594fcb2013-01-31 00:30:05 +000066 return
67 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
68 params, true),
69 "objc_msgSend",
70 llvm::AttributeSet::get(CGM.getLLVMContext(),
71 llvm::AttributeSet::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);
109 llvm::Type *resultType =
Reid Kleckneree7cf842014-12-01 22:02:27 +0000110 llvm::StructType::get(longDoubleType, longDoubleType, nullptr);
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:
Chris Lattnera5f58b02011-07-09 17:41:47 +0000176 llvm::Type *ShortTy, *IntTy, *LongTy, *LongLongTy;
Bob Wilson5f4e3a72011-11-30 01:57:58 +0000177 llvm::Type *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))
Chris Lattnera5f58b02011-07-09 17:41:47 +0000181 llvm::Type *ObjectPtrTy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000182
Fariborz Jahanian406b1172008-11-18 20:18:11 +0000183 /// PtrObjectPtrTy - LLVM type for id *
Chris Lattnera5f58b02011-07-09 17:41:47 +0000184 llvm::Type *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))
Chris Lattnera5f58b02011-07-09 17:41:47 +0000187 llvm::Type *SelectorPtrTy;
Douglas Gregor020de322012-01-17 18:36:30 +0000188
189private:
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;
Douglas Gregor020de322012-01-17 18:36:30 +0000193
194public:
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 }
204
205 return ExternalProtocolPtrTy;
206 }
207
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 *.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000216 llvm::Type *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*.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000226 llvm::Type *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 *.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000234 llvm::Type *CachePtrTy;
Fariborz Jahanian0a3cfcc2011-06-22 20:21:51 +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();
273 // void objc_setProperty_atomic(id self, SEL _cmd,
274 // id newValue, ptrdiff_t offset);
275 // void objc_setProperty_nonatomic(id self, SEL _cmd,
276 // id newValue, ptrdiff_t offset);
277 // void objc_setProperty_atomic_copy(id self, SEL _cmd,
278 // id newValue, ptrdiff_t offset);
279 // void objc_setProperty_nonatomic_copy(id self, SEL _cmd,
280 // id newValue, ptrdiff_t offset);
281
282 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";
301
302 return CGM.CreateRuntimeFunction(FTy, name);
303 }
Fariborz Jahanian5a8c2032010-04-12 18:18:10 +0000304
305 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);
312 Params.push_back(Ctx.LongTy);
313 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 }
320
Fariborz Jahanian1e1b5492012-01-06 18:07:23 +0000321 /// This routine declares and returns address of:
322 /// void objc_copyCppObjectAtomic(
323 /// void *dest, const void *src,
324 /// 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 }
338
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 }
400
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 }
443
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 *.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000504 llvm::Type *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 *.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000511 llvm::Type *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 *.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000517 llvm::Type *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 *.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000526 llvm::Type *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*.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000530 llvm::Type *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 *.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000536 llvm::Type *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 *.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000540 llvm::Type *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.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000544 llvm::Type *IvarListTy;
Daniel Dunbar22d82ed2008-08-21 04:36:09 +0000545 /// IvarListPtrTy - LLVM type for struct objc_ivar_list *.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000546 llvm::Type *IvarListPtrTy;
Daniel Dunbar22d82ed2008-08-21 04:36:09 +0000547 /// MethodListTy - LLVM type for struct objc_method_list.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000548 llvm::Type *MethodListTy;
Daniel Dunbar22d82ed2008-08-21 04:36:09 +0000549 /// MethodListPtrTy - LLVM type for struct objc_method_list *.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000550 llvm::Type *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.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000553 llvm::Type *ExceptionDataTy;
Fariborz Jahanian0a3cfcc2011-06-22 20:21:51 +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() };
Bill Wendling8594fcb2013-01-31 00:30:05 +0000591 return
592 CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.Int32Ty,
593 params, false),
594 "_setjmp",
595 llvm::AttributeSet::get(CGM.getLLVMContext(),
596 llvm::AttributeSet::FunctionIndex,
597 llvm::Attribute::NonLazyBind));
Chris Lattnerc6406db2009-04-22 02:26:14 +0000598 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000599
Daniel Dunbar8b8683f2008-08-12 00:12:39 +0000600public:
601 ObjCTypesHelper(CodeGen::CodeGenModule &cgm);
Daniel Dunbar8b8683f2008-08-12 00:12:39 +0000602};
603
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +0000604/// ObjCNonFragileABITypesHelper - will have all types needed by objective-c's
Fariborz Jahanian279eda62009-01-21 22:04:16 +0000605/// modern abi
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +0000606class ObjCNonFragileABITypesHelper : public ObjCCommonTypesHelper {
Fariborz Jahaniane4dc35d2009-02-04 20:42:28 +0000607public:
Fariborz Jahanian0232c052009-01-23 01:46:23 +0000608 // MethodListnfABITy - LLVM for struct _method_list_t
Chris Lattnera5f58b02011-07-09 17:41:47 +0000609 llvm::StructType *MethodListnfABITy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000610
Fariborz Jahanian0232c052009-01-23 01:46:23 +0000611 // MethodListnfABIPtrTy - LLVM for struct _method_list_t*
Chris Lattnera5f58b02011-07-09 17:41:47 +0000612 llvm::Type *MethodListnfABIPtrTy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000613
Fariborz Jahanian0232c052009-01-23 01:46:23 +0000614 // ProtocolnfABITy = LLVM for struct _protocol_t
Chris Lattnera5f58b02011-07-09 17:41:47 +0000615 llvm::StructType *ProtocolnfABITy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000616
Daniel Dunbar8de90f02009-02-15 07:36:20 +0000617 // ProtocolnfABIPtrTy = LLVM for struct _protocol_t*
Chris Lattnera5f58b02011-07-09 17:41:47 +0000618 llvm::Type *ProtocolnfABIPtrTy;
Daniel Dunbar8de90f02009-02-15 07:36:20 +0000619
Fariborz Jahanian0232c052009-01-23 01:46:23 +0000620 // ProtocolListnfABITy - LLVM for struct _objc_protocol_list
Chris Lattnera5f58b02011-07-09 17:41:47 +0000621 llvm::StructType *ProtocolListnfABITy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000622
Fariborz Jahanian0232c052009-01-23 01:46:23 +0000623 // ProtocolListnfABIPtrTy - LLVM for struct _objc_protocol_list*
Chris Lattnera5f58b02011-07-09 17:41:47 +0000624 llvm::Type *ProtocolListnfABIPtrTy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000625
Fariborz Jahanian0232c052009-01-23 01:46:23 +0000626 // ClassnfABITy - LLVM for struct _class_t
Chris Lattnera5f58b02011-07-09 17:41:47 +0000627 llvm::StructType *ClassnfABITy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000628
Fariborz Jahanian71394042009-01-23 23:53:38 +0000629 // ClassnfABIPtrTy - LLVM for struct _class_t*
Chris Lattnera5f58b02011-07-09 17:41:47 +0000630 llvm::Type *ClassnfABIPtrTy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000631
Fariborz Jahanian0232c052009-01-23 01:46:23 +0000632 // IvarnfABITy - LLVM for struct _ivar_t
Chris Lattnera5f58b02011-07-09 17:41:47 +0000633 llvm::StructType *IvarnfABITy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000634
Fariborz Jahanian0232c052009-01-23 01:46:23 +0000635 // IvarListnfABITy - LLVM for struct _ivar_list_t
Chris Lattnera5f58b02011-07-09 17:41:47 +0000636 llvm::StructType *IvarListnfABITy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000637
Fariborz Jahanian0232c052009-01-23 01:46:23 +0000638 // IvarListnfABIPtrTy = LLVM for struct _ivar_list_t*
Chris Lattnera5f58b02011-07-09 17:41:47 +0000639 llvm::Type *IvarListnfABIPtrTy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000640
Fariborz Jahanian0232c052009-01-23 01:46:23 +0000641 // ClassRonfABITy - LLVM for struct _class_ro_t
Chris Lattnera5f58b02011-07-09 17:41:47 +0000642 llvm::StructType *ClassRonfABITy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000643
Fariborz Jahanian0232c052009-01-23 01:46:23 +0000644 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
Chris Lattnera5f58b02011-07-09 17:41:47 +0000645 llvm::Type *ImpnfABITy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000646
Fariborz Jahanian0232c052009-01-23 01:46:23 +0000647 // CategorynfABITy - LLVM for struct _category_t
Chris Lattnera5f58b02011-07-09 17:41:47 +0000648 llvm::StructType *CategorynfABITy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000649
Fariborz Jahanian82c72e12009-02-03 23:49:23 +0000650 // New types for nonfragile abi messaging.
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000651
Fariborz Jahanian82c72e12009-02-03 23:49:23 +0000652 // MessageRefTy - LLVM for:
653 // struct _message_ref_t {
654 // IMP messenger;
655 // SEL name;
656 // };
Chris Lattnera5f58b02011-07-09 17:41:47 +0000657 llvm::StructType *MessageRefTy;
Fariborz Jahaniane4dc35d2009-02-04 20:42:28 +0000658 // MessageRefCTy - clang type for struct _message_ref_t
659 QualType MessageRefCTy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000660
Fariborz Jahanian82c72e12009-02-03 23:49:23 +0000661 // MessageRefPtrTy - LLVM for struct _message_ref_t*
Chris Lattnera5f58b02011-07-09 17:41:47 +0000662 llvm::Type *MessageRefPtrTy;
Fariborz Jahaniane4dc35d2009-02-04 20:42:28 +0000663 // MessageRefCPtrTy - clang type for struct _message_ref_t*
664 QualType MessageRefCPtrTy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000665
Fariborz Jahanian82c72e12009-02-03 23:49:23 +0000666 // SuperMessageRefTy - LLVM for:
667 // struct _super_message_ref_t {
668 // SUPER_IMP messenger;
669 // SEL name;
670 // };
Chris Lattnera5f58b02011-07-09 17:41:47 +0000671 llvm::StructType *SuperMessageRefTy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000672
Fariborz Jahanian82c72e12009-02-03 23:49:23 +0000673 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
Chris Lattnera5f58b02011-07-09 17:41:47 +0000674 llvm::Type *SuperMessageRefPtrTy;
Daniel Dunbar0b0dcd92009-02-24 07:47:38 +0000675
Chris Lattner2dfdb3e2009-04-22 02:53:24 +0000676 llvm::Constant *getMessageSendFixupFn() {
677 // id objc_msgSend_fixup(id, struct message_ref_t*, ...)
Chris Lattnera5f58b02011-07-09 17:41:47 +0000678 llvm::Type *params[] = { ObjectPtrTy, MessageRefPtrTy };
Owen Anderson9793f0e2009-07-29 22:16:19 +0000679 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
John McCall9dc0db22011-05-15 01:53:33 +0000680 params, true),
Chris Lattner2dfdb3e2009-04-22 02:53:24 +0000681 "objc_msgSend_fixup");
682 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000683
Chris Lattner2dfdb3e2009-04-22 02:53:24 +0000684 llvm::Constant *getMessageSendFpretFixupFn() {
685 // id objc_msgSend_fpret_fixup(id, struct message_ref_t*, ...)
Chris Lattnera5f58b02011-07-09 17:41:47 +0000686 llvm::Type *params[] = { ObjectPtrTy, MessageRefPtrTy };
Owen Anderson9793f0e2009-07-29 22:16:19 +0000687 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
John McCall9dc0db22011-05-15 01:53:33 +0000688 params, true),
Chris Lattner2dfdb3e2009-04-22 02:53:24 +0000689 "objc_msgSend_fpret_fixup");
690 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000691
Chris Lattner2dfdb3e2009-04-22 02:53:24 +0000692 llvm::Constant *getMessageSendStretFixupFn() {
693 // id objc_msgSend_stret_fixup(id, struct message_ref_t*, ...)
Chris Lattnera5f58b02011-07-09 17:41:47 +0000694 llvm::Type *params[] = { ObjectPtrTy, MessageRefPtrTy };
Owen Anderson9793f0e2009-07-29 22:16:19 +0000695 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
John McCall9dc0db22011-05-15 01:53:33 +0000696 params, true),
Chris Lattner2dfdb3e2009-04-22 02:53:24 +0000697 "objc_msgSend_stret_fixup");
698 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000699
Chris Lattner2dfdb3e2009-04-22 02:53:24 +0000700 llvm::Constant *getMessageSendSuper2FixupFn() {
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000701 // id objc_msgSendSuper2_fixup (struct objc_super *,
Chris Lattner2dfdb3e2009-04-22 02:53:24 +0000702 // struct _super_message_ref_t*, ...)
Chris Lattnera5f58b02011-07-09 17:41:47 +0000703 llvm::Type *params[] = { SuperPtrTy, SuperMessageRefPtrTy };
Owen Anderson9793f0e2009-07-29 22:16:19 +0000704 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
John McCall9dc0db22011-05-15 01:53:33 +0000705 params, true),
Chris Lattner2dfdb3e2009-04-22 02:53:24 +0000706 "objc_msgSendSuper2_fixup");
707 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000708
Chris Lattner2dfdb3e2009-04-22 02:53:24 +0000709 llvm::Constant *getMessageSendSuper2StretFixupFn() {
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000710 // id objc_msgSendSuper2_stret_fixup(struct objc_super *,
Chris Lattner2dfdb3e2009-04-22 02:53:24 +0000711 // struct _super_message_ref_t*, ...)
Chris Lattnera5f58b02011-07-09 17:41:47 +0000712 llvm::Type *params[] = { SuperPtrTy, SuperMessageRefPtrTy };
Owen Anderson9793f0e2009-07-29 22:16:19 +0000713 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
John McCall9dc0db22011-05-15 01:53:33 +0000714 params, true),
Chris Lattner2dfdb3e2009-04-22 02:53:24 +0000715 "objc_msgSendSuper2_stret_fixup");
716 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000717
Chris Lattnera7c00b42009-04-22 02:15:23 +0000718 llvm::Constant *getObjCEndCatchFn() {
John McCall9dc0db22011-05-15 01:53:33 +0000719 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.VoidTy, false),
Chris Lattnera7c00b42009-04-22 02:15:23 +0000720 "objc_end_catch");
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000721
Chris Lattnera7c00b42009-04-22 02:15:23 +0000722 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000723
Chris Lattnera7c00b42009-04-22 02:15:23 +0000724 llvm::Constant *getObjCBeginCatchFn() {
Chris Lattnera5f58b02011-07-09 17:41:47 +0000725 llvm::Type *params[] = { Int8PtrTy };
Owen Anderson9793f0e2009-07-29 22:16:19 +0000726 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(Int8PtrTy,
John McCall9dc0db22011-05-15 01:53:33 +0000727 params, false),
Chris Lattnera7c00b42009-04-22 02:15:23 +0000728 "objc_begin_catch");
729 }
Daniel Dunbarb1559a42009-03-01 04:46:24 +0000730
Chris Lattnera5f58b02011-07-09 17:41:47 +0000731 llvm::StructType *EHTypeTy;
732 llvm::Type *EHTypePtrTy;
Fariborz Jahanian0a3cfcc2011-06-22 20:21:51 +0000733
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +0000734 ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm);
Fariborz Jahanian279eda62009-01-21 22:04:16 +0000735};
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000736
Saleem Abdulrasool271106c2016-09-16 23:41:13 +0000737enum class ObjCLabelType {
738 ClassName,
739 MethodVarName,
740 MethodVarType,
741 PropertyName,
742};
743
Fariborz Jahanian279eda62009-01-21 22:04:16 +0000744class CGObjCCommonMac : public CodeGen::CGObjCRuntime {
Fariborz Jahaniancbaf73c2009-03-11 20:59:05 +0000745public:
Fariborz Jahaniancbaf73c2009-03-11 20:59:05 +0000746 class SKIP_SCAN {
Daniel Dunbar7b89ace2009-05-03 13:44:42 +0000747 public:
748 unsigned skip;
749 unsigned scan;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000750 SKIP_SCAN(unsigned _skip = 0, unsigned _scan = 0)
Daniel Dunbar7b89ace2009-05-03 13:44:42 +0000751 : skip(_skip), scan(_scan) {}
Fariborz Jahaniancbaf73c2009-03-11 20:59:05 +0000752 };
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000753
Fariborz Jahanian196f9382012-10-25 21:15:04 +0000754 /// opcode for captured block variables layout 'instructions'.
755 /// In the following descriptions, 'I' is the value of the immediate field.
756 /// (field following the opcode).
757 ///
758 enum BLOCK_LAYOUT_OPCODE {
759 /// An operator which affects how the following layout should be
760 /// interpreted.
761 /// I == 0: Halt interpretation and treat everything else as
762 /// a non-pointer. Note that this instruction is equal
763 /// to '\0'.
764 /// I != 0: Currently unused.
765 BLOCK_LAYOUT_OPERATOR = 0,
766
767 /// The next I+1 bytes do not contain a value of object pointer type.
768 /// Note that this can leave the stream unaligned, meaning that
769 /// subsequent word-size instructions do not begin at a multiple of
770 /// the pointer size.
771 BLOCK_LAYOUT_NON_OBJECT_BYTES = 1,
772
773 /// The next I+1 words do not contain a value of object pointer type.
774 /// This is simply an optimized version of BLOCK_LAYOUT_BYTES for
775 /// when the required skip quantity is a multiple of the pointer size.
776 BLOCK_LAYOUT_NON_OBJECT_WORDS = 2,
777
778 /// The next I+1 words are __strong pointers to Objective-C
779 /// objects or blocks.
780 BLOCK_LAYOUT_STRONG = 3,
781
782 /// The next I+1 words are pointers to __block variables.
783 BLOCK_LAYOUT_BYREF = 4,
784
785 /// The next I+1 words are __weak pointers to Objective-C
786 /// objects or blocks.
787 BLOCK_LAYOUT_WEAK = 5,
788
789 /// The next I+1 words are __unsafe_unretained pointers to
790 /// Objective-C objects or blocks.
791 BLOCK_LAYOUT_UNRETAINED = 6
792
793 /// The next I+1 words are block or object pointers with some
794 /// as-yet-unspecified ownership semantics. If we add more
795 /// flavors of ownership semantics, values will be taken from
796 /// this range.
797 ///
798 /// This is included so that older tools can at least continue
799 /// processing the layout past such things.
800 //BLOCK_LAYOUT_OWNERSHIP_UNKNOWN = 7..10,
801
802 /// All other opcodes are reserved. Halt interpretation and
803 /// treat everything else as opaque.
804 };
805
806 class RUN_SKIP {
807 public:
808 enum BLOCK_LAYOUT_OPCODE opcode;
Fariborz Jahanian7778d612012-11-07 20:00:32 +0000809 CharUnits block_var_bytepos;
810 CharUnits block_var_size;
Fariborz Jahanian196f9382012-10-25 21:15:04 +0000811 RUN_SKIP(enum BLOCK_LAYOUT_OPCODE Opcode = BLOCK_LAYOUT_OPERATOR,
Fariborz Jahanian7778d612012-11-07 20:00:32 +0000812 CharUnits BytePos = CharUnits::Zero(),
813 CharUnits Size = CharUnits::Zero())
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +0000814 : opcode(Opcode), block_var_bytepos(BytePos), block_var_size(Size) {}
Fariborz Jahanian196f9382012-10-25 21:15:04 +0000815
816 // Allow sorting based on byte pos.
817 bool operator<(const RUN_SKIP &b) const {
818 return block_var_bytepos < b.block_var_bytepos;
819 }
820 };
821
Fariborz Jahanian279eda62009-01-21 22:04:16 +0000822protected:
Owen Andersonae86c192009-07-13 04:10:07 +0000823 llvm::LLVMContext &VMContext;
Fariborz Jahanian279eda62009-01-21 22:04:16 +0000824 // FIXME! May not be needing this after all.
Daniel Dunbar8b8683f2008-08-12 00:12:39 +0000825 unsigned ObjCABI;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000826
Fariborz Jahanian196f9382012-10-25 21:15:04 +0000827 // arc/mrr layout of captured block literal variables.
828 SmallVector<RUN_SKIP, 16> RunSkipBlockVars;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000829
Daniel Dunbarc61d0e92008-08-25 06:02:07 +0000830 /// LazySymbols - Symbols to generate a lazy reference for. See
831 /// DefinedSymbols and FinishModule().
Daniel Dunbard027a922009-09-07 00:20:42 +0000832 llvm::SetVector<IdentifierInfo*> LazySymbols;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000833
Daniel Dunbarc61d0e92008-08-25 06:02:07 +0000834 /// DefinedSymbols - External symbols which are defined by this
835 /// module. The symbols in this list and LazySymbols are used to add
836 /// special linker symbols which ensure that Objective-C modules are
837 /// linked properly.
Daniel Dunbard027a922009-09-07 00:20:42 +0000838 llvm::SetVector<IdentifierInfo*> DefinedSymbols;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000839
Daniel Dunbar7bd00bd2008-08-12 06:48:42 +0000840 /// ClassNames - uniqued class names.
Fariborz Jahanian451b92a2014-07-16 16:16:04 +0000841 llvm::StringMap<llvm::GlobalVariable*> ClassNames;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000842
Daniel Dunbarcb515c82008-08-12 03:39:23 +0000843 /// MethodVarNames - uniqued method variable names.
844 llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000845
Fariborz Jahanian9adb2e62010-06-21 22:05:18 +0000846 /// DefinedCategoryNames - list of category names in form Class_Category.
Justin Lebar5e83dfe2016-10-21 21:45:01 +0000847 llvm::SmallSetVector<llvm::CachedHashString, 16> DefinedCategoryNames;
Fariborz Jahanian9adb2e62010-06-21 22:05:18 +0000848
Daniel Dunbarb036db82008-08-13 03:21:16 +0000849 /// MethodVarTypes - uniqued method type signatures. We have to use
850 /// a StringMap here because have no other unique reference.
851 llvm::StringMap<llvm::GlobalVariable*> MethodVarTypes;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000852
Daniel Dunbar3c76cb52008-08-26 21:51:14 +0000853 /// MethodDefinitions - map of methods which have been defined in
854 /// this translation unit.
855 llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> MethodDefinitions;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000856
Daniel Dunbar80a840b2008-08-23 00:19:03 +0000857 /// PropertyNames - uniqued method variable names.
858 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000859
Daniel Dunbar22d82ed2008-08-21 04:36:09 +0000860 /// ClassReferences - uniqued class references.
861 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000862
Daniel Dunbarcb515c82008-08-12 03:39:23 +0000863 /// SelectorReferences - uniqued selector references.
864 llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000865
Daniel Dunbarb036db82008-08-13 03:21:16 +0000866 /// Protocols - Protocols for which an objc_protocol structure has
867 /// been emitted. Forward declarations are handled by creating an
868 /// empty structure whose initializer is filled in when/if defined.
869 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> Protocols;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000870
Daniel Dunbarc475d422008-10-29 22:36:39 +0000871 /// DefinedProtocols - Protocols which have actually been
872 /// defined. We should not need this, see FIXME in GenerateProtocol.
873 llvm::DenseSet<IdentifierInfo*> DefinedProtocols;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000874
Daniel Dunbar22d82ed2008-08-21 04:36:09 +0000875 /// DefinedClasses - List of defined classes.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000876 SmallVector<llvm::GlobalValue*, 16> DefinedClasses;
Fariborz Jahanianf322f2f2014-03-11 00:25:05 +0000877
878 /// ImplementedClasses - List of @implemented classes.
879 SmallVector<const ObjCInterfaceDecl*, 16> ImplementedClasses;
Daniel Dunbar9a017d72009-05-15 22:33:15 +0000880
881 /// DefinedNonLazyClasses - List of defined "non-lazy" classes.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000882 SmallVector<llvm::GlobalValue*, 16> DefinedNonLazyClasses;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000883
Daniel Dunbar22d82ed2008-08-21 04:36:09 +0000884 /// DefinedCategories - List of defined categories.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000885 SmallVector<llvm::GlobalValue*, 16> DefinedCategories;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000886
Daniel Dunbar9a017d72009-05-15 22:33:15 +0000887 /// DefinedNonLazyCategories - List of defined "non-lazy" categories.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000888 SmallVector<llvm::GlobalValue*, 16> DefinedNonLazyCategories;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000889
Fariborz Jahanian0b1ccdc2009-01-21 23:34:32 +0000890 /// GetNameForMethod - Return a name for the given method.
891 /// \param[out] NameOut - The return value.
892 void GetNameForMethod(const ObjCMethodDecl *OMD,
893 const ObjCContainerDecl *CD,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000894 SmallVectorImpl<char> &NameOut);
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000895
Fariborz Jahanian0b1ccdc2009-01-21 23:34:32 +0000896 /// GetMethodVarName - Return a unique constant for the given
897 /// selector's name. The return value has type char *.
898 llvm::Constant *GetMethodVarName(Selector Sel);
899 llvm::Constant *GetMethodVarName(IdentifierInfo *Ident);
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000900
Fariborz Jahanian0b1ccdc2009-01-21 23:34:32 +0000901 /// GetMethodVarType - Return a unique constant for the given
Bob Wilson5f4e3a72011-11-30 01:57:58 +0000902 /// method's type encoding string. The return value has type char *.
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000903
Fariborz Jahanian0b1ccdc2009-01-21 23:34:32 +0000904 // FIXME: This is a horrible name.
Bob Wilson5f4e3a72011-11-30 01:57:58 +0000905 llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D,
906 bool Extended = false);
Daniel Dunbarf5c18462009-04-20 06:54:31 +0000907 llvm::Constant *GetMethodVarType(const FieldDecl *D);
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000908
Fariborz Jahanian0b1ccdc2009-01-21 23:34:32 +0000909 /// GetPropertyName - Return a unique constant for the given
910 /// name. The return value has type char *.
911 llvm::Constant *GetPropertyName(IdentifierInfo *Ident);
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000912
Fariborz Jahanian0b1ccdc2009-01-21 23:34:32 +0000913 // FIXME: This can be dropped once string functions are unified.
914 llvm::Constant *GetPropertyTypeString(const ObjCPropertyDecl *PD,
915 const Decl *Container);
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000916
Fariborz Jahanian9e3ad522009-01-24 20:21:50 +0000917 /// GetClassName - Return a unique constant for the given selector's
Fariborz Jahanian451b92a2014-07-16 16:16:04 +0000918 /// runtime name (which may change via use of objc_runtime_name attribute on
919 /// class or protocol definition. The return value has type char *.
920 llvm::Constant *GetClassName(StringRef RuntimeName);
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000921
Argyrios Kyrtzidis13257c52010-08-09 10:54:20 +0000922 llvm::Function *GetMethodDefinition(const ObjCMethodDecl *MD);
923
Fariborz Jahanianc559f3f2009-03-05 22:39:55 +0000924 /// BuildIvarLayout - Builds ivar layout bitmap for the class
925 /// implementation for the __strong or __weak case.
926 ///
John McCall460ce582015-10-22 18:38:17 +0000927 /// \param hasMRCWeakIvars - Whether we are compiling in MRC and there
928 /// are any weak ivars defined directly in the class. Meaningless unless
929 /// building a weak layout. Does not guarantee that the layout will
930 /// actually have any entries, because the ivar might be under-aligned.
Fariborz Jahanian1bf72882009-03-12 22:50:49 +0000931 llvm::Constant *BuildIvarLayout(const ObjCImplementationDecl *OI,
John McCall3fd13f062015-10-21 18:06:47 +0000932 CharUnits beginOffset,
933 CharUnits endOffset,
John McCall460ce582015-10-22 18:38:17 +0000934 bool forStrongLayout,
935 bool hasMRCWeakIvars);
936
937 llvm::Constant *BuildStrongIvarLayout(const ObjCImplementationDecl *OI,
938 CharUnits beginOffset,
939 CharUnits endOffset) {
940 return BuildIvarLayout(OI, beginOffset, endOffset, true, false);
941 }
942
943 llvm::Constant *BuildWeakIvarLayout(const ObjCImplementationDecl *OI,
944 CharUnits beginOffset,
945 CharUnits endOffset,
946 bool hasMRCWeakIvars) {
947 return BuildIvarLayout(OI, beginOffset, endOffset, false, hasMRCWeakIvars);
948 }
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +0000949
Fariborz Jahaniana9d44642012-11-14 17:15:51 +0000950 Qualifiers::ObjCLifetime getBlockCaptureLifetime(QualType QT, bool ByrefLayout);
Fariborz Jahanian2dd78192012-11-02 22:51:18 +0000951
Fariborz Jahanian39319c42012-10-30 20:05:29 +0000952 void UpdateRunSkipBlockVars(bool IsByref,
953 Qualifiers::ObjCLifetime LifeTime,
Fariborz Jahanian7778d612012-11-07 20:00:32 +0000954 CharUnits FieldOffset,
955 CharUnits FieldSize);
Fariborz Jahanian39319c42012-10-30 20:05:29 +0000956
957 void BuildRCBlockVarRecordLayout(const RecordType *RT,
Fariborz Jahaniana9d44642012-11-14 17:15:51 +0000958 CharUnits BytePos, bool &HasUnion,
959 bool ByrefLayout=false);
Fariborz Jahanian39319c42012-10-30 20:05:29 +0000960
961 void BuildRCRecordLayout(const llvm::StructLayout *RecLayout,
962 const RecordDecl *RD,
963 ArrayRef<const FieldDecl*> RecFields,
Fariborz Jahaniana9d44642012-11-14 17:15:51 +0000964 CharUnits BytePos, bool &HasUnion,
965 bool ByrefLayout);
Fariborz Jahanian39319c42012-10-30 20:05:29 +0000966
Fariborz Jahanian23290b02012-11-01 18:32:55 +0000967 uint64_t InlineLayoutInstruction(SmallVectorImpl<unsigned char> &Layout);
968
Fariborz Jahaniana9d44642012-11-14 17:15:51 +0000969 llvm::Constant *getBitmapBlockLayout(bool ComputeByrefLayout);
970
Fariborz Jahanian01dff422009-03-05 19:17:31 +0000971 /// GetIvarLayoutName - Returns a unique constant for the given
972 /// ivar layout bitmap.
973 llvm::Constant *GetIvarLayoutName(IdentifierInfo *Ident,
974 const ObjCCommonTypesHelper &ObjCTypes);
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000975
Fariborz Jahanian066347e2009-01-28 22:18:42 +0000976 /// EmitPropertyList - Emit the given property list. The return
977 /// value has type PropertyListPtrTy.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000978 llvm::Constant *EmitPropertyList(Twine Name,
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000979 const Decl *Container,
Fariborz Jahanian066347e2009-01-28 22:18:42 +0000980 const ObjCContainerDecl *OCD,
Manman Renad0e7912016-01-29 19:22:54 +0000981 const ObjCCommonTypesHelper &ObjCTypes,
982 bool IsClassProperty);
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000983
Bob Wilson5f4e3a72011-11-30 01:57:58 +0000984 /// EmitProtocolMethodTypes - Generate the array of extended method type
985 /// strings. The return value has type Int8PtrPtrTy.
986 llvm::Constant *EmitProtocolMethodTypes(Twine Name,
Bill Wendlingcb5b5ff2012-02-07 09:25:09 +0000987 ArrayRef<llvm::Constant*> MethodTypes,
Bob Wilson5f4e3a72011-11-30 01:57:58 +0000988 const ObjCCommonTypesHelper &ObjCTypes);
989
Fariborz Jahanian751c1e72009-12-12 21:26:21 +0000990 /// PushProtocolProperties - Push protocol's property on the input stack.
Bill Wendlinga515b582012-02-09 22:16:49 +0000991 void PushProtocolProperties(
992 llvm::SmallPtrSet<const IdentifierInfo*, 16> &PropertySet,
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000993 SmallVectorImpl<llvm::Constant*> &Properties,
Bill Wendlinga515b582012-02-09 22:16:49 +0000994 const Decl *Container,
Aaron Ballmandc4bea42014-03-13 18:47:37 +0000995 const ObjCProtocolDecl *Proto,
Manman Renad0e7912016-01-29 19:22:54 +0000996 const ObjCCommonTypesHelper &ObjCTypes,
997 bool IsClassProperty);
Fariborz Jahanian751c1e72009-12-12 21:26:21 +0000998
Fariborz Jahanian56b3b772009-01-29 19:24:30 +0000999 /// GetProtocolRef - Return a reference to the internal protocol
1000 /// description, creating an empty one if it has not been
1001 /// defined. The return value has type ProtocolPtrTy.
1002 llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD);
Fariborz Jahanian67726212009-03-08 20:18:37 +00001003
Douglas Gregor24ae22c2016-04-01 23:23:52 +00001004 /// Return a reference to the given Class using runtime calls rather than
1005 /// by a symbol reference.
1006 llvm::Value *EmitClassRefViaRuntime(CodeGenFunction &CGF,
1007 const ObjCInterfaceDecl *ID,
1008 ObjCCommonTypesHelper &ObjCTypes);
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
1020 /// 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
Daniel Dunbar4527d302009-04-14 17:42:51 +00001024 /// "llvm.used".
Alp Toker541d5072014-06-07 23:30:53 +00001025 llvm::GlobalVariable *CreateMetadataVar(Twine Name, llvm::Constant *Init,
John McCall7f416cc2015-09-08 08:05:57 +00001026 StringRef Section, CharUnits Align,
Daniel Dunbar463cc8a2009-03-09 20:50:13 +00001027 bool AddToUsed);
Daniel Dunbar30c65362009-03-09 20:09:19 +00001028
Saleem Abdulrasool271106c2016-09-16 23:41:13 +00001029 llvm::GlobalVariable *CreateCStringLiteral(StringRef Name,
Saleem Abdulrasool82f6add2016-09-20 18:38:54 +00001030 ObjCLabelType LabelType,
1031 bool ForceNonFragileABI = false,
1032 bool NullTerminate = true);
Saleem Abdulrasool271106c2016-09-16 23:41:13 +00001033
John McCall3fd13f062015-10-21 18:06:47 +00001034protected:
John McCall9e8bb002011-05-14 03:10:52 +00001035 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
1036 ReturnValueSlot Return,
1037 QualType ResultType,
1038 llvm::Value *Sel,
1039 llvm::Value *Arg0,
1040 QualType Arg0Ty,
1041 bool IsSuper,
1042 const CallArgList &CallArgs,
1043 const ObjCMethodDecl *OMD,
John McCall1e3157b2015-09-10 22:27:50 +00001044 const ObjCInterfaceDecl *ClassReceiver,
John McCall9e8bb002011-05-14 03:10:52 +00001045 const ObjCCommonTypesHelper &ObjCTypes);
Daniel Dunbarf5c18462009-04-20 06:54:31 +00001046
Daniel Dunbar5e639272010-04-25 20:39:01 +00001047 /// EmitImageInfo - Emit the image info marker used to encode some module
1048 /// level information.
1049 void EmitImageInfo();
1050
Fariborz Jahanian279eda62009-01-21 22:04:16 +00001051public:
Owen Andersonae86c192009-07-13 04:10:07 +00001052 CGObjCCommonMac(CodeGen::CodeGenModule &cgm) :
John McCalla729c622012-02-17 03:33:10 +00001053 CGObjCRuntime(cgm), VMContext(cgm.getLLVMContext()) { }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001054
John McCall3fd13f062015-10-21 18:06:47 +00001055 bool isNonFragileABI() const {
1056 return ObjCABI == 2;
1057 }
1058
John McCall7f416cc2015-09-08 08:05:57 +00001059 ConstantAddress GenerateConstantString(const StringLiteral *SL) override;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001060
Craig Topper4f12f102014-03-12 06:41:41 +00001061 llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
Craig Topper8a13c412014-05-21 05:09:00 +00001062 const ObjCContainerDecl *CD=nullptr) override;
Craig Topper4f12f102014-03-12 06:41:41 +00001063
1064 void GenerateProtocol(const ObjCProtocolDecl *PD) override;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001065
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00001066 /// GetOrEmitProtocol - Get the protocol object for the given
1067 /// declaration, emitting it if necessary. The return value has type
1068 /// ProtocolPtrTy.
1069 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD)=0;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001070
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00001071 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
1072 /// object for the given declaration, emitting it if needed. These
1073 /// forward references will be filled in with empty bodies if no
1074 /// definition is seen. The return value has type ProtocolPtrTy.
1075 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD)=0;
Craig Topper4f12f102014-03-12 06:41:41 +00001076 llvm::Constant *BuildGCBlockLayout(CodeGen::CodeGenModule &CGM,
1077 const CGBlockInfo &blockInfo) override;
1078 llvm::Constant *BuildRCBlockLayout(CodeGen::CodeGenModule &CGM,
1079 const CGBlockInfo &blockInfo) override;
1080
1081 llvm::Constant *BuildByrefLayout(CodeGen::CodeGenModule &CGM,
1082 QualType T) override;
Fariborz Jahanian279eda62009-01-21 22:04:16 +00001083};
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001084
Saleem Abdulrasoold48b0a32016-10-24 20:47:58 +00001085enum class MethodListType {
1086 CategoryInstanceMethods,
1087 CategoryClassMethods,
1088 InstanceMethods,
1089 ClassMethods,
1090 ProtocolInstanceMethods,
1091 ProtocolClassMethods,
1092 OptionalProtocolInstanceMethods,
1093 OptionalProtocolClassMethods,
1094};
1095
Fariborz Jahanian279eda62009-01-21 22:04:16 +00001096class CGObjCMac : public CGObjCCommonMac {
1097private:
1098 ObjCTypesHelper ObjCTypes;
Daniel Dunbar3ad53482008-08-11 21:35:06 +00001099
Daniel Dunbar7bd00bd2008-08-12 06:48:42 +00001100 /// EmitModuleInfo - Another marker encoding module level
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001101 /// information.
Daniel Dunbar7bd00bd2008-08-12 06:48:42 +00001102 void EmitModuleInfo();
1103
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00001104 /// EmitModuleSymols - Emit module symbols, the list of defined
1105 /// classes and categories. The result has type SymtabPtrTy.
Daniel Dunbar7bd00bd2008-08-12 06:48:42 +00001106 llvm::Constant *EmitModuleSymbols();
1107
Daniel Dunbar3ad53482008-08-11 21:35:06 +00001108 /// FinishModule - Write out global data structures at the end of
1109 /// processing a translation unit.
1110 void FinishModule();
Daniel Dunbarb036db82008-08-13 03:21:16 +00001111
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00001112 /// EmitClassExtension - Generate the class extension structure used
1113 /// to store the weak ivar layout and properties. The return value
1114 /// has type ClassExtensionPtrTy.
John McCall3fd13f062015-10-21 18:06:47 +00001115 llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID,
John McCall460ce582015-10-22 18:38:17 +00001116 CharUnits instanceSize,
Manman Renad0e7912016-01-29 19:22:54 +00001117 bool hasMRCWeakIvars,
1118 bool isClassProperty);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00001119
1120 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
1121 /// for the given class.
John McCall882987f2013-02-28 19:01:20 +00001122 llvm::Value *EmitClassRef(CodeGenFunction &CGF,
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00001123 const ObjCInterfaceDecl *ID);
Fariborz Jahanianeb80c982009-11-12 20:14:24 +00001124
John McCall882987f2013-02-28 19:01:20 +00001125 llvm::Value *EmitClassRefFromId(CodeGenFunction &CGF,
John McCall31168b02011-06-15 23:02:42 +00001126 IdentifierInfo *II);
Craig Topper4f12f102014-03-12 06:41:41 +00001127
1128 llvm::Value *EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) override;
1129
Fariborz Jahanianeb80c982009-11-12 20:14:24 +00001130 /// EmitSuperClassRef - Emits reference to class's main metadata class.
1131 llvm::Value *EmitSuperClassRef(const ObjCInterfaceDecl *ID);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00001132
1133 /// EmitIvarList - Emit the ivar list for the given
1134 /// implementation. If ForClass is true the list of class ivars
1135 /// (i.e. metaclass ivars) is emitted, otherwise the list of
1136 /// interface ivars will be emitted. The return value has type
1137 /// IvarListPtrTy.
1138 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanianb042a592009-01-28 19:12:34 +00001139 bool ForClass);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001140
Daniel Dunbarca8531a2008-08-25 08:19:24 +00001141 /// EmitMetaClass - Emit a forward reference to the class structure
1142 /// for the metaclass of the given interface. The return value has
1143 /// type ClassPtrTy.
1144 llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
1145
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00001146 /// EmitMetaClass - Emit a class structure for the metaclass of the
Daniel Dunbarca8531a2008-08-25 08:19:24 +00001147 /// given implementation. The return value has type ClassPtrTy.
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00001148 llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
1149 llvm::Constant *Protocols,
Bill Wendlingcb5b5ff2012-02-07 09:25:09 +00001150 ArrayRef<llvm::Constant*> Methods);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001151
Daniel Dunbareb1f9a22008-08-27 02:31:56 +00001152 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001153
Daniel Dunbareb1f9a22008-08-27 02:31:56 +00001154 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00001155
1156 /// EmitMethodList - Emit the method list for the given
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001157 /// implementation. The return value has type MethodListPtrTy.
Saleem Abdulrasoold48b0a32016-10-24 20:47:58 +00001158 llvm::Constant *EmitMethodList(Twine Name, MethodListType MLT,
Saleem Abdulrasool1e6c4062016-05-16 05:06:49 +00001159 ArrayRef<llvm::Constant *> Methods);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00001160
1161 /// EmitMethodDescList - Emit a method description list for a list of
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001162 /// method declarations.
Daniel Dunbarb036db82008-08-13 03:21:16 +00001163 /// - TypeName: The name for the type containing the methods.
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00001164 /// - IsProtocol: True iff these methods are for a protocol.
1165 /// - ClassMethds: True iff these are class methods.
Daniel Dunbarb036db82008-08-13 03:21:16 +00001166 /// - Required: When true, only "required" methods are
1167 /// listed. Similarly, when false only "optional" methods are
1168 /// listed. For classes this should always be true.
1169 /// - begin, end: The method list to output.
1170 ///
1171 /// The return value has type MethodDescriptionListPtrTy.
Saleem Abdulrasool1e6c4062016-05-16 05:06:49 +00001172 llvm::Constant *EmitMethodDescList(Twine Name, StringRef Section,
1173 ArrayRef<llvm::Constant *> Methods);
Daniel Dunbarb036db82008-08-13 03:21:16 +00001174
Daniel Dunbarc475d422008-10-29 22:36:39 +00001175 /// GetOrEmitProtocol - Get the protocol object for the given
1176 /// declaration, emitting it if necessary. The return value has type
1177 /// ProtocolPtrTy.
Craig Topper4f12f102014-03-12 06:41:41 +00001178 llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD) override;
Daniel Dunbarc475d422008-10-29 22:36:39 +00001179
1180 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
1181 /// object for the given declaration, emitting it if needed. These
1182 /// forward references will be filled in with empty bodies if no
1183 /// definition is seen. The return value has type ProtocolPtrTy.
Craig Topper4f12f102014-03-12 06:41:41 +00001184 llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) override;
Daniel Dunbarc475d422008-10-29 22:36:39 +00001185
Daniel Dunbarb036db82008-08-13 03:21:16 +00001186 /// EmitProtocolExtension - Generate the protocol extension
1187 /// structure used to store optional instance and class methods, and
1188 /// protocol properties. The return value has type
1189 /// ProtocolExtensionPtrTy.
Daniel Dunbareb1f9a22008-08-27 02:31:56 +00001190 llvm::Constant *
1191 EmitProtocolExtension(const ObjCProtocolDecl *PD,
Bill Wendlingcb5b5ff2012-02-07 09:25:09 +00001192 ArrayRef<llvm::Constant*> OptInstanceMethods,
1193 ArrayRef<llvm::Constant*> OptClassMethods,
1194 ArrayRef<llvm::Constant*> MethodTypesExt);
Daniel Dunbarb036db82008-08-13 03:21:16 +00001195
1196 /// EmitProtocolList - Generate the list of referenced
1197 /// protocols. The return value has type ProtocolListPtrTy.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001198 llvm::Constant *EmitProtocolList(Twine Name,
Daniel Dunbardec75f82008-08-21 21:57:41 +00001199 ObjCProtocolDecl::protocol_iterator begin,
1200 ObjCProtocolDecl::protocol_iterator end);
Daniel Dunbarb036db82008-08-13 03:21:16 +00001201
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00001202 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
1203 /// for the given selector.
John McCall7f416cc2015-09-08 08:05:57 +00001204 llvm::Value *EmitSelector(CodeGenFunction &CGF, Selector Sel);
1205 Address EmitSelectorAddr(CodeGenFunction &CGF, Selector Sel);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001206
1207public:
Daniel Dunbar303e2c22008-08-11 02:45:11 +00001208 CGObjCMac(CodeGen::CodeGenModule &cgm);
Daniel Dunbar303e2c22008-08-11 02:45:11 +00001209
Craig Topper4f12f102014-03-12 06:41:41 +00001210 llvm::Function *ModuleInitFunction() override;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001211
Craig Topper4f12f102014-03-12 06:41:41 +00001212 CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
1213 ReturnValueSlot Return,
1214 QualType ResultType,
1215 Selector Sel, llvm::Value *Receiver,
1216 const CallArgList &CallArgs,
1217 const ObjCInterfaceDecl *Class,
1218 const ObjCMethodDecl *Method) override;
Daniel Dunbar303e2c22008-08-11 02:45:11 +00001219
Craig Topper4f12f102014-03-12 06:41:41 +00001220 CodeGen::RValue
Daniel Dunbar97db84c2008-08-23 03:46:30 +00001221 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00001222 ReturnValueSlot Return, QualType ResultType,
1223 Selector Sel, const ObjCInterfaceDecl *Class,
1224 bool isCategoryImpl, llvm::Value *Receiver,
1225 bool IsClassMessage, const CallArgList &CallArgs,
1226 const ObjCMethodDecl *Method) override;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001227
Craig Topper4f12f102014-03-12 06:41:41 +00001228 llvm::Value *GetClass(CodeGenFunction &CGF,
1229 const ObjCInterfaceDecl *ID) override;
Daniel Dunbar303e2c22008-08-11 02:45:11 +00001230
John McCall7f416cc2015-09-08 08:05:57 +00001231 llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel) override;
1232 Address GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) override;
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001233
1234 /// The NeXT/Apple runtimes do not support typed selectors; just emit an
1235 /// untyped one.
Craig Topper4f12f102014-03-12 06:41:41 +00001236 llvm::Value *GetSelector(CodeGenFunction &CGF,
1237 const ObjCMethodDecl *Method) override;
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001238
Craig Topper4f12f102014-03-12 06:41:41 +00001239 llvm::Constant *GetEHType(QualType T) override;
John McCall2ca705e2010-07-24 00:37:23 +00001240
Craig Topper4f12f102014-03-12 06:41:41 +00001241 void GenerateCategory(const ObjCCategoryImplDecl *CMD) override;
Daniel Dunbar303e2c22008-08-11 02:45:11 +00001242
Craig Topper4f12f102014-03-12 06:41:41 +00001243 void GenerateClass(const ObjCImplementationDecl *ClassDecl) override;
Daniel Dunbar303e2c22008-08-11 02:45:11 +00001244
Craig Topper4f12f102014-03-12 06:41:41 +00001245 void RegisterAlias(const ObjCCompatibleAliasDecl *OAD) override {}
David Chisnall92d436b2012-01-31 18:59:20 +00001246
Craig Topper4f12f102014-03-12 06:41:41 +00001247 llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,
1248 const ObjCProtocolDecl *PD) override;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001249
Craig Topper4f12f102014-03-12 06:41:41 +00001250 llvm::Constant *GetPropertyGetFunction() override;
1251 llvm::Constant *GetPropertySetFunction() override;
1252 llvm::Constant *GetOptimizedPropertySetFunction(bool atomic,
1253 bool copy) override;
1254 llvm::Constant *GetGetStructFunction() override;
1255 llvm::Constant *GetSetStructFunction() override;
1256 llvm::Constant *GetCppAtomicObjectGetFunction() override;
1257 llvm::Constant *GetCppAtomicObjectSetFunction() override;
1258 llvm::Constant *EnumerationMutationFunction() override;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001259
Craig Topper4f12f102014-03-12 06:41:41 +00001260 void EmitTryStmt(CodeGen::CodeGenFunction &CGF,
1261 const ObjCAtTryStmt &S) override;
1262 void EmitSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
1263 const ObjCAtSynchronizedStmt &S) override;
John McCallbd309292010-07-06 01:34:17 +00001264 void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF, const Stmt &S);
Craig Topper4f12f102014-03-12 06:41:41 +00001265 void EmitThrowStmt(CodeGen::CodeGenFunction &CGF, const ObjCAtThrowStmt &S,
1266 bool ClearInsertionPoint=true) override;
1267 llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001268 Address AddrWeakObj) override;
Craig Topper4f12f102014-03-12 06:41:41 +00001269 void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001270 llvm::Value *src, Address dst) override;
Craig Topper4f12f102014-03-12 06:41:41 +00001271 void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001272 llvm::Value *src, Address dest,
Craig Topper4f12f102014-03-12 06:41:41 +00001273 bool threadlocal = false) override;
1274 void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001275 llvm::Value *src, Address dest,
Craig Topper4f12f102014-03-12 06:41:41 +00001276 llvm::Value *ivarOffset) override;
1277 void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001278 llvm::Value *src, Address dest) override;
Craig Topper4f12f102014-03-12 06:41:41 +00001279 void EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001280 Address dest, Address src,
Craig Topper4f12f102014-03-12 06:41:41 +00001281 llvm::Value *size) override;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001282
Craig Topper4f12f102014-03-12 06:41:41 +00001283 LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF, QualType ObjectTy,
1284 llvm::Value *BaseValue, const ObjCIvarDecl *Ivar,
1285 unsigned CVRQualifiers) override;
1286 llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
1287 const ObjCInterfaceDecl *Interface,
1288 const ObjCIvarDecl *Ivar) override;
1289
Fariborz Jahanian7bd3d1c2011-05-17 22:21:16 +00001290 /// GetClassGlobal - Return the global variable for the Objective-C
1291 /// class of the given name.
Benjamin Kramer0772c422016-02-13 13:42:54 +00001292 llvm::GlobalVariable *GetClassGlobal(StringRef Name,
Craig Toppera798a9d2014-03-02 09:32:10 +00001293 bool Weak = false) override {
David Blaikie83d382b2011-09-23 05:06:16 +00001294 llvm_unreachable("CGObjCMac::GetClassGlobal");
Fariborz Jahanian7bd3d1c2011-05-17 22:21:16 +00001295 }
Daniel Dunbar303e2c22008-08-11 02:45:11 +00001296};
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001297
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00001298class CGObjCNonFragileABIMac : public CGObjCCommonMac {
Fariborz Jahanian279eda62009-01-21 22:04:16 +00001299private:
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00001300 ObjCNonFragileABITypesHelper ObjCTypes;
Fariborz Jahanian71394042009-01-23 23:53:38 +00001301 llvm::GlobalVariable* ObjCEmptyCacheVar;
1302 llvm::GlobalVariable* ObjCEmptyVtableVar;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001303
Daniel Dunbar508a7dd2009-04-18 08:51:00 +00001304 /// SuperClassReferences - uniqued super class references.
1305 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> SuperClassReferences;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001306
Fariborz Jahanian6b7cd6e2009-02-06 20:09:23 +00001307 /// MetaClassReferences - uniqued meta class references.
1308 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> MetaClassReferences;
Daniel Dunbarb1559a42009-03-01 04:46:24 +00001309
1310 /// EHTypeReferences - uniqued class ehtype references.
1311 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> EHTypeReferences;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001312
John McCall9e8bb002011-05-14 03:10:52 +00001313 /// VTableDispatchMethods - List of methods for which we generate
1314 /// vtable-based message dispatch.
1315 llvm::DenseSet<Selector> VTableDispatchMethods;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001316
Fariborz Jahanian67260552009-11-17 21:37:35 +00001317 /// DefinedMetaClasses - List of defined meta-classes.
1318 std::vector<llvm::GlobalValue*> DefinedMetaClasses;
1319
John McCall9e8bb002011-05-14 03:10:52 +00001320 /// isVTableDispatchedSelector - Returns true if SEL is a
1321 /// vtable-based selector.
1322 bool isVTableDispatchedSelector(Selector Sel);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001323
Fariborz Jahanian71394042009-01-23 23:53:38 +00001324 /// FinishNonFragileABIModule - Write out global data structures at the end of
1325 /// processing a translation unit.
1326 void FinishNonFragileABIModule();
Daniel Dunbar8f28d012009-04-08 04:21:03 +00001327
Daniel Dunbar19573e72009-05-15 21:48:48 +00001328 /// AddModuleClassList - Add the given list of class pointers to the
1329 /// module with the provided symbol and section names.
Saleem Abdulrasool1e6c4062016-05-16 05:06:49 +00001330 void AddModuleClassList(ArrayRef<llvm::GlobalValue *> Container,
1331 StringRef SymbolName, StringRef SectionName);
Daniel Dunbar19573e72009-05-15 21:48:48 +00001332
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001333 llvm::GlobalVariable * BuildClassRoTInitializer(unsigned flags,
1334 unsigned InstanceStart,
1335 unsigned InstanceSize,
1336 const ObjCImplementationDecl *ID);
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00001337 llvm::GlobalVariable * BuildClassMetaData(const std::string &ClassName,
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001338 llvm::Constant *IsAGV,
Fariborz Jahanian4723fb72009-01-24 21:21:53 +00001339 llvm::Constant *SuperClassGV,
Fariborz Jahanian82208252009-01-31 00:59:10 +00001340 llvm::Constant *ClassRoGV,
Rafael Espindola554256c2014-02-26 22:25:45 +00001341 bool HiddenVisibility,
Fariborz Jahanianf322f2f2014-03-11 00:25:05 +00001342 bool Weak);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001343
Fariborz Jahanian99113fd2009-01-26 21:38:32 +00001344 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001345
Fariborz Jahaniand9c28b82009-01-30 00:46:37 +00001346 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001347
Fariborz Jahanian99113fd2009-01-26 21:38:32 +00001348 /// EmitMethodList - Emit the method list for the given
1349 /// implementation. The return value has type MethodListnfABITy.
Saleem Abdulrasoold48b0a32016-10-24 20:47:58 +00001350 llvm::Constant *EmitMethodList(Twine Name, MethodListType MLT,
Saleem Abdulrasool1e6c4062016-05-16 05:06:49 +00001351 ArrayRef<llvm::Constant *> Methods);
Saleem Abdulrasoold48b0a32016-10-24 20:47:58 +00001352
Fariborz Jahanian7415caa2009-01-27 19:38:51 +00001353 /// EmitIvarList - Emit the ivar list for the given
1354 /// implementation. If ForClass is true the list of class ivars
1355 /// (i.e. metaclass ivars) is emitted, otherwise the list of
1356 /// interface ivars will be emitted. The return value has type
1357 /// IvarListnfABIPtrTy.
1358 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001359
Fariborz Jahanian4e7ae062009-02-10 20:21:06 +00001360 llvm::Constant *EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,
Fariborz Jahanian3d3426f2009-01-28 01:36:42 +00001361 const ObjCIvarDecl *Ivar,
Eli Friedman8cbca202012-11-06 22:15:52 +00001362 unsigned long int offset);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001363
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00001364 /// GetOrEmitProtocol - Get the protocol object for the given
1365 /// declaration, emitting it if necessary. The return value has type
1366 /// ProtocolPtrTy.
Craig Topper4f12f102014-03-12 06:41:41 +00001367 llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD) override;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001368
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00001369 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
1370 /// object for the given declaration, emitting it if needed. These
1371 /// forward references will be filled in with empty bodies if no
1372 /// definition is seen. The return value has type ProtocolPtrTy.
Craig Topper4f12f102014-03-12 06:41:41 +00001373 llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) override;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001374
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00001375 /// EmitProtocolList - Generate the list of referenced
1376 /// protocols. The return value has type ProtocolListPtrTy.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001377 llvm::Constant *EmitProtocolList(Twine Name,
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00001378 ObjCProtocolDecl::protocol_iterator begin,
Fariborz Jahanian3d9296e2009-02-04 00:22:57 +00001379 ObjCProtocolDecl::protocol_iterator end);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001380
John McCall9e8bb002011-05-14 03:10:52 +00001381 CodeGen::RValue EmitVTableMessageSend(CodeGen::CodeGenFunction &CGF,
1382 ReturnValueSlot Return,
1383 QualType ResultType,
1384 Selector Sel,
1385 llvm::Value *Receiver,
1386 QualType Arg0Ty,
1387 bool IsSuper,
1388 const CallArgList &CallArgs,
1389 const ObjCMethodDecl *Method);
Fariborz Jahanian7bd3d1c2011-05-17 22:21:16 +00001390
Daniel Dunbarc6928bb2009-03-01 04:40:10 +00001391 /// GetClassGlobal - Return the global variable for the Objective-C
1392 /// class of the given name.
Benjamin Kramer0772c422016-02-13 13:42:54 +00001393 llvm::GlobalVariable *GetClassGlobal(StringRef Name,
Craig Toppera798a9d2014-03-02 09:32:10 +00001394 bool Weak = false) override;
Rafael Espindola554256c2014-02-26 22:25:45 +00001395
Fariborz Jahanian33f66e62009-02-05 20:41:40 +00001396 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
Daniel Dunbar508a7dd2009-04-18 08:51:00 +00001397 /// for the given class reference.
John McCall882987f2013-02-28 19:01:20 +00001398 llvm::Value *EmitClassRef(CodeGenFunction &CGF,
Daniel Dunbar508a7dd2009-04-18 08:51:00 +00001399 const ObjCInterfaceDecl *ID);
John McCall31168b02011-06-15 23:02:42 +00001400
John McCall882987f2013-02-28 19:01:20 +00001401 llvm::Value *EmitClassRefFromId(CodeGenFunction &CGF,
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00001402 IdentifierInfo *II, bool Weak,
1403 const ObjCInterfaceDecl *ID);
Craig Topper4f12f102014-03-12 06:41:41 +00001404
1405 llvm::Value *EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) override;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001406
Daniel Dunbar508a7dd2009-04-18 08:51:00 +00001407 /// EmitSuperClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
1408 /// for the given super class reference.
John McCall882987f2013-02-28 19:01:20 +00001409 llvm::Value *EmitSuperClassRef(CodeGenFunction &CGF,
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001410 const ObjCInterfaceDecl *ID);
1411
Fariborz Jahanian6b7cd6e2009-02-06 20:09:23 +00001412 /// EmitMetaClassRef - Return a Value * of the address of _class_t
1413 /// meta-data
John McCall882987f2013-02-28 19:01:20 +00001414 llvm::Value *EmitMetaClassRef(CodeGenFunction &CGF,
Fariborz Jahanian0b3bc242014-06-10 17:08:04 +00001415 const ObjCInterfaceDecl *ID, bool Weak);
Fariborz Jahanian6b7cd6e2009-02-06 20:09:23 +00001416
Fariborz Jahanian4e7ae062009-02-10 20:21:06 +00001417 /// ObjCIvarOffsetVariable - Returns the ivar offset variable for
1418 /// the given ivar.
1419 ///
Daniel Dunbara1060522009-04-19 00:31:15 +00001420 llvm::GlobalVariable * ObjCIvarOffsetVariable(
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001421 const ObjCInterfaceDecl *ID,
1422 const ObjCIvarDecl *Ivar);
1423
Fariborz Jahanian74b77222009-02-11 20:51:17 +00001424 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
1425 /// for the given selector.
John McCall7f416cc2015-09-08 08:05:57 +00001426 llvm::Value *EmitSelector(CodeGenFunction &CGF, Selector Sel);
1427 Address EmitSelectorAddr(CodeGenFunction &CGF, Selector Sel);
Daniel Dunbarb1559a42009-03-01 04:46:24 +00001428
Daniel Dunbar8f28d012009-04-08 04:21:03 +00001429 /// GetInterfaceEHType - Get the cached ehtype for the given Objective-C
Daniel Dunbarb1559a42009-03-01 04:46:24 +00001430 /// interface. The return value has type EHTypePtrTy.
John McCall2ca705e2010-07-24 00:37:23 +00001431 llvm::Constant *GetInterfaceEHType(const ObjCInterfaceDecl *ID,
Daniel Dunbar8f28d012009-04-08 04:21:03 +00001432 bool ForDefinition);
Daniel Dunbar15894b72009-04-07 05:48:37 +00001433
Saleem Abdulrasool1e6c4062016-05-16 05:06:49 +00001434 StringRef getMetaclassSymbolPrefix() const { return "OBJC_METACLASS_$_"; }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001435
Saleem Abdulrasool1e6c4062016-05-16 05:06:49 +00001436 StringRef getClassSymbolPrefix() const { return "OBJC_CLASS_$_"; }
Daniel Dunbar15894b72009-04-07 05:48:37 +00001437
Daniel Dunbar961202372009-05-03 12:57:56 +00001438 void GetClassSizeInfo(const ObjCImplementationDecl *OID,
Daniel Dunbar554fd792009-04-19 23:41:48 +00001439 uint32_t &InstanceStart,
1440 uint32_t &InstanceSize);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001441
Fariborz Jahaniane4128642009-05-12 20:06:41 +00001442 // Shamelessly stolen from Analysis/CFRefCount.cpp
Daniel Dunbar9a017d72009-05-15 22:33:15 +00001443 Selector GetNullarySelector(const char* name) const {
Fariborz Jahaniane4128642009-05-12 20:06:41 +00001444 IdentifierInfo* II = &CGM.getContext().Idents.get(name);
1445 return CGM.getContext().Selectors.getSelector(0, &II);
1446 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001447
Daniel Dunbar9a017d72009-05-15 22:33:15 +00001448 Selector GetUnarySelector(const char* name) const {
Fariborz Jahaniane4128642009-05-12 20:06:41 +00001449 IdentifierInfo* II = &CGM.getContext().Idents.get(name);
1450 return CGM.getContext().Selectors.getSelector(1, &II);
1451 }
Daniel Dunbar554fd792009-04-19 23:41:48 +00001452
Daniel Dunbar9a017d72009-05-15 22:33:15 +00001453 /// ImplementationIsNonLazy - Check whether the given category or
1454 /// class implementation is "non-lazy".
Fariborz Jahaniana6bed832009-05-21 01:03:45 +00001455 bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const;
Daniel Dunbar9a017d72009-05-15 22:33:15 +00001456
Saleem Abdulrasool5f25bc32013-02-17 04:03:34 +00001457 bool IsIvarOffsetKnownIdempotent(const CodeGen::CodeGenFunction &CGF,
Saleem Abdulrasool5f25bc32013-02-17 04:03:34 +00001458 const ObjCIvarDecl *IV) {
Fariborz Jahaniandafffbe2014-03-04 18:34:52 +00001459 // Annotate the load as an invariant load iff inside an instance method
1460 // and ivar belongs to instance method's class and one of its super class.
1461 // This check is needed because the ivar offset is a lazily
Saleem Abdulrasool5f25bc32013-02-17 04:03:34 +00001462 // initialised value that may depend on objc_msgSend to perform a fixup on
1463 // the first message dispatch.
1464 //
1465 // An additional opportunity to mark the load as invariant arises when the
1466 // base of the ivar access is a parameter to an Objective C method.
1467 // However, because the parameters are not available in the current
1468 // interface, we cannot perform this check.
Fariborz Jahaniandafffbe2014-03-04 18:34:52 +00001469 if (const ObjCMethodDecl *MD =
1470 dyn_cast_or_null<ObjCMethodDecl>(CGF.CurFuncDecl))
Fariborz Jahanian7a583022014-03-04 22:57:32 +00001471 if (MD->isInstanceMethod())
Fariborz Jahaniandafffbe2014-03-04 18:34:52 +00001472 if (const ObjCInterfaceDecl *ID = MD->getClassInterface())
1473 return IV->getContainingInterface()->isSuperClassOf(ID);
Saleem Abdulrasool5f25bc32013-02-17 04:03:34 +00001474 return false;
1475 }
1476
Fariborz Jahanian279eda62009-01-21 22:04:16 +00001477public:
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00001478 CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm);
Fariborz Jahanian71394042009-01-23 23:53:38 +00001479 // FIXME. All stubs for now!
Craig Topper4f12f102014-03-12 06:41:41 +00001480 llvm::Function *ModuleInitFunction() override;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001481
Craig Topper4f12f102014-03-12 06:41:41 +00001482 CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
1483 ReturnValueSlot Return,
1484 QualType ResultType, Selector Sel,
1485 llvm::Value *Receiver,
1486 const CallArgList &CallArgs,
1487 const ObjCInterfaceDecl *Class,
1488 const ObjCMethodDecl *Method) override;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001489
Craig Topper4f12f102014-03-12 06:41:41 +00001490 CodeGen::RValue
Fariborz Jahanian71394042009-01-23 23:53:38 +00001491 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00001492 ReturnValueSlot Return, QualType ResultType,
1493 Selector Sel, const ObjCInterfaceDecl *Class,
1494 bool isCategoryImpl, llvm::Value *Receiver,
1495 bool IsClassMessage, const CallArgList &CallArgs,
1496 const ObjCMethodDecl *Method) override;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001497
Craig Topper4f12f102014-03-12 06:41:41 +00001498 llvm::Value *GetClass(CodeGenFunction &CGF,
1499 const ObjCInterfaceDecl *ID) override;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001500
John McCall7f416cc2015-09-08 08:05:57 +00001501 llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel) override
1502 { return EmitSelector(CGF, Sel); }
1503 Address GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) override
1504 { return EmitSelectorAddr(CGF, Sel); }
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001505
1506 /// The NeXT/Apple runtimes do not support typed selectors; just emit an
1507 /// untyped one.
Craig Topper4f12f102014-03-12 06:41:41 +00001508 llvm::Value *GetSelector(CodeGenFunction &CGF,
1509 const ObjCMethodDecl *Method) override
John McCall882987f2013-02-28 19:01:20 +00001510 { return EmitSelector(CGF, Method->getSelector()); }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001511
Craig Topper4f12f102014-03-12 06:41:41 +00001512 void GenerateCategory(const ObjCCategoryImplDecl *CMD) override;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001513
Craig Topper4f12f102014-03-12 06:41:41 +00001514 void GenerateClass(const ObjCImplementationDecl *ClassDecl) override;
David Chisnall92d436b2012-01-31 18:59:20 +00001515
Craig Topper4f12f102014-03-12 06:41:41 +00001516 void RegisterAlias(const ObjCCompatibleAliasDecl *OAD) override {}
David Chisnall92d436b2012-01-31 18:59:20 +00001517
Craig Topper4f12f102014-03-12 06:41:41 +00001518 llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,
1519 const ObjCProtocolDecl *PD) override;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001520
Craig Topper4f12f102014-03-12 06:41:41 +00001521 llvm::Constant *GetEHType(QualType T) override;
John McCall2ca705e2010-07-24 00:37:23 +00001522
Craig Topper4f12f102014-03-12 06:41:41 +00001523 llvm::Constant *GetPropertyGetFunction() override {
Chris Lattnerce8754e2009-04-22 02:44:54 +00001524 return ObjCTypes.getGetPropertyFn();
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00001525 }
Craig Topper4f12f102014-03-12 06:41:41 +00001526 llvm::Constant *GetPropertySetFunction() override {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001527 return ObjCTypes.getSetPropertyFn();
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00001528 }
Craig Topper4f12f102014-03-12 06:41:41 +00001529
1530 llvm::Constant *GetOptimizedPropertySetFunction(bool atomic,
1531 bool copy) override {
Ted Kremeneke65b0862012-03-06 20:05:56 +00001532 return ObjCTypes.getOptimizedSetPropertyFn(atomic, copy);
1533 }
Craig Topper4f12f102014-03-12 06:41:41 +00001534
1535 llvm::Constant *GetSetStructFunction() override {
David Chisnall168b80f2010-12-26 22:13:16 +00001536 return ObjCTypes.getCopyStructFn();
1537 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001538
Craig Topper4f12f102014-03-12 06:41:41 +00001539 llvm::Constant *GetGetStructFunction() override {
Fariborz Jahanian5a8c2032010-04-12 18:18:10 +00001540 return ObjCTypes.getCopyStructFn();
1541 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001542
Craig Topper4f12f102014-03-12 06:41:41 +00001543 llvm::Constant *GetCppAtomicObjectSetFunction() override {
David Chisnall0d75e062012-12-17 18:54:24 +00001544 return ObjCTypes.getCppAtomicObjectFunction();
1545 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001546
Craig Topper4f12f102014-03-12 06:41:41 +00001547 llvm::Constant *GetCppAtomicObjectGetFunction() override {
Fariborz Jahanian1e1b5492012-01-06 18:07:23 +00001548 return ObjCTypes.getCppAtomicObjectFunction();
1549 }
Craig Topper4f12f102014-03-12 06:41:41 +00001550
1551 llvm::Constant *EnumerationMutationFunction() override {
Chris Lattnerce8754e2009-04-22 02:44:54 +00001552 return ObjCTypes.getEnumerationMutationFn();
Daniel Dunbard73ea8162009-02-16 18:48:45 +00001553 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001554
Craig Topper4f12f102014-03-12 06:41:41 +00001555 void EmitTryStmt(CodeGen::CodeGenFunction &CGF,
1556 const ObjCAtTryStmt &S) override;
1557 void EmitSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
1558 const ObjCAtSynchronizedStmt &S) override;
1559 void EmitThrowStmt(CodeGen::CodeGenFunction &CGF, const ObjCAtThrowStmt &S,
1560 bool ClearInsertionPoint=true) override;
1561 llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001562 Address AddrWeakObj) override;
Craig Topper4f12f102014-03-12 06:41:41 +00001563 void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001564 llvm::Value *src, Address edst) override;
Craig Topper4f12f102014-03-12 06:41:41 +00001565 void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001566 llvm::Value *src, Address dest,
Craig Topper4f12f102014-03-12 06:41:41 +00001567 bool threadlocal = false) override;
1568 void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001569 llvm::Value *src, Address dest,
Craig Topper4f12f102014-03-12 06:41:41 +00001570 llvm::Value *ivarOffset) override;
1571 void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001572 llvm::Value *src, Address dest) override;
Craig Topper4f12f102014-03-12 06:41:41 +00001573 void EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001574 Address dest, Address src,
Craig Topper4f12f102014-03-12 06:41:41 +00001575 llvm::Value *size) override;
1576 LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF, QualType ObjectTy,
1577 llvm::Value *BaseValue, const ObjCIvarDecl *Ivar,
1578 unsigned CVRQualifiers) override;
1579 llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
1580 const ObjCInterfaceDecl *Interface,
1581 const ObjCIvarDecl *Ivar) override;
Fariborz Jahanian279eda62009-01-21 22:04:16 +00001582};
Fariborz Jahanian715fdd52012-01-29 20:27:13 +00001583
1584/// A helper class for performing the null-initialization of a return
1585/// value.
1586struct NullReturnState {
1587 llvm::BasicBlock *NullBB;
Craig Topper8a13c412014-05-21 05:09:00 +00001588 NullReturnState() : NullBB(nullptr) {}
Fariborz Jahanian715fdd52012-01-29 20:27:13 +00001589
John McCall3d1e2c92013-02-12 05:53:35 +00001590 /// Perform a null-check of the given receiver.
Fariborz Jahanian715fdd52012-01-29 20:27:13 +00001591 void init(CodeGenFunction &CGF, llvm::Value *receiver) {
John McCall3d1e2c92013-02-12 05:53:35 +00001592 // Make blocks for the null-receiver and call edges.
1593 NullBB = CGF.createBasicBlock("msgSend.null-receiver");
1594 llvm::BasicBlock *callBB = CGF.createBasicBlock("msgSend.call");
Fariborz Jahanian715fdd52012-01-29 20:27:13 +00001595
1596 // Check for a null receiver and, if there is one, jump to the
John McCall3d1e2c92013-02-12 05:53:35 +00001597 // null-receiver block. There's no point in trying to avoid it:
1598 // we're always going to put *something* there, because otherwise
1599 // we shouldn't have done this null-check in the first place.
Fariborz Jahanian715fdd52012-01-29 20:27:13 +00001600 llvm::Value *isNull = CGF.Builder.CreateIsNull(receiver);
1601 CGF.Builder.CreateCondBr(isNull, NullBB, callBB);
1602
1603 // Otherwise, start performing the call.
1604 CGF.EmitBlock(callBB);
1605 }
1606
John McCall3d1e2c92013-02-12 05:53:35 +00001607 /// Complete the null-return operation. It is valid to call this
1608 /// regardless of whether 'init' has been called.
Fariborz Jahanianf2bda692012-01-30 21:40:37 +00001609 RValue complete(CodeGenFunction &CGF, RValue result, QualType resultType,
1610 const CallArgList &CallArgs,
1611 const ObjCMethodDecl *Method) {
John McCall3d1e2c92013-02-12 05:53:35 +00001612 // If we never had to do a null-check, just use the raw result.
Fariborz Jahanian715fdd52012-01-29 20:27:13 +00001613 if (!NullBB) return result;
John McCall3d1e2c92013-02-12 05:53:35 +00001614
1615 // The continuation block. This will be left null if we don't have an
1616 // IP, which can happen if the method we're calling is marked noreturn.
Craig Topper8a13c412014-05-21 05:09:00 +00001617 llvm::BasicBlock *contBB = nullptr;
1618
John McCall3d1e2c92013-02-12 05:53:35 +00001619 // Finish the call path.
1620 llvm::BasicBlock *callBB = CGF.Builder.GetInsertBlock();
1621 if (callBB) {
1622 contBB = CGF.createBasicBlock("msgSend.cont");
1623 CGF.Builder.CreateBr(contBB);
Fariborz Jahanianf2bda692012-01-30 21:40:37 +00001624 }
Fariborz Jahanian715fdd52012-01-29 20:27:13 +00001625
John McCall3d1e2c92013-02-12 05:53:35 +00001626 // Okay, start emitting the null-receiver block.
Fariborz Jahanian715fdd52012-01-29 20:27:13 +00001627 CGF.EmitBlock(NullBB);
Fariborz Jahanianf2bda692012-01-30 21:40:37 +00001628
John McCall3d1e2c92013-02-12 05:53:35 +00001629 // Release any consumed arguments we've got.
Fariborz Jahanianf2bda692012-01-30 21:40:37 +00001630 if (Method) {
1631 CallArgList::const_iterator I = CallArgs.begin();
1632 for (ObjCMethodDecl::param_const_iterator i = Method->param_begin(),
1633 e = Method->param_end(); i != e; ++i, ++I) {
1634 const ParmVarDecl *ParamDecl = (*i);
1635 if (ParamDecl->hasAttr<NSConsumedAttr>()) {
1636 RValue RV = I->RV;
1637 assert(RV.isScalar() &&
1638 "NullReturnState::complete - arg not on object");
John McCallcdda29c2013-03-13 03:10:54 +00001639 CGF.EmitARCRelease(RV.getScalarVal(), ARCImpreciseLifetime);
Fariborz Jahanianf2bda692012-01-30 21:40:37 +00001640 }
1641 }
1642 }
John McCall3d1e2c92013-02-12 05:53:35 +00001643
1644 // The phi code below assumes that we haven't needed any control flow yet.
1645 assert(CGF.Builder.GetInsertBlock() == NullBB);
1646
1647 // If we've got a void return, just jump to the continuation block.
1648 if (result.isScalar() && resultType->isVoidType()) {
1649 // No jumps required if the message-send was noreturn.
1650 if (contBB) CGF.EmitBlock(contBB);
Fariborz Jahanian715fdd52012-01-29 20:27:13 +00001651 return result;
1652 }
1653
John McCall3d1e2c92013-02-12 05:53:35 +00001654 // If we've got a scalar return, build a phi.
1655 if (result.isScalar()) {
1656 // Derive the null-initialization value.
1657 llvm::Constant *null = CGF.CGM.EmitNullConstant(resultType);
1658
1659 // If no join is necessary, just flow out.
1660 if (!contBB) return RValue::get(null);
1661
1662 // Otherwise, build a phi.
1663 CGF.EmitBlock(contBB);
1664 llvm::PHINode *phi = CGF.Builder.CreatePHI(null->getType(), 2);
1665 phi->addIncoming(result.getScalarVal(), callBB);
1666 phi->addIncoming(null, NullBB);
1667 return RValue::get(phi);
1668 }
1669
1670 // If we've got an aggregate return, null the buffer out.
1671 // FIXME: maybe we should be doing things differently for all the
1672 // cases where the ABI has us returning (1) non-agg values in
1673 // memory or (2) agg values in registers.
1674 if (result.isAggregate()) {
1675 assert(result.isAggregate() && "null init of non-aggregate result?");
John McCall7f416cc2015-09-08 08:05:57 +00001676 CGF.EmitNullInitialization(result.getAggregateAddress(), resultType);
John McCall3d1e2c92013-02-12 05:53:35 +00001677 if (contBB) CGF.EmitBlock(contBB);
1678 return result;
1679 }
1680
1681 // Complex types.
Fariborz Jahanian715fdd52012-01-29 20:27:13 +00001682 CGF.EmitBlock(contBB);
John McCall3d1e2c92013-02-12 05:53:35 +00001683 CodeGenFunction::ComplexPairTy callResult = result.getComplexVal();
1684
1685 // Find the scalar type and its zero value.
1686 llvm::Type *scalarTy = callResult.first->getType();
1687 llvm::Constant *scalarZero = llvm::Constant::getNullValue(scalarTy);
1688
1689 // Build phis for both coordinates.
1690 llvm::PHINode *real = CGF.Builder.CreatePHI(scalarTy, 2);
1691 real->addIncoming(callResult.first, callBB);
1692 real->addIncoming(scalarZero, NullBB);
1693 llvm::PHINode *imag = CGF.Builder.CreatePHI(scalarTy, 2);
1694 imag->addIncoming(callResult.second, callBB);
1695 imag->addIncoming(scalarZero, NullBB);
1696 return RValue::getComplex(real, imag);
Fariborz Jahanian715fdd52012-01-29 20:27:13 +00001697 }
1698};
1699
Daniel Dunbar303e2c22008-08-11 02:45:11 +00001700} // end anonymous namespace
Daniel Dunbar8b8683f2008-08-12 00:12:39 +00001701
1702/* *** Helper Functions *** */
1703
1704/// getConstantGEP() - Help routine to construct simple GEPs.
Owen Anderson170229f2009-07-14 23:10:40 +00001705static llvm::Constant *getConstantGEP(llvm::LLVMContext &VMContext,
David Blaikiee3b172a2015-04-02 18:55:21 +00001706 llvm::GlobalVariable *C, unsigned idx0,
Daniel Dunbar8b8683f2008-08-12 00:12:39 +00001707 unsigned idx1) {
1708 llvm::Value *Idxs[] = {
Owen Anderson41a75022009-08-13 21:57:51 +00001709 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), idx0),
1710 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), idx1)
Daniel Dunbar8b8683f2008-08-12 00:12:39 +00001711 };
David Blaikiee3b172a2015-04-02 18:55:21 +00001712 return llvm::ConstantExpr::getGetElementPtr(C->getValueType(), C, Idxs);
Daniel Dunbar8b8683f2008-08-12 00:12:39 +00001713}
1714
Daniel Dunbar8f28d012009-04-08 04:21:03 +00001715/// hasObjCExceptionAttribute - Return true if this class or any super
1716/// class has the __objc_exception__ attribute.
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001717static bool hasObjCExceptionAttribute(ASTContext &Context,
Douglas Gregor78bd61f2009-06-18 16:11:24 +00001718 const ObjCInterfaceDecl *OID) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001719 if (OID->hasAttr<ObjCExceptionAttr>())
Daniel Dunbar8f28d012009-04-08 04:21:03 +00001720 return true;
1721 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
Douglas Gregor78bd61f2009-06-18 16:11:24 +00001722 return hasObjCExceptionAttribute(Context, Super);
Daniel Dunbar8f28d012009-04-08 04:21:03 +00001723 return false;
1724}
1725
Daniel Dunbar8b8683f2008-08-12 00:12:39 +00001726/* *** CGObjCMac Public Interface *** */
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001727
Fariborz Jahanian279eda62009-01-21 22:04:16 +00001728CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm),
Mike Stump11289f42009-09-09 15:08:12 +00001729 ObjCTypes(cgm) {
Fariborz Jahanian279eda62009-01-21 22:04:16 +00001730 ObjCABI = 1;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001731 EmitImageInfo();
Daniel Dunbar303e2c22008-08-11 02:45:11 +00001732}
1733
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +00001734/// GetClass - Return a reference to the class for the given interface
1735/// decl.
John McCall882987f2013-02-28 19:01:20 +00001736llvm::Value *CGObjCMac::GetClass(CodeGenFunction &CGF,
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00001737 const ObjCInterfaceDecl *ID) {
John McCall882987f2013-02-28 19:01:20 +00001738 return EmitClassRef(CGF, ID);
Daniel Dunbar303e2c22008-08-11 02:45:11 +00001739}
1740
1741/// GetSelector - Return the pointer to the unique'd string for this selector.
John McCall7f416cc2015-09-08 08:05:57 +00001742llvm::Value *CGObjCMac::GetSelector(CodeGenFunction &CGF, Selector Sel) {
1743 return EmitSelector(CGF, Sel);
1744}
1745Address CGObjCMac::GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) {
1746 return EmitSelectorAddr(CGF, Sel);
Daniel Dunbar303e2c22008-08-11 02:45:11 +00001747}
John McCall882987f2013-02-28 19:01:20 +00001748llvm::Value *CGObjCMac::GetSelector(CodeGenFunction &CGF, const ObjCMethodDecl
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001749 *Method) {
John McCall882987f2013-02-28 19:01:20 +00001750 return EmitSelector(CGF, Method->getSelector());
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001751}
Daniel Dunbar303e2c22008-08-11 02:45:11 +00001752
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +00001753llvm::Constant *CGObjCMac::GetEHType(QualType T) {
Fariborz Jahanian0a3cfcc2011-06-22 20:21:51 +00001754 if (T->isObjCIdType() ||
1755 T->isObjCQualifiedIdType()) {
1756 return CGM.GetAddrOfRTTIDescriptor(
Douglas Gregor97673472011-08-11 20:58:55 +00001757 CGM.getContext().getObjCIdRedefinitionType(), /*ForEH=*/true);
Fariborz Jahanian0a3cfcc2011-06-22 20:21:51 +00001758 }
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +00001759 if (T->isObjCClassType() ||
1760 T->isObjCQualifiedClassType()) {
1761 return CGM.GetAddrOfRTTIDescriptor(
Douglas Gregor97673472011-08-11 20:58:55 +00001762 CGM.getContext().getObjCClassRedefinitionType(), /*ForEH=*/true);
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +00001763 }
1764 if (T->isObjCObjectPointerType())
1765 return CGM.GetAddrOfRTTIDescriptor(T, /*ForEH=*/true);
1766
John McCall2ca705e2010-07-24 00:37:23 +00001767 llvm_unreachable("asking for catch type for ObjC type in fragile runtime");
John McCall2ca705e2010-07-24 00:37:23 +00001768}
1769
Daniel Dunbar8b8683f2008-08-12 00:12:39 +00001770/// Generate a constant CFString object.
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001771/*
1772 struct __builtin_CFString {
1773 const int *isa; // point to __CFConstantStringClassReference
1774 int flags;
1775 const char *str;
1776 long length;
1777 };
Daniel Dunbar8b8683f2008-08-12 00:12:39 +00001778*/
1779
Fariborz Jahanian63408e82010-04-22 20:26:39 +00001780/// or Generate a constant NSString object.
1781/*
1782 struct __builtin_NSString {
1783 const int *isa; // point to __NSConstantStringClassReference
1784 const char *str;
1785 unsigned int length;
1786 };
1787*/
1788
John McCall7f416cc2015-09-08 08:05:57 +00001789ConstantAddress CGObjCCommonMac::GenerateConstantString(
David Chisnall481e3a82010-01-23 02:40:42 +00001790 const StringLiteral *SL) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001791 return (CGM.getLangOpts().NoConstantCFStrings == 0 ?
Fariborz Jahanian63408e82010-04-22 20:26:39 +00001792 CGM.GetAddrOfConstantCFString(SL) :
Fariborz Jahanian50c925f2010-10-19 17:19:29 +00001793 CGM.GetAddrOfConstantString(SL));
Daniel Dunbar303e2c22008-08-11 02:45:11 +00001794}
1795
Ted Kremeneke65b0862012-03-06 20:05:56 +00001796enum {
1797 kCFTaggedObjectID_Integer = (1 << 1) + 1
1798};
1799
Daniel Dunbar303e2c22008-08-11 02:45:11 +00001800/// Generates a message send where the super is the receiver. This is
1801/// a message send to self with special delivery semantics indicating
1802/// which class's method should be called.
Daniel Dunbar97db84c2008-08-23 03:46:30 +00001803CodeGen::RValue
1804CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +00001805 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +00001806 QualType ResultType,
1807 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +00001808 const ObjCInterfaceDecl *Class,
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +00001809 bool isCategoryImpl,
Daniel Dunbarca8531a2008-08-25 08:19:24 +00001810 llvm::Value *Receiver,
Daniel Dunbarc722b852008-08-30 03:02:31 +00001811 bool IsClassMessage,
Daniel Dunbaraff9fca2009-09-17 04:01:22 +00001812 const CodeGen::CallArgList &CallArgs,
1813 const ObjCMethodDecl *Method) {
Daniel Dunbarf6397fe2008-08-23 04:28:29 +00001814 // Create and init a super structure; this is a (receiver, class)
1815 // pair we will pass to objc_msgSendSuper.
John McCall7f416cc2015-09-08 08:05:57 +00001816 Address ObjCSuper =
1817 CGF.CreateTempAlloca(ObjCTypes.SuperTy, CGF.getPointerAlign(),
1818 "objc_super");
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001819 llvm::Value *ReceiverAsObject =
Daniel Dunbarf6397fe2008-08-23 04:28:29 +00001820 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
David Blaikie1ed728c2015-04-05 22:45:47 +00001821 CGF.Builder.CreateStore(
1822 ReceiverAsObject,
John McCall7f416cc2015-09-08 08:05:57 +00001823 CGF.Builder.CreateStructGEP(ObjCSuper, 0, CharUnits::Zero()));
Daniel Dunbarf6397fe2008-08-23 04:28:29 +00001824
Daniel Dunbarca8531a2008-08-25 08:19:24 +00001825 // If this is a class message the metaclass is passed as the target.
1826 llvm::Value *Target;
1827 if (IsClassMessage) {
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +00001828 if (isCategoryImpl) {
1829 // Message sent to 'super' in a class method defined in a category
1830 // implementation requires an odd treatment.
1831 // If we are in a class method, we must retrieve the
1832 // _metaclass_ for the current class, pointed at by
1833 // the class's "isa" pointer. The following assumes that
1834 // isa" is the first ivar in a class (which it must be).
John McCall882987f2013-02-28 19:01:20 +00001835 Target = EmitClassRef(CGF, Class->getSuperClass());
David Blaikie1ed728c2015-04-05 22:45:47 +00001836 Target = CGF.Builder.CreateStructGEP(ObjCTypes.ClassTy, Target, 0);
John McCall7f416cc2015-09-08 08:05:57 +00001837 Target = CGF.Builder.CreateAlignedLoad(Target, CGF.getPointerAlign());
Mike Stump658fe022009-07-30 22:28:39 +00001838 } else {
David Blaikie1ed728c2015-04-05 22:45:47 +00001839 llvm::Constant *MetaClassPtr = EmitMetaClassRef(Class);
1840 llvm::Value *SuperPtr =
1841 CGF.Builder.CreateStructGEP(ObjCTypes.ClassTy, MetaClassPtr, 1);
John McCall7f416cc2015-09-08 08:05:57 +00001842 llvm::Value *Super =
1843 CGF.Builder.CreateAlignedLoad(SuperPtr, CGF.getPointerAlign());
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +00001844 Target = Super;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001845 }
David Blaikie1ed728c2015-04-05 22:45:47 +00001846 } else if (isCategoryImpl)
John McCall882987f2013-02-28 19:01:20 +00001847 Target = EmitClassRef(CGF, Class->getSuperClass());
Fariborz Jahanianda2efb02009-11-14 02:18:31 +00001848 else {
Fariborz Jahanianeb80c982009-11-12 20:14:24 +00001849 llvm::Value *ClassPtr = EmitSuperClassRef(Class);
David Blaikie1ed728c2015-04-05 22:45:47 +00001850 ClassPtr = CGF.Builder.CreateStructGEP(ObjCTypes.ClassTy, ClassPtr, 1);
John McCall7f416cc2015-09-08 08:05:57 +00001851 Target = CGF.Builder.CreateAlignedLoad(ClassPtr, CGF.getPointerAlign());
Daniel Dunbarca8531a2008-08-25 08:19:24 +00001852 }
Mike Stump18bb9282009-05-16 07:57:57 +00001853 // FIXME: We shouldn't need to do this cast, rectify the ASTContext and
1854 // ObjCTypes types.
Chris Lattner2192fe52011-07-18 04:24:23 +00001855 llvm::Type *ClassTy =
Daniel Dunbarc722b852008-08-30 03:02:31 +00001856 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
Daniel Dunbarc475d422008-10-29 22:36:39 +00001857 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
John McCall7f416cc2015-09-08 08:05:57 +00001858 CGF.Builder.CreateStore(Target,
1859 CGF.Builder.CreateStructGEP(ObjCSuper, 1, CGF.getPointerSize()));
John McCall9e8bb002011-05-14 03:10:52 +00001860 return EmitMessageSend(CGF, Return, ResultType,
John McCall882987f2013-02-28 19:01:20 +00001861 EmitSelector(CGF, Sel),
John McCall7f416cc2015-09-08 08:05:57 +00001862 ObjCSuper.getPointer(), ObjCTypes.SuperPtrCTy,
John McCall1e3157b2015-09-10 22:27:50 +00001863 true, CallArgs, Method, Class, ObjCTypes);
Daniel Dunbar303e2c22008-08-11 02:45:11 +00001864}
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001865
1866/// Generate code for a message send expression.
Daniel Dunbar97db84c2008-08-23 03:46:30 +00001867CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +00001868 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +00001869 QualType ResultType,
1870 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +00001871 llvm::Value *Receiver,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001872 const CallArgList &CallArgs,
David Chisnall01aa4672010-04-28 19:33:36 +00001873 const ObjCInterfaceDecl *Class,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001874 const ObjCMethodDecl *Method) {
John McCall9e8bb002011-05-14 03:10:52 +00001875 return EmitMessageSend(CGF, Return, ResultType,
John McCall882987f2013-02-28 19:01:20 +00001876 EmitSelector(CGF, Sel),
John McCall9e8bb002011-05-14 03:10:52 +00001877 Receiver, CGF.getContext().getObjCIdType(),
John McCall1e3157b2015-09-10 22:27:50 +00001878 false, CallArgs, Method, Class, ObjCTypes);
1879}
1880
1881static bool isWeakLinkedClass(const ObjCInterfaceDecl *ID) {
1882 do {
1883 if (ID->isWeakImported())
1884 return true;
1885 } while ((ID = ID->getSuperClass()));
1886
1887 return false;
Daniel Dunbar97ff50d2008-08-23 09:25:55 +00001888}
1889
Daniel Dunbaraff9fca2009-09-17 04:01:22 +00001890CodeGen::RValue
John McCall9e8bb002011-05-14 03:10:52 +00001891CGObjCCommonMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
1892 ReturnValueSlot Return,
1893 QualType ResultType,
1894 llvm::Value *Sel,
1895 llvm::Value *Arg0,
1896 QualType Arg0Ty,
1897 bool IsSuper,
1898 const CallArgList &CallArgs,
1899 const ObjCMethodDecl *Method,
John McCall1e3157b2015-09-10 22:27:50 +00001900 const ObjCInterfaceDecl *ClassReceiver,
John McCall9e8bb002011-05-14 03:10:52 +00001901 const ObjCCommonTypesHelper &ObjCTypes) {
Daniel Dunbarc722b852008-08-30 03:02:31 +00001902 CallArgList ActualArgs;
Fariborz Jahanian969bc682009-04-24 21:07:43 +00001903 if (!IsSuper)
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001904 Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy);
Eli Friedman43dca6a2011-05-02 17:57:46 +00001905 ActualArgs.add(RValue::get(Arg0), Arg0Ty);
1906 ActualArgs.add(RValue::get(Sel), CGF.getContext().getObjCSelType());
John McCall31168b02011-06-15 23:02:42 +00001907 ActualArgs.addFrom(CallArgs);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001908
John McCalla729c622012-02-17 03:33:10 +00001909 // If we're calling a method, use the formal signature.
1910 MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001911
Anders Carlsson280e61f12010-06-21 20:59:55 +00001912 if (Method)
Alp Toker314cc812014-01-25 16:55:45 +00001913 assert(CGM.getContext().getCanonicalType(Method->getReturnType()) ==
1914 CGM.getContext().getCanonicalType(ResultType) &&
Anders Carlsson280e61f12010-06-21 20:59:55 +00001915 "Result type mismatch!");
1916
John McCall1e3157b2015-09-10 22:27:50 +00001917 bool ReceiverCanBeNull = true;
1918
1919 // Super dispatch assumes that self is non-null; even the messenger
1920 // doesn't have a null check internally.
1921 if (IsSuper) {
1922 ReceiverCanBeNull = false;
1923
1924 // If this is a direct dispatch of a class method, check whether the class,
1925 // or anything in its hierarchy, was weak-linked.
1926 } else if (ClassReceiver && Method && Method->isClassMethod()) {
1927 ReceiverCanBeNull = isWeakLinkedClass(ClassReceiver);
1928
1929 // If we're emitting a method, and self is const (meaning just ARC, for now),
1930 // and the receiver is a load of self, then self is a valid object.
1931 } else if (auto CurMethod =
1932 dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl)) {
1933 auto Self = CurMethod->getSelfDecl();
1934 if (Self->getType().isConstQualified()) {
1935 if (auto LI = dyn_cast<llvm::LoadInst>(Arg0->stripPointerCasts())) {
1936 llvm::Value *SelfAddr = CGF.GetAddrOfLocalVar(Self).getPointer();
1937 if (SelfAddr == LI->getPointerOperand()) {
1938 ReceiverCanBeNull = false;
1939 }
1940 }
1941 }
1942 }
1943
John McCall5880fb82011-05-14 21:12:11 +00001944 NullReturnState nullReturn;
1945
Craig Topper8a13c412014-05-21 05:09:00 +00001946 llvm::Constant *Fn = nullptr;
Tim Northovere77cc392014-03-29 13:28:05 +00001947 if (CGM.ReturnSlotInterferesWithArgs(MSI.CallInfo)) {
John McCall1e3157b2015-09-10 22:27:50 +00001948 if (ReceiverCanBeNull) nullReturn.init(CGF, Arg0);
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +00001949 Fn = (ObjCABI == 2) ? ObjCTypes.getSendStretFn2(IsSuper)
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001950 : ObjCTypes.getSendStretFn(IsSuper);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001951 } else if (CGM.ReturnTypeUsesFPRet(ResultType)) {
1952 Fn = (ObjCABI == 2) ? ObjCTypes.getSendFpretFn2(IsSuper)
1953 : ObjCTypes.getSendFpretFn(IsSuper);
Anders Carlsson2f1a6c32011-10-31 16:27:11 +00001954 } else if (CGM.ReturnTypeUsesFP2Ret(ResultType)) {
1955 Fn = (ObjCABI == 2) ? ObjCTypes.getSendFp2RetFn2(IsSuper)
1956 : ObjCTypes.getSendFp2retFn(IsSuper);
Daniel Dunbar3c683f5b2008-10-17 03:24:53 +00001957 } else {
Tim Northovere77cc392014-03-29 13:28:05 +00001958 // arm64 uses objc_msgSend for stret methods and yet null receiver check
1959 // must be made for it.
Ahmed Bougachaa3df87b2015-10-02 22:41:59 +00001960 if (ReceiverCanBeNull && CGM.ReturnTypeUsesSRet(MSI.CallInfo))
Tim Northovere77cc392014-03-29 13:28:05 +00001961 nullReturn.init(CGF, Arg0);
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +00001962 Fn = (ObjCABI == 2) ? ObjCTypes.getSendFn2(IsSuper)
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001963 : ObjCTypes.getSendFn(IsSuper);
Daniel Dunbar3c683f5b2008-10-17 03:24:53 +00001964 }
John McCall1e3157b2015-09-10 22:27:50 +00001965
1966 // Emit a null-check if there's a consumed argument other than the receiver.
1967 bool RequiresNullCheck = false;
1968 if (ReceiverCanBeNull && CGM.getLangOpts().ObjCAutoRefCount && Method) {
David Majnemer59f77922016-06-24 04:05:48 +00001969 for (const auto *ParamDecl : Method->parameters()) {
Fariborz Jahanianf2bda692012-01-30 21:40:37 +00001970 if (ParamDecl->hasAttr<NSConsumedAttr>()) {
1971 if (!nullReturn.NullBB)
1972 nullReturn.init(CGF, Arg0);
John McCall1e3157b2015-09-10 22:27:50 +00001973 RequiresNullCheck = true;
Fariborz Jahanianf2bda692012-01-30 21:40:37 +00001974 break;
1975 }
1976 }
John McCall1e3157b2015-09-10 22:27:50 +00001977 }
Fariborz Jahanianf2bda692012-01-30 21:40:37 +00001978
John McCall1e3157b2015-09-10 22:27:50 +00001979 llvm::Instruction *CallSite;
John McCalla729c622012-02-17 03:33:10 +00001980 Fn = llvm::ConstantExpr::getBitCast(Fn, MSI.MessengerType);
John McCall1e3157b2015-09-10 22:27:50 +00001981 RValue rvalue = CGF.EmitCall(MSI.CallInfo, Fn, Return, ActualArgs,
Samuel Antao798f11c2015-11-23 22:04:44 +00001982 CGCalleeInfo(), &CallSite);
John McCall1e3157b2015-09-10 22:27:50 +00001983
1984 // Mark the call as noreturn if the method is marked noreturn and the
1985 // receiver cannot be null.
1986 if (Method && Method->hasAttr<NoReturnAttr>() && !ReceiverCanBeNull) {
1987 llvm::CallSite(CallSite).setDoesNotReturn();
1988 }
1989
Fariborz Jahanianf2bda692012-01-30 21:40:37 +00001990 return nullReturn.complete(CGF, rvalue, ResultType, CallArgs,
John McCall1e3157b2015-09-10 22:27:50 +00001991 RequiresNullCheck ? Method : nullptr);
Daniel Dunbar303e2c22008-08-11 02:45:11 +00001992}
1993
John McCall3fd13f062015-10-21 18:06:47 +00001994static Qualifiers::GC GetGCAttrTypeForType(ASTContext &Ctx, QualType FQT,
1995 bool pointee = false) {
1996 // Note that GC qualification applies recursively to C pointer types
1997 // that aren't otherwise decorated. This is weird, but it's probably
1998 // an intentional workaround to the unreliable placement of GC qualifiers.
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00001999 if (FQT.isObjCGCStrong())
2000 return Qualifiers::Strong;
John McCall3fd13f062015-10-21 18:06:47 +00002001
2002 if (FQT.isObjCGCWeak())
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00002003 return Qualifiers::Weak;
John McCall3fd13f062015-10-21 18:06:47 +00002004
2005 if (auto ownership = FQT.getObjCLifetime()) {
2006 // Ownership does not apply recursively to C pointer types.
2007 if (pointee) return Qualifiers::GCNone;
2008 switch (ownership) {
2009 case Qualifiers::OCL_Weak: return Qualifiers::Weak;
2010 case Qualifiers::OCL_Strong: return Qualifiers::Strong;
2011 case Qualifiers::OCL_ExplicitNone: return Qualifiers::GCNone;
2012 case Qualifiers::OCL_Autoreleasing: llvm_unreachable("autoreleasing ivar?");
2013 case Qualifiers::OCL_None: llvm_unreachable("known nonzero");
2014 }
2015 llvm_unreachable("bad objc ownership");
2016 }
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00002017
John McCall3fd13f062015-10-21 18:06:47 +00002018 // Treat unqualified retainable pointers as strong.
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00002019 if (FQT->isObjCObjectPointerType() || FQT->isBlockPointerType())
2020 return Qualifiers::Strong;
2021
John McCall3fd13f062015-10-21 18:06:47 +00002022 // Walk into C pointer types, but only in GC.
2023 if (Ctx.getLangOpts().getGC() != LangOptions::NonGC) {
2024 if (const PointerType *PT = FQT->getAs<PointerType>())
2025 return GetGCAttrTypeForType(Ctx, PT->getPointeeType(), /*pointee*/ true);
2026 }
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00002027
2028 return Qualifiers::GCNone;
2029}
2030
John McCall3fd13f062015-10-21 18:06:47 +00002031namespace {
2032 struct IvarInfo {
2033 CharUnits Offset;
2034 uint64_t SizeInWords;
2035 IvarInfo(CharUnits offset, uint64_t sizeInWords)
2036 : Offset(offset), SizeInWords(sizeInWords) {}
2037
2038 // Allow sorting based on byte pos.
2039 bool operator<(const IvarInfo &other) const {
2040 return Offset < other.Offset;
2041 }
2042 };
2043
2044 /// A helper class for building GC layout strings.
2045 class IvarLayoutBuilder {
2046 CodeGenModule &CGM;
2047
2048 /// The start of the layout. Offsets will be relative to this value,
2049 /// and entries less than this value will be silently discarded.
2050 CharUnits InstanceBegin;
2051
2052 /// The end of the layout. Offsets will never exceed this value.
2053 CharUnits InstanceEnd;
2054
2055 /// Whether we're generating the strong layout or the weak layout.
2056 bool ForStrongLayout;
2057
2058 /// Whether the offsets in IvarsInfo might be out-of-order.
2059 bool IsDisordered = false;
2060
2061 llvm::SmallVector<IvarInfo, 8> IvarsInfo;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00002062
John McCall3fd13f062015-10-21 18:06:47 +00002063 public:
2064 IvarLayoutBuilder(CodeGenModule &CGM, CharUnits instanceBegin,
2065 CharUnits instanceEnd, bool forStrongLayout)
2066 : CGM(CGM), InstanceBegin(instanceBegin), InstanceEnd(instanceEnd),
2067 ForStrongLayout(forStrongLayout) {
2068 }
2069
2070 void visitRecord(const RecordType *RT, CharUnits offset);
2071
2072 template <class Iterator, class GetOffsetFn>
2073 void visitAggregate(Iterator begin, Iterator end,
2074 CharUnits aggrOffset,
2075 const GetOffsetFn &getOffset);
2076
2077 void visitField(const FieldDecl *field, CharUnits offset);
2078
2079 /// Add the layout of a block implementation.
2080 void visitBlock(const CGBlockInfo &blockInfo);
2081
2082 /// Is there any information for an interesting bitmap?
2083 bool hasBitmapData() const { return !IvarsInfo.empty(); }
2084
2085 llvm::Constant *buildBitmap(CGObjCCommonMac &CGObjC,
2086 llvm::SmallVectorImpl<unsigned char> &buffer);
2087
2088 static void dump(ArrayRef<unsigned char> buffer) {
2089 const unsigned char *s = buffer.data();
2090 for (unsigned i = 0, e = buffer.size(); i < e; i++)
2091 if (!(s[i] & 0xf0))
2092 printf("0x0%x%s", s[i], s[i] != 0 ? ", " : "");
2093 else
2094 printf("0x%x%s", s[i], s[i] != 0 ? ", " : "");
2095 printf("\n");
2096 }
2097 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00002098} // end anonymous namespace
John McCall3fd13f062015-10-21 18:06:47 +00002099
John McCall351762c2011-02-07 10:33:21 +00002100llvm::Constant *CGObjCCommonMac::BuildGCBlockLayout(CodeGenModule &CGM,
2101 const CGBlockInfo &blockInfo) {
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +00002102
Chris Lattnerece04092012-02-07 00:39:47 +00002103 llvm::Constant *nullPtr = llvm::Constant::getNullValue(CGM.Int8PtrTy);
John McCall460ce582015-10-22 18:38:17 +00002104 if (CGM.getLangOpts().getGC() == LangOptions::NonGC)
John McCall351762c2011-02-07 10:33:21 +00002105 return nullPtr;
2106
John McCall3fd13f062015-10-21 18:06:47 +00002107 IvarLayoutBuilder builder(CGM, CharUnits::Zero(), blockInfo.BlockSize,
2108 /*for strong layout*/ true);
2109
2110 builder.visitBlock(blockInfo);
2111
2112 if (!builder.hasBitmapData())
2113 return nullPtr;
2114
2115 llvm::SmallVector<unsigned char, 32> buffer;
2116 llvm::Constant *C = builder.buildBitmap(*this, buffer);
John McCallf5ea0722015-10-29 23:36:14 +00002117 if (CGM.getLangOpts().ObjCGCBitmapPrint && !buffer.empty()) {
John McCall3fd13f062015-10-21 18:06:47 +00002118 printf("\n block variable layout for block: ");
2119 builder.dump(buffer);
2120 }
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00002121
John McCall3fd13f062015-10-21 18:06:47 +00002122 return C;
2123}
2124
2125void IvarLayoutBuilder::visitBlock(const CGBlockInfo &blockInfo) {
Fariborz Jahaniancfddabf2010-09-09 00:21:45 +00002126 // __isa is the first field in block descriptor and must assume by runtime's
2127 // convention that it is GC'able.
John McCall3fd13f062015-10-21 18:06:47 +00002128 IvarsInfo.push_back(IvarInfo(CharUnits::Zero(), 1));
John McCall351762c2011-02-07 10:33:21 +00002129
2130 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
2131
John McCall351762c2011-02-07 10:33:21 +00002132 // Ignore the optional 'this' capture: C++ objects are not assumed
2133 // to be GC'ed.
2134
John McCall3fd13f062015-10-21 18:06:47 +00002135 CharUnits lastFieldOffset;
2136
John McCall351762c2011-02-07 10:33:21 +00002137 // Walk the captured variables.
Aaron Ballman9371dd22014-03-14 18:34:04 +00002138 for (const auto &CI : blockDecl->captures()) {
2139 const VarDecl *variable = CI.getVariable();
John McCall351762c2011-02-07 10:33:21 +00002140 QualType type = variable->getType();
2141
2142 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
2143
2144 // Ignore constant captures.
2145 if (capture.isConstant()) continue;
2146
John McCall3fd13f062015-10-21 18:06:47 +00002147 CharUnits fieldOffset = capture.getOffset();
2148
2149 // Block fields are not necessarily ordered; if we detect that we're
2150 // adding them out-of-order, make sure we sort later.
2151 if (fieldOffset < lastFieldOffset)
2152 IsDisordered = true;
2153 lastFieldOffset = fieldOffset;
John McCall351762c2011-02-07 10:33:21 +00002154
2155 // __block variables are passed by their descriptor address.
Aaron Ballman9371dd22014-03-14 18:34:04 +00002156 if (CI.isByRef()) {
John McCall3fd13f062015-10-21 18:06:47 +00002157 IvarsInfo.push_back(IvarInfo(fieldOffset, /*size in words*/ 1));
Fariborz Jahanian933c6722010-09-11 01:27:29 +00002158 continue;
John McCall351762c2011-02-07 10:33:21 +00002159 }
2160
2161 assert(!type->isArrayType() && "array variable should not be caught");
2162 if (const RecordType *record = type->getAs<RecordType>()) {
John McCall3fd13f062015-10-21 18:06:47 +00002163 visitRecord(record, fieldOffset);
Fariborz Jahanian903aba32010-08-05 21:00:25 +00002164 continue;
2165 }
Fariborz Jahanianf95e3582010-08-06 16:28:55 +00002166
John McCall351762c2011-02-07 10:33:21 +00002167 Qualifiers::GC GCAttr = GetGCAttrTypeForType(CGM.getContext(), type);
John McCall351762c2011-02-07 10:33:21 +00002168
John McCall3fd13f062015-10-21 18:06:47 +00002169 if (GCAttr == Qualifiers::Strong) {
2170 assert(CGM.getContext().getTypeSize(type)
2171 == CGM.getTarget().getPointerWidth(0));
2172 IvarsInfo.push_back(IvarInfo(fieldOffset, /*size in words*/ 1));
2173 }
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00002174 }
Fariborz Jahanianc05349e2010-08-04 16:57:49 +00002175}
2176
Fariborz Jahanian2c96d302012-11-04 18:19:40 +00002177/// getBlockCaptureLifetime - This routine returns life time of the captured
2178/// block variable for the purpose of block layout meta-data generation. FQT is
2179/// the type of the variable captured in the block.
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002180Qualifiers::ObjCLifetime CGObjCCommonMac::getBlockCaptureLifetime(QualType FQT,
2181 bool ByrefLayout) {
John McCall460ce582015-10-22 18:38:17 +00002182 // If it has an ownership qualifier, we're done.
2183 if (auto lifetime = FQT.getObjCLifetime())
2184 return lifetime;
2185
2186 // If it doesn't, and this is ARC, it has no ownership.
Fariborz Jahanian2dd78192012-11-02 22:51:18 +00002187 if (CGM.getLangOpts().ObjCAutoRefCount)
John McCall460ce582015-10-22 18:38:17 +00002188 return Qualifiers::OCL_None;
Fariborz Jahanian2dd78192012-11-02 22:51:18 +00002189
John McCall460ce582015-10-22 18:38:17 +00002190 // In MRC, retainable pointers are owned by non-__block variables.
Fariborz Jahanian2dd78192012-11-02 22:51:18 +00002191 if (FQT->isObjCObjectPointerType() || FQT->isBlockPointerType())
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002192 return ByrefLayout ? Qualifiers::OCL_ExplicitNone : Qualifiers::OCL_Strong;
Fariborz Jahanian2dd78192012-11-02 22:51:18 +00002193
2194 return Qualifiers::OCL_None;
2195}
2196
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002197void CGObjCCommonMac::UpdateRunSkipBlockVars(bool IsByref,
2198 Qualifiers::ObjCLifetime LifeTime,
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002199 CharUnits FieldOffset,
2200 CharUnits FieldSize) {
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002201 // __block variables are passed by their descriptor address.
2202 if (IsByref)
2203 RunSkipBlockVars.push_back(RUN_SKIP(BLOCK_LAYOUT_BYREF, FieldOffset,
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002204 FieldSize));
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002205 else if (LifeTime == Qualifiers::OCL_Strong)
2206 RunSkipBlockVars.push_back(RUN_SKIP(BLOCK_LAYOUT_STRONG, FieldOffset,
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002207 FieldSize));
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002208 else if (LifeTime == Qualifiers::OCL_Weak)
2209 RunSkipBlockVars.push_back(RUN_SKIP(BLOCK_LAYOUT_WEAK, FieldOffset,
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002210 FieldSize));
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002211 else if (LifeTime == Qualifiers::OCL_ExplicitNone)
2212 RunSkipBlockVars.push_back(RUN_SKIP(BLOCK_LAYOUT_UNRETAINED, FieldOffset,
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002213 FieldSize));
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002214 else
2215 RunSkipBlockVars.push_back(RUN_SKIP(BLOCK_LAYOUT_NON_OBJECT_BYTES,
2216 FieldOffset,
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002217 FieldSize));
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002218}
2219
2220void CGObjCCommonMac::BuildRCRecordLayout(const llvm::StructLayout *RecLayout,
2221 const RecordDecl *RD,
2222 ArrayRef<const FieldDecl*> RecFields,
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002223 CharUnits BytePos, bool &HasUnion,
2224 bool ByrefLayout) {
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002225 bool IsUnion = (RD && RD->isUnion());
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002226 CharUnits MaxUnionSize = CharUnits::Zero();
Craig Topper8a13c412014-05-21 05:09:00 +00002227 const FieldDecl *MaxField = nullptr;
2228 const FieldDecl *LastFieldBitfieldOrUnnamed = nullptr;
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002229 CharUnits MaxFieldOffset = CharUnits::Zero();
2230 CharUnits LastBitfieldOrUnnamedOffset = CharUnits::Zero();
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002231
2232 if (RecFields.empty())
2233 return;
John McCallc8e01702013-04-16 22:48:15 +00002234 unsigned ByteSizeInBits = CGM.getTarget().getCharWidth();
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002235
2236 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
2237 const FieldDecl *Field = RecFields[i];
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002238 // Note that 'i' here is actually the field index inside RD of Field,
2239 // although this dependency is hidden.
2240 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002241 CharUnits FieldOffset =
2242 CGM.getContext().toCharUnitsFromBits(RL.getFieldOffset(i));
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002243
2244 // Skip over unnamed or bitfields
2245 if (!Field->getIdentifier() || Field->isBitField()) {
2246 LastFieldBitfieldOrUnnamed = Field;
2247 LastBitfieldOrUnnamedOffset = FieldOffset;
2248 continue;
2249 }
Craig Topper8a13c412014-05-21 05:09:00 +00002250
2251 LastFieldBitfieldOrUnnamed = nullptr;
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002252 QualType FQT = Field->getType();
2253 if (FQT->isRecordType() || FQT->isUnionType()) {
2254 if (FQT->isUnionType())
2255 HasUnion = true;
2256
2257 BuildRCBlockVarRecordLayout(FQT->getAs<RecordType>(),
2258 BytePos + FieldOffset, HasUnion);
2259 continue;
2260 }
2261
2262 if (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
2263 const ConstantArrayType *CArray =
2264 dyn_cast_or_null<ConstantArrayType>(Array);
2265 uint64_t ElCount = CArray->getSize().getZExtValue();
2266 assert(CArray && "only array with known element size is supported");
2267 FQT = CArray->getElementType();
2268 while (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
2269 const ConstantArrayType *CArray =
2270 dyn_cast_or_null<ConstantArrayType>(Array);
2271 ElCount *= CArray->getSize().getZExtValue();
2272 FQT = CArray->getElementType();
2273 }
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002274 if (FQT->isRecordType() && ElCount) {
2275 int OldIndex = RunSkipBlockVars.size() - 1;
2276 const RecordType *RT = FQT->getAs<RecordType>();
2277 BuildRCBlockVarRecordLayout(RT, BytePos + FieldOffset,
2278 HasUnion);
2279
2280 // Replicate layout information for each array element. Note that
2281 // one element is already done.
2282 uint64_t ElIx = 1;
2283 for (int FirstIndex = RunSkipBlockVars.size() - 1 ;ElIx < ElCount; ElIx++) {
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002284 CharUnits Size = CGM.getContext().getTypeSizeInChars(RT);
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002285 for (int i = OldIndex+1; i <= FirstIndex; ++i)
2286 RunSkipBlockVars.push_back(
2287 RUN_SKIP(RunSkipBlockVars[i].opcode,
2288 RunSkipBlockVars[i].block_var_bytepos + Size*ElIx,
2289 RunSkipBlockVars[i].block_var_size));
2290 }
2291 continue;
2292 }
2293 }
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002294 CharUnits FieldSize = CGM.getContext().getTypeSizeInChars(Field->getType());
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002295 if (IsUnion) {
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002296 CharUnits UnionIvarSize = FieldSize;
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002297 if (UnionIvarSize > MaxUnionSize) {
2298 MaxUnionSize = UnionIvarSize;
2299 MaxField = Field;
2300 MaxFieldOffset = FieldOffset;
2301 }
2302 } else {
2303 UpdateRunSkipBlockVars(false,
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002304 getBlockCaptureLifetime(FQT, ByrefLayout),
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002305 BytePos + FieldOffset,
2306 FieldSize);
2307 }
2308 }
2309
2310 if (LastFieldBitfieldOrUnnamed) {
2311 if (LastFieldBitfieldOrUnnamed->isBitField()) {
2312 // Last field was a bitfield. Must update the info.
2313 uint64_t BitFieldSize
2314 = LastFieldBitfieldOrUnnamed->getBitWidthValue(CGM.getContext());
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002315 unsigned UnsSize = (BitFieldSize / ByteSizeInBits) +
Eli Friedman8cbca202012-11-06 22:15:52 +00002316 ((BitFieldSize % ByteSizeInBits) != 0);
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002317 CharUnits Size = CharUnits::fromQuantity(UnsSize);
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002318 Size += LastBitfieldOrUnnamedOffset;
2319 UpdateRunSkipBlockVars(false,
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002320 getBlockCaptureLifetime(LastFieldBitfieldOrUnnamed->getType(),
2321 ByrefLayout),
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002322 BytePos + LastBitfieldOrUnnamedOffset,
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002323 Size);
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002324 } else {
2325 assert(!LastFieldBitfieldOrUnnamed->getIdentifier() &&"Expected unnamed");
2326 // Last field was unnamed. Must update skip info.
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002327 CharUnits FieldSize
2328 = CGM.getContext().getTypeSizeInChars(LastFieldBitfieldOrUnnamed->getType());
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002329 UpdateRunSkipBlockVars(false,
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002330 getBlockCaptureLifetime(LastFieldBitfieldOrUnnamed->getType(),
2331 ByrefLayout),
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002332 BytePos + LastBitfieldOrUnnamedOffset,
2333 FieldSize);
2334 }
2335 }
2336
2337 if (MaxField)
2338 UpdateRunSkipBlockVars(false,
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002339 getBlockCaptureLifetime(MaxField->getType(), ByrefLayout),
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002340 BytePos + MaxFieldOffset,
2341 MaxUnionSize);
2342}
2343
2344void CGObjCCommonMac::BuildRCBlockVarRecordLayout(const RecordType *RT,
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002345 CharUnits BytePos,
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002346 bool &HasUnion,
2347 bool ByrefLayout) {
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002348 const RecordDecl *RD = RT->getDecl();
Aaron Ballman62e47c42014-03-10 13:43:55 +00002349 SmallVector<const FieldDecl*, 16> Fields(RD->fields());
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002350 llvm::Type *Ty = CGM.getTypes().ConvertType(QualType(RT, 0));
2351 const llvm::StructLayout *RecLayout =
2352 CGM.getDataLayout().getStructLayout(cast<llvm::StructType>(Ty));
2353
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002354 BuildRCRecordLayout(RecLayout, RD, Fields, BytePos, HasUnion, ByrefLayout);
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002355}
2356
Fariborz Jahanian23290b02012-11-01 18:32:55 +00002357/// InlineLayoutInstruction - This routine produce an inline instruction for the
2358/// block variable layout if it can. If not, it returns 0. Rules are as follow:
2359/// If ((uintptr_t) layout) < (1 << 12), the layout is inline. In the 64bit world,
2360/// an inline layout of value 0x0000000000000xyz is interpreted as follows:
2361/// x captured object pointers of BLOCK_LAYOUT_STRONG. Followed by
2362/// y captured object of BLOCK_LAYOUT_BYREF. Followed by
2363/// z captured object of BLOCK_LAYOUT_WEAK. If any of the above is missing, zero
2364/// replaces it. For example, 0x00000x00 means x BLOCK_LAYOUT_STRONG and no
2365/// BLOCK_LAYOUT_BYREF and no BLOCK_LAYOUT_WEAK objects are captured.
2366uint64_t CGObjCCommonMac::InlineLayoutInstruction(
2367 SmallVectorImpl<unsigned char> &Layout) {
2368 uint64_t Result = 0;
2369 if (Layout.size() <= 3) {
2370 unsigned size = Layout.size();
2371 unsigned strong_word_count = 0, byref_word_count=0, weak_word_count=0;
2372 unsigned char inst;
2373 enum BLOCK_LAYOUT_OPCODE opcode ;
2374 switch (size) {
2375 case 3:
2376 inst = Layout[0];
2377 opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
2378 if (opcode == BLOCK_LAYOUT_STRONG)
2379 strong_word_count = (inst & 0xF)+1;
2380 else
2381 return 0;
2382 inst = Layout[1];
2383 opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
2384 if (opcode == BLOCK_LAYOUT_BYREF)
2385 byref_word_count = (inst & 0xF)+1;
2386 else
2387 return 0;
2388 inst = Layout[2];
2389 opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
2390 if (opcode == BLOCK_LAYOUT_WEAK)
2391 weak_word_count = (inst & 0xF)+1;
2392 else
2393 return 0;
2394 break;
2395
2396 case 2:
2397 inst = Layout[0];
2398 opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
2399 if (opcode == BLOCK_LAYOUT_STRONG) {
2400 strong_word_count = (inst & 0xF)+1;
2401 inst = Layout[1];
2402 opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
2403 if (opcode == BLOCK_LAYOUT_BYREF)
2404 byref_word_count = (inst & 0xF)+1;
2405 else if (opcode == BLOCK_LAYOUT_WEAK)
2406 weak_word_count = (inst & 0xF)+1;
2407 else
2408 return 0;
2409 }
2410 else if (opcode == BLOCK_LAYOUT_BYREF) {
2411 byref_word_count = (inst & 0xF)+1;
2412 inst = Layout[1];
2413 opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
2414 if (opcode == BLOCK_LAYOUT_WEAK)
2415 weak_word_count = (inst & 0xF)+1;
2416 else
2417 return 0;
2418 }
2419 else
2420 return 0;
2421 break;
2422
2423 case 1:
2424 inst = Layout[0];
2425 opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
2426 if (opcode == BLOCK_LAYOUT_STRONG)
2427 strong_word_count = (inst & 0xF)+1;
2428 else if (opcode == BLOCK_LAYOUT_BYREF)
2429 byref_word_count = (inst & 0xF)+1;
2430 else if (opcode == BLOCK_LAYOUT_WEAK)
2431 weak_word_count = (inst & 0xF)+1;
2432 else
2433 return 0;
2434 break;
2435
2436 default:
2437 return 0;
2438 }
2439
2440 // Cannot inline when any of the word counts is 15. Because this is one less
2441 // than the actual work count (so 15 means 16 actual word counts),
2442 // and we can only display 0 thru 15 word counts.
2443 if (strong_word_count == 16 || byref_word_count == 16 || weak_word_count == 16)
2444 return 0;
2445
2446 unsigned count =
2447 (strong_word_count != 0) + (byref_word_count != 0) + (weak_word_count != 0);
2448
2449 if (size == count) {
2450 if (strong_word_count)
2451 Result = strong_word_count;
2452 Result <<= 4;
2453 if (byref_word_count)
2454 Result += byref_word_count;
2455 Result <<= 4;
2456 if (weak_word_count)
2457 Result += weak_word_count;
2458 }
2459 }
2460 return Result;
2461}
2462
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002463llvm::Constant *CGObjCCommonMac::getBitmapBlockLayout(bool ComputeByrefLayout) {
2464 llvm::Constant *nullPtr = llvm::Constant::getNullValue(CGM.Int8PtrTy);
2465 if (RunSkipBlockVars.empty())
2466 return nullPtr;
John McCallc8e01702013-04-16 22:48:15 +00002467 unsigned WordSizeInBits = CGM.getTarget().getPointerWidth(0);
2468 unsigned ByteSizeInBits = CGM.getTarget().getCharWidth();
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002469 unsigned WordSizeInBytes = WordSizeInBits/ByteSizeInBits;
2470
2471 // Sort on byte position; captures might not be allocated in order,
2472 // and unions can do funny things.
2473 llvm::array_pod_sort(RunSkipBlockVars.begin(), RunSkipBlockVars.end());
2474 SmallVector<unsigned char, 16> Layout;
2475
2476 unsigned size = RunSkipBlockVars.size();
2477 for (unsigned i = 0; i < size; i++) {
2478 enum BLOCK_LAYOUT_OPCODE opcode = RunSkipBlockVars[i].opcode;
2479 CharUnits start_byte_pos = RunSkipBlockVars[i].block_var_bytepos;
2480 CharUnits end_byte_pos = start_byte_pos;
2481 unsigned j = i+1;
2482 while (j < size) {
2483 if (opcode == RunSkipBlockVars[j].opcode) {
2484 end_byte_pos = RunSkipBlockVars[j++].block_var_bytepos;
2485 i++;
2486 }
2487 else
2488 break;
2489 }
2490 CharUnits size_in_bytes =
2491 end_byte_pos - start_byte_pos + RunSkipBlockVars[j-1].block_var_size;
2492 if (j < size) {
2493 CharUnits gap =
2494 RunSkipBlockVars[j].block_var_bytepos -
2495 RunSkipBlockVars[j-1].block_var_bytepos - RunSkipBlockVars[j-1].block_var_size;
2496 size_in_bytes += gap;
2497 }
2498 CharUnits residue_in_bytes = CharUnits::Zero();
2499 if (opcode == BLOCK_LAYOUT_NON_OBJECT_BYTES) {
2500 residue_in_bytes = size_in_bytes % WordSizeInBytes;
2501 size_in_bytes -= residue_in_bytes;
2502 opcode = BLOCK_LAYOUT_NON_OBJECT_WORDS;
2503 }
2504
2505 unsigned size_in_words = size_in_bytes.getQuantity() / WordSizeInBytes;
2506 while (size_in_words >= 16) {
2507 // Note that value in imm. is one less that the actual
2508 // value. So, 0xf means 16 words follow!
2509 unsigned char inst = (opcode << 4) | 0xf;
2510 Layout.push_back(inst);
2511 size_in_words -= 16;
2512 }
2513 if (size_in_words > 0) {
2514 // Note that value in imm. is one less that the actual
2515 // value. So, we subtract 1 away!
2516 unsigned char inst = (opcode << 4) | (size_in_words-1);
2517 Layout.push_back(inst);
2518 }
2519 if (residue_in_bytes > CharUnits::Zero()) {
2520 unsigned char inst =
2521 (BLOCK_LAYOUT_NON_OBJECT_BYTES << 4) | (residue_in_bytes.getQuantity()-1);
2522 Layout.push_back(inst);
2523 }
2524 }
2525
John McCall7f416cc2015-09-08 08:05:57 +00002526 while (!Layout.empty()) {
2527 unsigned char inst = Layout.back();
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002528 enum BLOCK_LAYOUT_OPCODE opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
2529 if (opcode == BLOCK_LAYOUT_NON_OBJECT_BYTES || opcode == BLOCK_LAYOUT_NON_OBJECT_WORDS)
2530 Layout.pop_back();
2531 else
2532 break;
2533 }
2534
2535 uint64_t Result = InlineLayoutInstruction(Layout);
2536 if (Result != 0) {
2537 // Block variable layout instruction has been inlined.
2538 if (CGM.getLangOpts().ObjCGCBitmapPrint) {
2539 if (ComputeByrefLayout)
John McCall7f416cc2015-09-08 08:05:57 +00002540 printf("\n Inline BYREF variable layout: ");
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002541 else
John McCall7f416cc2015-09-08 08:05:57 +00002542 printf("\n Inline block variable layout: ");
2543 printf("0x0%" PRIx64 "", Result);
2544 if (auto numStrong = (Result & 0xF00) >> 8)
2545 printf(", BL_STRONG:%d", (int) numStrong);
2546 if (auto numByref = (Result & 0x0F0) >> 4)
2547 printf(", BL_BYREF:%d", (int) numByref);
2548 if (auto numWeak = (Result & 0x00F) >> 0)
2549 printf(", BL_WEAK:%d", (int) numWeak);
2550 printf(", BL_OPERATOR:0\n");
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002551 }
Vedant Kumar3ed0df02015-12-21 19:43:25 +00002552 return llvm::ConstantInt::get(CGM.IntPtrTy, Result);
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002553 }
2554
2555 unsigned char inst = (BLOCK_LAYOUT_OPERATOR << 4) | 0;
2556 Layout.push_back(inst);
2557 std::string BitMap;
2558 for (unsigned i = 0, e = Layout.size(); i != e; i++)
2559 BitMap += Layout[i];
2560
2561 if (CGM.getLangOpts().ObjCGCBitmapPrint) {
2562 if (ComputeByrefLayout)
John McCall7f416cc2015-09-08 08:05:57 +00002563 printf("\n Byref variable layout: ");
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002564 else
John McCall7f416cc2015-09-08 08:05:57 +00002565 printf("\n Block variable layout: ");
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002566 for (unsigned i = 0, e = BitMap.size(); i != e; i++) {
2567 unsigned char inst = BitMap[i];
2568 enum BLOCK_LAYOUT_OPCODE opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
2569 unsigned delta = 1;
2570 switch (opcode) {
2571 case BLOCK_LAYOUT_OPERATOR:
2572 printf("BL_OPERATOR:");
2573 delta = 0;
2574 break;
2575 case BLOCK_LAYOUT_NON_OBJECT_BYTES:
2576 printf("BL_NON_OBJECT_BYTES:");
2577 break;
2578 case BLOCK_LAYOUT_NON_OBJECT_WORDS:
2579 printf("BL_NON_OBJECT_WORD:");
2580 break;
2581 case BLOCK_LAYOUT_STRONG:
2582 printf("BL_STRONG:");
2583 break;
2584 case BLOCK_LAYOUT_BYREF:
2585 printf("BL_BYREF:");
2586 break;
2587 case BLOCK_LAYOUT_WEAK:
2588 printf("BL_WEAK:");
2589 break;
2590 case BLOCK_LAYOUT_UNRETAINED:
2591 printf("BL_UNRETAINED:");
2592 break;
2593 }
2594 // Actual value of word count is one more that what is in the imm.
2595 // field of the instruction
2596 printf("%d", (inst & 0xf) + delta);
2597 if (i < e-1)
2598 printf(", ");
2599 else
2600 printf("\n");
2601 }
2602 }
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00002603
Saleem Abdulrasool82f6add2016-09-20 18:38:54 +00002604 auto *Entry = CreateCStringLiteral(BitMap, ObjCLabelType::ClassName,
2605 /*ForceNonFragileABI=*/true,
2606 /*NullTerminate=*/false);
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002607 return getConstantGEP(VMContext, Entry, 0, 0);
2608}
2609
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +00002610llvm::Constant *CGObjCCommonMac::BuildRCBlockLayout(CodeGenModule &CGM,
2611 const CGBlockInfo &blockInfo) {
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +00002612 assert(CGM.getLangOpts().getGC() == LangOptions::NonGC);
2613
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +00002614 RunSkipBlockVars.clear();
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002615 bool hasUnion = false;
2616
John McCallc8e01702013-04-16 22:48:15 +00002617 unsigned WordSizeInBits = CGM.getTarget().getPointerWidth(0);
2618 unsigned ByteSizeInBits = CGM.getTarget().getCharWidth();
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +00002619 unsigned WordSizeInBytes = WordSizeInBits/ByteSizeInBits;
2620
2621 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
2622
2623 // Calculate the basic layout of the block structure.
2624 const llvm::StructLayout *layout =
2625 CGM.getDataLayout().getStructLayout(blockInfo.StructureType);
2626
2627 // Ignore the optional 'this' capture: C++ objects are not assumed
2628 // to be GC'ed.
Fariborz Jahanian4cf177e2012-12-04 17:20:57 +00002629 if (blockInfo.BlockHeaderForcedGapSize != CharUnits::Zero())
2630 UpdateRunSkipBlockVars(false, Qualifiers::OCL_None,
2631 blockInfo.BlockHeaderForcedGapOffset,
2632 blockInfo.BlockHeaderForcedGapSize);
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +00002633 // Walk the captured variables.
Aaron Ballman9371dd22014-03-14 18:34:04 +00002634 for (const auto &CI : blockDecl->captures()) {
2635 const VarDecl *variable = CI.getVariable();
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +00002636 QualType type = variable->getType();
2637
2638 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
2639
2640 // Ignore constant captures.
2641 if (capture.isConstant()) continue;
2642
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002643 CharUnits fieldOffset =
2644 CharUnits::fromQuantity(layout->getElementOffset(capture.getIndex()));
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +00002645
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002646 assert(!type->isArrayType() && "array variable should not be caught");
Aaron Ballman9371dd22014-03-14 18:34:04 +00002647 if (!CI.isByRef())
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002648 if (const RecordType *record = type->getAs<RecordType>()) {
2649 BuildRCBlockVarRecordLayout(record, fieldOffset, hasUnion);
2650 continue;
2651 }
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002652 CharUnits fieldSize;
Aaron Ballman9371dd22014-03-14 18:34:04 +00002653 if (CI.isByRef())
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002654 fieldSize = CharUnits::fromQuantity(WordSizeInBytes);
2655 else
2656 fieldSize = CGM.getContext().getTypeSizeInChars(type);
Aaron Ballman9371dd22014-03-14 18:34:04 +00002657 UpdateRunSkipBlockVars(CI.isByRef(), getBlockCaptureLifetime(type, false),
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002658 fieldOffset, fieldSize);
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +00002659 }
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002660 return getBitmapBlockLayout(false);
2661}
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +00002662
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002663llvm::Constant *CGObjCCommonMac::BuildByrefLayout(CodeGen::CodeGenModule &CGM,
2664 QualType T) {
2665 assert(CGM.getLangOpts().getGC() == LangOptions::NonGC);
2666 assert(!T->isArrayType() && "__block array variable should not be caught");
2667 CharUnits fieldOffset;
2668 RunSkipBlockVars.clear();
2669 bool hasUnion = false;
2670 if (const RecordType *record = T->getAs<RecordType>()) {
2671 BuildRCBlockVarRecordLayout(record, fieldOffset, hasUnion, true /*ByrefLayout */);
2672 llvm::Constant *Result = getBitmapBlockLayout(true);
Vedant Kumar2f5bb1152015-12-21 20:21:15 +00002673 if (isa<llvm::ConstantInt>(Result))
2674 Result = llvm::ConstantExpr::getIntToPtr(Result, CGM.Int8PtrTy);
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002675 return Result;
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +00002676 }
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002677 llvm::Constant *nullPtr = llvm::Constant::getNullValue(CGM.Int8PtrTy);
2678 return nullPtr;
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +00002679}
2680
John McCall882987f2013-02-28 19:01:20 +00002681llvm::Value *CGObjCMac::GenerateProtocolRef(CodeGenFunction &CGF,
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00002682 const ObjCProtocolDecl *PD) {
Daniel Dunbar7050c552008-09-04 04:33:15 +00002683 // FIXME: I don't understand why gcc generates this, or where it is
Mike Stump18bb9282009-05-16 07:57:57 +00002684 // resolved. Investigate. Its also wasteful to look this up over and over.
Daniel Dunbar7050c552008-09-04 04:33:15 +00002685 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
2686
Owen Andersonade90fd2009-07-29 18:54:39 +00002687 return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
Douglas Gregor020de322012-01-17 18:36:30 +00002688 ObjCTypes.getExternalProtocolPtrTy());
Daniel Dunbar303e2c22008-08-11 02:45:11 +00002689}
2690
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00002691void CGObjCCommonMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
Mike Stump18bb9282009-05-16 07:57:57 +00002692 // FIXME: We shouldn't need this, the protocol decl should contain enough
2693 // information to tell us whether this was a declaration or a definition.
Daniel Dunbarc475d422008-10-29 22:36:39 +00002694 DefinedProtocols.insert(PD->getIdentifier());
2695
2696 // If we have generated a forward reference to this protocol, emit
2697 // it now. Otherwise do nothing, the protocol objects are lazily
2698 // emitted.
Daniel Dunbar59e476b2009-08-03 17:06:42 +00002699 if (Protocols.count(PD->getIdentifier()))
Daniel Dunbarc475d422008-10-29 22:36:39 +00002700 GetOrEmitProtocol(PD);
2701}
2702
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00002703llvm::Constant *CGObjCCommonMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbarc475d422008-10-29 22:36:39 +00002704 if (DefinedProtocols.count(PD->getIdentifier()))
2705 return GetOrEmitProtocol(PD);
Douglas Gregora9d84932011-05-27 01:19:52 +00002706
Daniel Dunbarc475d422008-10-29 22:36:39 +00002707 return GetOrEmitProtocolRef(PD);
2708}
2709
Douglas Gregor24ae22c2016-04-01 23:23:52 +00002710llvm::Value *CGObjCCommonMac::EmitClassRefViaRuntime(
2711 CodeGenFunction &CGF,
2712 const ObjCInterfaceDecl *ID,
2713 ObjCCommonTypesHelper &ObjCTypes) {
2714 llvm::Constant *lookUpClassFn = ObjCTypes.getLookUpClassFn();
2715
2716 llvm::Value *className =
2717 CGF.CGM.GetAddrOfConstantCString(ID->getObjCRuntimeNameAsString())
2718 .getPointer();
2719 ASTContext &ctx = CGF.CGM.getContext();
2720 className =
2721 CGF.Builder.CreateBitCast(className,
2722 CGF.ConvertType(
2723 ctx.getPointerType(ctx.CharTy.withConst())));
2724 llvm::CallInst *call = CGF.Builder.CreateCall(lookUpClassFn, className);
2725 call->setDoesNotThrow();
2726 return call;
2727}
2728
Daniel Dunbarb036db82008-08-13 03:21:16 +00002729/*
Rafael Espindolaf9e1e5e2014-02-20 14:09:04 +00002730// Objective-C 1.0 extensions
Daniel Dunbar59e476b2009-08-03 17:06:42 +00002731struct _objc_protocol {
2732struct _objc_protocol_extension *isa;
2733char *protocol_name;
2734struct _objc_protocol_list *protocol_list;
2735struct _objc__method_prototype_list *instance_methods;
2736struct _objc__method_prototype_list *class_methods
2737};
Daniel Dunbarb036db82008-08-13 03:21:16 +00002738
Daniel Dunbar59e476b2009-08-03 17:06:42 +00002739See EmitProtocolExtension().
Daniel Dunbarb036db82008-08-13 03:21:16 +00002740*/
Daniel Dunbarc475d422008-10-29 22:36:39 +00002741llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
John McCallf9582a72012-03-30 21:29:05 +00002742 llvm::GlobalVariable *Entry = Protocols[PD->getIdentifier()];
Daniel Dunbarc475d422008-10-29 22:36:39 +00002743
2744 // Early exit if a defining object has already been generated.
2745 if (Entry && Entry->hasInitializer())
2746 return Entry;
2747
Douglas Gregora715bff2012-01-01 19:51:50 +00002748 // Use the protocol definition, if there is one.
2749 if (const ObjCProtocolDecl *Def = PD->getDefinition())
2750 PD = Def;
2751
Daniel Dunbarc61d0e92008-08-25 06:02:07 +00002752 // FIXME: I don't understand why gcc generates this, or where it is
Mike Stump18bb9282009-05-16 07:57:57 +00002753 // resolved. Investigate. Its also wasteful to look this up over and over.
Daniel Dunbarc61d0e92008-08-25 06:02:07 +00002754 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
2755
Daniel Dunbareb1f9a22008-08-27 02:31:56 +00002756 // Construct method lists.
2757 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
2758 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Bob Wilson5f4e3a72011-11-30 01:57:58 +00002759 std::vector<llvm::Constant*> MethodTypesExt, OptMethodTypesExt;
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002760 for (const auto *MD : PD->instance_methods()) {
Daniel Dunbareb1f9a22008-08-27 02:31:56 +00002761 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Douglas Gregora9d84932011-05-27 01:19:52 +00002762 if (!C)
2763 return GetOrEmitProtocolRef(PD);
2764
Daniel Dunbareb1f9a22008-08-27 02:31:56 +00002765 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
2766 OptInstanceMethods.push_back(C);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00002767 OptMethodTypesExt.push_back(GetMethodVarType(MD, true));
Daniel Dunbareb1f9a22008-08-27 02:31:56 +00002768 } else {
2769 InstanceMethods.push_back(C);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00002770 MethodTypesExt.push_back(GetMethodVarType(MD, true));
Daniel Dunbar59e476b2009-08-03 17:06:42 +00002771 }
Daniel Dunbareb1f9a22008-08-27 02:31:56 +00002772 }
2773
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002774 for (const auto *MD : PD->class_methods()) {
Daniel Dunbareb1f9a22008-08-27 02:31:56 +00002775 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Douglas Gregora9d84932011-05-27 01:19:52 +00002776 if (!C)
2777 return GetOrEmitProtocolRef(PD);
2778
Daniel Dunbareb1f9a22008-08-27 02:31:56 +00002779 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
2780 OptClassMethods.push_back(C);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00002781 OptMethodTypesExt.push_back(GetMethodVarType(MD, true));
Daniel Dunbareb1f9a22008-08-27 02:31:56 +00002782 } else {
2783 ClassMethods.push_back(C);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00002784 MethodTypesExt.push_back(GetMethodVarType(MD, true));
Daniel Dunbar59e476b2009-08-03 17:06:42 +00002785 }
Daniel Dunbareb1f9a22008-08-27 02:31:56 +00002786 }
2787
Bob Wilson5f4e3a72011-11-30 01:57:58 +00002788 MethodTypesExt.insert(MethodTypesExt.end(),
2789 OptMethodTypesExt.begin(), OptMethodTypesExt.end());
2790
Benjamin Kramer22d24c22011-10-15 12:20:02 +00002791 llvm::Constant *Values[] = {
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00002792 EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods,
2793 MethodTypesExt),
2794 GetClassName(PD->getObjCRuntimeNameAsString()),
2795 EmitProtocolList("OBJC_PROTOCOL_REFS_" + PD->getName(),
2796 PD->protocol_begin(), PD->protocol_end()),
2797 EmitMethodDescList("OBJC_PROTOCOL_INSTANCE_METHODS_" + PD->getName(),
2798 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
2799 InstanceMethods),
2800 EmitMethodDescList("OBJC_PROTOCOL_CLASS_METHODS_" + PD->getName(),
2801 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
2802 ClassMethods)};
Owen Anderson0e0189d2009-07-27 22:29:56 +00002803 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
Daniel Dunbarb036db82008-08-13 03:21:16 +00002804 Values);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00002805
Daniel Dunbarb036db82008-08-13 03:21:16 +00002806 if (Entry) {
Rafael Espindola5d117f32014-03-06 01:10:46 +00002807 // Already created, update the initializer.
Rafael Espindolab3262952014-05-09 00:43:37 +00002808 assert(Entry->hasPrivateLinkage());
Daniel Dunbarb036db82008-08-13 03:21:16 +00002809 Entry->setInitializer(Init);
2810 } else {
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00002811 Entry = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ProtocolTy,
2812 false, llvm::GlobalValue::PrivateLinkage,
2813 Init, "OBJC_PROTOCOL_" + PD->getName());
Daniel Dunbarb036db82008-08-13 03:21:16 +00002814 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbarb036db82008-08-13 03:21:16 +00002815 // FIXME: Is this necessary? Why only for protocol?
2816 Entry->setAlignment(4);
John McCallf9582a72012-03-30 21:29:05 +00002817
2818 Protocols[PD->getIdentifier()] = Entry;
Daniel Dunbarb036db82008-08-13 03:21:16 +00002819 }
Rafael Espindola060062a2014-03-06 22:15:10 +00002820 CGM.addCompilerUsedGlobal(Entry);
Daniel Dunbarc475d422008-10-29 22:36:39 +00002821
2822 return Entry;
Daniel Dunbarb036db82008-08-13 03:21:16 +00002823}
2824
Daniel Dunbarc475d422008-10-29 22:36:39 +00002825llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbarb036db82008-08-13 03:21:16 +00002826 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
2827
2828 if (!Entry) {
Daniel Dunbarc475d422008-10-29 22:36:39 +00002829 // We use the initializer as a marker of whether this is a forward
2830 // reference or not. At module finalization we add the empty
2831 // contents for protocols which were referenced but never defined.
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00002832 Entry = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ProtocolTy,
2833 false, llvm::GlobalValue::PrivateLinkage,
2834 nullptr, "OBJC_PROTOCOL_" + PD->getName());
Daniel Dunbarb036db82008-08-13 03:21:16 +00002835 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbarb036db82008-08-13 03:21:16 +00002836 // FIXME: Is this necessary? Why only for protocol?
2837 Entry->setAlignment(4);
2838 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00002839
Daniel Dunbarb036db82008-08-13 03:21:16 +00002840 return Entry;
2841}
2842
2843/*
2844 struct _objc_protocol_extension {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00002845 uint32_t size;
2846 struct objc_method_description_list *optional_instance_methods;
2847 struct objc_method_description_list *optional_class_methods;
2848 struct objc_property_list *instance_properties;
Bob Wilson5f4e3a72011-11-30 01:57:58 +00002849 const char ** extendedMethodTypes;
Manman Rence7bff52016-01-29 23:46:55 +00002850 struct objc_property_list *class_properties;
Daniel Dunbarb036db82008-08-13 03:21:16 +00002851 };
2852*/
Daniel Dunbareb1f9a22008-08-27 02:31:56 +00002853llvm::Constant *
2854CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
Bill Wendlingcb5b5ff2012-02-07 09:25:09 +00002855 ArrayRef<llvm::Constant*> OptInstanceMethods,
2856 ArrayRef<llvm::Constant*> OptClassMethods,
2857 ArrayRef<llvm::Constant*> MethodTypesExt) {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00002858 uint64_t Size =
Micah Villmowdd31ca12012-10-08 16:25:52 +00002859 CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ProtocolExtensionTy);
Benjamin Kramer22d24c22011-10-15 12:20:02 +00002860 llvm::Constant *Values[] = {
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00002861 llvm::ConstantInt::get(ObjCTypes.IntTy, Size),
2862 EmitMethodDescList("OBJC_PROTOCOL_INSTANCE_METHODS_OPT_" + PD->getName(),
2863 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
2864 OptInstanceMethods),
2865 EmitMethodDescList("OBJC_PROTOCOL_CLASS_METHODS_OPT_" + PD->getName(),
2866 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
2867 OptClassMethods),
2868 EmitPropertyList("OBJC_$_PROP_PROTO_LIST_" + PD->getName(), nullptr, PD,
Manman Renad0e7912016-01-29 19:22:54 +00002869 ObjCTypes, false),
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00002870 EmitProtocolMethodTypes("OBJC_PROTOCOL_METHOD_TYPES_" + PD->getName(),
Manman Rence7bff52016-01-29 23:46:55 +00002871 MethodTypesExt, ObjCTypes),
2872 EmitPropertyList("OBJC_$_CLASS_PROP_PROTO_LIST_" + PD->getName(), nullptr,
2873 PD, ObjCTypes, true)};
Daniel Dunbarb036db82008-08-13 03:21:16 +00002874
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00002875 // Return null if no extension bits are used.
Daniel Dunbar59e476b2009-08-03 17:06:42 +00002876 if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
Manman Rence7bff52016-01-29 23:46:55 +00002877 Values[3]->isNullValue() && Values[4]->isNullValue() &&
2878 Values[5]->isNullValue())
Owen Anderson0b75f232009-07-31 20:28:54 +00002879 return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
Daniel Dunbarb036db82008-08-13 03:21:16 +00002880
Daniel Dunbar59e476b2009-08-03 17:06:42 +00002881 llvm::Constant *Init =
Owen Anderson0e0189d2009-07-27 22:29:56 +00002882 llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
Daniel Dunbarb036db82008-08-13 03:21:16 +00002883
Daniel Dunbarc2d4b622009-03-09 21:49:58 +00002884 // No special section, but goes in llvm.used
Alp Toker541d5072014-06-07 23:30:53 +00002885 return CreateMetadataVar("\01l_OBJC_PROTOCOLEXT_" + PD->getName(), Init,
John McCall7f416cc2015-09-08 08:05:57 +00002886 StringRef(), CGM.getPointerAlign(), true);
Daniel Dunbarb036db82008-08-13 03:21:16 +00002887}
2888
2889/*
2890 struct objc_protocol_list {
Bill Wendlinga515b582012-02-09 22:16:49 +00002891 struct objc_protocol_list *next;
2892 long count;
2893 Protocol *list[];
Daniel Dunbarb036db82008-08-13 03:21:16 +00002894 };
2895*/
Daniel Dunbardec75f82008-08-21 21:57:41 +00002896llvm::Constant *
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002897CGObjCMac::EmitProtocolList(Twine Name,
Daniel Dunbardec75f82008-08-21 21:57:41 +00002898 ObjCProtocolDecl::protocol_iterator begin,
2899 ObjCProtocolDecl::protocol_iterator end) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002900 SmallVector<llvm::Constant *, 16> ProtocolRefs;
Daniel Dunbarb036db82008-08-13 03:21:16 +00002901
Daniel Dunbardec75f82008-08-21 21:57:41 +00002902 for (; begin != end; ++begin)
2903 ProtocolRefs.push_back(GetProtocolRef(*begin));
Daniel Dunbarb036db82008-08-13 03:21:16 +00002904
2905 // Just return null for empty protocol lists
Daniel Dunbar59e476b2009-08-03 17:06:42 +00002906 if (ProtocolRefs.empty())
Owen Anderson0b75f232009-07-31 20:28:54 +00002907 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
Daniel Dunbarb036db82008-08-13 03:21:16 +00002908
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00002909 // This list is null terminated.
Owen Anderson0b75f232009-07-31 20:28:54 +00002910 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
Daniel Dunbarb036db82008-08-13 03:21:16 +00002911
Chris Lattnere64d7ba2011-06-20 04:01:35 +00002912 llvm::Constant *Values[3];
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00002913 // This field is only used by the runtime.
Owen Anderson0b75f232009-07-31 20:28:54 +00002914 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00002915 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy,
Daniel Dunbar59e476b2009-08-03 17:06:42 +00002916 ProtocolRefs.size() - 1);
2917 Values[2] =
2918 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
2919 ProtocolRefs.size()),
Daniel Dunbarb036db82008-08-13 03:21:16 +00002920 ProtocolRefs);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00002921
Chris Lattnere64d7ba2011-06-20 04:01:35 +00002922 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00002923 llvm::GlobalVariable *GV =
Daniel Dunbarc2d4b622009-03-09 21:49:58 +00002924 CreateMetadataVar(Name, Init, "__OBJC,__cat_cls_meth,regular,no_dead_strip",
John McCall7f416cc2015-09-08 08:05:57 +00002925 CGM.getPointerAlign(), false);
Owen Andersonade90fd2009-07-29 18:54:39 +00002926 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
Daniel Dunbarb036db82008-08-13 03:21:16 +00002927}
2928
Bill Wendlingcb5b5ff2012-02-07 09:25:09 +00002929void CGObjCCommonMac::
2930PushProtocolProperties(llvm::SmallPtrSet<const IdentifierInfo*,16> &PropertySet,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002931 SmallVectorImpl<llvm::Constant *> &Properties,
Bill Wendlingcb5b5ff2012-02-07 09:25:09 +00002932 const Decl *Container,
Aaron Ballmandc4bea42014-03-13 18:47:37 +00002933 const ObjCProtocolDecl *Proto,
Manman Renad0e7912016-01-29 19:22:54 +00002934 const ObjCCommonTypesHelper &ObjCTypes,
2935 bool IsClassProperty) {
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00002936 for (const auto *P : Proto->protocols())
Manman Renad0e7912016-01-29 19:22:54 +00002937 PushProtocolProperties(PropertySet, Properties, Container, P, ObjCTypes,
2938 IsClassProperty);
2939
2940 for (const auto *PD : Proto->properties()) {
2941 if (IsClassProperty != PD->isClassProperty())
2942 continue;
David Blaikie82e95a32014-11-19 07:49:47 +00002943 if (!PropertySet.insert(PD->getIdentifier()).second)
Fariborz Jahanian751c1e72009-12-12 21:26:21 +00002944 continue;
Benjamin Kramer22d24c22011-10-15 12:20:02 +00002945 llvm::Constant *Prop[] = {
2946 GetPropertyName(PD->getIdentifier()),
2947 GetPropertyTypeString(PD, Container)
2948 };
Fariborz Jahanian751c1e72009-12-12 21:26:21 +00002949 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy, Prop));
2950 }
2951}
2952
Daniel Dunbarb036db82008-08-13 03:21:16 +00002953/*
Daniel Dunbar80a840b2008-08-23 00:19:03 +00002954 struct _objc_property {
Bill Wendlinga515b582012-02-09 22:16:49 +00002955 const char * const name;
2956 const char * const attributes;
Daniel Dunbar80a840b2008-08-23 00:19:03 +00002957 };
2958
2959 struct _objc_property_list {
Bill Wendlinga515b582012-02-09 22:16:49 +00002960 uint32_t entsize; // sizeof (struct _objc_property)
2961 uint32_t prop_count;
2962 struct _objc_property[prop_count];
Daniel Dunbar80a840b2008-08-23 00:19:03 +00002963 };
2964*/
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002965llvm::Constant *CGObjCCommonMac::EmitPropertyList(Twine Name,
Daniel Dunbar59e476b2009-08-03 17:06:42 +00002966 const Decl *Container,
2967 const ObjCContainerDecl *OCD,
Manman Renad0e7912016-01-29 19:22:54 +00002968 const ObjCCommonTypesHelper &ObjCTypes,
2969 bool IsClassProperty) {
Manman Ren01b705e2016-04-19 19:05:03 +00002970 if (IsClassProperty) {
2971 // Make this entry NULL for OS X with deployment target < 10.11, for iOS
2972 // with deployment target < 9.0.
2973 const llvm::Triple &Triple = CGM.getTarget().getTriple();
2974 if ((Triple.isMacOSX() && Triple.isMacOSXVersionLT(10, 11)) ||
2975 (Triple.isiOS() && Triple.isOSVersionLT(9)))
2976 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
2977 }
2978
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002979 SmallVector<llvm::Constant *, 16> Properties;
Fariborz Jahanian751c1e72009-12-12 21:26:21 +00002980 llvm::SmallPtrSet<const IdentifierInfo*, 16> PropertySet;
Nico Weber08c93332015-12-03 17:44:51 +00002981
2982 auto AddProperty = [&](const ObjCPropertyDecl *PD) {
2983 llvm::Constant *Prop[] = {GetPropertyName(PD->getIdentifier()),
2984 GetPropertyTypeString(PD, Container)};
2985 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy, Prop));
2986 };
2987 if (const ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(OCD))
2988 for (const ObjCCategoryDecl *ClassExt : OID->known_extensions())
Manman Renad0e7912016-01-29 19:22:54 +00002989 for (auto *PD : ClassExt->properties()) {
2990 if (IsClassProperty != PD->isClassProperty())
2991 continue;
Nico Weber08c93332015-12-03 17:44:51 +00002992 PropertySet.insert(PD->getIdentifier());
2993 AddProperty(PD);
2994 }
Manman Renad0e7912016-01-29 19:22:54 +00002995
2996 for (const auto *PD : OCD->properties()) {
2997 if (IsClassProperty != PD->isClassProperty())
2998 continue;
Nico Weber08c93332015-12-03 17:44:51 +00002999 // Don't emit duplicate metadata for properties that were already in a
3000 // class extension.
3001 if (!PropertySet.insert(PD->getIdentifier()).second)
3002 continue;
3003 AddProperty(PD);
Daniel Dunbar80a840b2008-08-23 00:19:03 +00003004 }
Nico Weber08c93332015-12-03 17:44:51 +00003005
Fariborz Jahanian7966aff2010-06-22 16:33:55 +00003006 if (const ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(OCD)) {
Aaron Ballmana9f49e32014-03-13 20:55:22 +00003007 for (const auto *P : OID->all_referenced_protocols())
Manman Renad0e7912016-01-29 19:22:54 +00003008 PushProtocolProperties(PropertySet, Properties, Container, P, ObjCTypes,
3009 IsClassProperty);
Fariborz Jahanian7966aff2010-06-22 16:33:55 +00003010 }
3011 else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(OCD)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00003012 for (const auto *P : CD->protocols())
Manman Renad0e7912016-01-29 19:22:54 +00003013 PushProtocolProperties(PropertySet, Properties, Container, P, ObjCTypes,
3014 IsClassProperty);
Fariborz Jahanian7966aff2010-06-22 16:33:55 +00003015 }
Daniel Dunbar80a840b2008-08-23 00:19:03 +00003016
3017 // Return null for empty list.
3018 if (Properties.empty())
Owen Anderson0b75f232009-07-31 20:28:54 +00003019 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
Daniel Dunbar80a840b2008-08-23 00:19:03 +00003020
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003021 unsigned PropertySize =
Micah Villmowdd31ca12012-10-08 16:25:52 +00003022 CGM.getDataLayout().getTypeAllocSize(ObjCTypes.PropertyTy);
Chris Lattnere64d7ba2011-06-20 04:01:35 +00003023 llvm::Constant *Values[3];
Owen Andersonb7a2fe62009-07-24 23:12:58 +00003024 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
3025 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003026 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
Daniel Dunbar80a840b2008-08-23 00:19:03 +00003027 Properties.size());
Owen Anderson47034e12009-07-28 18:33:04 +00003028 Values[2] = llvm::ConstantArray::get(AT, Properties);
Chris Lattnere64d7ba2011-06-20 04:01:35 +00003029 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
Daniel Dunbar80a840b2008-08-23 00:19:03 +00003030
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003031 llvm::GlobalVariable *GV =
3032 CreateMetadataVar(Name, Init,
3033 (ObjCABI == 2) ? "__DATA, __objc_const" :
Daniel Dunbarb25452a2009-04-15 02:56:18 +00003034 "__OBJC,__property,regular,no_dead_strip",
John McCall7f416cc2015-09-08 08:05:57 +00003035 CGM.getPointerAlign(),
Daniel Dunbarb25452a2009-04-15 02:56:18 +00003036 true);
Owen Andersonade90fd2009-07-29 18:54:39 +00003037 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.PropertyListPtrTy);
Daniel Dunbar80a840b2008-08-23 00:19:03 +00003038}
3039
Bill Wendlingcb5b5ff2012-02-07 09:25:09 +00003040llvm::Constant *
3041CGObjCCommonMac::EmitProtocolMethodTypes(Twine Name,
3042 ArrayRef<llvm::Constant*> MethodTypes,
3043 const ObjCCommonTypesHelper &ObjCTypes) {
Bob Wilson5f4e3a72011-11-30 01:57:58 +00003044 // Return null for empty list.
3045 if (MethodTypes.empty())
3046 return llvm::Constant::getNullValue(ObjCTypes.Int8PtrPtrTy);
3047
3048 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
3049 MethodTypes.size());
3050 llvm::Constant *Init = llvm::ConstantArray::get(AT, MethodTypes);
3051
Alp Toker541d5072014-06-07 23:30:53 +00003052 llvm::GlobalVariable *GV = CreateMetadataVar(
3053 Name, Init, (ObjCABI == 2) ? "__DATA, __objc_const" : StringRef(),
John McCall7f416cc2015-09-08 08:05:57 +00003054 CGM.getPointerAlign(), true);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00003055 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.Int8PtrPtrTy);
3056}
3057
Daniel Dunbar80a840b2008-08-23 00:19:03 +00003058/*
Daniel Dunbarb036db82008-08-13 03:21:16 +00003059 struct objc_method_description_list {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003060 int count;
3061 struct objc_method_description list[];
Daniel Dunbarb036db82008-08-13 03:21:16 +00003062 };
3063*/
Daniel Dunbareb1f9a22008-08-27 02:31:56 +00003064llvm::Constant *
3065CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
Benjamin Kramer22d24c22011-10-15 12:20:02 +00003066 llvm::Constant *Desc[] = {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003067 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
Benjamin Kramer22d24c22011-10-15 12:20:02 +00003068 ObjCTypes.SelectorPtrTy),
3069 GetMethodVarType(MD)
3070 };
Douglas Gregora9d84932011-05-27 01:19:52 +00003071 if (!Desc[1])
Craig Topper8a13c412014-05-21 05:09:00 +00003072 return nullptr;
3073
Owen Anderson0e0189d2009-07-27 22:29:56 +00003074 return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
Daniel Dunbareb1f9a22008-08-27 02:31:56 +00003075 Desc);
3076}
Daniel Dunbarb036db82008-08-13 03:21:16 +00003077
Bill Wendlingcb5b5ff2012-02-07 09:25:09 +00003078llvm::Constant *
Saleem Abdulrasool1e6c4062016-05-16 05:06:49 +00003079CGObjCMac::EmitMethodDescList(Twine Name, StringRef Section,
3080 ArrayRef<llvm::Constant *> Methods) {
Daniel Dunbarb036db82008-08-13 03:21:16 +00003081 // Return null for empty list.
3082 if (Methods.empty())
Owen Anderson0b75f232009-07-31 20:28:54 +00003083 return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
Daniel Dunbarb036db82008-08-13 03:21:16 +00003084
Chris Lattnere64d7ba2011-06-20 04:01:35 +00003085 llvm::Constant *Values[2];
Owen Andersonb7a2fe62009-07-24 23:12:58 +00003086 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003087 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
Daniel Dunbarb036db82008-08-13 03:21:16 +00003088 Methods.size());
Owen Anderson47034e12009-07-28 18:33:04 +00003089 Values[1] = llvm::ConstantArray::get(AT, Methods);
Chris Lattnere64d7ba2011-06-20 04:01:35 +00003090 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
Daniel Dunbarb036db82008-08-13 03:21:16 +00003091
John McCall7f416cc2015-09-08 08:05:57 +00003092 llvm::GlobalVariable *GV =
3093 CreateMetadataVar(Name, Init, Section, CGM.getPointerAlign(), true);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003094 return llvm::ConstantExpr::getBitCast(GV,
Daniel Dunbarb036db82008-08-13 03:21:16 +00003095 ObjCTypes.MethodDescriptionListPtrTy);
Daniel Dunbar303e2c22008-08-11 02:45:11 +00003096}
3097
Daniel Dunbar938a77f2008-08-22 20:34:54 +00003098/*
3099 struct _objc_category {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003100 char *category_name;
3101 char *class_name;
3102 struct _objc_method_list *instance_methods;
3103 struct _objc_method_list *class_methods;
3104 struct _objc_protocol_list *protocols;
3105 uint32_t size; // <rdar://4585769>
3106 struct _objc_property_list *instance_properties;
Manman Ren96df0b32016-01-29 23:45:01 +00003107 struct _objc_property_list *class_properties;
Daniel Dunbar938a77f2008-08-22 20:34:54 +00003108 };
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003109*/
Daniel Dunbar92992502008-08-15 22:20:32 +00003110void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00003111 unsigned Size = CGM.getDataLayout().getTypeAllocSize(ObjCTypes.CategoryTy);
Daniel Dunbar938a77f2008-08-22 20:34:54 +00003112
Mike Stump18bb9282009-05-16 07:57:57 +00003113 // FIXME: This is poor design, the OCD should have a pointer to the category
3114 // decl. Additionally, note that Category can be null for the @implementation
3115 // w/o an @interface case. Sema should just create one for us as it does for
3116 // @implementation so everyone else can live life under a clear blue sky.
Daniel Dunbar938a77f2008-08-22 20:34:54 +00003117 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003118 const ObjCCategoryDecl *Category =
Daniel Dunbar28e76ca2008-08-26 23:03:11 +00003119 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Daniel Dunbar349e6fb2009-10-18 20:48:59 +00003120
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003121 SmallString<256> ExtName;
Daniel Dunbar349e6fb2009-10-18 20:48:59 +00003122 llvm::raw_svector_ostream(ExtName) << Interface->getName() << '_'
3123 << OCD->getName();
Daniel Dunbar938a77f2008-08-22 20:34:54 +00003124
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003125 SmallVector<llvm::Constant *, 16> InstanceMethods, ClassMethods;
Aaron Ballmanf26acce2014-03-13 19:50:17 +00003126 for (const auto *I : OCD->instance_methods())
Daniel Dunbar3c76cb52008-08-26 21:51:14 +00003127 // Instance methods should always be defined.
Aaron Ballmanf26acce2014-03-13 19:50:17 +00003128 InstanceMethods.push_back(GetMethodConstant(I));
3129
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00003130 for (const auto *I : OCD->class_methods())
Daniel Dunbar3c76cb52008-08-26 21:51:14 +00003131 // Class methods should always be defined.
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00003132 ClassMethods.push_back(GetMethodConstant(I));
Daniel Dunbar3c76cb52008-08-26 21:51:14 +00003133
Manman Ren96df0b32016-01-29 23:45:01 +00003134 llvm::Constant *Values[8];
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00003135 Values[0] = GetClassName(OCD->getName());
3136 Values[1] = GetClassName(Interface->getObjCRuntimeNameAsString());
Fariborz Jahaniane55f8662009-04-29 20:40:05 +00003137 LazySymbols.insert(Interface->getIdentifier());
Saleem Abdulrasoold48b0a32016-10-24 20:47:58 +00003138
3139 Values[2] = EmitMethodList(ExtName, MethodListType::CategoryInstanceMethods,
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00003140 InstanceMethods);
Saleem Abdulrasoold48b0a32016-10-24 20:47:58 +00003141 Values[3] = EmitMethodList(ExtName, MethodListType::CategoryClassMethods,
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00003142 ClassMethods);
Daniel Dunbareb1f9a22008-08-27 02:31:56 +00003143 if (Category) {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003144 Values[4] =
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00003145 EmitProtocolList("OBJC_CATEGORY_PROTOCOLS_" + ExtName.str(),
3146 Category->protocol_begin(), Category->protocol_end());
Daniel Dunbareb1f9a22008-08-27 02:31:56 +00003147 } else {
Owen Anderson0b75f232009-07-31 20:28:54 +00003148 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
Daniel Dunbareb1f9a22008-08-27 02:31:56 +00003149 }
Owen Andersonb7a2fe62009-07-24 23:12:58 +00003150 Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar28e76ca2008-08-26 23:03:11 +00003151
3152 // If there is no category @interface then there can be no properties.
3153 if (Category) {
Daniel Dunbar349e6fb2009-10-18 20:48:59 +00003154 Values[6] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ExtName.str(),
Manman Renad0e7912016-01-29 19:22:54 +00003155 OCD, Category, ObjCTypes, false);
Manman Ren96df0b32016-01-29 23:45:01 +00003156 Values[7] = EmitPropertyList("\01l_OBJC_$_CLASS_PROP_LIST_" + ExtName.str(),
3157 OCD, Category, ObjCTypes, true);
Daniel Dunbar28e76ca2008-08-26 23:03:11 +00003158 } else {
Owen Anderson0b75f232009-07-31 20:28:54 +00003159 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
Manman Ren96df0b32016-01-29 23:45:01 +00003160 Values[7] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
Daniel Dunbar28e76ca2008-08-26 23:03:11 +00003161 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003162
Owen Anderson0e0189d2009-07-27 22:29:56 +00003163 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
Daniel Dunbar938a77f2008-08-22 20:34:54 +00003164 Values);
3165
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003166 llvm::GlobalVariable *GV =
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00003167 CreateMetadataVar("OBJC_CATEGORY_" + ExtName.str(), Init,
John McCall7f416cc2015-09-08 08:05:57 +00003168 "__OBJC,__category,regular,no_dead_strip",
3169 CGM.getPointerAlign(), true);
Daniel Dunbar938a77f2008-08-22 20:34:54 +00003170 DefinedCategories.push_back(GV);
Justin Lebar5e83dfe2016-10-21 21:45:01 +00003171 DefinedCategoryNames.insert(llvm::CachedHashString(ExtName));
Fariborz Jahanianc0577942011-04-22 22:02:28 +00003172 // method definition entries must be clear for next implementation.
3173 MethodDefinitions.clear();
Daniel Dunbar303e2c22008-08-11 02:45:11 +00003174}
3175
John McCallef19dbb2012-10-17 04:53:23 +00003176enum FragileClassFlags {
John McCall460ce582015-10-22 18:38:17 +00003177 /// Apparently: is not a meta-class.
John McCallef19dbb2012-10-17 04:53:23 +00003178 FragileABI_Class_Factory = 0x00001,
John McCall460ce582015-10-22 18:38:17 +00003179
3180 /// Is a meta-class.
John McCallef19dbb2012-10-17 04:53:23 +00003181 FragileABI_Class_Meta = 0x00002,
John McCall460ce582015-10-22 18:38:17 +00003182
3183 /// Has a non-trivial constructor or destructor.
John McCallef19dbb2012-10-17 04:53:23 +00003184 FragileABI_Class_HasCXXStructors = 0x02000,
John McCall460ce582015-10-22 18:38:17 +00003185
3186 /// Has hidden visibility.
John McCall09ec1ec2015-10-21 22:06:03 +00003187 FragileABI_Class_Hidden = 0x20000,
John McCall460ce582015-10-22 18:38:17 +00003188
3189 /// Class implementation was compiled under ARC.
3190 FragileABI_Class_CompiledByARC = 0x04000000,
3191
3192 /// Class implementation was compiled under MRC and has MRC weak ivars.
3193 /// Exclusive with CompiledByARC.
3194 FragileABI_Class_HasMRCWeakIvars = 0x08000000,
John McCallef19dbb2012-10-17 04:53:23 +00003195};
3196
3197enum NonFragileClassFlags {
3198 /// Is a meta-class.
3199 NonFragileABI_Class_Meta = 0x00001,
3200
3201 /// Is a root class.
3202 NonFragileABI_Class_Root = 0x00002,
3203
John McCall460ce582015-10-22 18:38:17 +00003204 /// Has a non-trivial constructor or destructor.
John McCallef19dbb2012-10-17 04:53:23 +00003205 NonFragileABI_Class_HasCXXStructors = 0x00004,
3206
3207 /// Has hidden visibility.
3208 NonFragileABI_Class_Hidden = 0x00010,
3209
3210 /// Has the exception attribute.
3211 NonFragileABI_Class_Exception = 0x00020,
3212
3213 /// (Obsolete) ARC-specific: this class has a .release_ivars method
3214 NonFragileABI_Class_HasIvarReleaser = 0x00040,
3215
3216 /// Class implementation was compiled under ARC.
John McCall0d54a172012-10-17 04:53:31 +00003217 NonFragileABI_Class_CompiledByARC = 0x00080,
3218
3219 /// Class has non-trivial destructors, but zero-initialization is okay.
John McCall460ce582015-10-22 18:38:17 +00003220 NonFragileABI_Class_HasCXXDestructorOnly = 0x00100,
3221
3222 /// Class implementation was compiled under MRC and has MRC weak ivars.
3223 /// Exclusive with CompiledByARC.
3224 NonFragileABI_Class_HasMRCWeakIvars = 0x00200,
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003225};
3226
John McCall460ce582015-10-22 18:38:17 +00003227static bool hasWeakMember(QualType type) {
3228 if (type.getObjCLifetime() == Qualifiers::OCL_Weak) {
3229 return true;
3230 }
3231
3232 if (auto recType = type->getAs<RecordType>()) {
3233 for (auto field : recType->getDecl()->fields()) {
3234 if (hasWeakMember(field->getType()))
3235 return true;
3236 }
3237 }
3238
3239 return false;
3240}
3241
3242/// For compatibility, we only want to set the "HasMRCWeakIvars" flag
3243/// (and actually fill in a layout string) if we really do have any
3244/// __weak ivars.
3245static bool hasMRCWeakIvars(CodeGenModule &CGM,
3246 const ObjCImplementationDecl *ID) {
3247 if (!CGM.getLangOpts().ObjCWeak) return false;
3248 assert(CGM.getLangOpts().getGC() == LangOptions::NonGC);
3249
3250 for (const ObjCIvarDecl *ivar =
3251 ID->getClassInterface()->all_declared_ivar_begin();
3252 ivar; ivar = ivar->getNextIvar()) {
3253 if (hasWeakMember(ivar->getType()))
3254 return true;
3255 }
3256
3257 return false;
3258}
3259
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003260/*
3261 struct _objc_class {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003262 Class isa;
3263 Class super_class;
3264 const char *name;
3265 long version;
3266 long info;
3267 long instance_size;
3268 struct _objc_ivar_list *ivars;
3269 struct _objc_method_list *methods;
3270 struct _objc_cache *cache;
3271 struct _objc_protocol_list *protocols;
3272 // Objective-C 1.0 extensions (<rdr://4585769>)
3273 const char *ivar_layout;
3274 struct _objc_class_ext *ext;
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003275 };
3276
3277 See EmitClassExtension();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003278*/
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003279void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
Daniel Dunbarc61d0e92008-08-25 06:02:07 +00003280 DefinedSymbols.insert(ID->getIdentifier());
3281
Chris Lattner86d7d912008-11-24 03:54:41 +00003282 std::string ClassName = ID->getNameAsString();
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003283 // FIXME: Gross
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003284 ObjCInterfaceDecl *Interface =
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003285 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003286 llvm::Constant *Protocols =
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00003287 EmitProtocolList("OBJC_CLASS_PROTOCOLS_" + ID->getName(),
3288 Interface->all_referenced_protocol_begin(),
3289 Interface->all_referenced_protocol_end());
John McCallef19dbb2012-10-17 04:53:23 +00003290 unsigned Flags = FragileABI_Class_Factory;
John McCall0d54a172012-10-17 04:53:31 +00003291 if (ID->hasNonZeroConstructors() || ID->hasDestructors())
John McCallef19dbb2012-10-17 04:53:23 +00003292 Flags |= FragileABI_Class_HasCXXStructors;
John McCall09ec1ec2015-10-21 22:06:03 +00003293
John McCall460ce582015-10-22 18:38:17 +00003294 bool hasMRCWeak = false;
3295
John McCall09ec1ec2015-10-21 22:06:03 +00003296 if (CGM.getLangOpts().ObjCAutoRefCount)
3297 Flags |= FragileABI_Class_CompiledByARC;
John McCall460ce582015-10-22 18:38:17 +00003298 else if ((hasMRCWeak = hasMRCWeakIvars(CGM, ID)))
3299 Flags |= FragileABI_Class_HasMRCWeakIvars;
John McCall09ec1ec2015-10-21 22:06:03 +00003300
John McCall3fd13f062015-10-21 18:06:47 +00003301 CharUnits Size =
3302 CGM.getContext().getASTObjCImplementationLayout(ID).getSize();
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003303
3304 // FIXME: Set CXX-structors flag.
John McCall457a04e2010-10-22 21:05:15 +00003305 if (ID->getClassInterface()->getVisibility() == HiddenVisibility)
John McCallef19dbb2012-10-17 04:53:23 +00003306 Flags |= FragileABI_Class_Hidden;
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003307
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003308 SmallVector<llvm::Constant *, 16> InstanceMethods, ClassMethods;
Aaron Ballmanf26acce2014-03-13 19:50:17 +00003309 for (const auto *I : ID->instance_methods())
Daniel Dunbar3c76cb52008-08-26 21:51:14 +00003310 // Instance methods should always be defined.
Aaron Ballmanf26acce2014-03-13 19:50:17 +00003311 InstanceMethods.push_back(GetMethodConstant(I));
3312
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00003313 for (const auto *I : ID->class_methods())
Daniel Dunbar3c76cb52008-08-26 21:51:14 +00003314 // Class methods should always be defined.
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00003315 ClassMethods.push_back(GetMethodConstant(I));
Daniel Dunbar3c76cb52008-08-26 21:51:14 +00003316
Aaron Ballmand85eff42014-03-14 15:02:45 +00003317 for (const auto *PID : ID->property_impls()) {
Daniel Dunbar3c76cb52008-08-26 21:51:14 +00003318 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
3319 ObjCPropertyDecl *PD = PID->getPropertyDecl();
3320
3321 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
3322 if (llvm::Constant *C = GetMethodConstant(MD))
3323 InstanceMethods.push_back(C);
3324 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
3325 if (llvm::Constant *C = GetMethodConstant(MD))
3326 InstanceMethods.push_back(C);
3327 }
3328 }
3329
Chris Lattnere64d7ba2011-06-20 04:01:35 +00003330 llvm::Constant *Values[12];
Daniel Dunbarccf61832009-05-03 08:56:52 +00003331 Values[ 0] = EmitMetaClass(ID, Protocols, ClassMethods);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003332 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
Daniel Dunbarc61d0e92008-08-25 06:02:07 +00003333 // Record a reference to the super class.
3334 LazySymbols.insert(Super->getIdentifier());
3335
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003336 Values[ 1] =
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00003337 llvm::ConstantExpr::getBitCast(GetClassName(Super->getObjCRuntimeNameAsString()),
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003338 ObjCTypes.ClassPtrTy);
3339 } else {
Owen Anderson0b75f232009-07-31 20:28:54 +00003340 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003341 }
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00003342 Values[ 2] = GetClassName(ID->getObjCRuntimeNameAsString());
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003343 // Version is always 0.
Owen Andersonb7a2fe62009-07-24 23:12:58 +00003344 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
3345 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
John McCall3fd13f062015-10-21 18:06:47 +00003346 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size.getQuantity());
Fariborz Jahanianb042a592009-01-28 19:12:34 +00003347 Values[ 6] = EmitIvarList(ID, false);
Saleem Abdulrasoold48b0a32016-10-24 20:47:58 +00003348 Values[ 7] = EmitMethodList(ID->getName(), MethodListType::InstanceMethods,
3349 InstanceMethods);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003350 // cache is always NULL.
Owen Anderson0b75f232009-07-31 20:28:54 +00003351 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003352 Values[ 9] = Protocols;
John McCall460ce582015-10-22 18:38:17 +00003353 Values[10] = BuildStrongIvarLayout(ID, CharUnits::Zero(), Size);
Manman Renad0e7912016-01-29 19:22:54 +00003354 Values[11] = EmitClassExtension(ID, Size, hasMRCWeak,
3355 false/*isClassProperty*/);
Owen Anderson0e0189d2009-07-27 22:29:56 +00003356 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003357 Values);
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00003358 std::string Name("OBJC_CLASS_");
Fariborz Jahanianeb80c982009-11-12 20:14:24 +00003359 Name += ClassName;
3360 const char *Section = "__OBJC,__class,regular,no_dead_strip";
3361 // Check for a forward reference.
Rafael Espindola554256c2014-02-26 22:25:45 +00003362 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
Fariborz Jahanianeb80c982009-11-12 20:14:24 +00003363 if (GV) {
3364 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
3365 "Forward metaclass reference has incorrect type.");
Fariborz Jahanianeb80c982009-11-12 20:14:24 +00003366 GV->setInitializer(Init);
3367 GV->setSection(Section);
John McCall7f416cc2015-09-08 08:05:57 +00003368 GV->setAlignment(CGM.getPointerAlign().getQuantity());
Rafael Espindola060062a2014-03-06 22:15:10 +00003369 CGM.addCompilerUsedGlobal(GV);
Rafael Espindola21039aa2014-02-27 16:26:32 +00003370 } else
John McCall7f416cc2015-09-08 08:05:57 +00003371 GV = CreateMetadataVar(Name, Init, Section, CGM.getPointerAlign(), true);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003372 DefinedClasses.push_back(GV);
Fariborz Jahanianf322f2f2014-03-11 00:25:05 +00003373 ImplementedClasses.push_back(Interface);
Fariborz Jahanianc0577942011-04-22 22:02:28 +00003374 // method definition entries must be clear for next implementation.
3375 MethodDefinitions.clear();
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003376}
3377
3378llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
3379 llvm::Constant *Protocols,
Bill Wendlingcb5b5ff2012-02-07 09:25:09 +00003380 ArrayRef<llvm::Constant*> Methods) {
John McCallef19dbb2012-10-17 04:53:23 +00003381 unsigned Flags = FragileABI_Class_Meta;
Micah Villmowdd31ca12012-10-08 16:25:52 +00003382 unsigned Size = CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ClassTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003383
John McCall457a04e2010-10-22 21:05:15 +00003384 if (ID->getClassInterface()->getVisibility() == HiddenVisibility)
John McCallef19dbb2012-10-17 04:53:23 +00003385 Flags |= FragileABI_Class_Hidden;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003386
Chris Lattnere64d7ba2011-06-20 04:01:35 +00003387 llvm::Constant *Values[12];
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003388 // The isa for the metaclass is the root of the hierarchy.
3389 const ObjCInterfaceDecl *Root = ID->getClassInterface();
3390 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
3391 Root = Super;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003392 Values[ 0] =
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00003393 llvm::ConstantExpr::getBitCast(GetClassName(Root->getObjCRuntimeNameAsString()),
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003394 ObjCTypes.ClassPtrTy);
Daniel Dunbar938a77f2008-08-22 20:34:54 +00003395 // The super class for the metaclass is emitted as the name of the
3396 // super class. The runtime fixes this up to point to the
3397 // *metaclass* for the super class.
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003398 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003399 Values[ 1] =
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00003400 llvm::ConstantExpr::getBitCast(GetClassName(Super->getObjCRuntimeNameAsString()),
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003401 ObjCTypes.ClassPtrTy);
3402 } else {
Owen Anderson0b75f232009-07-31 20:28:54 +00003403 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003404 }
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00003405 Values[ 2] = GetClassName(ID->getObjCRuntimeNameAsString());
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003406 // Version is always 0.
Owen Andersonb7a2fe62009-07-24 23:12:58 +00003407 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
3408 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
3409 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanianb042a592009-01-28 19:12:34 +00003410 Values[ 6] = EmitIvarList(ID, true);
Saleem Abdulrasoold48b0a32016-10-24 20:47:58 +00003411 Values[ 7] = EmitMethodList(ID->getName(), MethodListType::ClassMethods,
3412 Methods);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003413 // cache is always NULL.
Owen Anderson0b75f232009-07-31 20:28:54 +00003414 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003415 Values[ 9] = Protocols;
3416 // ivar_layout for metaclass is always NULL.
Owen Anderson0b75f232009-07-31 20:28:54 +00003417 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Manman Renad0e7912016-01-29 19:22:54 +00003418 // The class extension is used to store class properties for metaclasses.
3419 Values[11] = EmitClassExtension(ID, CharUnits::Zero(), false/*hasMRCWeak*/,
3420 true/*isClassProperty*/);
Owen Anderson0e0189d2009-07-27 22:29:56 +00003421 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003422 Values);
3423
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00003424 std::string Name("OBJC_METACLASS_");
Benjamin Kramer1bbcbd02012-07-31 11:45:39 +00003425 Name += ID->getName();
Daniel Dunbarca8531a2008-08-25 08:19:24 +00003426
3427 // Check for a forward reference.
Rafael Espindola554256c2014-02-26 22:25:45 +00003428 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
Daniel Dunbarca8531a2008-08-25 08:19:24 +00003429 if (GV) {
3430 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
3431 "Forward metaclass reference has incorrect type.");
Daniel Dunbarca8531a2008-08-25 08:19:24 +00003432 GV->setInitializer(Init);
3433 } else {
Owen Andersonc10c8d32009-07-08 19:05:04 +00003434 GV = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassTy, false,
Rafael Espindola5179a4e2014-02-27 19:01:11 +00003435 llvm::GlobalValue::PrivateLinkage,
Owen Andersonc10c8d32009-07-08 19:05:04 +00003436 Init, Name);
Daniel Dunbarca8531a2008-08-25 08:19:24 +00003437 }
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003438 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
Daniel Dunbarae333842009-03-09 22:18:41 +00003439 GV->setAlignment(4);
Rafael Espindola060062a2014-03-06 22:15:10 +00003440 CGM.addCompilerUsedGlobal(GV);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003441
3442 return GV;
3443}
3444
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003445llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00003446 std::string Name = "OBJC_METACLASS_" + ID->getNameAsString();
Daniel Dunbarca8531a2008-08-25 08:19:24 +00003447
Mike Stump18bb9282009-05-16 07:57:57 +00003448 // FIXME: Should we look these up somewhere other than the module. Its a bit
3449 // silly since we only generate these while processing an implementation, so
3450 // exactly one pointer would work if know when we entered/exitted an
3451 // implementation block.
Daniel Dunbarca8531a2008-08-25 08:19:24 +00003452
3453 // Check for an existing forward reference.
Fariborz Jahanian475831b2009-01-07 20:11:22 +00003454 // Previously, metaclass with internal linkage may have been defined.
3455 // pass 'true' as 2nd argument so it is returned.
Rafael Espindola21039aa2014-02-27 16:26:32 +00003456 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
3457 if (!GV)
3458 GV = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassTy, false,
Craig Topper8a13c412014-05-21 05:09:00 +00003459 llvm::GlobalValue::PrivateLinkage, nullptr,
3460 Name);
Rafael Espindola21039aa2014-02-27 16:26:32 +00003461
3462 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
3463 "Forward metaclass reference has incorrect type.");
Rafael Espindola21039aa2014-02-27 16:26:32 +00003464 return GV;
Daniel Dunbarca8531a2008-08-25 08:19:24 +00003465}
3466
Fariborz Jahanianeb80c982009-11-12 20:14:24 +00003467llvm::Value *CGObjCMac::EmitSuperClassRef(const ObjCInterfaceDecl *ID) {
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00003468 std::string Name = "OBJC_CLASS_" + ID->getNameAsString();
Rafael Espindola21039aa2014-02-27 16:26:32 +00003469 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
3470
3471 if (!GV)
3472 GV = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassTy, false,
Craig Topper8a13c412014-05-21 05:09:00 +00003473 llvm::GlobalValue::PrivateLinkage, nullptr,
3474 Name);
Rafael Espindola21039aa2014-02-27 16:26:32 +00003475
3476 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
3477 "Forward class metadata reference has incorrect type.");
Rafael Espindola21039aa2014-02-27 16:26:32 +00003478 return GV;
Fariborz Jahanianeb80c982009-11-12 20:14:24 +00003479}
3480
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003481/*
John McCall3fd13f062015-10-21 18:06:47 +00003482 Emit a "class extension", which in this specific context means extra
3483 data that doesn't fit in the normal fragile-ABI class structure, and
3484 has nothing to do with the language concept of a class extension.
3485
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003486 struct objc_class_ext {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003487 uint32_t size;
3488 const char *weak_ivar_layout;
3489 struct _objc_property_list *properties;
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003490 };
3491*/
3492llvm::Constant *
John McCall3fd13f062015-10-21 18:06:47 +00003493CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID,
Manman Renad0e7912016-01-29 19:22:54 +00003494 CharUnits InstanceSize, bool hasMRCWeakIvars,
3495 bool isClassProperty) {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003496 uint64_t Size =
Micah Villmowdd31ca12012-10-08 16:25:52 +00003497 CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ClassExtensionTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003498
Chris Lattnere64d7ba2011-06-20 04:01:35 +00003499 llvm::Constant *Values[3];
Owen Andersonb7a2fe62009-07-24 23:12:58 +00003500 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Manman Ren92e0a712016-02-21 05:31:05 +00003501 if (isClassProperty) {
3502 llvm::Type *PtrTy = CGM.Int8PtrTy;
3503 Values[1] = llvm::Constant::getNullValue(PtrTy);
3504 } else
Manman Renad0e7912016-01-29 19:22:54 +00003505 Values[1] = BuildWeakIvarLayout(ID, CharUnits::Zero(), InstanceSize,
3506 hasMRCWeakIvars);
3507 if (isClassProperty)
3508 Values[2] = EmitPropertyList("\01l_OBJC_$_CLASS_PROP_LIST_" + ID->getName(),
3509 ID, ID->getClassInterface(), ObjCTypes, true);
3510 else
3511 Values[2] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ID->getName(),
3512 ID, ID->getClassInterface(), ObjCTypes, false);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003513
3514 // Return null if no extension bits are used.
Manman Renad0e7912016-01-29 19:22:54 +00003515 if ((!Values[1] || Values[1]->isNullValue()) && Values[2]->isNullValue())
Owen Anderson0b75f232009-07-31 20:28:54 +00003516 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003517
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003518 llvm::Constant *Init =
Owen Anderson0e0189d2009-07-27 22:29:56 +00003519 llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00003520 return CreateMetadataVar("OBJC_CLASSEXT_" + ID->getName(), Init,
John McCall7f416cc2015-09-08 08:05:57 +00003521 "__OBJC,__class_ext,regular,no_dead_strip",
3522 CGM.getPointerAlign(), true);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003523}
3524
3525/*
3526 struct objc_ivar {
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00003527 char *ivar_name;
3528 char *ivar_type;
3529 int ivar_offset;
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003530 };
3531
3532 struct objc_ivar_list {
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00003533 int ivar_count;
3534 struct objc_ivar list[count];
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003535 };
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003536*/
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003537llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanianb042a592009-01-28 19:12:34 +00003538 bool ForClass) {
Benjamin Kramer22d24c22011-10-15 12:20:02 +00003539 std::vector<llvm::Constant*> Ivars;
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003540
3541 // When emitting the root class GCC emits ivar entries for the
3542 // actual class structure. It is not clear if we need to follow this
3543 // behavior; for now lets try and get away with not doing it. If so,
3544 // the cleanest solution would be to make up an ObjCInterfaceDecl
3545 // for the class.
3546 if (ForClass)
Owen Anderson0b75f232009-07-31 20:28:54 +00003547 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003548
Jordy Rosea91768e2011-07-22 02:08:32 +00003549 const ObjCInterfaceDecl *OID = ID->getClassInterface();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003550
Jordy Rosea91768e2011-07-22 02:08:32 +00003551 for (const ObjCIvarDecl *IVD = OID->all_declared_ivar_begin();
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00003552 IVD; IVD = IVD->getNextIvar()) {
Fariborz Jahanian7c809592009-06-04 01:19:09 +00003553 // Ignore unnamed bit-fields.
3554 if (!IVD->getDeclName())
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003555 continue;
Benjamin Kramer22d24c22011-10-15 12:20:02 +00003556 llvm::Constant *Ivar[] = {
3557 GetMethodVarName(IVD->getIdentifier()),
3558 GetMethodVarType(IVD),
3559 llvm::ConstantInt::get(ObjCTypes.IntTy,
Eli Friedman8cbca202012-11-06 22:15:52 +00003560 ComputeIvarBaseOffset(CGM, OID, IVD))
Benjamin Kramer22d24c22011-10-15 12:20:02 +00003561 };
Owen Anderson0e0189d2009-07-27 22:29:56 +00003562 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003563 }
3564
3565 // Return null for empty list.
3566 if (Ivars.empty())
Owen Anderson0b75f232009-07-31 20:28:54 +00003567 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003568
Chris Lattnere64d7ba2011-06-20 04:01:35 +00003569 llvm::Constant *Values[2];
Owen Andersonb7a2fe62009-07-24 23:12:58 +00003570 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
Owen Anderson9793f0e2009-07-29 22:16:19 +00003571 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003572 Ivars.size());
Owen Anderson47034e12009-07-28 18:33:04 +00003573 Values[1] = llvm::ConstantArray::get(AT, Ivars);
Chris Lattnere64d7ba2011-06-20 04:01:35 +00003574 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003575
Daniel Dunbarc2d4b622009-03-09 21:49:58 +00003576 llvm::GlobalVariable *GV;
3577 if (ForClass)
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00003578 GV =
3579 CreateMetadataVar("OBJC_CLASS_VARIABLES_" + ID->getName(), Init,
John McCall7f416cc2015-09-08 08:05:57 +00003580 "__OBJC,__class_vars,regular,no_dead_strip",
3581 CGM.getPointerAlign(), true);
Daniel Dunbarc2d4b622009-03-09 21:49:58 +00003582 else
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00003583 GV = CreateMetadataVar("OBJC_INSTANCE_VARIABLES_" + ID->getName(), Init,
John McCall7f416cc2015-09-08 08:05:57 +00003584 "__OBJC,__instance_vars,regular,no_dead_strip",
3585 CGM.getPointerAlign(), true);
Owen Andersonade90fd2009-07-29 18:54:39 +00003586 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.IvarListPtrTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003587}
3588
3589/*
3590 struct objc_method {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003591 SEL method_name;
3592 char *method_types;
3593 void *method;
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003594 };
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003595
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003596 struct objc_method_list {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003597 struct objc_method_list *obsolete;
3598 int count;
3599 struct objc_method methods_list[count];
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003600 };
3601*/
Daniel Dunbar3c76cb52008-08-26 21:51:14 +00003602
3603/// GetMethodConstant - Return a struct objc_method constant for the
3604/// given method if it has been defined. The result is null if the
3605/// method has not been defined. The return value has type MethodPtrTy.
Daniel Dunbareb1f9a22008-08-27 02:31:56 +00003606llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
Argyrios Kyrtzidis13257c52010-08-09 10:54:20 +00003607 llvm::Function *Fn = GetMethodDefinition(MD);
Daniel Dunbar3c76cb52008-08-26 21:51:14 +00003608 if (!Fn)
Craig Topper8a13c412014-05-21 05:09:00 +00003609 return nullptr;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003610
Benjamin Kramer22d24c22011-10-15 12:20:02 +00003611 llvm::Constant *Method[] = {
Owen Andersonade90fd2009-07-29 18:54:39 +00003612 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
Benjamin Kramer22d24c22011-10-15 12:20:02 +00003613 ObjCTypes.SelectorPtrTy),
3614 GetMethodVarType(MD),
3615 llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy)
3616 };
Owen Anderson0e0189d2009-07-27 22:29:56 +00003617 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
Daniel Dunbar3c76cb52008-08-26 21:51:14 +00003618}
3619
Saleem Abdulrasoold48b0a32016-10-24 20:47:58 +00003620llvm::Constant *CGObjCMac::EmitMethodList(Twine Name, MethodListType MLT,
Saleem Abdulrasool1e6c4062016-05-16 05:06:49 +00003621 ArrayRef<llvm::Constant *> Methods) {
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003622 // Return null for empty list.
3623 if (Methods.empty())
Owen Anderson0b75f232009-07-31 20:28:54 +00003624 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003625
Chris Lattnere64d7ba2011-06-20 04:01:35 +00003626 llvm::Constant *Values[3];
Owen Anderson0b75f232009-07-31 20:28:54 +00003627 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00003628 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
Owen Anderson9793f0e2009-07-29 22:16:19 +00003629 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003630 Methods.size());
Owen Anderson47034e12009-07-28 18:33:04 +00003631 Values[2] = llvm::ConstantArray::get(AT, Methods);
Chris Lattnere64d7ba2011-06-20 04:01:35 +00003632 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003633
Saleem Abdulrasoold48b0a32016-10-24 20:47:58 +00003634 StringRef Prefix;
3635 StringRef Section;
3636 switch (MLT) {
3637 case MethodListType::CategoryInstanceMethods:
3638 Prefix = "OBJC_CATEGORY_INSTANCE_METHODS_";
3639 Section = "__OBJC,__cat_inst_meth,regular,no_dead_strip";
3640 break;
3641 case MethodListType::CategoryClassMethods:
3642 Prefix = "OBJC_CATEGORY_CLASS_METHODS_";
3643 Section = "__OBJC,__cat_cls_meth,regular,no_dead_strip";
3644 break;
3645 case MethodListType::InstanceMethods:
3646 Prefix = "OBJC_INSTANCE_METHODS_";
3647 Section = "__OBJC,__inst_meth,regular,no_dead_strip";
3648 break;
3649 case MethodListType::ClassMethods:
3650 Prefix = "OBJC_CLASS_METHODS_";
3651 Section = "__OBJC,__cls_meth,regular,no_dead_strip";
3652 break;
3653
3654 case MethodListType::ProtocolInstanceMethods:
3655 case MethodListType::ProtocolClassMethods:
3656 case MethodListType::OptionalProtocolInstanceMethods:
3657 case MethodListType::OptionalProtocolClassMethods:
3658 llvm_unreachable("unsupported method list type");
3659 }
3660
3661 llvm::GlobalVariable *GV = CreateMetadataVar(Prefix + Name, Init, Section,
3662 CGM.getPointerAlign(), true);
Chris Lattnere64d7ba2011-06-20 04:01:35 +00003663 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.MethodListPtrTy);
Daniel Dunbara94ecd22008-08-16 03:19:19 +00003664}
3665
Fariborz Jahanian99113fd2009-01-26 21:38:32 +00003666llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD,
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003667 const ObjCContainerDecl *CD) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003668 SmallString<256> Name;
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +00003669 GetNameForMethod(OMD, CD, Name);
Daniel Dunbara94ecd22008-08-16 03:19:19 +00003670
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +00003671 CodeGenTypes &Types = CGM.getTypes();
Chris Lattner2192fe52011-07-18 04:24:23 +00003672 llvm::FunctionType *MethodTy =
John McCalla729c622012-02-17 03:33:10 +00003673 Types.GetFunctionType(Types.arrangeObjCMethodDeclaration(OMD));
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003674 llvm::Function *Method =
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00003675 llvm::Function::Create(MethodTy,
Daniel Dunbara94ecd22008-08-16 03:19:19 +00003676 llvm::GlobalValue::InternalLinkage,
Daniel Dunbard2386812009-10-19 01:21:19 +00003677 Name.str(),
Daniel Dunbara94ecd22008-08-16 03:19:19 +00003678 &CGM.getModule());
Daniel Dunbar3c76cb52008-08-26 21:51:14 +00003679 MethodDefinitions.insert(std::make_pair(OMD, Method));
Daniel Dunbara94ecd22008-08-16 03:19:19 +00003680
Daniel Dunbara94ecd22008-08-16 03:19:19 +00003681 return Method;
Daniel Dunbar303e2c22008-08-11 02:45:11 +00003682}
3683
Alp Toker541d5072014-06-07 23:30:53 +00003684llvm::GlobalVariable *CGObjCCommonMac::CreateMetadataVar(Twine Name,
3685 llvm::Constant *Init,
3686 StringRef Section,
John McCall7f416cc2015-09-08 08:05:57 +00003687 CharUnits Align,
Alp Toker541d5072014-06-07 23:30:53 +00003688 bool AddToUsed) {
Chris Lattner2192fe52011-07-18 04:24:23 +00003689 llvm::Type *Ty = Init->getType();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003690 llvm::GlobalVariable *GV =
Owen Andersonc10c8d32009-07-08 19:05:04 +00003691 new llvm::GlobalVariable(CGM.getModule(), Ty, false,
Rafael Espindola5179a4e2014-02-27 19:01:11 +00003692 llvm::GlobalValue::PrivateLinkage, Init, Name);
Alp Toker541d5072014-06-07 23:30:53 +00003693 if (!Section.empty())
Daniel Dunbar30c65362009-03-09 20:09:19 +00003694 GV->setSection(Section);
John McCall7f416cc2015-09-08 08:05:57 +00003695 GV->setAlignment(Align.getQuantity());
Daniel Dunbar463cc8a2009-03-09 20:50:13 +00003696 if (AddToUsed)
Rafael Espindola060062a2014-03-06 22:15:10 +00003697 CGM.addCompilerUsedGlobal(GV);
Daniel Dunbar30c65362009-03-09 20:09:19 +00003698 return GV;
3699}
3700
Saleem Abdulrasool271106c2016-09-16 23:41:13 +00003701llvm::GlobalVariable *
Saleem Abdulrasool82f6add2016-09-20 18:38:54 +00003702CGObjCCommonMac::CreateCStringLiteral(StringRef Name, ObjCLabelType Type,
3703 bool ForceNonFragileABI,
3704 bool NullTerminate) {
Saleem Abdulrasool271106c2016-09-16 23:41:13 +00003705 StringRef Label;
3706 switch (Type) {
3707 case ObjCLabelType::ClassName: Label = "OBJC_CLASS_NAME_"; break;
3708 case ObjCLabelType::MethodVarName: Label = "OBJC_METH_VAR_NAME_"; break;
3709 case ObjCLabelType::MethodVarType: Label = "OBJC_METH_VAR_TYPE_"; break;
3710 case ObjCLabelType::PropertyName: Label = "OBJC_PROP_NAME_ATTR_"; break;
3711 }
3712
Saleem Abdulrasool82f6add2016-09-20 18:38:54 +00003713 bool NonFragile = ForceNonFragileABI || isNonFragileABI();
3714
Saleem Abdulrasool271106c2016-09-16 23:41:13 +00003715 StringRef Section;
3716 switch (Type) {
3717 case ObjCLabelType::ClassName:
Saleem Abdulrasool82f6add2016-09-20 18:38:54 +00003718 Section = NonFragile ? "__TEXT,__objc_classname,cstring_literals"
3719 : "__TEXT,__cstring,cstring_literals";
Saleem Abdulrasool271106c2016-09-16 23:41:13 +00003720 break;
3721 case ObjCLabelType::MethodVarName:
Saleem Abdulrasool82f6add2016-09-20 18:38:54 +00003722 Section = NonFragile ? "__TEXT,__objc_methname,cstring_literals"
3723 : "__TEXT,__cstring,cstring_literals";
Saleem Abdulrasool271106c2016-09-16 23:41:13 +00003724 break;
3725 case ObjCLabelType::MethodVarType:
Saleem Abdulrasool82f6add2016-09-20 18:38:54 +00003726 Section = NonFragile ? "__TEXT,__objc_methtype,cstring_literals"
3727 : "__TEXT,__cstring,cstring_literals";
Saleem Abdulrasool271106c2016-09-16 23:41:13 +00003728 break;
3729 case ObjCLabelType::PropertyName:
3730 Section = "__TEXT,__cstring,cstring_literals";
3731 break;
3732 }
3733
Saleem Abdulrasool82f6add2016-09-20 18:38:54 +00003734 llvm::Constant *Value =
3735 llvm::ConstantDataArray::getString(VMContext, Name, NullTerminate);
Saleem Abdulrasool271106c2016-09-16 23:41:13 +00003736 llvm::GlobalVariable *GV =
Saleem Abdulrasool0c54dc82016-09-18 16:12:04 +00003737 new llvm::GlobalVariable(CGM.getModule(), Value->getType(),
3738 /*isConstant=*/true,
Saleem Abdulrasool271106c2016-09-16 23:41:13 +00003739 llvm::GlobalValue::PrivateLinkage, Value, Label);
Saleem Abdulrasool3f307512016-09-18 16:12:14 +00003740 if (CGM.getTriple().isOSBinFormatMachO())
3741 GV->setSection(Section);
3742 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Saleem Abdulrasool271106c2016-09-16 23:41:13 +00003743 GV->setAlignment(CharUnits::One().getQuantity());
3744 CGM.addCompilerUsedGlobal(GV);
3745
3746 return GV;
3747}
3748
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003749llvm::Function *CGObjCMac::ModuleInitFunction() {
Daniel Dunbar3ad53482008-08-11 21:35:06 +00003750 // Abuse this interface function as a place to finalize.
3751 FinishModule();
Craig Topper8a13c412014-05-21 05:09:00 +00003752 return nullptr;
Daniel Dunbar303e2c22008-08-11 02:45:11 +00003753}
3754
Chris Lattnerd4808922009-03-22 21:03:39 +00003755llvm::Constant *CGObjCMac::GetPropertyGetFunction() {
Chris Lattnerce8754e2009-04-22 02:44:54 +00003756 return ObjCTypes.getGetPropertyFn();
Daniel Dunbara91c3e02008-09-24 03:38:44 +00003757}
3758
Chris Lattnerd4808922009-03-22 21:03:39 +00003759llvm::Constant *CGObjCMac::GetPropertySetFunction() {
Chris Lattnerce8754e2009-04-22 02:44:54 +00003760 return ObjCTypes.getSetPropertyFn();
Daniel Dunbara91c3e02008-09-24 03:38:44 +00003761}
3762
Ted Kremeneke65b0862012-03-06 20:05:56 +00003763llvm::Constant *CGObjCMac::GetOptimizedPropertySetFunction(bool atomic,
3764 bool copy) {
3765 return ObjCTypes.getOptimizedSetPropertyFn(atomic, copy);
3766}
3767
David Chisnall168b80f2010-12-26 22:13:16 +00003768llvm::Constant *CGObjCMac::GetGetStructFunction() {
3769 return ObjCTypes.getCopyStructFn();
3770}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00003771
David Chisnall168b80f2010-12-26 22:13:16 +00003772llvm::Constant *CGObjCMac::GetSetStructFunction() {
Fariborz Jahanian5a8c2032010-04-12 18:18:10 +00003773 return ObjCTypes.getCopyStructFn();
3774}
3775
David Chisnall0d75e062012-12-17 18:54:24 +00003776llvm::Constant *CGObjCMac::GetCppAtomicObjectGetFunction() {
3777 return ObjCTypes.getCppAtomicObjectFunction();
3778}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00003779
David Chisnall0d75e062012-12-17 18:54:24 +00003780llvm::Constant *CGObjCMac::GetCppAtomicObjectSetFunction() {
Fariborz Jahanian1e1b5492012-01-06 18:07:23 +00003781 return ObjCTypes.getCppAtomicObjectFunction();
3782}
3783
Chris Lattnerd4808922009-03-22 21:03:39 +00003784llvm::Constant *CGObjCMac::EnumerationMutationFunction() {
Chris Lattnerce8754e2009-04-22 02:44:54 +00003785 return ObjCTypes.getEnumerationMutationFn();
Anders Carlsson3f35a262008-08-31 04:05:03 +00003786}
3787
John McCallbd309292010-07-06 01:34:17 +00003788void CGObjCMac::EmitTryStmt(CodeGenFunction &CGF, const ObjCAtTryStmt &S) {
3789 return EmitTryOrSynchronizedStmt(CGF, S);
3790}
3791
3792void CGObjCMac::EmitSynchronizedStmt(CodeGenFunction &CGF,
3793 const ObjCAtSynchronizedStmt &S) {
3794 return EmitTryOrSynchronizedStmt(CGF, S);
3795}
3796
John McCall65bea082010-07-21 06:59:36 +00003797namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00003798 struct PerformFragileFinally final : EHScopeStack::Cleanup {
John McCall65bea082010-07-21 06:59:36 +00003799 const Stmt &S;
John McCall7f416cc2015-09-08 08:05:57 +00003800 Address SyncArgSlot;
3801 Address CallTryExitVar;
3802 Address ExceptionData;
John McCall65bea082010-07-21 06:59:36 +00003803 ObjCTypesHelper &ObjCTypes;
3804 PerformFragileFinally(const Stmt *S,
John McCall7f416cc2015-09-08 08:05:57 +00003805 Address SyncArgSlot,
3806 Address CallTryExitVar,
3807 Address ExceptionData,
John McCall65bea082010-07-21 06:59:36 +00003808 ObjCTypesHelper *ObjCTypes)
John McCall2dd7d442010-08-04 05:59:32 +00003809 : S(*S), SyncArgSlot(SyncArgSlot), CallTryExitVar(CallTryExitVar),
John McCall65bea082010-07-21 06:59:36 +00003810 ExceptionData(ExceptionData), ObjCTypes(*ObjCTypes) {}
3811
Craig Topper4f12f102014-03-12 06:41:41 +00003812 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall65bea082010-07-21 06:59:36 +00003813 // Check whether we need to call objc_exception_try_exit.
3814 // In optimized code, this branch will always be folded.
3815 llvm::BasicBlock *FinallyCallExit =
3816 CGF.createBasicBlock("finally.call_exit");
3817 llvm::BasicBlock *FinallyNoCallExit =
3818 CGF.createBasicBlock("finally.no_call_exit");
3819 CGF.Builder.CreateCondBr(CGF.Builder.CreateLoad(CallTryExitVar),
3820 FinallyCallExit, FinallyNoCallExit);
3821
3822 CGF.EmitBlock(FinallyCallExit);
John McCall882987f2013-02-28 19:01:20 +00003823 CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionTryExitFn(),
John McCall7f416cc2015-09-08 08:05:57 +00003824 ExceptionData.getPointer());
John McCall65bea082010-07-21 06:59:36 +00003825
3826 CGF.EmitBlock(FinallyNoCallExit);
3827
3828 if (isa<ObjCAtTryStmt>(S)) {
3829 if (const ObjCAtFinallyStmt* FinallyStmt =
John McCallcebe0ca2010-08-11 00:16:14 +00003830 cast<ObjCAtTryStmt>(S).getFinallyStmt()) {
John McCall638d4f52013-04-03 00:56:07 +00003831 // Don't try to do the @finally if this is an EH cleanup.
3832 if (flags.isForEHCleanup()) return;
3833
John McCallcebe0ca2010-08-11 00:16:14 +00003834 // Save the current cleanup destination in case there's
3835 // control flow inside the finally statement.
3836 llvm::Value *CurCleanupDest =
3837 CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot());
3838
John McCall65bea082010-07-21 06:59:36 +00003839 CGF.EmitStmt(FinallyStmt->getFinallyBody());
3840
John McCallcebe0ca2010-08-11 00:16:14 +00003841 if (CGF.HaveInsertPoint()) {
3842 CGF.Builder.CreateStore(CurCleanupDest,
3843 CGF.getNormalCleanupDestSlot());
3844 } else {
3845 // Currently, the end of the cleanup must always exist.
3846 CGF.EnsureInsertPoint();
3847 }
3848 }
John McCall65bea082010-07-21 06:59:36 +00003849 } else {
3850 // Emit objc_sync_exit(expr); as finally's sole statement for
3851 // @synchronized.
John McCall2dd7d442010-08-04 05:59:32 +00003852 llvm::Value *SyncArg = CGF.Builder.CreateLoad(SyncArgSlot);
John McCall882987f2013-02-28 19:01:20 +00003853 CGF.EmitNounwindRuntimeCall(ObjCTypes.getSyncExitFn(), SyncArg);
John McCall65bea082010-07-21 06:59:36 +00003854 }
3855 }
3856 };
John McCall42227ed2010-07-31 23:20:56 +00003857
3858 class FragileHazards {
3859 CodeGenFunction &CGF;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003860 SmallVector<llvm::Value*, 20> Locals;
John McCall42227ed2010-07-31 23:20:56 +00003861 llvm::DenseSet<llvm::BasicBlock*> BlocksBeforeTry;
3862
3863 llvm::InlineAsm *ReadHazard;
3864 llvm::InlineAsm *WriteHazard;
3865
3866 llvm::FunctionType *GetAsmFnType();
3867
3868 void collectLocals();
3869 void emitReadHazard(CGBuilderTy &Builder);
3870
3871 public:
3872 FragileHazards(CodeGenFunction &CGF);
John McCall2dd7d442010-08-04 05:59:32 +00003873
John McCall42227ed2010-07-31 23:20:56 +00003874 void emitWriteHazard();
John McCall2dd7d442010-08-04 05:59:32 +00003875 void emitHazardsInNewBlocks();
John McCall42227ed2010-07-31 23:20:56 +00003876 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00003877} // end anonymous namespace
John McCall42227ed2010-07-31 23:20:56 +00003878
3879/// Create the fragile-ABI read and write hazards based on the current
3880/// state of the function, which is presumed to be immediately prior
3881/// to a @try block. These hazards are used to maintain correct
3882/// semantics in the face of optimization and the fragile ABI's
3883/// cavalier use of setjmp/longjmp.
3884FragileHazards::FragileHazards(CodeGenFunction &CGF) : CGF(CGF) {
3885 collectLocals();
3886
3887 if (Locals.empty()) return;
3888
3889 // Collect all the blocks in the function.
3890 for (llvm::Function::iterator
3891 I = CGF.CurFn->begin(), E = CGF.CurFn->end(); I != E; ++I)
3892 BlocksBeforeTry.insert(&*I);
3893
3894 llvm::FunctionType *AsmFnTy = GetAsmFnType();
3895
3896 // Create a read hazard for the allocas. This inhibits dead-store
3897 // optimizations and forces the values to memory. This hazard is
3898 // inserted before any 'throwing' calls in the protected scope to
3899 // reflect the possibility that the variables might be read from the
3900 // catch block if the call throws.
3901 {
3902 std::string Constraint;
3903 for (unsigned I = 0, E = Locals.size(); I != E; ++I) {
3904 if (I) Constraint += ',';
3905 Constraint += "*m";
3906 }
3907
3908 ReadHazard = llvm::InlineAsm::get(AsmFnTy, "", Constraint, true, false);
3909 }
3910
3911 // Create a write hazard for the allocas. This inhibits folding
3912 // loads across the hazard. This hazard is inserted at the
3913 // beginning of the catch path to reflect the possibility that the
3914 // variables might have been written within the protected scope.
3915 {
3916 std::string Constraint;
3917 for (unsigned I = 0, E = Locals.size(); I != E; ++I) {
3918 if (I) Constraint += ',';
3919 Constraint += "=*m";
3920 }
3921
3922 WriteHazard = llvm::InlineAsm::get(AsmFnTy, "", Constraint, true, false);
3923 }
3924}
3925
3926/// Emit a write hazard at the current location.
3927void FragileHazards::emitWriteHazard() {
3928 if (Locals.empty()) return;
3929
John McCall882987f2013-02-28 19:01:20 +00003930 CGF.EmitNounwindRuntimeCall(WriteHazard, Locals);
John McCall42227ed2010-07-31 23:20:56 +00003931}
3932
John McCall42227ed2010-07-31 23:20:56 +00003933void FragileHazards::emitReadHazard(CGBuilderTy &Builder) {
3934 assert(!Locals.empty());
John McCall882987f2013-02-28 19:01:20 +00003935 llvm::CallInst *call = Builder.CreateCall(ReadHazard, Locals);
3936 call->setDoesNotThrow();
3937 call->setCallingConv(CGF.getRuntimeCC());
John McCall42227ed2010-07-31 23:20:56 +00003938}
3939
3940/// Emit read hazards in all the protected blocks, i.e. all the blocks
3941/// which have been inserted since the beginning of the try.
John McCall2dd7d442010-08-04 05:59:32 +00003942void FragileHazards::emitHazardsInNewBlocks() {
John McCall42227ed2010-07-31 23:20:56 +00003943 if (Locals.empty()) return;
3944
John McCall7f416cc2015-09-08 08:05:57 +00003945 CGBuilderTy Builder(CGF, CGF.getLLVMContext());
John McCall42227ed2010-07-31 23:20:56 +00003946
3947 // Iterate through all blocks, skipping those prior to the try.
3948 for (llvm::Function::iterator
3949 FI = CGF.CurFn->begin(), FE = CGF.CurFn->end(); FI != FE; ++FI) {
3950 llvm::BasicBlock &BB = *FI;
3951 if (BlocksBeforeTry.count(&BB)) continue;
3952
3953 // Walk through all the calls in the block.
3954 for (llvm::BasicBlock::iterator
3955 BI = BB.begin(), BE = BB.end(); BI != BE; ++BI) {
3956 llvm::Instruction &I = *BI;
3957
3958 // Ignore instructions that aren't non-intrinsic calls.
3959 // These are the only calls that can possibly call longjmp.
3960 if (!isa<llvm::CallInst>(I) && !isa<llvm::InvokeInst>(I)) continue;
3961 if (isa<llvm::IntrinsicInst>(I))
3962 continue;
3963
3964 // Ignore call sites marked nounwind. This may be questionable,
3965 // since 'nounwind' doesn't necessarily mean 'does not call longjmp'.
3966 llvm::CallSite CS(&I);
3967 if (CS.doesNotThrow()) continue;
3968
John McCall2dd7d442010-08-04 05:59:32 +00003969 // Insert a read hazard before the call. This will ensure that
3970 // any writes to the locals are performed before making the
3971 // call. If the call throws, then this is sufficient to
3972 // guarantee correctness as long as it doesn't also write to any
3973 // locals.
John McCall42227ed2010-07-31 23:20:56 +00003974 Builder.SetInsertPoint(&BB, BI);
3975 emitReadHazard(Builder);
3976 }
3977 }
3978}
3979
3980static void addIfPresent(llvm::DenseSet<llvm::Value*> &S, llvm::Value *V) {
3981 if (V) S.insert(V);
3982}
3983
John McCall7f416cc2015-09-08 08:05:57 +00003984static void addIfPresent(llvm::DenseSet<llvm::Value*> &S, Address V) {
3985 if (V.isValid()) S.insert(V.getPointer());
3986}
3987
John McCall42227ed2010-07-31 23:20:56 +00003988void FragileHazards::collectLocals() {
3989 // Compute a set of allocas to ignore.
3990 llvm::DenseSet<llvm::Value*> AllocasToIgnore;
3991 addIfPresent(AllocasToIgnore, CGF.ReturnValue);
3992 addIfPresent(AllocasToIgnore, CGF.NormalCleanupDest);
John McCall42227ed2010-07-31 23:20:56 +00003993
3994 // Collect all the allocas currently in the function. This is
3995 // probably way too aggressive.
3996 llvm::BasicBlock &Entry = CGF.CurFn->getEntryBlock();
3997 for (llvm::BasicBlock::iterator
3998 I = Entry.begin(), E = Entry.end(); I != E; ++I)
3999 if (isa<llvm::AllocaInst>(*I) && !AllocasToIgnore.count(&*I))
4000 Locals.push_back(&*I);
4001}
4002
4003llvm::FunctionType *FragileHazards::GetAsmFnType() {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004004 SmallVector<llvm::Type *, 16> tys(Locals.size());
John McCall9dc0db22011-05-15 01:53:33 +00004005 for (unsigned i = 0, e = Locals.size(); i != e; ++i)
4006 tys[i] = Locals[i]->getType();
4007 return llvm::FunctionType::get(CGF.VoidTy, tys, false);
John McCall65bea082010-07-21 06:59:36 +00004008}
4009
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004010/*
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004011
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004012 Objective-C setjmp-longjmp (sjlj) Exception Handling
4013 --
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004014
John McCallbd309292010-07-06 01:34:17 +00004015 A catch buffer is a setjmp buffer plus:
4016 - a pointer to the exception that was caught
4017 - a pointer to the previous exception data buffer
4018 - two pointers of reserved storage
4019 Therefore catch buffers form a stack, with a pointer to the top
4020 of the stack kept in thread-local storage.
4021
4022 objc_exception_try_enter pushes a catch buffer onto the EH stack.
4023 objc_exception_try_exit pops the given catch buffer, which is
4024 required to be the top of the EH stack.
4025 objc_exception_throw pops the top of the EH stack, writes the
4026 thrown exception into the appropriate field, and longjmps
4027 to the setjmp buffer. It crashes the process (with a printf
4028 and an abort()) if there are no catch buffers on the stack.
4029 objc_exception_extract just reads the exception pointer out of the
4030 catch buffer.
4031
4032 There's no reason an implementation couldn't use a light-weight
4033 setjmp here --- something like __builtin_setjmp, but API-compatible
4034 with the heavyweight setjmp. This will be more important if we ever
4035 want to implement correct ObjC/C++ exception interactions for the
4036 fragile ABI.
4037
4038 Note that for this use of setjmp/longjmp to be correct, we may need
4039 to mark some local variables volatile: if a non-volatile local
4040 variable is modified between the setjmp and the longjmp, it has
4041 indeterminate value. For the purposes of LLVM IR, it may be
4042 sufficient to make loads and stores within the @try (to variables
4043 declared outside the @try) volatile. This is necessary for
4044 optimized correctness, but is not currently being done; this is
4045 being tracked as rdar://problem/8160285
4046
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004047 The basic framework for a @try-catch-finally is as follows:
4048 {
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004049 objc_exception_data d;
4050 id _rethrow = null;
Anders Carlssonda0e4562009-02-07 21:26:04 +00004051 bool _call_try_exit = true;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004052
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004053 objc_exception_try_enter(&d);
4054 if (!setjmp(d.jmp_buf)) {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004055 ... try body ...
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004056 } else {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004057 // exception path
4058 id _caught = objc_exception_extract(&d);
4059
4060 // enter new try scope for handlers
4061 if (!setjmp(d.jmp_buf)) {
4062 ... match exception and execute catch blocks ...
4063
4064 // fell off end, rethrow.
4065 _rethrow = _caught;
4066 ... jump-through-finally to finally_rethrow ...
4067 } else {
4068 // exception in catch block
4069 _rethrow = objc_exception_extract(&d);
4070 _call_try_exit = false;
4071 ... jump-through-finally to finally_rethrow ...
4072 }
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004073 }
Daniel Dunbar2efd5382008-09-30 01:06:03 +00004074 ... jump-through-finally to finally_end ...
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004075
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004076 finally:
Anders Carlssonda0e4562009-02-07 21:26:04 +00004077 if (_call_try_exit)
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004078 objc_exception_try_exit(&d);
Anders Carlssonda0e4562009-02-07 21:26:04 +00004079
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004080 ... finally block ....
Daniel Dunbar2efd5382008-09-30 01:06:03 +00004081 ... dispatch to finally destination ...
4082
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004083 finally_rethrow:
Daniel Dunbar2efd5382008-09-30 01:06:03 +00004084 objc_exception_throw(_rethrow);
4085
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004086 finally_end:
4087 }
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004088
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004089 This framework differs slightly from the one gcc uses, in that gcc
4090 uses _rethrow to determine if objc_exception_try_exit should be called
4091 and if the object should be rethrown. This breaks in the face of
4092 throwing nil and introduces unnecessary branches.
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004093
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004094 We specialize this framework for a few particular circumstances:
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004095
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004096 - If there are no catch blocks, then we avoid emitting the second
4097 exception handling context.
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004098
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004099 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
4100 e)) we avoid emitting the code to rethrow an uncaught exception.
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004101
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004102 - FIXME: If there is no @finally block we can do a few more
4103 simplifications.
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004104
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004105 Rethrows and Jumps-Through-Finally
4106 --
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004107
John McCallbd309292010-07-06 01:34:17 +00004108 '@throw;' is supported by pushing the currently-caught exception
4109 onto ObjCEHStack while the @catch blocks are emitted.
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004110
John McCallbd309292010-07-06 01:34:17 +00004111 Branches through the @finally block are handled with an ordinary
4112 normal cleanup. We do not register an EH cleanup; fragile-ABI ObjC
4113 exceptions are not compatible with C++ exceptions, and this is
4114 hardly the only place where this will go wrong.
Daniel Dunbar2efd5382008-09-30 01:06:03 +00004115
John McCallbd309292010-07-06 01:34:17 +00004116 @synchronized(expr) { stmt; } is emitted as if it were:
4117 id synch_value = expr;
4118 objc_sync_enter(synch_value);
4119 @try { stmt; } @finally { objc_sync_exit(synch_value); }
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004120*/
4121
Fariborz Jahanianc2ad6dc2008-11-21 00:49:24 +00004122void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
4123 const Stmt &S) {
4124 bool isTry = isa<ObjCAtTryStmt>(S);
John McCallbd309292010-07-06 01:34:17 +00004125
4126 // A destination for the fall-through edges of the catch handlers to
4127 // jump to.
4128 CodeGenFunction::JumpDest FinallyEnd =
4129 CGF.getJumpDestInCurrentScope("finally.end");
4130
4131 // A destination for the rethrow edge of the catch handlers to jump
4132 // to.
4133 CodeGenFunction::JumpDest FinallyRethrow =
4134 CGF.getJumpDestInCurrentScope("finally.rethrow");
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004135
Daniel Dunbar94ceb612009-02-24 01:43:46 +00004136 // For @synchronized, call objc_sync_enter(sync.expr). The
4137 // evaluation of the expression must occur before we enter the
John McCall2dd7d442010-08-04 05:59:32 +00004138 // @synchronized. We can't avoid a temp here because we need the
4139 // value to be preserved. If the backend ever does liveness
4140 // correctly after setjmp, this will be unnecessary.
John McCall7f416cc2015-09-08 08:05:57 +00004141 Address SyncArgSlot = Address::invalid();
Daniel Dunbar94ceb612009-02-24 01:43:46 +00004142 if (!isTry) {
John McCall2dd7d442010-08-04 05:59:32 +00004143 llvm::Value *SyncArg =
Daniel Dunbar94ceb612009-02-24 01:43:46 +00004144 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
4145 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
John McCall882987f2013-02-28 19:01:20 +00004146 CGF.EmitNounwindRuntimeCall(ObjCTypes.getSyncEnterFn(), SyncArg);
John McCall2dd7d442010-08-04 05:59:32 +00004147
John McCall7f416cc2015-09-08 08:05:57 +00004148 SyncArgSlot = CGF.CreateTempAlloca(SyncArg->getType(),
4149 CGF.getPointerAlign(), "sync.arg");
John McCall2dd7d442010-08-04 05:59:32 +00004150 CGF.Builder.CreateStore(SyncArg, SyncArgSlot);
Daniel Dunbar94ceb612009-02-24 01:43:46 +00004151 }
Daniel Dunbar2efd5382008-09-30 01:06:03 +00004152
John McCall2dd7d442010-08-04 05:59:32 +00004153 // Allocate memory for the setjmp buffer. This needs to be kept
4154 // live throughout the try and catch blocks.
John McCall7f416cc2015-09-08 08:05:57 +00004155 Address ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
4156 CGF.getPointerAlign(),
4157 "exceptiondata.ptr");
John McCall2dd7d442010-08-04 05:59:32 +00004158
John McCall42227ed2010-07-31 23:20:56 +00004159 // Create the fragile hazards. Note that this will not capture any
4160 // of the allocas required for exception processing, but will
4161 // capture the current basic block (which extends all the way to the
4162 // setjmp call) as "before the @try".
4163 FragileHazards Hazards(CGF);
4164
John McCallbd309292010-07-06 01:34:17 +00004165 // Create a flag indicating whether the cleanup needs to call
4166 // objc_exception_try_exit. This is true except when
4167 // - no catches match and we're branching through the cleanup
4168 // just to rethrow the exception, or
4169 // - a catch matched and we're falling out of the catch handler.
John McCall2dd7d442010-08-04 05:59:32 +00004170 // The setjmp-safety rule here is that we should always store to this
4171 // variable in a place that dominates the branch through the cleanup
4172 // without passing through any setjmps.
John McCall7f416cc2015-09-08 08:05:57 +00004173 Address CallTryExitVar = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(),
4174 CharUnits::One(),
4175 "_call_try_exit");
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004176
John McCall9916e3f2010-10-04 23:42:51 +00004177 // A slot containing the exception to rethrow. Only needed when we
4178 // have both a @catch and a @finally.
John McCall7f416cc2015-09-08 08:05:57 +00004179 Address PropagatingExnVar = Address::invalid();
John McCall9916e3f2010-10-04 23:42:51 +00004180
John McCallbd309292010-07-06 01:34:17 +00004181 // Push a normal cleanup to leave the try scope.
John McCall638d4f52013-04-03 00:56:07 +00004182 CGF.EHStack.pushCleanup<PerformFragileFinally>(NormalAndEHCleanup, &S,
John McCall2dd7d442010-08-04 05:59:32 +00004183 SyncArgSlot,
John McCallcda666c2010-07-21 07:22:38 +00004184 CallTryExitVar,
4185 ExceptionData,
4186 &ObjCTypes);
John McCallbd309292010-07-06 01:34:17 +00004187
4188 // Enter a try block:
4189 // - Call objc_exception_try_enter to push ExceptionData on top of
4190 // the EH stack.
Nico Weber6307cf02015-02-26 20:43:00 +00004191 CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionTryEnterFn(),
John McCall7f416cc2015-09-08 08:05:57 +00004192 ExceptionData.getPointer());
John McCallbd309292010-07-06 01:34:17 +00004193
4194 // - Call setjmp on the exception data buffer.
4195 llvm::Constant *Zero = llvm::ConstantInt::get(CGF.Builder.getInt32Ty(), 0);
4196 llvm::Value *GEPIndexes[] = { Zero, Zero, Zero };
David Blaikie6b2a8302015-04-03 17:47:16 +00004197 llvm::Value *SetJmpBuffer = CGF.Builder.CreateGEP(
John McCall7f416cc2015-09-08 08:05:57 +00004198 ObjCTypes.ExceptionDataTy, ExceptionData.getPointer(), GEPIndexes,
4199 "setjmp_buffer");
Nico Weber6307cf02015-02-26 20:43:00 +00004200 llvm::CallInst *SetJmpResult = CGF.EmitNounwindRuntimeCall(
4201 ObjCTypes.getSetJmpFn(), SetJmpBuffer, "setjmp_result");
Bill Wendlingbd26cf92011-12-19 23:53:28 +00004202 SetJmpResult->setCanReturnTwice();
John McCallbd309292010-07-06 01:34:17 +00004203
4204 // If setjmp returned 0, enter the protected block; otherwise,
4205 // branch to the handler.
Daniel Dunbar75283ff2008-11-11 02:29:29 +00004206 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
4207 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
John McCallbd309292010-07-06 01:34:17 +00004208 llvm::Value *DidCatch =
John McCallcebe0ca2010-08-11 00:16:14 +00004209 CGF.Builder.CreateIsNotNull(SetJmpResult, "did_catch_exception");
4210 CGF.Builder.CreateCondBr(DidCatch, TryHandler, TryBlock);
Anders Carlsson4f1c7c32008-09-09 17:59:25 +00004211
John McCallbd309292010-07-06 01:34:17 +00004212 // Emit the protected block.
Anders Carlsson4f1c7c32008-09-09 17:59:25 +00004213 CGF.EmitBlock(TryBlock);
John McCall2dd7d442010-08-04 05:59:32 +00004214 CGF.Builder.CreateStore(CGF.Builder.getTrue(), CallTryExitVar);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004215 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
John McCallbd309292010-07-06 01:34:17 +00004216 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
John McCall2dd7d442010-08-04 05:59:32 +00004217
4218 CGBuilderTy::InsertPoint TryFallthroughIP = CGF.Builder.saveAndClearIP();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004219
John McCallbd309292010-07-06 01:34:17 +00004220 // Emit the exception handler block.
Daniel Dunbar7f086782008-09-27 23:30:04 +00004221 CGF.EmitBlock(TryHandler);
Daniel Dunbarb22ff592008-09-27 07:03:52 +00004222
John McCall42227ed2010-07-31 23:20:56 +00004223 // Don't optimize loads of the in-scope locals across this point.
4224 Hazards.emitWriteHazard();
4225
John McCallbd309292010-07-06 01:34:17 +00004226 // For a @synchronized (or a @try with no catches), just branch
4227 // through the cleanup to the rethrow block.
4228 if (!isTry || !cast<ObjCAtTryStmt>(S).getNumCatchStmts()) {
4229 // Tell the cleanup not to re-pop the exit.
John McCall2dd7d442010-08-04 05:59:32 +00004230 CGF.Builder.CreateStore(CGF.Builder.getFalse(), CallTryExitVar);
Anders Carlssonbfee7e92009-02-09 20:38:58 +00004231 CGF.EmitBranchThroughCleanup(FinallyRethrow);
John McCallbd309292010-07-06 01:34:17 +00004232
4233 // Otherwise, we have to match against the caught exceptions.
4234 } else {
John McCall2dd7d442010-08-04 05:59:32 +00004235 // Retrieve the exception object. We may emit multiple blocks but
4236 // nothing can cross this so the value is already in SSA form.
4237 llvm::CallInst *Caught =
John McCall882987f2013-02-28 19:01:20 +00004238 CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionExtractFn(),
John McCall7f416cc2015-09-08 08:05:57 +00004239 ExceptionData.getPointer(), "caught");
John McCall2dd7d442010-08-04 05:59:32 +00004240
John McCallbd309292010-07-06 01:34:17 +00004241 // Push the exception to rethrow onto the EH value stack for the
4242 // benefit of any @throws in the handlers.
4243 CGF.ObjCEHValueStack.push_back(Caught);
4244
Douglas Gregor96c79492010-04-23 22:50:49 +00004245 const ObjCAtTryStmt* AtTryStmt = cast<ObjCAtTryStmt>(&S);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004246
Craig Topper8a13c412014-05-21 05:09:00 +00004247 bool HasFinally = (AtTryStmt->getFinallyStmt() != nullptr);
John McCallbd309292010-07-06 01:34:17 +00004248
Craig Topper8a13c412014-05-21 05:09:00 +00004249 llvm::BasicBlock *CatchBlock = nullptr;
4250 llvm::BasicBlock *CatchHandler = nullptr;
John McCall2dd7d442010-08-04 05:59:32 +00004251 if (HasFinally) {
John McCall9916e3f2010-10-04 23:42:51 +00004252 // Save the currently-propagating exception before
4253 // objc_exception_try_enter clears the exception slot.
4254 PropagatingExnVar = CGF.CreateTempAlloca(Caught->getType(),
John McCall7f416cc2015-09-08 08:05:57 +00004255 CGF.getPointerAlign(),
John McCall9916e3f2010-10-04 23:42:51 +00004256 "propagating_exception");
4257 CGF.Builder.CreateStore(Caught, PropagatingExnVar);
4258
John McCall2dd7d442010-08-04 05:59:32 +00004259 // Enter a new exception try block (in case a @catch block
4260 // throws an exception).
John McCall882987f2013-02-28 19:01:20 +00004261 CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionTryEnterFn(),
John McCall7f416cc2015-09-08 08:05:57 +00004262 ExceptionData.getPointer());
Anders Carlsson4f1c7c32008-09-09 17:59:25 +00004263
John McCall2dd7d442010-08-04 05:59:32 +00004264 llvm::CallInst *SetJmpResult =
John McCall882987f2013-02-28 19:01:20 +00004265 CGF.EmitNounwindRuntimeCall(ObjCTypes.getSetJmpFn(),
4266 SetJmpBuffer, "setjmp.result");
Bill Wendlingbd26cf92011-12-19 23:53:28 +00004267 SetJmpResult->setCanReturnTwice();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004268
John McCall2dd7d442010-08-04 05:59:32 +00004269 llvm::Value *Threw =
4270 CGF.Builder.CreateIsNotNull(SetJmpResult, "did_catch_exception");
4271
4272 CatchBlock = CGF.createBasicBlock("catch");
4273 CatchHandler = CGF.createBasicBlock("catch_for_catch");
4274 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
4275
4276 CGF.EmitBlock(CatchBlock);
4277 }
4278
4279 CGF.Builder.CreateStore(CGF.Builder.getInt1(HasFinally), CallTryExitVar);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004280
Daniel Dunbarb22ff592008-09-27 07:03:52 +00004281 // Handle catch list. As a special case we check if everything is
4282 // matched and avoid generating code for falling off the end if
4283 // so.
4284 bool AllMatched = false;
Douglas Gregor96c79492010-04-23 22:50:49 +00004285 for (unsigned I = 0, N = AtTryStmt->getNumCatchStmts(); I != N; ++I) {
4286 const ObjCAtCatchStmt *CatchStmt = AtTryStmt->getCatchStmt(I);
Anders Carlsson4f1c7c32008-09-09 17:59:25 +00004287
Douglas Gregor46a572b2010-04-26 16:46:50 +00004288 const VarDecl *CatchParam = CatchStmt->getCatchParamDecl();
Craig Topper8a13c412014-05-21 05:09:00 +00004289 const ObjCObjectPointerType *OPT = nullptr;
Daniel Dunbar523208f2008-09-27 07:36:24 +00004290
Anders Carlsson4f1c7c32008-09-09 17:59:25 +00004291 // catch(...) always matches.
Daniel Dunbarb22ff592008-09-27 07:03:52 +00004292 if (!CatchParam) {
4293 AllMatched = true;
4294 } else {
John McCall9dd450b2009-09-21 23:43:11 +00004295 OPT = CatchParam->getType()->getAs<ObjCObjectPointerType>();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004296
John McCallbd309292010-07-06 01:34:17 +00004297 // catch(id e) always matches under this ABI, since only
4298 // ObjC exceptions end up here in the first place.
Daniel Dunbar86919f42008-09-27 22:21:14 +00004299 // FIXME: For the time being we also match id<X>; this should
4300 // be rejected by Sema instead.
Eli Friedman55179ca2009-07-11 00:57:02 +00004301 if (OPT && (OPT->isObjCIdType() || OPT->isObjCQualifiedIdType()))
Daniel Dunbarb22ff592008-09-27 07:03:52 +00004302 AllMatched = true;
Anders Carlsson4f1c7c32008-09-09 17:59:25 +00004303 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004304
John McCallbd309292010-07-06 01:34:17 +00004305 // If this is a catch-all, we don't need to test anything.
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004306 if (AllMatched) {
John McCallbd309292010-07-06 01:34:17 +00004307 CodeGenFunction::RunCleanupsScope CatchVarCleanups(CGF);
4308
Anders Carlsson9396a892008-09-11 09:15:33 +00004309 if (CatchParam) {
John McCall1c9c3fd2010-10-15 04:57:14 +00004310 CGF.EmitAutoVarDecl(*CatchParam);
Daniel Dunbar5c7e3932008-11-11 23:11:34 +00004311 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
John McCallbd309292010-07-06 01:34:17 +00004312
4313 // These types work out because ConvertType(id) == i8*.
John McCall17f02752015-10-30 00:56:02 +00004314 EmitInitOfCatchParam(CGF, Caught, CatchParam);
Anders Carlsson9396a892008-09-11 09:15:33 +00004315 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004316
Anders Carlsson9396a892008-09-11 09:15:33 +00004317 CGF.EmitStmt(CatchStmt->getCatchBody());
John McCallbd309292010-07-06 01:34:17 +00004318
4319 // The scope of the catch variable ends right here.
4320 CatchVarCleanups.ForceCleanup();
4321
Anders Carlssonbfee7e92009-02-09 20:38:58 +00004322 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson4f1c7c32008-09-09 17:59:25 +00004323 break;
4324 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004325
Steve Naroff7cae42b2009-07-10 23:34:53 +00004326 assert(OPT && "Unexpected non-object pointer type in @catch");
John McCall96fa4842010-05-17 21:00:27 +00004327 const ObjCObjectType *ObjTy = OPT->getObjectType();
John McCallbd309292010-07-06 01:34:17 +00004328
4329 // FIXME: @catch (Class c) ?
John McCall96fa4842010-05-17 21:00:27 +00004330 ObjCInterfaceDecl *IDecl = ObjTy->getInterface();
4331 assert(IDecl && "Catch parameter must have Objective-C type!");
Anders Carlsson4f1c7c32008-09-09 17:59:25 +00004332
4333 // Check if the @catch block matches the exception object.
John McCall882987f2013-02-28 19:01:20 +00004334 llvm::Value *Class = EmitClassRef(CGF, IDecl);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004335
John McCall882987f2013-02-28 19:01:20 +00004336 llvm::Value *matchArgs[] = { Class, Caught };
John McCallbd309292010-07-06 01:34:17 +00004337 llvm::CallInst *Match =
John McCall882987f2013-02-28 19:01:20 +00004338 CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionMatchFn(),
4339 matchArgs, "match");
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004340
John McCallbd309292010-07-06 01:34:17 +00004341 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("match");
4342 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch.next");
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004343
4344 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
Daniel Dunbar7f086782008-09-27 23:30:04 +00004345 MatchedBlock, NextCatchBlock);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004346
Anders Carlsson4f1c7c32008-09-09 17:59:25 +00004347 // Emit the @catch block.
4348 CGF.EmitBlock(MatchedBlock);
John McCallbd309292010-07-06 01:34:17 +00004349
4350 // Collect any cleanups for the catch variable. The scope lasts until
4351 // the end of the catch body.
John McCall2dd7d442010-08-04 05:59:32 +00004352 CodeGenFunction::RunCleanupsScope CatchVarCleanups(CGF);
John McCallbd309292010-07-06 01:34:17 +00004353
John McCall1c9c3fd2010-10-15 04:57:14 +00004354 CGF.EmitAutoVarDecl(*CatchParam);
Daniel Dunbar5c7e3932008-11-11 23:11:34 +00004355 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004356
John McCallbd309292010-07-06 01:34:17 +00004357 // Initialize the catch variable.
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004358 llvm::Value *Tmp =
4359 CGF.Builder.CreateBitCast(Caught,
Benjamin Kramer76399eb2011-09-27 21:06:10 +00004360 CGF.ConvertType(CatchParam->getType()));
John McCall17f02752015-10-30 00:56:02 +00004361 EmitInitOfCatchParam(CGF, Tmp, CatchParam);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004362
Anders Carlsson9396a892008-09-11 09:15:33 +00004363 CGF.EmitStmt(CatchStmt->getCatchBody());
John McCallbd309292010-07-06 01:34:17 +00004364
4365 // We're done with the catch variable.
4366 CatchVarCleanups.ForceCleanup();
4367
Anders Carlssonbfee7e92009-02-09 20:38:58 +00004368 CGF.EmitBranchThroughCleanup(FinallyEnd);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004369
Anders Carlsson4f1c7c32008-09-09 17:59:25 +00004370 CGF.EmitBlock(NextCatchBlock);
4371 }
4372
John McCallbd309292010-07-06 01:34:17 +00004373 CGF.ObjCEHValueStack.pop_back();
4374
John McCall2dd7d442010-08-04 05:59:32 +00004375 // If nothing wanted anything to do with the caught exception,
4376 // kill the extract call.
4377 if (Caught->use_empty())
4378 Caught->eraseFromParent();
4379
4380 if (!AllMatched)
4381 CGF.EmitBranchThroughCleanup(FinallyRethrow);
4382
4383 if (HasFinally) {
4384 // Emit the exception handler for the @catch blocks.
4385 CGF.EmitBlock(CatchHandler);
4386
4387 // In theory we might now need a write hazard, but actually it's
4388 // unnecessary because there's no local-accessing code between
4389 // the try's write hazard and here.
4390 //Hazards.emitWriteHazard();
4391
John McCall9916e3f2010-10-04 23:42:51 +00004392 // Extract the new exception and save it to the
4393 // propagating-exception slot.
John McCall7f416cc2015-09-08 08:05:57 +00004394 assert(PropagatingExnVar.isValid());
John McCall9916e3f2010-10-04 23:42:51 +00004395 llvm::CallInst *NewCaught =
John McCall882987f2013-02-28 19:01:20 +00004396 CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionExtractFn(),
John McCall7f416cc2015-09-08 08:05:57 +00004397 ExceptionData.getPointer(), "caught");
John McCall9916e3f2010-10-04 23:42:51 +00004398 CGF.Builder.CreateStore(NewCaught, PropagatingExnVar);
4399
John McCall2dd7d442010-08-04 05:59:32 +00004400 // Don't pop the catch handler; the throw already did.
4401 CGF.Builder.CreateStore(CGF.Builder.getFalse(), CallTryExitVar);
Anders Carlssonbfee7e92009-02-09 20:38:58 +00004402 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbarb22ff592008-09-27 07:03:52 +00004403 }
Anders Carlsson4f1c7c32008-09-09 17:59:25 +00004404 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004405
John McCall42227ed2010-07-31 23:20:56 +00004406 // Insert read hazards as required in the new blocks.
John McCall2dd7d442010-08-04 05:59:32 +00004407 Hazards.emitHazardsInNewBlocks();
John McCall42227ed2010-07-31 23:20:56 +00004408
John McCallbd309292010-07-06 01:34:17 +00004409 // Pop the cleanup.
John McCall2dd7d442010-08-04 05:59:32 +00004410 CGF.Builder.restoreIP(TryFallthroughIP);
4411 if (CGF.HaveInsertPoint())
4412 CGF.Builder.CreateStore(CGF.Builder.getTrue(), CallTryExitVar);
John McCallbd309292010-07-06 01:34:17 +00004413 CGF.PopCleanupBlock();
John McCall2dd7d442010-08-04 05:59:32 +00004414 CGF.EmitBlock(FinallyEnd.getBlock(), true);
Anders Carlssonbfee7e92009-02-09 20:38:58 +00004415
John McCallbd309292010-07-06 01:34:17 +00004416 // Emit the rethrow block.
John McCall42227ed2010-07-31 23:20:56 +00004417 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
John McCallad5d61e2010-07-23 21:56:41 +00004418 CGF.EmitBlock(FinallyRethrow.getBlock(), true);
John McCallbd309292010-07-06 01:34:17 +00004419 if (CGF.HaveInsertPoint()) {
John McCall9916e3f2010-10-04 23:42:51 +00004420 // If we have a propagating-exception variable, check it.
4421 llvm::Value *PropagatingExn;
John McCall7f416cc2015-09-08 08:05:57 +00004422 if (PropagatingExnVar.isValid()) {
John McCall9916e3f2010-10-04 23:42:51 +00004423 PropagatingExn = CGF.Builder.CreateLoad(PropagatingExnVar);
John McCall2dd7d442010-08-04 05:59:32 +00004424
John McCall9916e3f2010-10-04 23:42:51 +00004425 // Otherwise, just look in the buffer for the exception to throw.
4426 } else {
4427 llvm::CallInst *Caught =
John McCall882987f2013-02-28 19:01:20 +00004428 CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionExtractFn(),
John McCall7f416cc2015-09-08 08:05:57 +00004429 ExceptionData.getPointer());
John McCall9916e3f2010-10-04 23:42:51 +00004430 PropagatingExn = Caught;
4431 }
4432
John McCall882987f2013-02-28 19:01:20 +00004433 CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionThrowFn(),
4434 PropagatingExn);
John McCallbd309292010-07-06 01:34:17 +00004435 CGF.Builder.CreateUnreachable();
Fariborz Jahaniane2caaaa2008-11-21 19:21:53 +00004436 }
Anders Carlsson4f1c7c32008-09-09 17:59:25 +00004437
John McCall42227ed2010-07-31 23:20:56 +00004438 CGF.Builder.restoreIP(SavedIP);
Anders Carlsson1963b0c2008-09-09 10:04:29 +00004439}
4440
4441void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian1eab0522013-01-10 19:02:56 +00004442 const ObjCAtThrowStmt &S,
4443 bool ClearInsertionPoint) {
Anders Carlssone005aa12008-09-09 16:16:55 +00004444 llvm::Value *ExceptionAsObject;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004445
Anders Carlssone005aa12008-09-09 16:16:55 +00004446 if (const Expr *ThrowExpr = S.getThrowExpr()) {
John McCall248512a2011-10-01 10:32:24 +00004447 llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004448 ExceptionAsObject =
Benjamin Kramer76399eb2011-09-27 21:06:10 +00004449 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy);
Anders Carlssone005aa12008-09-09 16:16:55 +00004450 } else {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004451 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004452 "Unexpected rethrow outside @catch block.");
Anders Carlssonbf8a1be2009-02-07 21:37:21 +00004453 ExceptionAsObject = CGF.ObjCEHValueStack.back();
Anders Carlssone005aa12008-09-09 16:16:55 +00004454 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004455
John McCall882987f2013-02-28 19:01:20 +00004456 CGF.EmitRuntimeCall(ObjCTypes.getExceptionThrowFn(), ExceptionAsObject)
John McCallbd309292010-07-06 01:34:17 +00004457 ->setDoesNotReturn();
Anders Carlsson4f1c7c32008-09-09 17:59:25 +00004458 CGF.Builder.CreateUnreachable();
Daniel Dunbar5c7e3932008-11-11 23:11:34 +00004459
4460 // Clear the insertion point to indicate we are in unreachable code.
Fariborz Jahanian1eab0522013-01-10 19:02:56 +00004461 if (ClearInsertionPoint)
4462 CGF.Builder.ClearInsertionPoint();
Anders Carlsson1963b0c2008-09-09 10:04:29 +00004463}
4464
Fariborz Jahanian83f45b552008-11-18 22:37:34 +00004465/// EmitObjCWeakRead - Code gen for loading value of a __weak
Fariborz Jahanianf5125d12008-11-18 21:45:40 +00004466/// object: objc_read_weak (id *src)
4467///
Fariborz Jahanian83f45b552008-11-18 22:37:34 +00004468llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00004469 Address AddrWeakObj) {
4470 llvm::Type* DestTy = AddrWeakObj.getElementType();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004471 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj,
4472 ObjCTypes.PtrObjectPtrTy);
John McCall882987f2013-02-28 19:01:20 +00004473 llvm::Value *read_weak =
4474 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcReadWeakFn(),
John McCall7f416cc2015-09-08 08:05:57 +00004475 AddrWeakObj.getPointer(), "weakread");
Eli Friedmana374b682009-03-07 03:57:15 +00004476 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanianf5125d12008-11-18 21:45:40 +00004477 return read_weak;
4478}
4479
Fariborz Jahanian83f45b552008-11-18 22:37:34 +00004480/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
4481/// objc_assign_weak (id src, id *dst)
4482///
4483void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00004484 llvm::Value *src, Address dst) {
Chris Lattner2192fe52011-07-18 04:24:23 +00004485 llvm::Type * SrcTy = src->getType();
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00004486 if (!isa<llvm::PointerType>(SrcTy)) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00004487 unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00004488 assert(Size <= 8 && "does not support size > 8");
4489 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004490 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian1b074a32009-03-13 00:42:52 +00004491 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
4492 }
Fariborz Jahanian50a12702008-11-19 17:34:06 +00004493 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
4494 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00004495 llvm::Value *args[] = { src, dst.getPointer() };
John McCall882987f2013-02-28 19:01:20 +00004496 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignWeakFn(),
4497 args, "weakassign");
Fariborz Jahanian83f45b552008-11-18 22:37:34 +00004498}
4499
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00004500/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
4501/// objc_assign_global (id src, id *dst)
4502///
4503void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00004504 llvm::Value *src, Address dst,
Fariborz Jahanian217af242010-07-20 20:30:03 +00004505 bool threadlocal) {
Chris Lattner2192fe52011-07-18 04:24:23 +00004506 llvm::Type * SrcTy = src->getType();
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00004507 if (!isa<llvm::PointerType>(SrcTy)) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00004508 unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00004509 assert(Size <= 8 && "does not support size > 8");
4510 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004511 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian1b074a32009-03-13 00:42:52 +00004512 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
4513 }
Fariborz Jahanian50a12702008-11-19 17:34:06 +00004514 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
4515 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00004516 llvm::Value *args[] = { src, dst.getPointer() };
Fariborz Jahanian217af242010-07-20 20:30:03 +00004517 if (!threadlocal)
John McCall882987f2013-02-28 19:01:20 +00004518 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignGlobalFn(),
4519 args, "globalassign");
Fariborz Jahanian217af242010-07-20 20:30:03 +00004520 else
John McCall882987f2013-02-28 19:01:20 +00004521 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignThreadLocalFn(),
4522 args, "threadlocalassign");
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00004523}
4524
Fariborz Jahaniane881b532008-11-20 19:23:36 +00004525/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00004526/// objc_assign_ivar (id src, id *dst, ptrdiff_t ivaroffset)
Fariborz Jahaniane881b532008-11-20 19:23:36 +00004527///
4528void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00004529 llvm::Value *src, Address dst,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00004530 llvm::Value *ivarOffset) {
4531 assert(ivarOffset && "EmitObjCIvarAssign - ivarOffset is NULL");
Chris Lattner2192fe52011-07-18 04:24:23 +00004532 llvm::Type * SrcTy = src->getType();
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00004533 if (!isa<llvm::PointerType>(SrcTy)) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00004534 unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00004535 assert(Size <= 8 && "does not support size > 8");
4536 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004537 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian1b074a32009-03-13 00:42:52 +00004538 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
4539 }
Fariborz Jahaniane881b532008-11-20 19:23:36 +00004540 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
4541 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00004542 llvm::Value *args[] = { src, dst.getPointer(), ivarOffset };
John McCall882987f2013-02-28 19:01:20 +00004543 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignIvarFn(), args);
Fariborz Jahaniane881b532008-11-20 19:23:36 +00004544}
4545
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00004546/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
4547/// objc_assign_strongCast (id src, id *dst)
4548///
4549void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00004550 llvm::Value *src, Address dst) {
Chris Lattner2192fe52011-07-18 04:24:23 +00004551 llvm::Type * SrcTy = src->getType();
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00004552 if (!isa<llvm::PointerType>(SrcTy)) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00004553 unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00004554 assert(Size <= 8 && "does not support size > 8");
4555 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004556 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian1b074a32009-03-13 00:42:52 +00004557 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
4558 }
Fariborz Jahanian50a12702008-11-19 17:34:06 +00004559 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
4560 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00004561 llvm::Value *args[] = { src, dst.getPointer() };
John McCall882987f2013-02-28 19:01:20 +00004562 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignStrongCastFn(),
John McCall7f416cc2015-09-08 08:05:57 +00004563 args, "strongassign");
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00004564}
4565
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00004566void CGObjCMac::EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00004567 Address DestPtr,
4568 Address SrcPtr,
Fariborz Jahanian021510e2010-06-15 22:44:06 +00004569 llvm::Value *size) {
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00004570 SrcPtr = CGF.Builder.CreateBitCast(SrcPtr, ObjCTypes.Int8PtrTy);
4571 DestPtr = CGF.Builder.CreateBitCast(DestPtr, ObjCTypes.Int8PtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00004572 llvm::Value *args[] = { DestPtr.getPointer(), SrcPtr.getPointer(), size };
John McCall882987f2013-02-28 19:01:20 +00004573 CGF.EmitNounwindRuntimeCall(ObjCTypes.GcMemmoveCollectableFn(), args);
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00004574}
4575
Fariborz Jahanian9f84b782009-02-02 20:02:29 +00004576/// EmitObjCValueForIvar - Code Gen for ivar reference.
4577///
Fariborz Jahanian712bfa62009-02-03 19:03:09 +00004578LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
4579 QualType ObjectTy,
4580 llvm::Value *BaseValue,
4581 const ObjCIvarDecl *Ivar,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +00004582 unsigned CVRQualifiers) {
John McCall8b07ec22010-05-15 11:32:37 +00004583 const ObjCInterfaceDecl *ID =
4584 ObjectTy->getAs<ObjCObjectType>()->getInterface();
Daniel Dunbar9fd114d2009-04-22 07:32:20 +00004585 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
4586 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian9f84b782009-02-02 20:02:29 +00004587}
4588
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00004589llvm::Value *CGObjCMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar722f4242009-04-22 05:08:15 +00004590 const ObjCInterfaceDecl *Interface,
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00004591 const ObjCIvarDecl *Ivar) {
Eli Friedman8cbca202012-11-06 22:15:52 +00004592 uint64_t Offset = ComputeIvarBaseOffset(CGM, Interface, Ivar);
4593 return llvm::ConstantInt::get(
4594 CGM.getTypes().ConvertType(CGM.getContext().LongTy),
4595 Offset);
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00004596}
4597
Daniel Dunbar3ad53482008-08-11 21:35:06 +00004598/* *** Private Interface *** */
4599
4600/// EmitImageInfo - Emit the image info marker used to encode some module
4601/// level information.
4602///
4603/// See: <rdr://4810609&4810587&4810587>
4604/// struct IMAGE_INFO {
4605/// unsigned version;
4606/// unsigned flags;
4607/// };
4608enum ImageInfoFlags {
Fariborz Jahanian39c17a82014-01-14 22:01:08 +00004609 eImageInfo_FixAndContinue = (1 << 0), // This flag is no longer set by clang.
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004610 eImageInfo_GarbageCollected = (1 << 1),
4611 eImageInfo_GCOnly = (1 << 2),
Fariborz Jahanian39c17a82014-01-14 22:01:08 +00004612 eImageInfo_OptimizedByDyld = (1 << 3), // This flag is set by the dyld shared cache.
Daniel Dunbar75e909f2009-04-20 07:11:47 +00004613
Daniel Dunbar5e639272010-04-25 20:39:01 +00004614 // A flag indicating that the module has no instances of a @synthesize of a
4615 // superclass variable. <rdar://problem/6803242>
Fariborz Jahanian39c17a82014-01-14 22:01:08 +00004616 eImageInfo_CorrectedSynthesize = (1 << 4), // This flag is no longer set by clang.
Manman Ren96df0b32016-01-29 23:45:01 +00004617 eImageInfo_ImageIsSimulated = (1 << 5),
4618 eImageInfo_ClassProperties = (1 << 6)
Daniel Dunbar3ad53482008-08-11 21:35:06 +00004619};
4620
Daniel Dunbar5e639272010-04-25 20:39:01 +00004621void CGObjCCommonMac::EmitImageInfo() {
Daniel Dunbar3ad53482008-08-11 21:35:06 +00004622 unsigned version = 0; // Version is unused?
Bill Wendlingb6f795e2012-02-16 01:13:30 +00004623 const char *Section = (ObjCABI == 1) ?
4624 "__OBJC, __image_info,regular" :
4625 "__DATA, __objc_imageinfo, regular, no_dead_strip";
Daniel Dunbar3ad53482008-08-11 21:35:06 +00004626
Bill Wendlingb6f795e2012-02-16 01:13:30 +00004627 // Generate module-level named metadata to convey this information to the
4628 // linker and code-gen.
4629 llvm::Module &Mod = CGM.getModule();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004630
Bill Wendlingb6f795e2012-02-16 01:13:30 +00004631 // Add the ObjC ABI version to the module flags.
4632 Mod.addModuleFlag(llvm::Module::Error, "Objective-C Version", ObjCABI);
4633 Mod.addModuleFlag(llvm::Module::Error, "Objective-C Image Info Version",
4634 version);
4635 Mod.addModuleFlag(llvm::Module::Error, "Objective-C Image Info Section",
4636 llvm::MDString::get(VMContext,Section));
Daniel Dunbar3ad53482008-08-11 21:35:06 +00004637
David Blaikiebbafb8a2012-03-11 07:00:24 +00004638 if (CGM.getLangOpts().getGC() == LangOptions::NonGC) {
Bill Wendlingb6f795e2012-02-16 01:13:30 +00004639 // Non-GC overrides those files which specify GC.
4640 Mod.addModuleFlag(llvm::Module::Override,
4641 "Objective-C Garbage Collection", (uint32_t)0);
4642 } else {
4643 // Add the ObjC garbage collection value.
4644 Mod.addModuleFlag(llvm::Module::Error,
4645 "Objective-C Garbage Collection",
4646 eImageInfo_GarbageCollected);
Daniel Dunbarc2d4b622009-03-09 21:49:58 +00004647
David Blaikiebbafb8a2012-03-11 07:00:24 +00004648 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
Bill Wendlingb6f795e2012-02-16 01:13:30 +00004649 // Add the ObjC GC Only value.
4650 Mod.addModuleFlag(llvm::Module::Error, "Objective-C GC Only",
4651 eImageInfo_GCOnly);
4652
4653 // Require that GC be specified and set to eImageInfo_GarbageCollected.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00004654 llvm::Metadata *Ops[2] = {
4655 llvm::MDString::get(VMContext, "Objective-C Garbage Collection"),
4656 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
4657 llvm::Type::getInt32Ty(VMContext), eImageInfo_GarbageCollected))};
Bill Wendlingb6f795e2012-02-16 01:13:30 +00004658 Mod.addModuleFlag(llvm::Module::Require, "Objective-C GC Only",
4659 llvm::MDNode::get(VMContext, Ops));
4660 }
4661 }
Bill Wendling1e60a2c2012-04-24 11:04:57 +00004662
4663 // Indicate whether we're compiling this to run on a simulator.
4664 const llvm::Triple &Triple = CGM.getTarget().getTriple();
Tim Northover756447a2015-10-30 16:30:36 +00004665 if ((Triple.isiOS() || Triple.isWatchOS()) &&
Bill Wendling1e60a2c2012-04-24 11:04:57 +00004666 (Triple.getArch() == llvm::Triple::x86 ||
4667 Triple.getArch() == llvm::Triple::x86_64))
4668 Mod.addModuleFlag(llvm::Module::Error, "Objective-C Is Simulated",
4669 eImageInfo_ImageIsSimulated);
Manman Ren96df0b32016-01-29 23:45:01 +00004670
4671 // Indicate whether we are generating class properties.
4672 Mod.addModuleFlag(llvm::Module::Error, "Objective-C Class Properties",
4673 eImageInfo_ClassProperties);
Daniel Dunbar3ad53482008-08-11 21:35:06 +00004674}
4675
Daniel Dunbar7bd00bd2008-08-12 06:48:42 +00004676// struct objc_module {
4677// unsigned long version;
4678// unsigned long size;
4679// const char *name;
4680// Symtab symtab;
4681// };
4682
4683// FIXME: Get from somewhere
4684static const int ModuleVersion = 7;
4685
4686void CGObjCMac::EmitModuleInfo() {
Micah Villmowdd31ca12012-10-08 16:25:52 +00004687 uint64_t Size = CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ModuleTy);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004688
Benjamin Kramer22d24c22011-10-15 12:20:02 +00004689 llvm::Constant *Values[] = {
4690 llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion),
4691 llvm::ConstantInt::get(ObjCTypes.LongTy, Size),
4692 // This used to be the filename, now it is unused. <rdr://4327263>
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00004693 GetClassName(StringRef("")),
Benjamin Kramer22d24c22011-10-15 12:20:02 +00004694 EmitModuleSymbols()
4695 };
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00004696 CreateMetadataVar("OBJC_MODULES",
Owen Anderson0e0189d2009-07-27 22:29:56 +00004697 llvm::ConstantStruct::get(ObjCTypes.ModuleTy, Values),
John McCall7f416cc2015-09-08 08:05:57 +00004698 "__OBJC,__module_info,regular,no_dead_strip",
4699 CGM.getPointerAlign(), true);
Daniel Dunbar7bd00bd2008-08-12 06:48:42 +00004700}
4701
4702llvm::Constant *CGObjCMac::EmitModuleSymbols() {
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00004703 unsigned NumClasses = DefinedClasses.size();
4704 unsigned NumCategories = DefinedCategories.size();
4705
Daniel Dunbarc61d0e92008-08-25 06:02:07 +00004706 // Return null if no symbols were defined.
4707 if (!NumClasses && !NumCategories)
Owen Anderson0b75f232009-07-31 20:28:54 +00004708 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
Daniel Dunbarc61d0e92008-08-25 06:02:07 +00004709
Chris Lattnere64d7ba2011-06-20 04:01:35 +00004710 llvm::Constant *Values[5];
Owen Andersonb7a2fe62009-07-24 23:12:58 +00004711 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
Owen Anderson0b75f232009-07-31 20:28:54 +00004712 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00004713 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
4714 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00004715
Daniel Dunbar938a77f2008-08-22 20:34:54 +00004716 // The runtime expects exactly the list of defined classes followed
4717 // by the list of defined categories, in a single array.
Chris Lattner3def9ae2012-02-06 22:16:34 +00004718 SmallVector<llvm::Constant*, 8> Symbols(NumClasses + NumCategories);
Fariborz Jahanianf322f2f2014-03-11 00:25:05 +00004719 for (unsigned i=0; i<NumClasses; i++) {
4720 const ObjCInterfaceDecl *ID = ImplementedClasses[i];
4721 assert(ID);
4722 if (ObjCImplementationDecl *IMP = ID->getImplementation())
4723 // We are implementing a weak imported interface. Give it external linkage
4724 if (ID->isWeakImported() && !IMP->isWeakImported())
4725 DefinedClasses[i]->setLinkage(llvm::GlobalVariable::ExternalLinkage);
4726
Owen Andersonade90fd2009-07-29 18:54:39 +00004727 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
Daniel Dunbar938a77f2008-08-22 20:34:54 +00004728 ObjCTypes.Int8PtrTy);
Fariborz Jahanianf322f2f2014-03-11 00:25:05 +00004729 }
Daniel Dunbar938a77f2008-08-22 20:34:54 +00004730 for (unsigned i=0; i<NumCategories; i++)
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004731 Symbols[NumClasses + i] =
Owen Andersonade90fd2009-07-29 18:54:39 +00004732 llvm::ConstantExpr::getBitCast(DefinedCategories[i],
Daniel Dunbar938a77f2008-08-22 20:34:54 +00004733 ObjCTypes.Int8PtrTy);
4734
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004735 Values[4] =
Owen Anderson9793f0e2009-07-29 22:16:19 +00004736 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Chris Lattner3def9ae2012-02-06 22:16:34 +00004737 Symbols.size()),
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00004738 Symbols);
4739
Chris Lattnere64d7ba2011-06-20 04:01:35 +00004740 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00004741
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00004742 llvm::GlobalVariable *GV = CreateMetadataVar(
John McCall7f416cc2015-09-08 08:05:57 +00004743 "OBJC_SYMBOLS", Init, "__OBJC,__symbols,regular,no_dead_strip",
4744 CGM.getPointerAlign(), true);
Owen Andersonade90fd2009-07-29 18:54:39 +00004745 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00004746}
4747
John McCall882987f2013-02-28 19:01:20 +00004748llvm::Value *CGObjCMac::EmitClassRefFromId(CodeGenFunction &CGF,
4749 IdentifierInfo *II) {
John McCall31168b02011-06-15 23:02:42 +00004750 LazySymbols.insert(II);
4751
4752 llvm::GlobalVariable *&Entry = ClassReferences[II];
4753
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00004754 if (!Entry) {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004755 llvm::Constant *Casted =
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00004756 llvm::ConstantExpr::getBitCast(GetClassName(II->getName()),
John McCall31168b02011-06-15 23:02:42 +00004757 ObjCTypes.ClassPtrTy);
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00004758 Entry = CreateMetadataVar(
4759 "OBJC_CLASS_REFERENCES_", Casted,
John McCall7f416cc2015-09-08 08:05:57 +00004760 "__OBJC,__cls_refs,literal_pointers,no_dead_strip",
4761 CGM.getPointerAlign(), true);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00004762 }
John McCall31168b02011-06-15 23:02:42 +00004763
John McCall7f416cc2015-09-08 08:05:57 +00004764 return CGF.Builder.CreateAlignedLoad(Entry, CGF.getPointerAlign());
Daniel Dunbar7bd00bd2008-08-12 06:48:42 +00004765}
4766
John McCall882987f2013-02-28 19:01:20 +00004767llvm::Value *CGObjCMac::EmitClassRef(CodeGenFunction &CGF,
John McCall31168b02011-06-15 23:02:42 +00004768 const ObjCInterfaceDecl *ID) {
Douglas Gregor24ae22c2016-04-01 23:23:52 +00004769 // If the class has the objc_runtime_visible attribute, we need to
4770 // use the Objective-C runtime to get the class.
4771 if (ID->hasAttr<ObjCRuntimeVisibleAttr>())
4772 return EmitClassRefViaRuntime(CGF, ID, ObjCTypes);
4773
John McCall882987f2013-02-28 19:01:20 +00004774 return EmitClassRefFromId(CGF, ID->getIdentifier());
John McCall31168b02011-06-15 23:02:42 +00004775}
4776
John McCall882987f2013-02-28 19:01:20 +00004777llvm::Value *CGObjCMac::EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) {
John McCall31168b02011-06-15 23:02:42 +00004778 IdentifierInfo *II = &CGM.getContext().Idents.get("NSAutoreleasePool");
John McCall882987f2013-02-28 19:01:20 +00004779 return EmitClassRefFromId(CGF, II);
John McCall31168b02011-06-15 23:02:42 +00004780}
4781
John McCall7f416cc2015-09-08 08:05:57 +00004782llvm::Value *CGObjCMac::EmitSelector(CodeGenFunction &CGF, Selector Sel) {
4783 return CGF.Builder.CreateLoad(EmitSelectorAddr(CGF, Sel));
4784}
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004785
John McCall7f416cc2015-09-08 08:05:57 +00004786Address CGObjCMac::EmitSelectorAddr(CodeGenFunction &CGF, Selector Sel) {
4787 CharUnits Align = CGF.getPointerAlign();
4788
4789 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
Daniel Dunbarcb515c82008-08-12 03:39:23 +00004790 if (!Entry) {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004791 llvm::Constant *Casted =
Owen Andersonade90fd2009-07-29 18:54:39 +00004792 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
Daniel Dunbarcb515c82008-08-12 03:39:23 +00004793 ObjCTypes.SelectorPtrTy);
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00004794 Entry = CreateMetadataVar(
4795 "OBJC_SELECTOR_REFERENCES_", Casted,
John McCall7f416cc2015-09-08 08:05:57 +00004796 "__OBJC,__message_refs,literal_pointers,no_dead_strip", Align, true);
Michael Gottesman5c205962013-02-05 23:08:45 +00004797 Entry->setExternallyInitialized(true);
Daniel Dunbarcb515c82008-08-12 03:39:23 +00004798 }
4799
John McCall7f416cc2015-09-08 08:05:57 +00004800 return Address(Entry, Align);
Daniel Dunbarcb515c82008-08-12 03:39:23 +00004801}
4802
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00004803llvm::Constant *CGObjCCommonMac::GetClassName(StringRef RuntimeName) {
4804 llvm::GlobalVariable *&Entry = ClassNames[RuntimeName];
4805 if (!Entry)
Saleem Abdulrasool271106c2016-09-16 23:41:13 +00004806 Entry = CreateCStringLiteral(RuntimeName, ObjCLabelType::ClassName);
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00004807 return getConstantGEP(VMContext, Entry, 0, 0);
Daniel Dunbar7bd00bd2008-08-12 06:48:42 +00004808}
4809
Argyrios Kyrtzidis13257c52010-08-09 10:54:20 +00004810llvm::Function *CGObjCCommonMac::GetMethodDefinition(const ObjCMethodDecl *MD) {
4811 llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*>::iterator
4812 I = MethodDefinitions.find(MD);
4813 if (I != MethodDefinitions.end())
4814 return I->second;
4815
Craig Topper8a13c412014-05-21 05:09:00 +00004816 return nullptr;
Argyrios Kyrtzidis13257c52010-08-09 10:54:20 +00004817}
4818
Fariborz Jahanian01dff422009-03-05 19:17:31 +00004819/// GetIvarLayoutName - Returns a unique constant for the given
4820/// ivar layout bitmap.
4821llvm::Constant *CGObjCCommonMac::GetIvarLayoutName(IdentifierInfo *Ident,
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004822 const ObjCCommonTypesHelper &ObjCTypes) {
Owen Anderson0b75f232009-07-31 20:28:54 +00004823 return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Fariborz Jahanian01dff422009-03-05 19:17:31 +00004824}
4825
John McCall3fd13f062015-10-21 18:06:47 +00004826void IvarLayoutBuilder::visitRecord(const RecordType *RT,
4827 CharUnits offset) {
Daniel Dunbar15bd8882009-05-03 14:10:34 +00004828 const RecordDecl *RD = RT->getDecl();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004829
John McCall3fd13f062015-10-21 18:06:47 +00004830 // If this is a union, remember that we had one, because it might mess
4831 // up the ordering of layout entries.
4832 if (RD->isUnion())
4833 IsDisordered = true;
4834
4835 const ASTRecordLayout *recLayout = nullptr;
4836 visitAggregate(RD->field_begin(), RD->field_end(), offset,
4837 [&](const FieldDecl *field) -> CharUnits {
4838 if (!recLayout)
4839 recLayout = &CGM.getContext().getASTRecordLayout(RD);
4840 auto offsetInBits = recLayout->getFieldOffset(field->getFieldIndex());
4841 return CGM.getContext().toCharUnitsFromBits(offsetInBits);
4842 });
Daniel Dunbar15bd8882009-05-03 14:10:34 +00004843}
4844
John McCall3fd13f062015-10-21 18:06:47 +00004845template <class Iterator, class GetOffsetFn>
4846void IvarLayoutBuilder::visitAggregate(Iterator begin, Iterator end,
4847 CharUnits aggregateOffset,
4848 const GetOffsetFn &getOffset) {
4849 for (; begin != end; ++begin) {
4850 auto field = *begin;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004851
John McCall3fd13f062015-10-21 18:06:47 +00004852 // Skip over bitfields.
4853 if (field->isBitField()) {
4854 continue;
4855 }
4856
4857 // Compute the offset of the field within the aggregate.
4858 CharUnits fieldOffset = aggregateOffset + getOffset(field);
4859
4860 visitField(field, fieldOffset);
4861 }
4862}
4863
4864/// Collect layout information for the given fields into IvarsInfo.
4865void IvarLayoutBuilder::visitField(const FieldDecl *field,
4866 CharUnits fieldOffset) {
4867 QualType fieldType = field->getType();
4868
4869 // Drill down into arrays.
4870 uint64_t numElts = 1;
4871 while (auto arrayType = CGM.getContext().getAsConstantArrayType(fieldType)) {
4872 numElts *= arrayType->getSize().getZExtValue();
4873 fieldType = arrayType->getElementType();
4874 }
4875
4876 assert(!fieldType->isArrayType() && "ivar of non-constant array type?");
4877
4878 // If we ended up with a zero-sized array, we've done what we can do within
4879 // the limits of this layout encoding.
4880 if (numElts == 0) return;
4881
4882 // Recurse if the base element type is a record type.
4883 if (auto recType = fieldType->getAs<RecordType>()) {
4884 size_t oldEnd = IvarsInfo.size();
4885
4886 visitRecord(recType, fieldOffset);
4887
4888 // If we have an array, replicate the first entry's layout information.
4889 auto numEltEntries = IvarsInfo.size() - oldEnd;
4890 if (numElts != 1 && numEltEntries != 0) {
4891 CharUnits eltSize = CGM.getContext().getTypeSizeInChars(recType);
4892 for (uint64_t eltIndex = 1; eltIndex != numElts; ++eltIndex) {
4893 // Copy the last numEltEntries onto the end of the array, adjusting
4894 // each for the element size.
4895 for (size_t i = 0; i != numEltEntries; ++i) {
4896 auto firstEntry = IvarsInfo[oldEnd + i];
4897 IvarsInfo.push_back(IvarInfo(firstEntry.Offset + eltIndex * eltSize,
4898 firstEntry.SizeInWords));
4899 }
4900 }
4901 }
4902
Fariborz Jahanian524bb202009-03-10 16:22:08 +00004903 return;
Fariborz Jahanian3b0f8862009-03-11 00:07:04 +00004904 }
Daniel Dunbar15bd8882009-05-03 14:10:34 +00004905
John McCall3fd13f062015-10-21 18:06:47 +00004906 // Classify the element type.
4907 Qualifiers::GC GCAttr = GetGCAttrTypeForType(CGM.getContext(), fieldType);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004908
John McCall3fd13f062015-10-21 18:06:47 +00004909 // If it matches what we're looking for, add an entry.
4910 if ((ForStrongLayout && GCAttr == Qualifiers::Strong)
4911 || (!ForStrongLayout && GCAttr == Qualifiers::Weak)) {
4912 assert(CGM.getContext().getTypeSizeInChars(fieldType)
4913 == CGM.getPointerSize());
4914 IvarsInfo.push_back(IvarInfo(fieldOffset, numElts));
4915 }
Fariborz Jahanianc559f3f2009-03-05 22:39:55 +00004916}
4917
John McCall3fd13f062015-10-21 18:06:47 +00004918/// buildBitmap - This routine does the horsework of taking the offsets of
4919/// strong/weak references and creating a bitmap. The bitmap is also
4920/// returned in the given buffer, suitable for being passed to \c dump().
4921llvm::Constant *IvarLayoutBuilder::buildBitmap(CGObjCCommonMac &CGObjC,
4922 llvm::SmallVectorImpl<unsigned char> &buffer) {
4923 // The bitmap is a series of skip/scan instructions, aligned to word
4924 // boundaries. The skip is performed first.
4925 const unsigned char MaxNibble = 0xF;
4926 const unsigned char SkipMask = 0xF0, SkipShift = 4;
4927 const unsigned char ScanMask = 0x0F, ScanShift = 0;
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00004928
John McCall3fd13f062015-10-21 18:06:47 +00004929 assert(!IvarsInfo.empty() && "generating bitmap for no data");
4930
4931 // Sort the ivar info on byte position in case we encounterred a
4932 // union nested in the ivar list.
4933 if (IsDisordered) {
4934 // This isn't a stable sort, but our algorithm should handle it fine.
4935 llvm::array_pod_sort(IvarsInfo.begin(), IvarsInfo.end());
4936 } else {
Craig Toppera3467052016-01-03 19:43:20 +00004937 assert(std::is_sorted(IvarsInfo.begin(), IvarsInfo.end()));
John McCall3fd13f062015-10-21 18:06:47 +00004938 }
4939 assert(IvarsInfo.back().Offset < InstanceEnd);
4940
4941 assert(buffer.empty());
4942
4943 // Skip the next N words.
4944 auto skip = [&](unsigned numWords) {
4945 assert(numWords > 0);
4946
4947 // Try to merge into the previous byte. Since scans happen second, we
4948 // can't do this if it includes a scan.
4949 if (!buffer.empty() && !(buffer.back() & ScanMask)) {
4950 unsigned lastSkip = buffer.back() >> SkipShift;
4951 if (lastSkip < MaxNibble) {
4952 unsigned claimed = std::min(MaxNibble - lastSkip, numWords);
4953 numWords -= claimed;
4954 lastSkip += claimed;
4955 buffer.back() = (lastSkip << SkipShift);
4956 }
4957 }
4958
4959 while (numWords >= MaxNibble) {
4960 buffer.push_back(MaxNibble << SkipShift);
4961 numWords -= MaxNibble;
4962 }
4963 if (numWords) {
4964 buffer.push_back(numWords << SkipShift);
4965 }
4966 };
4967
4968 // Scan the next N words.
4969 auto scan = [&](unsigned numWords) {
4970 assert(numWords > 0);
4971
4972 // Try to merge into the previous byte. Since scans happen second, we can
4973 // do this even if it includes a skip.
4974 if (!buffer.empty()) {
4975 unsigned lastScan = (buffer.back() & ScanMask) >> ScanShift;
4976 if (lastScan < MaxNibble) {
4977 unsigned claimed = std::min(MaxNibble - lastScan, numWords);
4978 numWords -= claimed;
4979 lastScan += claimed;
4980 buffer.back() = (buffer.back() & SkipMask) | (lastScan << ScanShift);
4981 }
4982 }
4983
4984 while (numWords >= MaxNibble) {
4985 buffer.push_back(MaxNibble << ScanShift);
4986 numWords -= MaxNibble;
4987 }
4988 if (numWords) {
4989 buffer.push_back(numWords << ScanShift);
4990 }
4991 };
4992
4993 // One past the end of the last scan.
4994 unsigned endOfLastScanInWords = 0;
4995 const CharUnits WordSize = CGM.getPointerSize();
4996
4997 // Consider all the scan requests.
4998 for (auto &request : IvarsInfo) {
4999 CharUnits beginOfScan = request.Offset - InstanceBegin;
5000
5001 // Ignore scan requests that don't start at an even multiple of the
5002 // word size. We can't encode them.
5003 if ((beginOfScan % WordSize) != 0) continue;
5004
5005 // Ignore scan requests that start before the instance start.
5006 // This assumes that scans never span that boundary. The boundary
5007 // isn't the true start of the ivars, because in the fragile-ARC case
5008 // it's rounded up to word alignment, but the test above should leave
5009 // us ignoring that possibility.
5010 if (beginOfScan.isNegative()) {
5011 assert(request.Offset + request.SizeInWords * WordSize <= InstanceBegin);
5012 continue;
5013 }
5014
5015 unsigned beginOfScanInWords = beginOfScan / WordSize;
5016 unsigned endOfScanInWords = beginOfScanInWords + request.SizeInWords;
5017
5018 // If the scan starts some number of words after the last one ended,
5019 // skip forward.
5020 if (beginOfScanInWords > endOfLastScanInWords) {
5021 skip(beginOfScanInWords - endOfLastScanInWords);
5022
5023 // Otherwise, start scanning where the last left off.
5024 } else {
5025 beginOfScanInWords = endOfLastScanInWords;
5026
5027 // If that leaves us with nothing to scan, ignore this request.
5028 if (beginOfScanInWords >= endOfScanInWords) continue;
5029 }
5030
5031 // Scan to the end of the request.
5032 assert(beginOfScanInWords < endOfScanInWords);
5033 scan(endOfScanInWords - beginOfScanInWords);
5034 endOfLastScanInWords = endOfScanInWords;
5035 }
5036
John McCallf5ea0722015-10-29 23:36:14 +00005037 if (buffer.empty())
5038 return llvm::ConstantPointerNull::get(CGM.Int8PtrTy);
5039
John McCall3fd13f062015-10-21 18:06:47 +00005040 // For GC layouts, emit a skip to the end of the allocation so that we
5041 // have precise information about the entire thing. This isn't useful
5042 // or necessary for the ARC-style layout strings.
5043 if (CGM.getLangOpts().getGC() != LangOptions::NonGC) {
5044 unsigned lastOffsetInWords =
5045 (InstanceEnd - InstanceBegin + WordSize - CharUnits::One()) / WordSize;
5046 if (lastOffsetInWords > endOfLastScanInWords) {
5047 skip(lastOffsetInWords - endOfLastScanInWords);
5048 }
5049 }
5050
5051 // Null terminate the string.
5052 buffer.push_back(0);
5053
Saleem Abdulrasool271106c2016-09-16 23:41:13 +00005054 auto *Entry = CGObjC.CreateCStringLiteral(
5055 reinterpret_cast<char *>(buffer.data()), ObjCLabelType::ClassName);
John McCall3fd13f062015-10-21 18:06:47 +00005056 return getConstantGEP(CGM.getLLVMContext(), Entry, 0, 0);
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00005057}
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005058
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00005059/// BuildIvarLayout - Builds ivar layout bitmap for the class
5060/// implementation for the __strong or __weak case.
5061/// The layout map displays which words in ivar list must be skipped
5062/// and which must be scanned by GC (see below). String is built of bytes.
5063/// Each byte is divided up in two nibbles (4-bit each). Left nibble is count
5064/// of words to skip and right nibble is count of words to scan. So, each
5065/// nibble represents up to 15 workds to skip or scan. Skipping the rest is
5066/// represented by a 0x00 byte which also ends the string.
5067/// 1. when ForStrongLayout is true, following ivars are scanned:
5068/// - id, Class
5069/// - object *
5070/// - __strong anything
5071///
5072/// 2. When ForStrongLayout is false, following ivars are scanned:
5073/// - __weak anything
5074///
John McCall3fd13f062015-10-21 18:06:47 +00005075llvm::Constant *
5076CGObjCCommonMac::BuildIvarLayout(const ObjCImplementationDecl *OMD,
5077 CharUnits beginOffset, CharUnits endOffset,
John McCall460ce582015-10-22 18:38:17 +00005078 bool ForStrongLayout, bool HasMRCWeakIvars) {
5079 // If this is MRC, and we're either building a strong layout or there
5080 // are no weak ivars, bail out early.
Chris Lattnerece04092012-02-07 00:39:47 +00005081 llvm::Type *PtrTy = CGM.Int8PtrTy;
David Blaikiebbafb8a2012-03-11 07:00:24 +00005082 if (CGM.getLangOpts().getGC() == LangOptions::NonGC &&
John McCall460ce582015-10-22 18:38:17 +00005083 !CGM.getLangOpts().ObjCAutoRefCount &&
5084 (ForStrongLayout || !HasMRCWeakIvars))
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00005085 return llvm::Constant::getNullValue(PtrTy);
5086
Jordy Rosea91768e2011-07-22 02:08:32 +00005087 const ObjCInterfaceDecl *OI = OMD->getClassInterface();
John McCall3fd13f062015-10-21 18:06:47 +00005088 SmallVector<const ObjCIvarDecl*, 32> ivars;
5089
5090 // GC layout strings include the complete object layout, possibly
5091 // inaccurately in the non-fragile ABI; the runtime knows how to fix this
5092 // up.
5093 //
5094 // ARC layout strings only include the class's ivars. In non-fragile
John McCallf5ea0722015-10-29 23:36:14 +00005095 // runtimes, that means starting at InstanceStart, rounded up to word
5096 // alignment. In fragile runtimes, there's no InstanceStart, so it means
John McCalld80218f2015-11-19 02:27:55 +00005097 // starting at the offset of the first ivar, rounded up to word alignment.
John McCall460ce582015-10-22 18:38:17 +00005098 //
5099 // MRC weak layout strings follow the ARC style.
John McCall3fd13f062015-10-21 18:06:47 +00005100 CharUnits baseOffset;
John McCall460ce582015-10-22 18:38:17 +00005101 if (CGM.getLangOpts().getGC() == LangOptions::NonGC) {
Jordy Rosea91768e2011-07-22 02:08:32 +00005102 for (const ObjCIvarDecl *IVD = OI->all_declared_ivar_begin();
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00005103 IVD; IVD = IVD->getNextIvar())
John McCall3fd13f062015-10-21 18:06:47 +00005104 ivars.push_back(IVD);
5105
5106 if (isNonFragileABI()) {
5107 baseOffset = beginOffset; // InstanceStart
John McCalld80218f2015-11-19 02:27:55 +00005108 } else if (!ivars.empty()) {
5109 baseOffset =
5110 CharUnits::fromQuantity(ComputeIvarBaseOffset(CGM, OMD, ivars[0]));
John McCall3fd13f062015-10-21 18:06:47 +00005111 } else {
5112 baseOffset = CharUnits::Zero();
5113 }
John McCallf5ea0722015-10-29 23:36:14 +00005114
Rui Ueyama83aa9792016-01-14 21:00:27 +00005115 baseOffset = baseOffset.alignTo(CGM.getPointerAlign());
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00005116 }
5117 else {
John McCall3fd13f062015-10-21 18:06:47 +00005118 CGM.getContext().DeepCollectObjCIvars(OI, true, ivars);
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00005119
John McCall3fd13f062015-10-21 18:06:47 +00005120 baseOffset = CharUnits::Zero();
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00005121 }
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00005122
John McCall3fd13f062015-10-21 18:06:47 +00005123 if (ivars.empty())
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00005124 return llvm::Constant::getNullValue(PtrTy);
5125
John McCall3fd13f062015-10-21 18:06:47 +00005126 IvarLayoutBuilder builder(CGM, baseOffset, endOffset, ForStrongLayout);
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00005127
John McCall3fd13f062015-10-21 18:06:47 +00005128 builder.visitAggregate(ivars.begin(), ivars.end(), CharUnits::Zero(),
5129 [&](const ObjCIvarDecl *ivar) -> CharUnits {
5130 return CharUnits::fromQuantity(ComputeIvarBaseOffset(CGM, OMD, ivar));
5131 });
5132
5133 if (!builder.hasBitmapData())
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00005134 return llvm::Constant::getNullValue(PtrTy);
John McCall3fd13f062015-10-21 18:06:47 +00005135
5136 llvm::SmallVector<unsigned char, 4> buffer;
5137 llvm::Constant *C = builder.buildBitmap(*this, buffer);
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00005138
John McCallf5ea0722015-10-29 23:36:14 +00005139 if (CGM.getLangOpts().ObjCGCBitmapPrint && !buffer.empty()) {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005140 printf("\n%s ivar layout for class '%s': ",
Fariborz Jahanian80c9ce22009-04-20 22:03:45 +00005141 ForStrongLayout ? "strong" : "weak",
Ben Langmuire013bdc2014-07-11 00:43:47 +00005142 OMD->getClassInterface()->getName().str().c_str());
John McCall3fd13f062015-10-21 18:06:47 +00005143 builder.dump(buffer);
Fariborz Jahanian80c9ce22009-04-20 22:03:45 +00005144 }
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00005145 return C;
Fariborz Jahanianc559f3f2009-03-05 22:39:55 +00005146}
5147
Fariborz Jahanian0b1ccdc2009-01-21 23:34:32 +00005148llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) {
Daniel Dunbarcb515c82008-08-12 03:39:23 +00005149 llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
Chris Lattner3def9ae2012-02-06 22:16:34 +00005150 // FIXME: Avoid std::string in "Sel.getAsString()"
Daniel Dunbarc2d4b622009-03-09 21:49:58 +00005151 if (!Entry)
Saleem Abdulrasool271106c2016-09-16 23:41:13 +00005152 Entry = CreateCStringLiteral(Sel.getAsString(), ObjCLabelType::MethodVarName);
Owen Anderson170229f2009-07-14 23:10:40 +00005153 return getConstantGEP(VMContext, Entry, 0, 0);
Daniel Dunbarb036db82008-08-13 03:21:16 +00005154}
5155
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00005156// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian0b1ccdc2009-01-21 23:34:32 +00005157llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) {
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00005158 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
5159}
5160
Daniel Dunbarf5c18462009-04-20 06:54:31 +00005161llvm::Constant *CGObjCCommonMac::GetMethodVarType(const FieldDecl *Field) {
Devang Patel4b6e4bb2009-03-04 18:21:39 +00005162 std::string TypeStr;
5163 CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
5164
5165 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
Daniel Dunbarc2d4b622009-03-09 21:49:58 +00005166 if (!Entry)
Saleem Abdulrasool271106c2016-09-16 23:41:13 +00005167 Entry = CreateCStringLiteral(TypeStr, ObjCLabelType::MethodVarType);
Owen Anderson170229f2009-07-14 23:10:40 +00005168 return getConstantGEP(VMContext, Entry, 0, 0);
Daniel Dunbarcb515c82008-08-12 03:39:23 +00005169}
5170
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005171llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D,
5172 bool Extended) {
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00005173 std::string TypeStr;
Bill Wendlinge22bef72012-02-09 22:45:21 +00005174 if (CGM.getContext().getObjCEncodingForMethodDecl(D, TypeStr, Extended))
Craig Topper8a13c412014-05-21 05:09:00 +00005175 return nullptr;
Devang Patel4b6e4bb2009-03-04 18:21:39 +00005176
5177 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
Daniel Dunbar3241fae2009-04-14 23:14:47 +00005178 if (!Entry)
Saleem Abdulrasool271106c2016-09-16 23:41:13 +00005179 Entry = CreateCStringLiteral(TypeStr, ObjCLabelType::MethodVarType);
Owen Anderson170229f2009-07-14 23:10:40 +00005180 return getConstantGEP(VMContext, Entry, 0, 0);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00005181}
5182
Daniel Dunbar80a840b2008-08-23 00:19:03 +00005183// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian0b1ccdc2009-01-21 23:34:32 +00005184llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) {
Daniel Dunbar80a840b2008-08-23 00:19:03 +00005185 llvm::GlobalVariable *&Entry = PropertyNames[Ident];
Daniel Dunbarc2d4b622009-03-09 21:49:58 +00005186 if (!Entry)
Saleem Abdulrasool271106c2016-09-16 23:41:13 +00005187 Entry = CreateCStringLiteral(Ident->getName(), ObjCLabelType::PropertyName);
Owen Anderson170229f2009-07-14 23:10:40 +00005188 return getConstantGEP(VMContext, Entry, 0, 0);
Daniel Dunbar80a840b2008-08-23 00:19:03 +00005189}
5190
5191// FIXME: Merge into a single cstring creation function.
Daniel Dunbar4932b362008-08-28 04:38:10 +00005192// FIXME: This Decl should be more precise.
Daniel Dunbarc2d4b622009-03-09 21:49:58 +00005193llvm::Constant *
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005194CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
5195 const Decl *Container) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005196 std::string TypeStr;
5197 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
Daniel Dunbar80a840b2008-08-23 00:19:03 +00005198 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
5199}
5200
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005201void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D,
Fariborz Jahanian0b1ccdc2009-01-21 23:34:32 +00005202 const ObjCContainerDecl *CD,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005203 SmallVectorImpl<char> &Name) {
Daniel Dunbard2386812009-10-19 01:21:19 +00005204 llvm::raw_svector_ostream OS(Name);
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +00005205 assert (CD && "Missing container decl in GetNameForMethod");
Daniel Dunbard2386812009-10-19 01:21:19 +00005206 OS << '\01' << (D->isInstanceMethod() ? '-' : '+')
5207 << '[' << CD->getName();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005208 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbard2386812009-10-19 01:21:19 +00005209 dyn_cast<ObjCCategoryImplDecl>(D->getDeclContext()))
Benjamin Kramer2f569922012-02-07 11:57:45 +00005210 OS << '(' << *CID << ')';
Daniel Dunbard2386812009-10-19 01:21:19 +00005211 OS << ' ' << D->getSelector().getAsString() << ']';
Daniel Dunbara94ecd22008-08-16 03:19:19 +00005212}
5213
Daniel Dunbar3ad53482008-08-11 21:35:06 +00005214void CGObjCMac::FinishModule() {
Daniel Dunbar7bd00bd2008-08-12 06:48:42 +00005215 EmitModuleInfo();
5216
Daniel Dunbarc475d422008-10-29 22:36:39 +00005217 // Emit the dummy bodies for any protocols which were referenced but
5218 // never defined.
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005219 for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
Chris Lattnerf56501c2009-07-17 23:57:13 +00005220 I = Protocols.begin(), e = Protocols.end(); I != e; ++I) {
5221 if (I->second->hasInitializer())
Daniel Dunbarc475d422008-10-29 22:36:39 +00005222 continue;
Daniel Dunbar7bd00bd2008-08-12 06:48:42 +00005223
Benjamin Kramer22d24c22011-10-15 12:20:02 +00005224 llvm::Constant *Values[5];
Owen Anderson0b75f232009-07-31 20:28:54 +00005225 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00005226 Values[1] = GetClassName(I->first->getName());
Owen Anderson0b75f232009-07-31 20:28:54 +00005227 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
Daniel Dunbarc475d422008-10-29 22:36:39 +00005228 Values[3] = Values[4] =
Owen Anderson0b75f232009-07-31 20:28:54 +00005229 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
Owen Anderson0e0189d2009-07-27 22:29:56 +00005230 I->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
Daniel Dunbarc475d422008-10-29 22:36:39 +00005231 Values));
Rafael Espindola060062a2014-03-06 22:15:10 +00005232 CGM.addCompilerUsedGlobal(I->second);
Daniel Dunbarc475d422008-10-29 22:36:39 +00005233 }
5234
Daniel Dunbarc61d0e92008-08-25 06:02:07 +00005235 // Add assembler directives to add lazy undefined symbol references
5236 // for classes which are referenced but not defined. This is
5237 // important for correct linker interaction.
Daniel Dunbard027a922009-09-07 00:20:42 +00005238 //
5239 // FIXME: It would be nice if we had an LLVM construct for this.
Saleem Abdulrasool62c07eb2016-09-12 21:15:23 +00005240 if ((!LazySymbols.empty() || !DefinedSymbols.empty()) &&
5241 CGM.getTriple().isOSBinFormatMachO()) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00005242 SmallString<256> Asm;
Daniel Dunbard027a922009-09-07 00:20:42 +00005243 Asm += CGM.getModule().getModuleInlineAsm();
5244 if (!Asm.empty() && Asm.back() != '\n')
5245 Asm += '\n';
Daniel Dunbarc61d0e92008-08-25 06:02:07 +00005246
Daniel Dunbard027a922009-09-07 00:20:42 +00005247 llvm::raw_svector_ostream OS(Asm);
Saleem Abdulrasool39217d42016-09-16 14:24:26 +00005248 for (const auto *Sym : DefinedSymbols)
Saleem Abdulrasool62c07eb2016-09-12 21:15:23 +00005249 OS << "\t.objc_class_name_" << Sym->getName() << "=0\n"
5250 << "\t.globl .objc_class_name_" << Sym->getName() << "\n";
Saleem Abdulrasool39217d42016-09-16 14:24:26 +00005251 for (const auto *Sym : LazySymbols)
Saleem Abdulrasool62c07eb2016-09-12 21:15:23 +00005252 OS << "\t.lazy_reference .objc_class_name_" << Sym->getName() << "\n";
5253 for (const auto &Category : DefinedCategoryNames)
5254 OS << "\t.objc_category_name_" << Category << "=0\n"
5255 << "\t.globl .objc_category_name_" << Category << "\n";
Fariborz Jahanian9adb2e62010-06-21 22:05:18 +00005256
Daniel Dunbard027a922009-09-07 00:20:42 +00005257 CGM.getModule().setModuleInlineAsm(OS.str());
Daniel Dunbarc61d0e92008-08-25 06:02:07 +00005258 }
Daniel Dunbar3ad53482008-08-11 21:35:06 +00005259}
5260
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005261CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm)
Saleem Abdulrasool4f515a62016-07-13 02:58:44 +00005262 : CGObjCCommonMac(cgm), ObjCTypes(cgm), ObjCEmptyCacheVar(nullptr),
5263 ObjCEmptyVtableVar(nullptr) {
Fariborz Jahanian279eda62009-01-21 22:04:16 +00005264 ObjCABI = 2;
5265}
5266
Daniel Dunbar3ad53482008-08-11 21:35:06 +00005267/* *** */
5268
Fariborz Jahanian279eda62009-01-21 22:04:16 +00005269ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm)
Craig Topper8a13c412014-05-21 05:09:00 +00005270 : VMContext(cgm.getLLVMContext()), CGM(cgm), ExternalProtocolPtrTy(nullptr)
Douglas Gregora95f9aa2012-01-17 23:38:32 +00005271{
Daniel Dunbar7bd00bd2008-08-12 06:48:42 +00005272 CodeGen::CodeGenTypes &Types = CGM.getTypes();
5273 ASTContext &Ctx = CGM.getContext();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005274
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00005275 ShortTy = Types.ConvertType(Ctx.ShortTy);
Daniel Dunbarb036db82008-08-13 03:21:16 +00005276 IntTy = Types.ConvertType(Ctx.IntTy);
Daniel Dunbar7bd00bd2008-08-12 06:48:42 +00005277 LongTy = Types.ConvertType(Ctx.LongTy);
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00005278 LongLongTy = Types.ConvertType(Ctx.LongLongTy);
Chris Lattnerece04092012-02-07 00:39:47 +00005279 Int8PtrTy = CGM.Int8PtrTy;
5280 Int8PtrPtrTy = CGM.Int8PtrPtrTy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005281
Tim Northover238b5082014-03-29 13:42:40 +00005282 // arm64 targets use "int" ivar offset variables. All others,
5283 // including OS X x86_64 and Windows x86_64, use "long" ivar offsets.
Tim Northover40956e62014-07-23 12:32:58 +00005284 if (CGM.getTarget().getTriple().getArch() == llvm::Triple::aarch64)
Tim Northover238b5082014-03-29 13:42:40 +00005285 IvarOffsetVarTy = IntTy;
5286 else
5287 IvarOffsetVarTy = LongTy;
5288
Daniel Dunbar7bd00bd2008-08-12 06:48:42 +00005289 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
Owen Anderson9793f0e2009-07-29 22:16:19 +00005290 PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
Daniel Dunbar7bd00bd2008-08-12 06:48:42 +00005291 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005292
Fariborz Jahanian279eda62009-01-21 22:04:16 +00005293 // I'm not sure I like this. The implicit coordination is a bit
5294 // gross. We should solve this in a reasonable fashion because this
5295 // is a pretty common task (match some runtime data structure with
5296 // an LLVM data structure).
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005297
Fariborz Jahanian279eda62009-01-21 22:04:16 +00005298 // FIXME: This is leaked.
5299 // FIXME: Merge with rewriter code?
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005300
Fariborz Jahanian279eda62009-01-21 22:04:16 +00005301 // struct _objc_super {
5302 // id self;
5303 // Class cls;
5304 // }
Abramo Bagnara6150c882010-05-11 21:36:43 +00005305 RecordDecl *RD = RecordDecl::Create(Ctx, TTK_Struct,
Daniel Dunbar0c005372010-04-29 16:29:11 +00005306 Ctx.getTranslationUnitDecl(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00005307 SourceLocation(), SourceLocation(),
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005308 &Ctx.Idents.get("_objc_super"));
Craig Topper8a13c412014-05-21 05:09:00 +00005309 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), SourceLocation(),
5310 nullptr, Ctx.getObjCIdType(), nullptr, nullptr,
5311 false, ICIS_NoInit));
5312 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), SourceLocation(),
5313 nullptr, Ctx.getObjCClassType(), nullptr,
5314 nullptr, false, ICIS_NoInit));
Douglas Gregord5058122010-02-11 01:19:42 +00005315 RD->completeDefinition();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005316
Fariborz Jahanian279eda62009-01-21 22:04:16 +00005317 SuperCTy = Ctx.getTagDeclType(RD);
5318 SuperPtrCTy = Ctx.getPointerType(SuperCTy);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005319
Fariborz Jahanian279eda62009-01-21 22:04:16 +00005320 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005321 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
5322
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005323 // struct _prop_t {
5324 // char *name;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005325 // char *attributes;
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005326 // }
Chris Lattner5ec04a52011-08-12 17:43:31 +00005327 PropertyTy = llvm::StructType::create("struct._prop_t",
Reid Kleckneree7cf842014-12-01 22:02:27 +00005328 Int8PtrTy, Int8PtrTy, nullptr);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005329
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005330 // struct _prop_list_t {
Fariborz Jahanian0232c052009-01-23 01:46:23 +00005331 // uint32_t entsize; // sizeof(struct _prop_t)
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005332 // uint32_t count_of_properties;
Fariborz Jahanian0232c052009-01-23 01:46:23 +00005333 // struct _prop_t prop_list[count_of_properties];
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005334 // }
Chris Lattnera5f58b02011-07-09 17:41:47 +00005335 PropertyListTy =
Chris Lattner5ec04a52011-08-12 17:43:31 +00005336 llvm::StructType::create("struct._prop_list_t", IntTy, IntTy,
Reid Kleckneree7cf842014-12-01 22:02:27 +00005337 llvm::ArrayType::get(PropertyTy, 0), nullptr);
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005338 // struct _prop_list_t *
Owen Anderson9793f0e2009-07-29 22:16:19 +00005339 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005340
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005341 // struct _objc_method {
5342 // SEL _cmd;
5343 // char *method_type;
5344 // char *_imp;
5345 // }
Chris Lattner5ec04a52011-08-12 17:43:31 +00005346 MethodTy = llvm::StructType::create("struct._objc_method",
5347 SelectorPtrTy, Int8PtrTy, Int8PtrTy,
Reid Kleckneree7cf842014-12-01 22:02:27 +00005348 nullptr);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005349
Fariborz Jahanian0232c052009-01-23 01:46:23 +00005350 // struct _objc_cache *
Chris Lattner5ec04a52011-08-12 17:43:31 +00005351 CacheTy = llvm::StructType::create(VMContext, "struct._objc_cache");
Owen Anderson9793f0e2009-07-29 22:16:19 +00005352 CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
Fariborz Jahanian279eda62009-01-21 22:04:16 +00005353}
Daniel Dunbar7bd00bd2008-08-12 06:48:42 +00005354
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005355ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
Mike Stump11289f42009-09-09 15:08:12 +00005356 : ObjCCommonTypesHelper(cgm) {
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005357 // struct _objc_method_description {
5358 // SEL name;
5359 // char *types;
5360 // }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005361 MethodDescriptionTy =
Chris Lattner5ec04a52011-08-12 17:43:31 +00005362 llvm::StructType::create("struct._objc_method_description",
Reid Kleckneree7cf842014-12-01 22:02:27 +00005363 SelectorPtrTy, Int8PtrTy, nullptr);
Daniel Dunbarb036db82008-08-13 03:21:16 +00005364
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005365 // struct _objc_method_description_list {
5366 // int count;
5367 // struct _objc_method_description[1];
5368 // }
Reid Kleckneree7cf842014-12-01 22:02:27 +00005369 MethodDescriptionListTy = llvm::StructType::create(
5370 "struct._objc_method_description_list", IntTy,
5371 llvm::ArrayType::get(MethodDescriptionTy, 0), nullptr);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005372
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005373 // struct _objc_method_description_list *
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005374 MethodDescriptionListPtrTy =
Owen Anderson9793f0e2009-07-29 22:16:19 +00005375 llvm::PointerType::getUnqual(MethodDescriptionListTy);
Daniel Dunbarb036db82008-08-13 03:21:16 +00005376
Daniel Dunbarb036db82008-08-13 03:21:16 +00005377 // Protocol description structures
5378
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005379 // struct _objc_protocol_extension {
5380 // uint32_t size; // sizeof(struct _objc_protocol_extension)
5381 // struct _objc_method_description_list *optional_instance_methods;
5382 // struct _objc_method_description_list *optional_class_methods;
5383 // struct _objc_property_list *instance_properties;
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005384 // const char ** extendedMethodTypes;
Manman Rence7bff52016-01-29 23:46:55 +00005385 // struct _objc_property_list *class_properties;
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005386 // }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005387 ProtocolExtensionTy =
Chris Lattner5ec04a52011-08-12 17:43:31 +00005388 llvm::StructType::create("struct._objc_protocol_extension",
5389 IntTy, MethodDescriptionListPtrTy,
5390 MethodDescriptionListPtrTy, PropertyListPtrTy,
Manman Rence7bff52016-01-29 23:46:55 +00005391 Int8PtrPtrTy, PropertyListPtrTy, nullptr);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005392
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005393 // struct _objc_protocol_extension *
Owen Anderson9793f0e2009-07-29 22:16:19 +00005394 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
Daniel Dunbarb036db82008-08-13 03:21:16 +00005395
Daniel Dunbarc475d422008-10-29 22:36:39 +00005396 // Handle recursive construction of Protocol and ProtocolList types
Daniel Dunbarb036db82008-08-13 03:21:16 +00005397
Chris Lattnera5f58b02011-07-09 17:41:47 +00005398 ProtocolTy =
Chris Lattner5ec04a52011-08-12 17:43:31 +00005399 llvm::StructType::create(VMContext, "struct._objc_protocol");
Daniel Dunbarb036db82008-08-13 03:21:16 +00005400
Chris Lattnera5f58b02011-07-09 17:41:47 +00005401 ProtocolListTy =
Chris Lattner5ec04a52011-08-12 17:43:31 +00005402 llvm::StructType::create(VMContext, "struct._objc_protocol_list");
Chris Lattnera5f58b02011-07-09 17:41:47 +00005403 ProtocolListTy->setBody(llvm::PointerType::getUnqual(ProtocolListTy),
Fariborz Jahanian279eda62009-01-21 22:04:16 +00005404 LongTy,
Chris Lattnera5f58b02011-07-09 17:41:47 +00005405 llvm::ArrayType::get(ProtocolTy, 0),
Reid Kleckneree7cf842014-12-01 22:02:27 +00005406 nullptr);
Daniel Dunbarb036db82008-08-13 03:21:16 +00005407
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005408 // struct _objc_protocol {
5409 // struct _objc_protocol_extension *isa;
5410 // char *protocol_name;
5411 // struct _objc_protocol **_objc_protocol_list;
5412 // struct _objc_method_description_list *instance_methods;
5413 // struct _objc_method_description_list *class_methods;
5414 // }
Chris Lattnera5f58b02011-07-09 17:41:47 +00005415 ProtocolTy->setBody(ProtocolExtensionPtrTy, Int8PtrTy,
5416 llvm::PointerType::getUnqual(ProtocolListTy),
5417 MethodDescriptionListPtrTy,
5418 MethodDescriptionListPtrTy,
Reid Kleckneree7cf842014-12-01 22:02:27 +00005419 nullptr);
Daniel Dunbarb036db82008-08-13 03:21:16 +00005420
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005421 // struct _objc_protocol_list *
Owen Anderson9793f0e2009-07-29 22:16:19 +00005422 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
Daniel Dunbarb036db82008-08-13 03:21:16 +00005423
Owen Anderson9793f0e2009-07-29 22:16:19 +00005424 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00005425
5426 // Class description structures
5427
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005428 // struct _objc_ivar {
5429 // char *ivar_name;
5430 // char *ivar_type;
5431 // int ivar_offset;
5432 // }
Chris Lattner5ec04a52011-08-12 17:43:31 +00005433 IvarTy = llvm::StructType::create("struct._objc_ivar",
Reid Kleckneree7cf842014-12-01 22:02:27 +00005434 Int8PtrTy, Int8PtrTy, IntTy, nullptr);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00005435
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005436 // struct _objc_ivar_list *
Chris Lattnera5f58b02011-07-09 17:41:47 +00005437 IvarListTy =
Chris Lattner5ec04a52011-08-12 17:43:31 +00005438 llvm::StructType::create(VMContext, "struct._objc_ivar_list");
Owen Anderson9793f0e2009-07-29 22:16:19 +00005439 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00005440
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005441 // struct _objc_method_list *
Chris Lattnera5f58b02011-07-09 17:41:47 +00005442 MethodListTy =
Chris Lattner5ec04a52011-08-12 17:43:31 +00005443 llvm::StructType::create(VMContext, "struct._objc_method_list");
Owen Anderson9793f0e2009-07-29 22:16:19 +00005444 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00005445
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005446 // struct _objc_class_extension *
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005447 ClassExtensionTy =
Chris Lattner5ec04a52011-08-12 17:43:31 +00005448 llvm::StructType::create("struct._objc_class_extension",
Reid Kleckneree7cf842014-12-01 22:02:27 +00005449 IntTy, Int8PtrTy, PropertyListPtrTy, nullptr);
Owen Anderson9793f0e2009-07-29 22:16:19 +00005450 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00005451
Chris Lattner5ec04a52011-08-12 17:43:31 +00005452 ClassTy = llvm::StructType::create(VMContext, "struct._objc_class");
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00005453
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005454 // struct _objc_class {
5455 // Class isa;
5456 // Class super_class;
5457 // char *name;
5458 // long version;
5459 // long info;
5460 // long instance_size;
5461 // struct _objc_ivar_list *ivars;
5462 // struct _objc_method_list *methods;
5463 // struct _objc_cache *cache;
5464 // struct _objc_protocol_list *protocols;
5465 // char *ivar_layout;
5466 // struct _objc_class_ext *ext;
5467 // };
Chris Lattnera5f58b02011-07-09 17:41:47 +00005468 ClassTy->setBody(llvm::PointerType::getUnqual(ClassTy),
5469 llvm::PointerType::getUnqual(ClassTy),
5470 Int8PtrTy,
5471 LongTy,
5472 LongTy,
5473 LongTy,
5474 IvarListPtrTy,
5475 MethodListPtrTy,
5476 CachePtrTy,
5477 ProtocolListPtrTy,
5478 Int8PtrTy,
5479 ClassExtensionPtrTy,
Reid Kleckneree7cf842014-12-01 22:02:27 +00005480 nullptr);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005481
Owen Anderson9793f0e2009-07-29 22:16:19 +00005482 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00005483
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005484 // struct _objc_category {
5485 // char *category_name;
5486 // char *class_name;
5487 // struct _objc_method_list *instance_method;
5488 // struct _objc_method_list *class_method;
Manman Renb3736772016-01-25 22:37:47 +00005489 // struct _objc_protocol_list *protocols;
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005490 // uint32_t size; // sizeof(struct _objc_category)
5491 // struct _objc_property_list *instance_properties;// category's @property
Manman Ren96df0b32016-01-29 23:45:01 +00005492 // struct _objc_property_list *class_properties;
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005493 // }
Chris Lattnera5f58b02011-07-09 17:41:47 +00005494 CategoryTy =
Chris Lattner5ec04a52011-08-12 17:43:31 +00005495 llvm::StructType::create("struct._objc_category",
5496 Int8PtrTy, Int8PtrTy, MethodListPtrTy,
5497 MethodListPtrTy, ProtocolListPtrTy,
Manman Ren96df0b32016-01-29 23:45:01 +00005498 IntTy, PropertyListPtrTy, PropertyListPtrTy,
5499 nullptr);
Daniel Dunbar938a77f2008-08-22 20:34:54 +00005500
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00005501 // Global metadata structures
5502
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005503 // struct _objc_symtab {
5504 // long sel_ref_cnt;
5505 // SEL *refs;
5506 // short cls_def_cnt;
5507 // short cat_def_cnt;
5508 // char *defs[cls_def_cnt + cat_def_cnt];
5509 // }
Chris Lattnera5f58b02011-07-09 17:41:47 +00005510 SymtabTy =
Chris Lattner5ec04a52011-08-12 17:43:31 +00005511 llvm::StructType::create("struct._objc_symtab",
5512 LongTy, SelectorPtrTy, ShortTy, ShortTy,
Reid Kleckneree7cf842014-12-01 22:02:27 +00005513 llvm::ArrayType::get(Int8PtrTy, 0), nullptr);
Owen Anderson9793f0e2009-07-29 22:16:19 +00005514 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00005515
Fariborz Jahanianeee54df2009-01-22 00:37:21 +00005516 // struct _objc_module {
5517 // long version;
5518 // long size; // sizeof(struct _objc_module)
5519 // char *name;
5520 // struct _objc_symtab* symtab;
5521 // }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005522 ModuleTy =
Chris Lattner5ec04a52011-08-12 17:43:31 +00005523 llvm::StructType::create("struct._objc_module",
Reid Kleckneree7cf842014-12-01 22:02:27 +00005524 LongTy, LongTy, Int8PtrTy, SymtabPtrTy, nullptr);
Daniel Dunbar97ff50d2008-08-23 09:25:55 +00005525
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005526
Mike Stump18bb9282009-05-16 07:57:57 +00005527 // FIXME: This is the size of the setjmp buffer and should be target
5528 // specific. 18 is what's used on 32-bit X86.
Anders Carlsson9ff22482008-09-09 10:10:21 +00005529 uint64_t SetJmpBufferSize = 18;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005530
Anders Carlsson9ff22482008-09-09 10:10:21 +00005531 // Exceptions
Chris Lattnerece04092012-02-07 00:39:47 +00005532 llvm::Type *StackPtrTy = llvm::ArrayType::get(CGM.Int8PtrTy, 4);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005533
5534 ExceptionDataTy =
Chris Lattner5ec04a52011-08-12 17:43:31 +00005535 llvm::StructType::create("struct._objc_exception_data",
Chris Lattnerece04092012-02-07 00:39:47 +00005536 llvm::ArrayType::get(CGM.Int32Ty,SetJmpBufferSize),
Reid Kleckneree7cf842014-12-01 22:02:27 +00005537 StackPtrTy, nullptr);
Daniel Dunbar8b8683f2008-08-12 00:12:39 +00005538}
5539
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005540ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm)
Mike Stump11289f42009-09-09 15:08:12 +00005541 : ObjCCommonTypesHelper(cgm) {
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005542 // struct _method_list_t {
5543 // uint32_t entsize; // sizeof(struct _objc_method)
5544 // uint32_t method_count;
5545 // struct _objc_method method_list[method_count];
5546 // }
Chris Lattnera5f58b02011-07-09 17:41:47 +00005547 MethodListnfABITy =
Chris Lattner5ec04a52011-08-12 17:43:31 +00005548 llvm::StructType::create("struct.__method_list_t", IntTy, IntTy,
Reid Kleckneree7cf842014-12-01 22:02:27 +00005549 llvm::ArrayType::get(MethodTy, 0), nullptr);
Fariborz Jahanian0232c052009-01-23 01:46:23 +00005550 // struct method_list_t *
Owen Anderson9793f0e2009-07-29 22:16:19 +00005551 MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005552
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005553 // struct _protocol_t {
5554 // id isa; // NULL
5555 // const char * const protocol_name;
Fariborz Jahanian0232c052009-01-23 01:46:23 +00005556 // const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005557 // const struct method_list_t * const instance_methods;
5558 // const struct method_list_t * const class_methods;
5559 // const struct method_list_t *optionalInstanceMethods;
5560 // const struct method_list_t *optionalClassMethods;
Fariborz Jahanian0232c052009-01-23 01:46:23 +00005561 // const struct _prop_list_t * properties;
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005562 // const uint32_t size; // sizeof(struct _protocol_t)
5563 // const uint32_t flags; // = 0
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005564 // const char ** extendedMethodTypes;
Fariborz Jahanian6a9c46b2015-03-31 22:22:40 +00005565 // const char *demangledName;
Manman Rence7bff52016-01-29 23:46:55 +00005566 // const struct _prop_list_t * class_properties;
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005567 // }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005568
Fariborz Jahanian0232c052009-01-23 01:46:23 +00005569 // Holder for struct _protocol_list_t *
Chris Lattnera5f58b02011-07-09 17:41:47 +00005570 ProtocolListnfABITy =
Chris Lattner5ec04a52011-08-12 17:43:31 +00005571 llvm::StructType::create(VMContext, "struct._objc_protocol_list");
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005572
Chris Lattnera5f58b02011-07-09 17:41:47 +00005573 ProtocolnfABITy =
Chris Lattner5ec04a52011-08-12 17:43:31 +00005574 llvm::StructType::create("struct._protocol_t", ObjectPtrTy, Int8PtrTy,
5575 llvm::PointerType::getUnqual(ProtocolListnfABITy),
5576 MethodListnfABIPtrTy, MethodListnfABIPtrTy,
5577 MethodListnfABIPtrTy, MethodListnfABIPtrTy,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005578 PropertyListPtrTy, IntTy, IntTy, Int8PtrPtrTy,
Manman Rence7bff52016-01-29 23:46:55 +00005579 Int8PtrTy, PropertyListPtrTy,
Reid Kleckneree7cf842014-12-01 22:02:27 +00005580 nullptr);
Daniel Dunbar8de90f02009-02-15 07:36:20 +00005581
5582 // struct _protocol_t*
Owen Anderson9793f0e2009-07-29 22:16:19 +00005583 ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005584
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00005585 // struct _protocol_list_t {
Fariborz Jahanian0232c052009-01-23 01:46:23 +00005586 // long protocol_count; // Note, this is 32/64 bit
Daniel Dunbar8de90f02009-02-15 07:36:20 +00005587 // struct _protocol_t *[protocol_count];
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005588 // }
Chris Lattnera5f58b02011-07-09 17:41:47 +00005589 ProtocolListnfABITy->setBody(LongTy,
5590 llvm::ArrayType::get(ProtocolnfABIPtrTy, 0),
Reid Kleckneree7cf842014-12-01 22:02:27 +00005591 nullptr);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005592
Fariborz Jahanian0232c052009-01-23 01:46:23 +00005593 // struct _objc_protocol_list*
Owen Anderson9793f0e2009-07-29 22:16:19 +00005594 ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005595
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005596 // struct _ivar_t {
Tim Northover238b5082014-03-29 13:42:40 +00005597 // unsigned [long] int *offset; // pointer to ivar offset location
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005598 // char *name;
5599 // char *type;
5600 // uint32_t alignment;
5601 // uint32_t size;
5602 // }
Tim Northover238b5082014-03-29 13:42:40 +00005603 IvarnfABITy = llvm::StructType::create(
5604 "struct._ivar_t", llvm::PointerType::getUnqual(IvarOffsetVarTy),
Reid Kleckneree7cf842014-12-01 22:02:27 +00005605 Int8PtrTy, Int8PtrTy, IntTy, IntTy, nullptr);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005606
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005607 // struct _ivar_list_t {
5608 // uint32 entsize; // sizeof(struct _ivar_t)
5609 // uint32 count;
5610 // struct _iver_t list[count];
5611 // }
Chris Lattnera5f58b02011-07-09 17:41:47 +00005612 IvarListnfABITy =
Chris Lattner5ec04a52011-08-12 17:43:31 +00005613 llvm::StructType::create("struct._ivar_list_t", IntTy, IntTy,
Reid Kleckneree7cf842014-12-01 22:02:27 +00005614 llvm::ArrayType::get(IvarnfABITy, 0), nullptr);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005615
Owen Anderson9793f0e2009-07-29 22:16:19 +00005616 IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005617
Fariborz Jahanian0232c052009-01-23 01:46:23 +00005618 // struct _class_ro_t {
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005619 // uint32_t const flags;
5620 // uint32_t const instanceStart;
5621 // uint32_t const instanceSize;
5622 // uint32_t const reserved; // only when building for 64bit targets
5623 // const uint8_t * const ivarLayout;
5624 // const char *const name;
5625 // const struct _method_list_t * const baseMethods;
5626 // const struct _objc_protocol_list *const baseProtocols;
5627 // const struct _ivar_list_t *const ivars;
5628 // const uint8_t * const weakIvarLayout;
5629 // const struct _prop_list_t * const properties;
5630 // }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005631
Fariborz Jahanian0232c052009-01-23 01:46:23 +00005632 // FIXME. Add 'reserved' field in 64bit abi mode!
Chris Lattner5ec04a52011-08-12 17:43:31 +00005633 ClassRonfABITy = llvm::StructType::create("struct._class_ro_t",
5634 IntTy, IntTy, IntTy, Int8PtrTy,
5635 Int8PtrTy, MethodListnfABIPtrTy,
5636 ProtocolListnfABIPtrTy,
5637 IvarListnfABIPtrTy,
Reid Kleckneree7cf842014-12-01 22:02:27 +00005638 Int8PtrTy, PropertyListPtrTy,
5639 nullptr);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005640
Fariborz Jahanian0232c052009-01-23 01:46:23 +00005641 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
Chris Lattnera5f58b02011-07-09 17:41:47 +00005642 llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy };
John McCall9dc0db22011-05-15 01:53:33 +00005643 ImpnfABITy = llvm::FunctionType::get(ObjectPtrTy, params, false)
5644 ->getPointerTo();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005645
Fariborz Jahanian0232c052009-01-23 01:46:23 +00005646 // struct _class_t {
5647 // struct _class_t *isa;
5648 // struct _class_t * const superclass;
5649 // void *cache;
5650 // IMP *vtable;
5651 // struct class_ro_t *ro;
5652 // }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005653
Chris Lattner5ec04a52011-08-12 17:43:31 +00005654 ClassnfABITy = llvm::StructType::create(VMContext, "struct._class_t");
Chris Lattnera5f58b02011-07-09 17:41:47 +00005655 ClassnfABITy->setBody(llvm::PointerType::getUnqual(ClassnfABITy),
5656 llvm::PointerType::getUnqual(ClassnfABITy),
5657 CachePtrTy,
5658 llvm::PointerType::getUnqual(ImpnfABITy),
5659 llvm::PointerType::getUnqual(ClassRonfABITy),
Reid Kleckneree7cf842014-12-01 22:02:27 +00005660 nullptr);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005661
Fariborz Jahanian71394042009-01-23 23:53:38 +00005662 // LLVM for struct _class_t *
Owen Anderson9793f0e2009-07-29 22:16:19 +00005663 ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005664
Fariborz Jahanian0232c052009-01-23 01:46:23 +00005665 // struct _category_t {
5666 // const char * const name;
5667 // struct _class_t *const cls;
5668 // const struct _method_list_t * const instance_methods;
5669 // const struct _method_list_t * const class_methods;
5670 // const struct _protocol_list_t * const protocols;
5671 // const struct _prop_list_t * const properties;
Manman Ren96df0b32016-01-29 23:45:01 +00005672 // const struct _prop_list_t * const class_properties;
Manman Ren42ff3902016-02-24 17:49:50 +00005673 // const uint32_t size;
Fariborz Jahanian5a63e4c2009-01-23 17:41:22 +00005674 // }
Chris Lattner5ec04a52011-08-12 17:43:31 +00005675 CategorynfABITy = llvm::StructType::create("struct._category_t",
5676 Int8PtrTy, ClassnfABIPtrTy,
5677 MethodListnfABIPtrTy,
5678 MethodListnfABIPtrTy,
5679 ProtocolListnfABIPtrTy,
5680 PropertyListPtrTy,
Manman Ren96df0b32016-01-29 23:45:01 +00005681 PropertyListPtrTy,
Manman Ren42ff3902016-02-24 17:49:50 +00005682 IntTy,
Reid Kleckneree7cf842014-12-01 22:02:27 +00005683 nullptr);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005684
Fariborz Jahanian82c72e12009-02-03 23:49:23 +00005685 // New types for nonfragile abi messaging.
Fariborz Jahaniane4dc35d2009-02-04 20:42:28 +00005686 CodeGen::CodeGenTypes &Types = CGM.getTypes();
5687 ASTContext &Ctx = CGM.getContext();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005688
Fariborz Jahanian82c72e12009-02-03 23:49:23 +00005689 // MessageRefTy - LLVM for:
5690 // struct _message_ref_t {
5691 // IMP messenger;
5692 // SEL name;
5693 // };
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005694
Fariborz Jahaniane4dc35d2009-02-04 20:42:28 +00005695 // First the clang type for struct _message_ref_t
Abramo Bagnara6150c882010-05-11 21:36:43 +00005696 RecordDecl *RD = RecordDecl::Create(Ctx, TTK_Struct,
Daniel Dunbar0c005372010-04-29 16:29:11 +00005697 Ctx.getTranslationUnitDecl(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00005698 SourceLocation(), SourceLocation(),
Fariborz Jahaniane4dc35d2009-02-04 20:42:28 +00005699 &Ctx.Idents.get("_message_ref_t"));
Craig Topper8a13c412014-05-21 05:09:00 +00005700 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), SourceLocation(),
5701 nullptr, Ctx.VoidPtrTy, nullptr, nullptr, false,
Richard Smith2b013182012-06-10 03:12:00 +00005702 ICIS_NoInit));
Craig Topper8a13c412014-05-21 05:09:00 +00005703 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), SourceLocation(),
5704 nullptr, Ctx.getObjCSelType(), nullptr, nullptr,
5705 false, ICIS_NoInit));
Douglas Gregord5058122010-02-11 01:19:42 +00005706 RD->completeDefinition();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005707
Fariborz Jahaniane4dc35d2009-02-04 20:42:28 +00005708 MessageRefCTy = Ctx.getTagDeclType(RD);
5709 MessageRefCPtrTy = Ctx.getPointerType(MessageRefCTy);
5710 MessageRefTy = cast<llvm::StructType>(Types.ConvertType(MessageRefCTy));
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005711
Fariborz Jahanian82c72e12009-02-03 23:49:23 +00005712 // MessageRefPtrTy - LLVM for struct _message_ref_t*
Owen Anderson9793f0e2009-07-29 22:16:19 +00005713 MessageRefPtrTy = llvm::PointerType::getUnqual(MessageRefTy);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005714
Fariborz Jahanian82c72e12009-02-03 23:49:23 +00005715 // SuperMessageRefTy - LLVM for:
5716 // struct _super_message_ref_t {
5717 // SUPER_IMP messenger;
5718 // SEL name;
5719 // };
Chris Lattnera5f58b02011-07-09 17:41:47 +00005720 SuperMessageRefTy =
Chris Lattner5ec04a52011-08-12 17:43:31 +00005721 llvm::StructType::create("struct._super_message_ref_t",
Reid Kleckneree7cf842014-12-01 22:02:27 +00005722 ImpnfABITy, SelectorPtrTy, nullptr);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005723
Fariborz Jahanian82c72e12009-02-03 23:49:23 +00005724 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005725 SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy);
Fariborz Jahanian0a3cfcc2011-06-22 20:21:51 +00005726
Daniel Dunbarb1559a42009-03-01 04:46:24 +00005727
5728 // struct objc_typeinfo {
5729 // const void** vtable; // objc_ehtype_vtable + 2
5730 // const char* name; // c++ typeinfo string
5731 // Class cls;
5732 // };
Chris Lattnera5f58b02011-07-09 17:41:47 +00005733 EHTypeTy =
Chris Lattner5ec04a52011-08-12 17:43:31 +00005734 llvm::StructType::create("struct._objc_typeinfo",
5735 llvm::PointerType::getUnqual(Int8PtrTy),
Reid Kleckneree7cf842014-12-01 22:02:27 +00005736 Int8PtrTy, ClassnfABIPtrTy, nullptr);
Owen Anderson9793f0e2009-07-29 22:16:19 +00005737 EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy);
Daniel Dunbar8b8683f2008-08-12 00:12:39 +00005738}
5739
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005740llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() {
Fariborz Jahanian71394042009-01-23 23:53:38 +00005741 FinishNonFragileABIModule();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005742
Craig Topper8a13c412014-05-21 05:09:00 +00005743 return nullptr;
Fariborz Jahanian71394042009-01-23 23:53:38 +00005744}
5745
Saleem Abdulrasool1e6c4062016-05-16 05:06:49 +00005746void CGObjCNonFragileABIMac::AddModuleClassList(
5747 ArrayRef<llvm::GlobalValue *> Container, StringRef SymbolName,
5748 StringRef SectionName) {
Daniel Dunbar19573e72009-05-15 21:48:48 +00005749 unsigned NumClasses = Container.size();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005750
Daniel Dunbar19573e72009-05-15 21:48:48 +00005751 if (!NumClasses)
5752 return;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005753
Chris Lattner3def9ae2012-02-06 22:16:34 +00005754 SmallVector<llvm::Constant*, 8> Symbols(NumClasses);
Daniel Dunbar19573e72009-05-15 21:48:48 +00005755 for (unsigned i=0; i<NumClasses; i++)
Owen Andersonade90fd2009-07-29 18:54:39 +00005756 Symbols[i] = llvm::ConstantExpr::getBitCast(Container[i],
Daniel Dunbar19573e72009-05-15 21:48:48 +00005757 ObjCTypes.Int8PtrTy);
Chris Lattner3def9ae2012-02-06 22:16:34 +00005758 llvm::Constant *Init =
Owen Anderson9793f0e2009-07-29 22:16:19 +00005759 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Chris Lattner3def9ae2012-02-06 22:16:34 +00005760 Symbols.size()),
Daniel Dunbar19573e72009-05-15 21:48:48 +00005761 Symbols);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005762
Daniel Dunbar19573e72009-05-15 21:48:48 +00005763 llvm::GlobalVariable *GV =
Owen Andersonc10c8d32009-07-08 19:05:04 +00005764 new llvm::GlobalVariable(CGM.getModule(), Init->getType(), false,
Rafael Espindola5179a4e2014-02-27 19:01:11 +00005765 llvm::GlobalValue::PrivateLinkage,
Daniel Dunbar19573e72009-05-15 21:48:48 +00005766 Init,
Owen Andersonc10c8d32009-07-08 19:05:04 +00005767 SymbolName);
Micah Villmowdd31ca12012-10-08 16:25:52 +00005768 GV->setAlignment(CGM.getDataLayout().getABITypeAlignment(Init->getType()));
Daniel Dunbar19573e72009-05-15 21:48:48 +00005769 GV->setSection(SectionName);
Rafael Espindola060062a2014-03-06 22:15:10 +00005770 CGM.addCompilerUsedGlobal(GV);
Daniel Dunbar19573e72009-05-15 21:48:48 +00005771}
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005772
Fariborz Jahanian71394042009-01-23 23:53:38 +00005773void CGObjCNonFragileABIMac::FinishNonFragileABIModule() {
5774 // nonfragile abi has no module definition.
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005775
Daniel Dunbar19573e72009-05-15 21:48:48 +00005776 // Build list of all implemented class addresses in array
Fariborz Jahanian279abd32009-01-30 20:55:31 +00005777 // L_OBJC_LABEL_CLASS_$.
Fariborz Jahanianf322f2f2014-03-11 00:25:05 +00005778
5779 for (unsigned i=0, NumClasses=ImplementedClasses.size(); i<NumClasses; i++) {
5780 const ObjCInterfaceDecl *ID = ImplementedClasses[i];
5781 assert(ID);
5782 if (ObjCImplementationDecl *IMP = ID->getImplementation())
5783 // We are implementing a weak imported interface. Give it external linkage
Fariborz Jahanianbc94c942014-07-15 17:14:34 +00005784 if (ID->isWeakImported() && !IMP->isWeakImported()) {
Fariborz Jahanianf322f2f2014-03-11 00:25:05 +00005785 DefinedClasses[i]->setLinkage(llvm::GlobalVariable::ExternalLinkage);
Fariborz Jahanianbc94c942014-07-15 17:14:34 +00005786 DefinedMetaClasses[i]->setLinkage(llvm::GlobalVariable::ExternalLinkage);
5787 }
Fariborz Jahanianf322f2f2014-03-11 00:25:05 +00005788 }
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00005789
5790 AddModuleClassList(DefinedClasses, "OBJC_LABEL_CLASS_$",
Daniel Dunbar19573e72009-05-15 21:48:48 +00005791 "__DATA, __objc_classlist, regular, no_dead_strip");
Rafael Espindola554256c2014-02-26 22:25:45 +00005792
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00005793 AddModuleClassList(DefinedNonLazyClasses, "OBJC_LABEL_NONLAZY_CLASS_$",
Daniel Dunbar9a017d72009-05-15 22:33:15 +00005794 "__DATA, __objc_nlclslist, regular, no_dead_strip");
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005795
Fariborz Jahanian279abd32009-01-30 20:55:31 +00005796 // Build list of all implemented category addresses in array
5797 // L_OBJC_LABEL_CATEGORY_$.
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00005798 AddModuleClassList(DefinedCategories, "OBJC_LABEL_CATEGORY_$",
Daniel Dunbar19573e72009-05-15 21:48:48 +00005799 "__DATA, __objc_catlist, regular, no_dead_strip");
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00005800 AddModuleClassList(DefinedNonLazyCategories, "OBJC_LABEL_NONLAZY_CATEGORY_$",
Daniel Dunbar9a017d72009-05-15 22:33:15 +00005801 "__DATA, __objc_nlcatlist, regular, no_dead_strip");
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005802
Daniel Dunbar5e639272010-04-25 20:39:01 +00005803 EmitImageInfo();
Fariborz Jahanian71394042009-01-23 23:53:38 +00005804}
5805
John McCall9e8bb002011-05-14 03:10:52 +00005806/// isVTableDispatchedSelector - Returns true if SEL is not in the list of
5807/// VTableDispatchMethods; false otherwise. What this means is that
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005808/// except for the 19 selectors in the list, we generate 32bit-style
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +00005809/// message dispatch call for all the rest.
John McCall9e8bb002011-05-14 03:10:52 +00005810bool CGObjCNonFragileABIMac::isVTableDispatchedSelector(Selector Sel) {
5811 // At various points we've experimented with using vtable-based
5812 // dispatch for all methods.
Daniel Dunbarfca18c1b42010-04-24 17:56:46 +00005813 switch (CGM.getCodeGenOpts().getObjCDispatchMethod()) {
Daniel Dunbarfca18c1b42010-04-24 17:56:46 +00005814 case CodeGenOptions::Legacy:
Fariborz Jahaniandfb39832010-04-19 17:53:30 +00005815 return false;
John McCall9e8bb002011-05-14 03:10:52 +00005816 case CodeGenOptions::NonLegacy:
5817 return true;
Daniel Dunbarfca18c1b42010-04-24 17:56:46 +00005818 case CodeGenOptions::Mixed:
5819 break;
5820 }
5821
5822 // If so, see whether this selector is in the white-list of things which must
5823 // use the new dispatch convention. We lazily build a dense set for this.
John McCall9e8bb002011-05-14 03:10:52 +00005824 if (VTableDispatchMethods.empty()) {
5825 VTableDispatchMethods.insert(GetNullarySelector("alloc"));
5826 VTableDispatchMethods.insert(GetNullarySelector("class"));
5827 VTableDispatchMethods.insert(GetNullarySelector("self"));
5828 VTableDispatchMethods.insert(GetNullarySelector("isFlipped"));
5829 VTableDispatchMethods.insert(GetNullarySelector("length"));
5830 VTableDispatchMethods.insert(GetNullarySelector("count"));
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005831
John McCall9e8bb002011-05-14 03:10:52 +00005832 // These are vtable-based if GC is disabled.
5833 // Optimistically use vtable dispatch for hybrid compiles.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005834 if (CGM.getLangOpts().getGC() != LangOptions::GCOnly) {
John McCall9e8bb002011-05-14 03:10:52 +00005835 VTableDispatchMethods.insert(GetNullarySelector("retain"));
5836 VTableDispatchMethods.insert(GetNullarySelector("release"));
5837 VTableDispatchMethods.insert(GetNullarySelector("autorelease"));
5838 }
5839
5840 VTableDispatchMethods.insert(GetUnarySelector("allocWithZone"));
5841 VTableDispatchMethods.insert(GetUnarySelector("isKindOfClass"));
5842 VTableDispatchMethods.insert(GetUnarySelector("respondsToSelector"));
5843 VTableDispatchMethods.insert(GetUnarySelector("objectForKey"));
5844 VTableDispatchMethods.insert(GetUnarySelector("objectAtIndex"));
5845 VTableDispatchMethods.insert(GetUnarySelector("isEqualToString"));
5846 VTableDispatchMethods.insert(GetUnarySelector("isEqual"));
5847
5848 // These are vtable-based if GC is enabled.
5849 // Optimistically use vtable dispatch for hybrid compiles.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005850 if (CGM.getLangOpts().getGC() != LangOptions::NonGC) {
John McCall9e8bb002011-05-14 03:10:52 +00005851 VTableDispatchMethods.insert(GetNullarySelector("hash"));
5852 VTableDispatchMethods.insert(GetUnarySelector("addObject"));
5853
5854 // "countByEnumeratingWithState:objects:count"
5855 IdentifierInfo *KeyIdents[] = {
5856 &CGM.getContext().Idents.get("countByEnumeratingWithState"),
5857 &CGM.getContext().Idents.get("objects"),
5858 &CGM.getContext().Idents.get("count")
5859 };
5860 VTableDispatchMethods.insert(
5861 CGM.getContext().Selectors.getSelector(3, KeyIdents));
5862 }
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +00005863 }
Daniel Dunbarfca18c1b42010-04-24 17:56:46 +00005864
John McCall9e8bb002011-05-14 03:10:52 +00005865 return VTableDispatchMethods.count(Sel);
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +00005866}
5867
Fariborz Jahanian9e3ad522009-01-24 20:21:50 +00005868/// BuildClassRoTInitializer - generate meta-data for:
5869/// struct _class_ro_t {
5870/// uint32_t const flags;
5871/// uint32_t const instanceStart;
5872/// uint32_t const instanceSize;
5873/// uint32_t const reserved; // only when building for 64bit targets
5874/// const uint8_t * const ivarLayout;
5875/// const char *const name;
5876/// const struct _method_list_t * const baseMethods;
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00005877/// const struct _protocol_list_t *const baseProtocols;
Fariborz Jahanian9e3ad522009-01-24 20:21:50 +00005878/// const struct _ivar_list_t *const ivars;
5879/// const uint8_t * const weakIvarLayout;
5880/// const struct _prop_list_t * const properties;
5881/// }
5882///
5883llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer(
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005884 unsigned flags,
5885 unsigned InstanceStart,
5886 unsigned InstanceSize,
5887 const ObjCImplementationDecl *ID) {
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00005888 std::string ClassName = ID->getObjCRuntimeNameAsString();
Benjamin Kramer22d24c22011-10-15 12:20:02 +00005889 llvm::Constant *Values[10]; // 11 for 64bit targets!
John McCall31168b02011-06-15 23:02:42 +00005890
John McCall3fd13f062015-10-21 18:06:47 +00005891 CharUnits beginInstance = CharUnits::fromQuantity(InstanceStart);
5892 CharUnits endInstance = CharUnits::fromQuantity(InstanceSize);
5893
John McCall460ce582015-10-22 18:38:17 +00005894 bool hasMRCWeak = false;
David Blaikiebbafb8a2012-03-11 07:00:24 +00005895 if (CGM.getLangOpts().ObjCAutoRefCount)
John McCallef19dbb2012-10-17 04:53:23 +00005896 flags |= NonFragileABI_Class_CompiledByARC;
John McCall460ce582015-10-22 18:38:17 +00005897 else if ((hasMRCWeak = hasMRCWeakIvars(CGM, ID)))
5898 flags |= NonFragileABI_Class_HasMRCWeakIvars;
John McCall31168b02011-06-15 23:02:42 +00005899
Owen Andersonb7a2fe62009-07-24 23:12:58 +00005900 Values[ 0] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
5901 Values[ 1] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceStart);
5902 Values[ 2] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceSize);
Fariborz Jahanian9e3ad522009-01-24 20:21:50 +00005903 // FIXME. For 64bit targets add 0 here.
John McCallef19dbb2012-10-17 04:53:23 +00005904 Values[ 3] = (flags & NonFragileABI_Class_Meta)
Craig Topper8a13c412014-05-21 05:09:00 +00005905 ? GetIvarLayoutName(nullptr, ObjCTypes)
John McCall460ce582015-10-22 18:38:17 +00005906 : BuildStrongIvarLayout(ID, beginInstance, endInstance);
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00005907 Values[ 4] = GetClassName(ID->getObjCRuntimeNameAsString());
Fariborz Jahanian99113fd2009-01-26 21:38:32 +00005908 // const struct _method_list_t * const baseMethods;
5909 std::vector<llvm::Constant*> Methods;
John McCallef19dbb2012-10-17 04:53:23 +00005910 if (flags & NonFragileABI_Class_Meta) {
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00005911 for (const auto *I : ID->class_methods())
Fariborz Jahanian99113fd2009-01-26 21:38:32 +00005912 // Class methods should always be defined.
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00005913 Methods.push_back(GetMethodConstant(I));
Fariborz Jahanian99113fd2009-01-26 21:38:32 +00005914 } else {
Aaron Ballmanf26acce2014-03-13 19:50:17 +00005915 for (const auto *I : ID->instance_methods())
Fariborz Jahanian99113fd2009-01-26 21:38:32 +00005916 // Instance methods should always be defined.
Aaron Ballmanf26acce2014-03-13 19:50:17 +00005917 Methods.push_back(GetMethodConstant(I));
5918
Aaron Ballmand85eff42014-03-14 15:02:45 +00005919 for (const auto *PID : ID->property_impls()) {
Fariborz Jahaniand27a8202009-01-28 22:46:49 +00005920 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize){
5921 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005922
Fariborz Jahaniand27a8202009-01-28 22:46:49 +00005923 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
5924 if (llvm::Constant *C = GetMethodConstant(MD))
5925 Methods.push_back(C);
5926 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
5927 if (llvm::Constant *C = GetMethodConstant(MD))
5928 Methods.push_back(C);
5929 }
5930 }
Fariborz Jahanian99113fd2009-01-26 21:38:32 +00005931 }
Saleem Abdulrasoold48b0a32016-10-24 20:47:58 +00005932
5933 Values[ 5] = EmitMethodList(ID->getObjCRuntimeNameAsString(),
5934 (flags & NonFragileABI_Class_Meta)
5935 ? MethodListType::ClassMethods
5936 : MethodListType::InstanceMethods,
5937 Methods);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005938
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00005939 const ObjCInterfaceDecl *OID = ID->getClassInterface();
5940 assert(OID && "CGObjCNonFragileABIMac::BuildClassRoTInitializer");
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005941 Values[ 6] = EmitProtocolList("\01l_OBJC_CLASS_PROTOCOLS_$_"
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00005942 + OID->getObjCRuntimeNameAsString(),
Ted Kremenek0ef508d2010-09-01 01:21:15 +00005943 OID->all_referenced_protocol_begin(),
5944 OID->all_referenced_protocol_end());
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005945
John McCallef19dbb2012-10-17 04:53:23 +00005946 if (flags & NonFragileABI_Class_Meta) {
Owen Anderson0b75f232009-07-31 20:28:54 +00005947 Values[ 7] = llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
Craig Topper8a13c412014-05-21 05:09:00 +00005948 Values[ 8] = GetIvarLayoutName(nullptr, ObjCTypes);
Manman Renad0e7912016-01-29 19:22:54 +00005949 Values[ 9] = EmitPropertyList(
5950 "\01l_OBJC_$_CLASS_PROP_LIST_" + ID->getObjCRuntimeNameAsString(),
5951 ID, ID->getClassInterface(), ObjCTypes, true);
John McCallef19dbb2012-10-17 04:53:23 +00005952 } else {
5953 Values[ 7] = EmitIvarList(ID);
John McCall460ce582015-10-22 18:38:17 +00005954 Values[ 8] = BuildWeakIvarLayout(ID, beginInstance, endInstance,
5955 hasMRCWeak);
Manman Renad0e7912016-01-29 19:22:54 +00005956 Values[ 9] = EmitPropertyList(
5957 "\01l_OBJC_$_PROP_LIST_" + ID->getObjCRuntimeNameAsString(),
5958 ID, ID->getClassInterface(), ObjCTypes, false);
John McCallef19dbb2012-10-17 04:53:23 +00005959 }
Owen Anderson0e0189d2009-07-27 22:29:56 +00005960 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassRonfABITy,
Fariborz Jahanian9e3ad522009-01-24 20:21:50 +00005961 Values);
5962 llvm::GlobalVariable *CLASS_RO_GV =
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005963 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassRonfABITy, false,
Rafael Espindola5179a4e2014-02-27 19:01:11 +00005964 llvm::GlobalValue::PrivateLinkage,
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005965 Init,
John McCallef19dbb2012-10-17 04:53:23 +00005966 (flags & NonFragileABI_Class_Meta) ?
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005967 std::string("\01l_OBJC_METACLASS_RO_$_")+ClassName :
5968 std::string("\01l_OBJC_CLASS_RO_$_")+ClassName);
Fariborz Jahanianc22f2362009-01-31 02:43:27 +00005969 CLASS_RO_GV->setAlignment(
Micah Villmowdd31ca12012-10-08 16:25:52 +00005970 CGM.getDataLayout().getABITypeAlignment(ObjCTypes.ClassRonfABITy));
Fariborz Jahanian40a4bcd2009-01-28 01:05:23 +00005971 CLASS_RO_GV->setSection("__DATA, __objc_const");
Fariborz Jahanian9e3ad522009-01-24 20:21:50 +00005972 return CLASS_RO_GV;
Fariborz Jahanian2612e142009-01-26 22:58:07 +00005973
Fariborz Jahanian9e3ad522009-01-24 20:21:50 +00005974}
5975
5976/// BuildClassMetaData - This routine defines that to-level meta-data
5977/// for the given ClassName for:
5978/// struct _class_t {
5979/// struct _class_t *isa;
5980/// struct _class_t * const superclass;
5981/// void *cache;
5982/// IMP *vtable;
5983/// struct class_ro_t *ro;
5984/// }
5985///
Rafael Espindola554256c2014-02-26 22:25:45 +00005986llvm::GlobalVariable *CGObjCNonFragileABIMac::BuildClassMetaData(
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00005987 const std::string &ClassName, llvm::Constant *IsAGV, llvm::Constant *SuperClassGV,
Rafael Espindola554256c2014-02-26 22:25:45 +00005988 llvm::Constant *ClassRoGV, bool HiddenVisibility, bool Weak) {
Benjamin Kramer22d24c22011-10-15 12:20:02 +00005989 llvm::Constant *Values[] = {
5990 IsAGV,
5991 SuperClassGV,
5992 ObjCEmptyCacheVar, // &ObjCEmptyCacheVar
5993 ObjCEmptyVtableVar, // &ObjCEmptyVtableVar
5994 ClassRoGV // &CLASS_RO_GV
5995 };
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005996 if (!Values[1])
5997 Values[1] = llvm::Constant::getNullValue(ObjCTypes.ClassnfABIPtrTy);
Fariborz Jahanian42d49552013-10-24 17:40:28 +00005998 if (!Values[3])
5999 Values[3] = llvm::Constant::getNullValue(
6000 llvm::PointerType::getUnqual(ObjCTypes.ImpnfABITy));
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006001 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassnfABITy,
Fariborz Jahanian9e3ad522009-01-24 20:21:50 +00006002 Values);
Rafael Espindola554256c2014-02-26 22:25:45 +00006003 llvm::GlobalVariable *GV = GetClassGlobal(ClassName, Weak);
Daniel Dunbarc6928bb2009-03-01 04:40:10 +00006004 GV->setInitializer(Init);
Fariborz Jahanian04087232009-01-31 01:07:39 +00006005 GV->setSection("__DATA, __objc_data");
Fariborz Jahanianc22f2362009-01-31 02:43:27 +00006006 GV->setAlignment(
Micah Villmowdd31ca12012-10-08 16:25:52 +00006007 CGM.getDataLayout().getABITypeAlignment(ObjCTypes.ClassnfABITy));
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00006008 if (!CGM.getTriple().isOSBinFormatCOFF())
6009 if (HiddenVisibility)
6010 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahanian4723fb72009-01-24 21:21:53 +00006011 return GV;
Fariborz Jahanian9e3ad522009-01-24 20:21:50 +00006012}
6013
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006014bool
Fariborz Jahaniana6bed832009-05-21 01:03:45 +00006015CGObjCNonFragileABIMac::ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
Craig Topper8a13c412014-05-21 05:09:00 +00006016 return OD->getClassMethod(GetNullarySelector("load")) != nullptr;
Daniel Dunbar9a017d72009-05-15 22:33:15 +00006017}
6018
Daniel Dunbar961202372009-05-03 12:57:56 +00006019void CGObjCNonFragileABIMac::GetClassSizeInfo(const ObjCImplementationDecl *OID,
Daniel Dunbar554fd792009-04-19 23:41:48 +00006020 uint32_t &InstanceStart,
6021 uint32_t &InstanceSize) {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006022 const ASTRecordLayout &RL =
Daniel Dunbar9252ee12009-05-04 21:26:30 +00006023 CGM.getContext().getASTObjCImplementationLayout(OID);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006024
Daniel Dunbar9b042e02009-05-04 23:23:09 +00006025 // InstanceSize is really instance end.
Ken Dyckd5090c12011-02-11 02:20:09 +00006026 InstanceSize = RL.getDataSize().getQuantity();
Daniel Dunbar9b042e02009-05-04 23:23:09 +00006027
6028 // If there are no fields, the start is the same as the end.
6029 if (!RL.getFieldCount())
6030 InstanceStart = InstanceSize;
6031 else
Ken Dyckc5ca8762011-04-14 00:43:09 +00006032 InstanceStart = RL.getFieldOffset(0) / CGM.getContext().getCharWidth();
Daniel Dunbar554fd792009-04-19 23:41:48 +00006033}
6034
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00006035static llvm::GlobalValue::DLLStorageClassTypes getStorage(CodeGenModule &CGM,
6036 StringRef Name) {
6037 IdentifierInfo &II = CGM.getContext().Idents.get(Name);
6038 TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
6039 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
6040
6041 const VarDecl *VD = nullptr;
6042 for (const auto &Result : DC->lookup(&II))
6043 if ((VD = dyn_cast<VarDecl>(Result)))
6044 break;
6045
6046 if (!VD)
6047 return llvm::GlobalValue::DLLImportStorageClass;
6048 if (VD->hasAttr<DLLExportAttr>())
6049 return llvm::GlobalValue::DLLExportStorageClass;
6050 if (VD->hasAttr<DLLImportAttr>())
6051 return llvm::GlobalValue::DLLImportStorageClass;
6052 return llvm::GlobalValue::DefaultStorageClass;
6053}
6054
Fariborz Jahanian71394042009-01-23 23:53:38 +00006055void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) {
Fariborz Jahanian71394042009-01-23 23:53:38 +00006056 if (!ObjCEmptyCacheVar) {
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00006057 ObjCEmptyCacheVar =
6058 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.CacheTy, false,
6059 llvm::GlobalValue::ExternalLinkage, nullptr,
6060 "_objc_empty_cache");
6061 if (CGM.getTriple().isOSBinFormatCOFF())
6062 ObjCEmptyCacheVar->setDLLStorageClass(getStorage(CGM, "_objc_empty_cache"));
Craig Topper8a13c412014-05-21 05:09:00 +00006063
Saleem Abdulrasool4f515a62016-07-13 02:58:44 +00006064 // Only OS X with deployment version <10.9 use the empty vtable symbol
Fariborz Jahanian42d49552013-10-24 17:40:28 +00006065 const llvm::Triple &Triple = CGM.getTarget().getTriple();
Saleem Abdulrasool4f515a62016-07-13 02:58:44 +00006066 if (Triple.isMacOSX() && Triple.isMacOSXVersionLT(10, 9))
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00006067 ObjCEmptyVtableVar =
6068 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ImpnfABITy, false,
6069 llvm::GlobalValue::ExternalLinkage, nullptr,
6070 "_objc_empty_vtable");
Fariborz Jahanian71394042009-01-23 23:53:38 +00006071 }
Saleem Abdulrasoolbc2d9992016-07-16 22:42:04 +00006072
Daniel Dunbare3f5cfc2009-04-20 20:18:54 +00006073 // FIXME: Is this correct (that meta class size is never computed)?
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006074 uint32_t InstanceStart =
Micah Villmowdd31ca12012-10-08 16:25:52 +00006075 CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ClassnfABITy);
Fariborz Jahanian9e3ad522009-01-24 20:21:50 +00006076 uint32_t InstanceSize = InstanceStart;
John McCallef19dbb2012-10-17 04:53:23 +00006077 uint32_t flags = NonFragileABI_Class_Meta;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006078
Fariborz Jahanian9e3ad522009-01-24 20:21:50 +00006079 llvm::GlobalVariable *SuperClassGV, *IsAGV;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006080
Saleem Abdulrasool10fd1ff2016-07-16 22:42:06 +00006081 StringRef ClassName = ID->getObjCRuntimeNameAsString();
Saleem Abdulrasoolbc2d9992016-07-16 22:42:04 +00006082 const auto *CI = ID->getClassInterface();
6083 assert(CI && "CGObjCNonFragileABIMac::GenerateClass - class is 0");
6084
John McCall0d54a172012-10-17 04:53:31 +00006085 // Build the flags for the metaclass.
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00006086 bool classIsHidden = (CGM.getTriple().isOSBinFormatCOFF())
6087 ? !CI->hasAttr<DLLExportAttr>()
6088 : CI->getVisibility() == HiddenVisibility;
Fariborz Jahanian82208252009-01-31 00:59:10 +00006089 if (classIsHidden)
John McCallef19dbb2012-10-17 04:53:23 +00006090 flags |= NonFragileABI_Class_Hidden;
John McCall0d54a172012-10-17 04:53:31 +00006091
6092 // FIXME: why is this flag set on the metaclass?
6093 // ObjC metaclasses have no fields and don't really get constructed.
6094 if (ID->hasNonZeroConstructors() || ID->hasDestructors()) {
John McCallef19dbb2012-10-17 04:53:23 +00006095 flags |= NonFragileABI_Class_HasCXXStructors;
John McCall0d54a172012-10-17 04:53:31 +00006096 if (!ID->hasNonZeroConstructors())
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00006097 flags |= NonFragileABI_Class_HasCXXDestructorOnly;
John McCall0d54a172012-10-17 04:53:31 +00006098 }
6099
Saleem Abdulrasoolbc2d9992016-07-16 22:42:04 +00006100 if (!CI->getSuperClass()) {
Fariborz Jahanian9e3ad522009-01-24 20:21:50 +00006101 // class is root
John McCallef19dbb2012-10-17 04:53:23 +00006102 flags |= NonFragileABI_Class_Root;
Saleem Abdulrasoolbc2d9992016-07-16 22:42:04 +00006103
Saleem Abdulrasool10fd1ff2016-07-16 22:42:06 +00006104 SuperClassGV = GetClassGlobal((getClassSymbolPrefix() + ClassName).str(),
6105 CI->isWeakImported());
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00006106 if (CGM.getTriple().isOSBinFormatCOFF())
6107 if (CI->hasAttr<DLLImportAttr>())
6108 SuperClassGV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
Saleem Abdulrasoolbc2d9992016-07-16 22:42:04 +00006109
Saleem Abdulrasool10fd1ff2016-07-16 22:42:06 +00006110 IsAGV = GetClassGlobal((getMetaclassSymbolPrefix() + ClassName).str(),
6111 CI->isWeakImported());
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00006112 if (CGM.getTriple().isOSBinFormatCOFF())
6113 if (CI->hasAttr<DLLImportAttr>())
6114 IsAGV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
Fariborz Jahanian9e3ad522009-01-24 20:21:50 +00006115 } else {
Fariborz Jahanian4723fb72009-01-24 21:21:53 +00006116 // Has a root. Current class is not a root.
Fariborz Jahanian03b300b2009-02-26 18:23:47 +00006117 const ObjCInterfaceDecl *Root = ID->getClassInterface();
6118 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
6119 Root = Super;
Saleem Abdulrasoolbc2d9992016-07-16 22:42:04 +00006120
6121 const auto *Super = CI->getSuperClass();
Saleem Abdulrasool10fd1ff2016-07-16 22:42:06 +00006122 StringRef RootClassName = Root->getObjCRuntimeNameAsString();
6123 StringRef SuperClassName = Super->getObjCRuntimeNameAsString();
Saleem Abdulrasoolbc2d9992016-07-16 22:42:04 +00006124
Saleem Abdulrasool10fd1ff2016-07-16 22:42:06 +00006125 IsAGV = GetClassGlobal((getMetaclassSymbolPrefix() + RootClassName).str(),
6126 Root->isWeakImported());
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00006127 if (CGM.getTriple().isOSBinFormatCOFF())
6128 if (Root->hasAttr<DLLImportAttr>())
6129 IsAGV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006130
Fariborz Jahanian03b300b2009-02-26 18:23:47 +00006131 // work on super class metadata symbol.
Saleem Abdulrasool10fd1ff2016-07-16 22:42:06 +00006132 SuperClassGV =
6133 GetClassGlobal((getMetaclassSymbolPrefix() + SuperClassName).str(),
6134 Super->isWeakImported());
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00006135 if (CGM.getTriple().isOSBinFormatCOFF())
6136 if (Super->hasAttr<DLLImportAttr>())
6137 SuperClassGV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
Fariborz Jahanian9e3ad522009-01-24 20:21:50 +00006138 }
Saleem Abdulrasoolbc2d9992016-07-16 22:42:04 +00006139
6140 llvm::GlobalVariable *CLASS_RO_GV =
6141 BuildClassRoTInitializer(flags, InstanceStart, InstanceSize, ID);
6142
Saleem Abdulrasoolbc2d9992016-07-16 22:42:04 +00006143 llvm::GlobalVariable *MetaTClass =
Saleem Abdulrasool10fd1ff2016-07-16 22:42:06 +00006144 BuildClassMetaData((getMetaclassSymbolPrefix() + ClassName).str(), IsAGV,
6145 SuperClassGV, CLASS_RO_GV, classIsHidden,
6146 CI->isWeakImported());
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00006147 if (CGM.getTriple().isOSBinFormatCOFF())
6148 if (CI->hasAttr<DLLExportAttr>())
6149 MetaTClass->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
Fariborz Jahanian67260552009-11-17 21:37:35 +00006150 DefinedMetaClasses.push_back(MetaTClass);
Daniel Dunbar15894b72009-04-07 05:48:37 +00006151
Fariborz Jahanian4723fb72009-01-24 21:21:53 +00006152 // Metadata for the class
John McCallef19dbb2012-10-17 04:53:23 +00006153 flags = 0;
Fariborz Jahanian82208252009-01-31 00:59:10 +00006154 if (classIsHidden)
John McCallef19dbb2012-10-17 04:53:23 +00006155 flags |= NonFragileABI_Class_Hidden;
John McCall0d54a172012-10-17 04:53:31 +00006156
6157 if (ID->hasNonZeroConstructors() || ID->hasDestructors()) {
John McCallef19dbb2012-10-17 04:53:23 +00006158 flags |= NonFragileABI_Class_HasCXXStructors;
Daniel Dunbar8f28d012009-04-08 04:21:03 +00006159
John McCall0d54a172012-10-17 04:53:31 +00006160 // Set a flag to enable a runtime optimization when a class has
6161 // fields that require destruction but which don't require
6162 // anything except zero-initialization during construction. This
6163 // is most notably true of __strong and __weak types, but you can
6164 // also imagine there being C++ types with non-trivial default
6165 // constructors that merely set all fields to null.
6166 if (!ID->hasNonZeroConstructors())
6167 flags |= NonFragileABI_Class_HasCXXDestructorOnly;
6168 }
6169
Saleem Abdulrasoolbc2d9992016-07-16 22:42:04 +00006170 if (hasObjCExceptionAttribute(CGM.getContext(), CI))
John McCallef19dbb2012-10-17 04:53:23 +00006171 flags |= NonFragileABI_Class_Exception;
Daniel Dunbar8f28d012009-04-08 04:21:03 +00006172
Saleem Abdulrasoolbc2d9992016-07-16 22:42:04 +00006173 if (!CI->getSuperClass()) {
John McCallef19dbb2012-10-17 04:53:23 +00006174 flags |= NonFragileABI_Class_Root;
Craig Topper8a13c412014-05-21 05:09:00 +00006175 SuperClassGV = nullptr;
Chris Lattnerb433b272009-04-19 06:02:28 +00006176 } else {
Fariborz Jahanian4723fb72009-01-24 21:21:53 +00006177 // Has a root. Current class is not a root.
Saleem Abdulrasoolbc2d9992016-07-16 22:42:04 +00006178 const auto *Super = CI->getSuperClass();
Saleem Abdulrasool10fd1ff2016-07-16 22:42:06 +00006179 StringRef SuperClassName = Super->getObjCRuntimeNameAsString();
Saleem Abdulrasoolbc2d9992016-07-16 22:42:04 +00006180
Saleem Abdulrasool10fd1ff2016-07-16 22:42:06 +00006181 SuperClassGV =
6182 GetClassGlobal((getClassSymbolPrefix() + SuperClassName).str(),
6183 Super->isWeakImported());
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00006184 if (CGM.getTriple().isOSBinFormatCOFF())
6185 if (Super->hasAttr<DLLImportAttr>())
6186 SuperClassGV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
Fariborz Jahanian4723fb72009-01-24 21:21:53 +00006187 }
Saleem Abdulrasoolbc2d9992016-07-16 22:42:04 +00006188
Daniel Dunbar961202372009-05-03 12:57:56 +00006189 GetClassSizeInfo(ID, InstanceStart, InstanceSize);
Saleem Abdulrasoolbc2d9992016-07-16 22:42:04 +00006190 CLASS_RO_GV =
6191 BuildClassRoTInitializer(flags, InstanceStart, InstanceSize, ID);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006192
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006193 llvm::GlobalVariable *ClassMD =
Saleem Abdulrasool10fd1ff2016-07-16 22:42:06 +00006194 BuildClassMetaData((getClassSymbolPrefix() + ClassName).str(), MetaTClass,
6195 SuperClassGV, CLASS_RO_GV, classIsHidden,
6196 CI->isWeakImported());
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00006197 if (CGM.getTriple().isOSBinFormatCOFF())
6198 if (CI->hasAttr<DLLExportAttr>())
6199 ClassMD->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
Fariborz Jahanian279abd32009-01-30 20:55:31 +00006200 DefinedClasses.push_back(ClassMD);
Saleem Abdulrasoolbc2d9992016-07-16 22:42:04 +00006201 ImplementedClasses.push_back(CI);
Daniel Dunbar8f28d012009-04-08 04:21:03 +00006202
Daniel Dunbar9a017d72009-05-15 22:33:15 +00006203 // Determine if this class is also "non-lazy".
6204 if (ImplementationIsNonLazy(ID))
6205 DefinedNonLazyClasses.push_back(ClassMD);
6206
Daniel Dunbar8f28d012009-04-08 04:21:03 +00006207 // Force the definition of the EHType if necessary.
John McCallef19dbb2012-10-17 04:53:23 +00006208 if (flags & NonFragileABI_Class_Exception)
Saleem Abdulrasoolbc2d9992016-07-16 22:42:04 +00006209 GetInterfaceEHType(CI, true);
Fariborz Jahanianc0577942011-04-22 22:02:28 +00006210 // Make sure method definition entries are all clear for next implementation.
6211 MethodDefinitions.clear();
Fariborz Jahanian71394042009-01-23 23:53:38 +00006212}
6213
Fariborz Jahanian097feda2009-01-30 18:58:59 +00006214/// GenerateProtocolRef - This routine is called to generate code for
6215/// a protocol reference expression; as in:
6216/// @code
6217/// @protocol(Proto1);
6218/// @endcode
6219/// It generates a weak reference to l_OBJC_PROTOCOL_REFERENCE_$_Proto1
6220/// which will hold address of the protocol meta-data.
6221///
John McCall882987f2013-02-28 19:01:20 +00006222llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CodeGenFunction &CGF,
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006223 const ObjCProtocolDecl *PD) {
6224
Fariborz Jahanian464423d2009-04-10 18:47:34 +00006225 // This routine is called for @protocol only. So, we must build definition
6226 // of protocol's meta-data (not a reference to it!)
6227 //
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006228 llvm::Constant *Init =
6229 llvm::ConstantExpr::getBitCast(GetOrEmitProtocol(PD),
Douglas Gregor020de322012-01-17 18:36:30 +00006230 ObjCTypes.getExternalProtocolPtrTy());
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006231
Fariborz Jahanian097feda2009-01-30 18:58:59 +00006232 std::string ProtocolName("\01l_OBJC_PROTOCOL_REFERENCE_$_");
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006233 ProtocolName += PD->getObjCRuntimeNameAsString();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006234
John McCall7f416cc2015-09-08 08:05:57 +00006235 CharUnits Align = CGF.getPointerAlign();
6236
Fariborz Jahanian097feda2009-01-30 18:58:59 +00006237 llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName);
6238 if (PTGV)
John McCall7f416cc2015-09-08 08:05:57 +00006239 return CGF.Builder.CreateAlignedLoad(PTGV, Align);
Fariborz Jahanian097feda2009-01-30 18:58:59 +00006240 PTGV = new llvm::GlobalVariable(
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006241 CGM.getModule(),
6242 Init->getType(), false,
Rafael Espindola70efc5b2014-03-06 18:54:12 +00006243 llvm::GlobalValue::WeakAnyLinkage,
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006244 Init,
6245 ProtocolName);
Fariborz Jahanian097feda2009-01-30 18:58:59 +00006246 PTGV->setSection("__DATA, __objc_protorefs, coalesced, no_dead_strip");
Rafael Espindola70efc5b2014-03-06 18:54:12 +00006247 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
John McCall7f416cc2015-09-08 08:05:57 +00006248 PTGV->setAlignment(Align.getQuantity());
Rafael Espindola060062a2014-03-06 22:15:10 +00006249 CGM.addCompilerUsedGlobal(PTGV);
John McCall7f416cc2015-09-08 08:05:57 +00006250 return CGF.Builder.CreateAlignedLoad(PTGV, Align);
Fariborz Jahanian097feda2009-01-30 18:58:59 +00006251}
6252
Fariborz Jahanian0c8d0602009-01-26 18:32:24 +00006253/// GenerateCategory - Build metadata for a category implementation.
6254/// struct _category_t {
6255/// const char * const name;
6256/// struct _class_t *const cls;
6257/// const struct _method_list_t * const instance_methods;
6258/// const struct _method_list_t * const class_methods;
6259/// const struct _protocol_list_t * const protocols;
6260/// const struct _prop_list_t * const properties;
Manman Ren96df0b32016-01-29 23:45:01 +00006261/// const struct _prop_list_t * const class_properties;
Manman Ren42ff3902016-02-24 17:49:50 +00006262/// const uint32_t size;
Fariborz Jahanian0c8d0602009-01-26 18:32:24 +00006263/// }
6264///
Daniel Dunbar9a017d72009-05-15 22:33:15 +00006265void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Fariborz Jahanian0c8d0602009-01-26 18:32:24 +00006266 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Fariborz Jahanian2612e142009-01-26 22:58:07 +00006267 const char *Prefix = "\01l_OBJC_$_CATEGORY_";
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006268
6269 llvm::SmallString<64> ExtCatName(Prefix);
6270 ExtCatName += Interface->getObjCRuntimeNameAsString();
6271 ExtCatName += "_$_";
6272 ExtCatName += OCD->getNameAsString();
6273
6274 llvm::SmallString<64> ExtClassName(getClassSymbolPrefix());
6275 ExtClassName += Interface->getObjCRuntimeNameAsString();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006276
Manman Ren42ff3902016-02-24 17:49:50 +00006277 llvm::Constant *Values[8];
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006278 Values[0] = GetClassName(OCD->getIdentifier()->getName());
Fariborz Jahanian0c8d0602009-01-26 18:32:24 +00006279 // meta-class entry symbol
Rafael Espindola554256c2014-02-26 22:25:45 +00006280 llvm::GlobalVariable *ClassGV =
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006281 GetClassGlobal(ExtClassName.str(), Interface->isWeakImported());
Rafael Espindola554256c2014-02-26 22:25:45 +00006282
Fariborz Jahanian0c8d0602009-01-26 18:32:24 +00006283 Values[1] = ClassGV;
Fariborz Jahanian2612e142009-01-26 22:58:07 +00006284 std::vector<llvm::Constant*> Methods;
Saleem Abdulrasool209150a2016-10-24 21:25:57 +00006285 std::string ListName =
6286 (Interface->getObjCRuntimeNameAsString() + "_$_" + OCD->getName()).str();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006287
Aaron Ballmanf26acce2014-03-13 19:50:17 +00006288 for (const auto *I : OCD->instance_methods())
Fariborz Jahanian2612e142009-01-26 22:58:07 +00006289 // Instance methods should always be defined.
Aaron Ballmanf26acce2014-03-13 19:50:17 +00006290 Methods.push_back(GetMethodConstant(I));
Saleem Abdulrasoold48b0a32016-10-24 20:47:58 +00006291 Values[2] = EmitMethodList(ListName, MethodListType::CategoryInstanceMethods,
Fariborz Jahanian2612e142009-01-26 22:58:07 +00006292 Methods);
6293
Fariborz Jahanian2612e142009-01-26 22:58:07 +00006294 Methods.clear();
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00006295 for (const auto *I : OCD->class_methods())
Fariborz Jahanian2612e142009-01-26 22:58:07 +00006296 // Class methods should always be defined.
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00006297 Methods.push_back(GetMethodConstant(I));
Saleem Abdulrasoold48b0a32016-10-24 20:47:58 +00006298 Values[3] =
6299 EmitMethodList(ListName, MethodListType::CategoryClassMethods, Methods);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006300
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006301 const ObjCCategoryDecl *Category =
Fariborz Jahanian066347e2009-01-28 22:18:42 +00006302 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Fariborz Jahaniand8fc1052009-02-13 17:52:22 +00006303 if (Category) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00006304 SmallString<256> ExtName;
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006305 llvm::raw_svector_ostream(ExtName) << Interface->getObjCRuntimeNameAsString() << "_$_"
Daniel Dunbar349e6fb2009-10-18 20:48:59 +00006306 << OCD->getName();
Fariborz Jahaniand8fc1052009-02-13 17:52:22 +00006307 Values[4] = EmitProtocolList("\01l_OBJC_CATEGORY_PROTOCOLS_$_"
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006308 + Interface->getObjCRuntimeNameAsString() + "_$_"
6309 + Category->getName(),
6310 Category->protocol_begin(),
6311 Category->protocol_end());
Daniel Dunbar349e6fb2009-10-18 20:48:59 +00006312 Values[5] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ExtName.str(),
Manman Renad0e7912016-01-29 19:22:54 +00006313 OCD, Category, ObjCTypes, false);
Manman Ren96df0b32016-01-29 23:45:01 +00006314 Values[6] = EmitPropertyList("\01l_OBJC_$_CLASS_PROP_LIST_" + ExtName.str(),
6315 OCD, Category, ObjCTypes, true);
Mike Stump658fe022009-07-30 22:28:39 +00006316 } else {
Owen Anderson0b75f232009-07-31 20:28:54 +00006317 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
6318 Values[5] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
Manman Ren96df0b32016-01-29 23:45:01 +00006319 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
Fariborz Jahaniand8fc1052009-02-13 17:52:22 +00006320 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006321
Manman Ren42ff3902016-02-24 17:49:50 +00006322 unsigned Size = CGM.getDataLayout().getTypeAllocSize(ObjCTypes.CategorynfABITy);
6323 Values[7] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
6324
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006325 llvm::Constant *Init =
6326 llvm::ConstantStruct::get(ObjCTypes.CategorynfABITy,
Fariborz Jahanian0c8d0602009-01-26 18:32:24 +00006327 Values);
6328 llvm::GlobalVariable *GCATV
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006329 = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.CategorynfABITy,
Fariborz Jahanian0c8d0602009-01-26 18:32:24 +00006330 false,
Rafael Espindola5179a4e2014-02-27 19:01:11 +00006331 llvm::GlobalValue::PrivateLinkage,
Fariborz Jahanian0c8d0602009-01-26 18:32:24 +00006332 Init,
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006333 ExtCatName.str());
Fariborz Jahanianc22f2362009-01-31 02:43:27 +00006334 GCATV->setAlignment(
Micah Villmowdd31ca12012-10-08 16:25:52 +00006335 CGM.getDataLayout().getABITypeAlignment(ObjCTypes.CategorynfABITy));
Fariborz Jahanian40a4bcd2009-01-28 01:05:23 +00006336 GCATV->setSection("__DATA, __objc_const");
Rafael Espindola060062a2014-03-06 22:15:10 +00006337 CGM.addCompilerUsedGlobal(GCATV);
Fariborz Jahanian0c8d0602009-01-26 18:32:24 +00006338 DefinedCategories.push_back(GCATV);
Daniel Dunbar9a017d72009-05-15 22:33:15 +00006339
6340 // Determine if this category is also "non-lazy".
6341 if (ImplementationIsNonLazy(OCD))
6342 DefinedNonLazyCategories.push_back(GCATV);
Fariborz Jahanianc0577942011-04-22 22:02:28 +00006343 // method definition entries must be clear for next implementation.
6344 MethodDefinitions.clear();
Fariborz Jahanian0c8d0602009-01-26 18:32:24 +00006345}
Fariborz Jahanian99113fd2009-01-26 21:38:32 +00006346
6347/// GetMethodConstant - Return a struct objc_method constant for the
6348/// given method if it has been defined. The result is null if the
6349/// method has not been defined. The return value has type MethodPtrTy.
6350llvm::Constant *CGObjCNonFragileABIMac::GetMethodConstant(
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006351 const ObjCMethodDecl *MD) {
Argyrios Kyrtzidis13257c52010-08-09 10:54:20 +00006352 llvm::Function *Fn = GetMethodDefinition(MD);
Fariborz Jahanian99113fd2009-01-26 21:38:32 +00006353 if (!Fn)
Craig Topper8a13c412014-05-21 05:09:00 +00006354 return nullptr;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006355
Benjamin Kramer22d24c22011-10-15 12:20:02 +00006356 llvm::Constant *Method[] = {
Owen Andersonade90fd2009-07-29 18:54:39 +00006357 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
Benjamin Kramer22d24c22011-10-15 12:20:02 +00006358 ObjCTypes.SelectorPtrTy),
6359 GetMethodVarType(MD),
6360 llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy)
6361 };
Owen Anderson0e0189d2009-07-27 22:29:56 +00006362 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
Fariborz Jahanian99113fd2009-01-26 21:38:32 +00006363}
6364
6365/// EmitMethodList - Build meta-data for method declarations
6366/// struct _method_list_t {
6367/// uint32_t entsize; // sizeof(struct _objc_method)
6368/// uint32_t method_count;
6369/// struct _objc_method method_list[method_count];
6370/// }
6371///
Bill Wendlingcb5b5ff2012-02-07 09:25:09 +00006372llvm::Constant *
Saleem Abdulrasoold48b0a32016-10-24 20:47:58 +00006373CGObjCNonFragileABIMac::EmitMethodList(Twine Name, MethodListType MLT,
Saleem Abdulrasool1e6c4062016-05-16 05:06:49 +00006374 ArrayRef<llvm::Constant *> Methods) {
Fariborz Jahanian99113fd2009-01-26 21:38:32 +00006375 // Return null for empty list.
6376 if (Methods.empty())
Owen Anderson0b75f232009-07-31 20:28:54 +00006377 return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006378
Chris Lattnere64d7ba2011-06-20 04:01:35 +00006379 llvm::Constant *Values[3];
Fariborz Jahanian99113fd2009-01-26 21:38:32 +00006380 // sizeof(struct _objc_method)
Micah Villmowdd31ca12012-10-08 16:25:52 +00006381 unsigned Size = CGM.getDataLayout().getTypeAllocSize(ObjCTypes.MethodTy);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00006382 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Fariborz Jahanian99113fd2009-01-26 21:38:32 +00006383 // method_count
Owen Andersonb7a2fe62009-07-24 23:12:58 +00006384 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
Owen Anderson9793f0e2009-07-29 22:16:19 +00006385 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
Fariborz Jahanian99113fd2009-01-26 21:38:32 +00006386 Methods.size());
Owen Anderson47034e12009-07-28 18:33:04 +00006387 Values[2] = llvm::ConstantArray::get(AT, Methods);
Chris Lattnere64d7ba2011-06-20 04:01:35 +00006388 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006389
Saleem Abdulrasoold48b0a32016-10-24 20:47:58 +00006390 StringRef Prefix;
6391 switch (MLT) {
6392 case MethodListType::CategoryInstanceMethods:
6393 Prefix = "\01l_OBJC_$_CATEGORY_INSTANCE_METHODS_";
6394 break;
6395 case MethodListType::CategoryClassMethods:
6396 Prefix = "\01l_OBJC_$_CATEGORY_CLASS_METHODS_";
6397 break;
6398 case MethodListType::InstanceMethods:
6399 Prefix = "\01l_OBJC_$_INSTANCE_METHODS_";
6400 break;
6401 case MethodListType::ClassMethods:
6402 Prefix = "\01l_OBJC_$_CLASS_METHODS_";
6403 break;
6404
6405 case MethodListType::ProtocolInstanceMethods:
6406 Prefix = "\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_";
6407 break;
6408 case MethodListType::ProtocolClassMethods:
6409 Prefix = "\01l_OBJC_$_PROTOCOL_CLASS_METHODS_";
6410 break;
6411 case MethodListType::OptionalProtocolInstanceMethods:
6412 Prefix = "\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_";
6413 break;
6414 case MethodListType::OptionalProtocolClassMethods:
6415 Prefix = "\01l_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_";
6416 break;
6417 }
6418
6419 auto *GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(), false,
6420 llvm::GlobalValue::PrivateLinkage, Init,
6421 Prefix + Name);
Micah Villmowdd31ca12012-10-08 16:25:52 +00006422 GV->setAlignment(CGM.getDataLayout().getABITypeAlignment(Init->getType()));
Saleem Abdulrasoold48b0a32016-10-24 20:47:58 +00006423 GV->setSection("__DATA, __objc_const");
Rafael Espindola060062a2014-03-06 22:15:10 +00006424 CGM.addCompilerUsedGlobal(GV);
Chris Lattnere64d7ba2011-06-20 04:01:35 +00006425 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.MethodListnfABIPtrTy);
Fariborz Jahanian99113fd2009-01-26 21:38:32 +00006426}
Fariborz Jahanian7415caa2009-01-27 19:38:51 +00006427
Fariborz Jahanian4e7ae062009-02-10 20:21:06 +00006428/// ObjCIvarOffsetVariable - Returns the ivar offset variable for
6429/// the given ivar.
Daniel Dunbar8c7f9812010-04-02 21:14:02 +00006430llvm::GlobalVariable *
6431CGObjCNonFragileABIMac::ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
6432 const ObjCIvarDecl *Ivar) {
6433 const ObjCInterfaceDecl *Container = Ivar->getContainingInterface();
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006434 llvm::SmallString<64> Name("OBJC_IVAR_$_");
6435 Name += Container->getObjCRuntimeNameAsString();
6436 Name += ".";
6437 Name += Ivar->getName();
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00006438 llvm::GlobalVariable *IvarOffsetGV = CGM.getModule().getGlobalVariable(Name);
6439 if (!IvarOffsetGV) {
6440 IvarOffsetGV =
6441 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.IvarOffsetVarTy,
6442 false, llvm::GlobalValue::ExternalLinkage,
6443 nullptr, Name.str());
6444 if (CGM.getTriple().isOSBinFormatCOFF()) {
6445 bool IsPrivateOrPackage =
6446 Ivar->getAccessControl() == ObjCIvarDecl::Private ||
6447 Ivar->getAccessControl() == ObjCIvarDecl::Package;
6448
6449 if (ID->hasAttr<DLLExportAttr>() && !IsPrivateOrPackage)
6450 IvarOffsetGV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
6451 else if (ID->hasAttr<DLLImportAttr>())
6452 IvarOffsetGV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
6453 }
6454 }
Fariborz Jahanian4e7ae062009-02-10 20:21:06 +00006455 return IvarOffsetGV;
6456}
6457
Daniel Dunbar8c7f9812010-04-02 21:14:02 +00006458llvm::Constant *
6459CGObjCNonFragileABIMac::EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,
6460 const ObjCIvarDecl *Ivar,
Eli Friedman8cbca202012-11-06 22:15:52 +00006461 unsigned long int Offset) {
Daniel Dunbarbf90b332009-04-19 00:44:02 +00006462 llvm::GlobalVariable *IvarOffsetGV = ObjCIvarOffsetVariable(ID, Ivar);
Tim Northover238b5082014-03-29 13:42:40 +00006463 IvarOffsetGV->setInitializer(
6464 llvm::ConstantInt::get(ObjCTypes.IvarOffsetVarTy, Offset));
Fariborz Jahanianc22f2362009-01-31 02:43:27 +00006465 IvarOffsetGV->setAlignment(
Tim Northover238b5082014-03-29 13:42:40 +00006466 CGM.getDataLayout().getABITypeAlignment(ObjCTypes.IvarOffsetVarTy));
Daniel Dunbarbf90b332009-04-19 00:44:02 +00006467
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00006468 if (!CGM.getTriple().isOSBinFormatCOFF()) {
6469 // FIXME: This matches gcc, but shouldn't the visibility be set on the use
6470 // as well (i.e., in ObjCIvarOffsetVariable).
6471 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
6472 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
6473 ID->getVisibility() == HiddenVisibility)
6474 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
6475 else
6476 IvarOffsetGV->setVisibility(llvm::GlobalValue::DefaultVisibility);
6477 }
6478
Bill Wendlingf7d45982011-05-04 21:37:25 +00006479 IvarOffsetGV->setSection("__DATA, __objc_ivar");
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00006480 return IvarOffsetGV;
Fariborz Jahanian40a4bcd2009-01-28 01:05:23 +00006481}
6482
Fariborz Jahanian7415caa2009-01-27 19:38:51 +00006483/// EmitIvarList - Emit the ivar list for the given
Daniel Dunbar508a7dd2009-04-18 08:51:00 +00006484/// implementation. The return value has type
Fariborz Jahanian7415caa2009-01-27 19:38:51 +00006485/// IvarListnfABIPtrTy.
6486/// struct _ivar_t {
Tim Northover238b5082014-03-29 13:42:40 +00006487/// unsigned [long] int *offset; // pointer to ivar offset location
Fariborz Jahanian7415caa2009-01-27 19:38:51 +00006488/// char *name;
6489/// char *type;
6490/// uint32_t alignment;
6491/// uint32_t size;
6492/// }
6493/// struct _ivar_list_t {
6494/// uint32 entsize; // sizeof(struct _ivar_t)
6495/// uint32 count;
6496/// struct _iver_t list[count];
6497/// }
6498///
Daniel Dunbarf5c18462009-04-20 06:54:31 +00006499
Fariborz Jahanian7415caa2009-01-27 19:38:51 +00006500llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList(
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006501 const ObjCImplementationDecl *ID) {
6502
Benjamin Kramer22d24c22011-10-15 12:20:02 +00006503 std::vector<llvm::Constant*> Ivars;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006504
Jordy Rosea91768e2011-07-22 02:08:32 +00006505 const ObjCInterfaceDecl *OID = ID->getClassInterface();
Fariborz Jahanian7415caa2009-01-27 19:38:51 +00006506 assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface");
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006507
Fariborz Jahanian40a4bcd2009-01-28 01:05:23 +00006508 // FIXME. Consolidate this with similar code in GenerateClass.
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006509
Jordy Rosea91768e2011-07-22 02:08:32 +00006510 for (const ObjCIvarDecl *IVD = OID->all_declared_ivar_begin();
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00006511 IVD; IVD = IVD->getNextIvar()) {
Fariborz Jahanian7c809592009-06-04 01:19:09 +00006512 // Ignore unnamed bit-fields.
6513 if (!IVD->getDeclName())
6514 continue;
Benjamin Kramer22d24c22011-10-15 12:20:02 +00006515 llvm::Constant *Ivar[5];
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006516 Ivar[0] = EmitIvarOffsetVar(ID->getClassInterface(), IVD,
Daniel Dunbar961202372009-05-03 12:57:56 +00006517 ComputeIvarBaseOffset(CGM, ID, IVD));
Daniel Dunbar725dc2c2009-04-22 08:22:17 +00006518 Ivar[1] = GetMethodVarName(IVD->getIdentifier());
6519 Ivar[2] = GetMethodVarType(IVD);
Chris Lattner2192fe52011-07-18 04:24:23 +00006520 llvm::Type *FieldTy =
Daniel Dunbar725dc2c2009-04-22 08:22:17 +00006521 CGM.getTypes().ConvertTypeForMem(IVD->getType());
Micah Villmowdd31ca12012-10-08 16:25:52 +00006522 unsigned Size = CGM.getDataLayout().getTypeAllocSize(FieldTy);
Fariborz Jahanian7415caa2009-01-27 19:38:51 +00006523 unsigned Align = CGM.getContext().getPreferredTypeAlign(
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006524 IVD->getType().getTypePtr()) >> 3;
Fariborz Jahanian7415caa2009-01-27 19:38:51 +00006525 Align = llvm::Log2_32(Align);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00006526 Ivar[3] = llvm::ConstantInt::get(ObjCTypes.IntTy, Align);
Daniel Dunbarae032262009-04-20 00:33:43 +00006527 // NOTE. Size of a bitfield does not match gcc's, because of the
6528 // way bitfields are treated special in each. But I am told that
6529 // 'size' for bitfield ivars is ignored by the runtime so it does
6530 // not matter. If it matters, there is enough info to get the
6531 // bitfield right!
Owen Andersonb7a2fe62009-07-24 23:12:58 +00006532 Ivar[4] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Owen Anderson0e0189d2009-07-27 22:29:56 +00006533 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarnfABITy, Ivar));
Fariborz Jahanian7415caa2009-01-27 19:38:51 +00006534 }
6535 // Return null for empty list.
6536 if (Ivars.empty())
Owen Anderson0b75f232009-07-31 20:28:54 +00006537 return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
Chris Lattnere64d7ba2011-06-20 04:01:35 +00006538
6539 llvm::Constant *Values[3];
Micah Villmowdd31ca12012-10-08 16:25:52 +00006540 unsigned Size = CGM.getDataLayout().getTypeAllocSize(ObjCTypes.IvarnfABITy);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00006541 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
6542 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
Owen Anderson9793f0e2009-07-29 22:16:19 +00006543 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarnfABITy,
Fariborz Jahanian7415caa2009-01-27 19:38:51 +00006544 Ivars.size());
Owen Anderson47034e12009-07-28 18:33:04 +00006545 Values[2] = llvm::ConstantArray::get(AT, Ivars);
Chris Lattnere64d7ba2011-06-20 04:01:35 +00006546 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
Fariborz Jahanian7415caa2009-01-27 19:38:51 +00006547 const char *Prefix = "\01l_OBJC_$_INSTANCE_VARIABLES_";
6548 llvm::GlobalVariable *GV =
Owen Andersonc10c8d32009-07-08 19:05:04 +00006549 new llvm::GlobalVariable(CGM.getModule(), Init->getType(), false,
Rafael Espindola5179a4e2014-02-27 19:01:11 +00006550 llvm::GlobalValue::PrivateLinkage,
Fariborz Jahanian7415caa2009-01-27 19:38:51 +00006551 Init,
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006552 Prefix + OID->getObjCRuntimeNameAsString());
Fariborz Jahanianc22f2362009-01-31 02:43:27 +00006553 GV->setAlignment(
Micah Villmowdd31ca12012-10-08 16:25:52 +00006554 CGM.getDataLayout().getABITypeAlignment(Init->getType()));
Fariborz Jahanian40a4bcd2009-01-28 01:05:23 +00006555 GV->setSection("__DATA, __objc_const");
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006556
Rafael Espindola060062a2014-03-06 22:15:10 +00006557 CGM.addCompilerUsedGlobal(GV);
Owen Andersonade90fd2009-07-29 18:54:39 +00006558 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.IvarListnfABIPtrTy);
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006559}
6560
6561llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef(
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006562 const ObjCProtocolDecl *PD) {
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006563 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006564
Akira Hatanaka7f550f32016-02-11 06:36:35 +00006565 if (!Entry)
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006566 // We use the initializer as a marker of whether this is a forward
6567 // reference or not. At module finalization we add the empty
6568 // contents for protocols which were referenced but never defined.
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006569 Entry =
Rafael Espindola5d117f32014-03-06 01:10:46 +00006570 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ProtocolnfABITy,
Rafael Espindola24615092014-09-12 20:14:20 +00006571 false, llvm::GlobalValue::ExternalLinkage,
Craig Topper8a13c412014-05-21 05:09:00 +00006572 nullptr,
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006573 "\01l_OBJC_PROTOCOL_$_" + PD->getObjCRuntimeNameAsString());
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006574
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006575 return Entry;
6576}
6577
6578/// GetOrEmitProtocol - Generate the protocol meta-data:
6579/// @code
6580/// struct _protocol_t {
6581/// id isa; // NULL
6582/// const char * const protocol_name;
6583/// const struct _protocol_list_t * protocol_list; // super protocols
6584/// const struct method_list_t * const instance_methods;
6585/// const struct method_list_t * const class_methods;
6586/// const struct method_list_t *optionalInstanceMethods;
6587/// const struct method_list_t *optionalClassMethods;
6588/// const struct _prop_list_t * properties;
6589/// const uint32_t size; // sizeof(struct _protocol_t)
6590/// const uint32_t flags; // = 0
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006591/// const char ** extendedMethodTypes;
Fariborz Jahanian6a9c46b2015-03-31 22:22:40 +00006592/// const char *demangledName;
Manman Rence7bff52016-01-29 23:46:55 +00006593/// const struct _prop_list_t * class_properties;
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006594/// }
6595/// @endcode
6596///
6597
6598llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol(
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006599 const ObjCProtocolDecl *PD) {
John McCallf9582a72012-03-30 21:29:05 +00006600 llvm::GlobalVariable *Entry = Protocols[PD->getIdentifier()];
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006601
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006602 // Early exit if a defining object has already been generated.
6603 if (Entry && Entry->hasInitializer())
6604 return Entry;
6605
Douglas Gregora715bff2012-01-01 19:51:50 +00006606 // Use the protocol definition, if there is one.
6607 if (const ObjCProtocolDecl *Def = PD->getDefinition())
6608 PD = Def;
6609
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006610 // Construct method lists.
6611 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
6612 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006613 std::vector<llvm::Constant*> MethodTypesExt, OptMethodTypesExt;
Aaron Ballmanf26acce2014-03-13 19:50:17 +00006614 for (const auto *MD : PD->instance_methods()) {
Fariborz Jahaniand9c28b82009-01-30 00:46:37 +00006615 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Douglas Gregora9d84932011-05-27 01:19:52 +00006616 if (!C)
6617 return GetOrEmitProtocolRef(PD);
6618
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006619 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6620 OptInstanceMethods.push_back(C);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006621 OptMethodTypesExt.push_back(GetMethodVarType(MD, true));
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006622 } else {
6623 InstanceMethods.push_back(C);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006624 MethodTypesExt.push_back(GetMethodVarType(MD, true));
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006625 }
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006626 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006627
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00006628 for (const auto *MD : PD->class_methods()) {
Fariborz Jahaniand9c28b82009-01-30 00:46:37 +00006629 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Douglas Gregora9d84932011-05-27 01:19:52 +00006630 if (!C)
6631 return GetOrEmitProtocolRef(PD);
6632
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006633 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6634 OptClassMethods.push_back(C);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006635 OptMethodTypesExt.push_back(GetMethodVarType(MD, true));
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006636 } else {
6637 ClassMethods.push_back(C);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006638 MethodTypesExt.push_back(GetMethodVarType(MD, true));
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006639 }
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006640 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006641
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006642 MethodTypesExt.insert(MethodTypesExt.end(),
6643 OptMethodTypesExt.begin(), OptMethodTypesExt.end());
6644
Manman Rence7bff52016-01-29 23:46:55 +00006645 llvm::Constant *Values[13];
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006646 // isa is NULL
Owen Anderson0b75f232009-07-31 20:28:54 +00006647 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ObjectPtrTy);
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006648 Values[1] = GetClassName(PD->getObjCRuntimeNameAsString());
6649 Values[2] = EmitProtocolList("\01l_OBJC_$_PROTOCOL_REFS_" + PD->getObjCRuntimeNameAsString(),
Daniel Dunbar349e6fb2009-10-18 20:48:59 +00006650 PD->protocol_begin(),
6651 PD->protocol_end());
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006652
Saleem Abdulrasoold48b0a32016-10-24 20:47:58 +00006653 Values[3] =
6654 EmitMethodList(PD->getObjCRuntimeNameAsString(),
6655 MethodListType::ProtocolInstanceMethods, InstanceMethods);
6656 Values[4] =
6657 EmitMethodList(PD->getObjCRuntimeNameAsString(),
6658 MethodListType::ProtocolClassMethods, ClassMethods);
6659 Values[5] = EmitMethodList(PD->getObjCRuntimeNameAsString(),
6660 MethodListType::OptionalProtocolInstanceMethods,
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006661 OptInstanceMethods);
Saleem Abdulrasoold48b0a32016-10-24 20:47:58 +00006662 Values[6] = EmitMethodList(PD->getObjCRuntimeNameAsString(),
6663 MethodListType::OptionalProtocolClassMethods,
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006664 OptClassMethods);
Saleem Abdulrasoold48b0a32016-10-24 20:47:58 +00006665
Manman Renad0e7912016-01-29 19:22:54 +00006666 Values[7] = EmitPropertyList(
6667 "\01l_OBJC_$_PROP_LIST_" + PD->getObjCRuntimeNameAsString(),
6668 nullptr, PD, ObjCTypes, false);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006669 uint32_t Size =
Micah Villmowdd31ca12012-10-08 16:25:52 +00006670 CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ProtocolnfABITy);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00006671 Values[8] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Owen Anderson0b75f232009-07-31 20:28:54 +00006672 Values[9] = llvm::Constant::getNullValue(ObjCTypes.IntTy);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006673 Values[10] = EmitProtocolMethodTypes("\01l_OBJC_$_PROTOCOL_METHOD_TYPES_"
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006674 + PD->getObjCRuntimeNameAsString(),
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006675 MethodTypesExt, ObjCTypes);
Fariborz Jahanian6a9c46b2015-03-31 22:22:40 +00006676 // const char *demangledName;
6677 Values[11] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Manman Rence7bff52016-01-29 23:46:55 +00006678
6679 Values[12] = EmitPropertyList(
6680 "\01l_OBJC_$_CLASS_PROP_LIST_" + PD->getObjCRuntimeNameAsString(),
6681 nullptr, PD, ObjCTypes, true);
Fariborz Jahanian6a9c46b2015-03-31 22:22:40 +00006682
Owen Anderson0e0189d2009-07-27 22:29:56 +00006683 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolnfABITy,
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006684 Values);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006685
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006686 if (Entry) {
Rafael Espindola24615092014-09-12 20:14:20 +00006687 // Already created, fix the linkage and update the initializer.
6688 Entry->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006689 Entry->setInitializer(Init);
6690 } else {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006691 Entry =
Daniel Dunbar349e6fb2009-10-18 20:48:59 +00006692 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ProtocolnfABITy,
Rafael Espindola70efc5b2014-03-06 18:54:12 +00006693 false, llvm::GlobalValue::WeakAnyLinkage, Init,
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006694 "\01l_OBJC_PROTOCOL_$_" + PD->getObjCRuntimeNameAsString());
Fariborz Jahanianc22f2362009-01-31 02:43:27 +00006695 Entry->setAlignment(
Micah Villmowdd31ca12012-10-08 16:25:52 +00006696 CGM.getDataLayout().getABITypeAlignment(ObjCTypes.ProtocolnfABITy));
John McCallf9582a72012-03-30 21:29:05 +00006697
6698 Protocols[PD->getIdentifier()] = Entry;
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006699 }
Rafael Espindola70efc5b2014-03-06 18:54:12 +00006700 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
Rafael Espindola060062a2014-03-06 22:15:10 +00006701 CGM.addCompilerUsedGlobal(Entry);
Chris Lattnerf56501c2009-07-17 23:57:13 +00006702
Fariborz Jahanian61cd4b52009-01-29 20:10:59 +00006703 // Use this protocol meta-data to build protocol list table in section
6704 // __DATA, __objc_protolist
Daniel Dunbar349e6fb2009-10-18 20:48:59 +00006705 llvm::GlobalVariable *PTGV =
6706 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ProtocolnfABIPtrTy,
Rafael Espindola70efc5b2014-03-06 18:54:12 +00006707 false, llvm::GlobalValue::WeakAnyLinkage, Entry,
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006708 "\01l_OBJC_LABEL_PROTOCOL_$_" + PD->getObjCRuntimeNameAsString());
Fariborz Jahanianc22f2362009-01-31 02:43:27 +00006709 PTGV->setAlignment(
Micah Villmowdd31ca12012-10-08 16:25:52 +00006710 CGM.getDataLayout().getABITypeAlignment(ObjCTypes.ProtocolnfABIPtrTy));
Daniel Dunbarb25452a2009-04-15 02:56:18 +00006711 PTGV->setSection("__DATA, __objc_protolist, coalesced, no_dead_strip");
Rafael Espindola70efc5b2014-03-06 18:54:12 +00006712 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Rafael Espindola060062a2014-03-06 22:15:10 +00006713 CGM.addCompilerUsedGlobal(PTGV);
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006714 return Entry;
6715}
6716
6717/// EmitProtocolList - Generate protocol list meta-data:
6718/// @code
6719/// struct _protocol_list_t {
6720/// long protocol_count; // Note, this is 32/64 bit
6721/// struct _protocol_t[protocol_count];
6722/// }
6723/// @endcode
6724///
6725llvm::Constant *
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006726CGObjCNonFragileABIMac::EmitProtocolList(Twine Name,
Daniel Dunbar349e6fb2009-10-18 20:48:59 +00006727 ObjCProtocolDecl::protocol_iterator begin,
6728 ObjCProtocolDecl::protocol_iterator end) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006729 SmallVector<llvm::Constant *, 16> ProtocolRefs;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006730
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006731 // Just return null for empty protocol lists
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006732 if (begin == end)
Owen Anderson0b75f232009-07-31 20:28:54 +00006733 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006734
Daniel Dunbar8de90f02009-02-15 07:36:20 +00006735 // FIXME: We shouldn't need to do this lookup here, should we?
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00006736 SmallString<256> TmpName;
Daniel Dunbar349e6fb2009-10-18 20:48:59 +00006737 Name.toVector(TmpName);
6738 llvm::GlobalVariable *GV =
6739 CGM.getModule().getGlobalVariable(TmpName.str(), true);
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006740 if (GV)
Daniel Dunbar349e6fb2009-10-18 20:48:59 +00006741 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListnfABIPtrTy);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006742
Daniel Dunbar8de90f02009-02-15 07:36:20 +00006743 for (; begin != end; ++begin)
6744 ProtocolRefs.push_back(GetProtocolRef(*begin)); // Implemented???
6745
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006746 // This list is null terminated.
Owen Anderson0b75f232009-07-31 20:28:54 +00006747 ProtocolRefs.push_back(llvm::Constant::getNullValue(
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006748 ObjCTypes.ProtocolnfABIPtrTy));
6749
Chris Lattnere64d7ba2011-06-20 04:01:35 +00006750 llvm::Constant *Values[2];
Owen Anderson170229f2009-07-14 23:10:40 +00006751 Values[0] =
Owen Andersonb7a2fe62009-07-24 23:12:58 +00006752 llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006753 Values[1] =
Bill Wendlinga515b582012-02-09 22:16:49 +00006754 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolnfABIPtrTy,
6755 ProtocolRefs.size()),
6756 ProtocolRefs);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006757
Chris Lattnere64d7ba2011-06-20 04:01:35 +00006758 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
Owen Andersonc10c8d32009-07-08 19:05:04 +00006759 GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(), false,
Rafael Espindola5179a4e2014-02-27 19:01:11 +00006760 llvm::GlobalValue::PrivateLinkage,
Chris Lattnere64d7ba2011-06-20 04:01:35 +00006761 Init, Name);
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006762 GV->setSection("__DATA, __objc_const");
Fariborz Jahanianc22f2362009-01-31 02:43:27 +00006763 GV->setAlignment(
Micah Villmowdd31ca12012-10-08 16:25:52 +00006764 CGM.getDataLayout().getABITypeAlignment(Init->getType()));
Rafael Espindola060062a2014-03-06 22:15:10 +00006765 CGM.addCompilerUsedGlobal(GV);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006766 return llvm::ConstantExpr::getBitCast(GV,
Daniel Dunbar8de90f02009-02-15 07:36:20 +00006767 ObjCTypes.ProtocolListnfABIPtrTy);
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006768}
6769
Fariborz Jahaniand9c28b82009-01-30 00:46:37 +00006770/// GetMethodDescriptionConstant - This routine build following meta-data:
6771/// struct _objc_method {
6772/// SEL _cmd;
6773/// char *method_type;
6774/// char *_imp;
6775/// }
6776
6777llvm::Constant *
6778CGObjCNonFragileABIMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
Benjamin Kramer22d24c22011-10-15 12:20:02 +00006779 llvm::Constant *Desc[3];
Owen Anderson170229f2009-07-14 23:10:40 +00006780 Desc[0] =
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006781 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
6782 ObjCTypes.SelectorPtrTy);
Fariborz Jahaniand9c28b82009-01-30 00:46:37 +00006783 Desc[1] = GetMethodVarType(MD);
Douglas Gregora9d84932011-05-27 01:19:52 +00006784 if (!Desc[1])
Craig Topper8a13c412014-05-21 05:09:00 +00006785 return nullptr;
6786
Fariborz Jahanian097feda2009-01-30 18:58:59 +00006787 // Protocol methods have no implementation. So, this entry is always NULL.
Owen Anderson0b75f232009-07-31 20:28:54 +00006788 Desc[2] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Owen Anderson0e0189d2009-07-27 22:29:56 +00006789 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Desc);
Fariborz Jahaniand9c28b82009-01-30 00:46:37 +00006790}
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00006791
6792/// EmitObjCValueForIvar - Code Gen for nonfragile ivar reference.
6793/// This code gen. amounts to generating code for:
6794/// @code
6795/// (type *)((char *)base + _OBJC_IVAR_$_.ivar;
6796/// @encode
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006797///
Fariborz Jahanian712bfa62009-02-03 19:03:09 +00006798LValue CGObjCNonFragileABIMac::EmitObjCValueForIvar(
John McCall96fa4842010-05-17 21:00:27 +00006799 CodeGen::CodeGenFunction &CGF,
6800 QualType ObjectTy,
6801 llvm::Value *BaseValue,
6802 const ObjCIvarDecl *Ivar,
6803 unsigned CVRQualifiers) {
6804 ObjCInterfaceDecl *ID = ObjectTy->getAs<ObjCObjectType>()->getInterface();
Fariborz Jahaniancaabf1b2012-02-20 22:42:22 +00006805 llvm::Value *Offset = EmitIvarOffset(CGF, ID, Ivar);
Daniel Dunbar9fd114d2009-04-22 07:32:20 +00006806 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
Fariborz Jahaniancaabf1b2012-02-20 22:42:22 +00006807 Offset);
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00006808}
6809
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00006810llvm::Value *CGObjCNonFragileABIMac::EmitIvarOffset(
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006811 CodeGen::CodeGenFunction &CGF,
6812 const ObjCInterfaceDecl *Interface,
6813 const ObjCIvarDecl *Ivar) {
Tim Northover238b5082014-03-29 13:42:40 +00006814 llvm::Value *IvarOffsetValue = ObjCIvarOffsetVariable(Interface, Ivar);
John McCall7f416cc2015-09-08 08:05:57 +00006815 IvarOffsetValue = CGF.Builder.CreateAlignedLoad(IvarOffsetValue,
6816 CGF.getSizeAlign(), "ivar");
Tim Northover238b5082014-03-29 13:42:40 +00006817 if (IsIvarOffsetKnownIdempotent(CGF, Ivar))
6818 cast<llvm::LoadInst>(IvarOffsetValue)
6819 ->setMetadata(CGM.getModule().getMDKindID("invariant.load"),
Craig Topper5fc8fc22014-08-27 06:28:36 +00006820 llvm::MDNode::get(VMContext, None));
Tim Northover238b5082014-03-29 13:42:40 +00006821
6822 // This could be 32bit int or 64bit integer depending on the architecture.
6823 // Cast it to 64bit integer value, if it is a 32bit integer ivar offset value
6824 // as this is what caller always expectes.
6825 if (ObjCTypes.IvarOffsetVarTy == ObjCTypes.IntTy)
6826 IvarOffsetValue = CGF.Builder.CreateIntCast(
6827 IvarOffsetValue, ObjCTypes.LongTy, true, "ivar.conv");
6828 return IvarOffsetValue;
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00006829}
6830
John McCall234eac82011-05-13 23:16:18 +00006831static void appendSelectorForMessageRefTable(std::string &buffer,
6832 Selector selector) {
6833 if (selector.isUnarySelector()) {
6834 buffer += selector.getNameForSlot(0);
6835 return;
6836 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006837
John McCall234eac82011-05-13 23:16:18 +00006838 for (unsigned i = 0, e = selector.getNumArgs(); i != e; ++i) {
6839 buffer += selector.getNameForSlot(i);
6840 buffer += '_';
6841 }
6842}
6843
Eric Christopherd160c502016-01-29 01:35:53 +00006844/// Emit a "vtable" message send. We emit a weak hidden-visibility
John McCall9e8bb002011-05-14 03:10:52 +00006845/// struct, initially containing the selector pointer and a pointer to
6846/// a "fixup" variant of the appropriate objc_msgSend. To call, we
6847/// load and call the function pointer, passing the address of the
6848/// struct as the second parameter. The runtime determines whether
6849/// the selector is currently emitted using vtable dispatch; if so, it
6850/// substitutes a stub function which simply tail-calls through the
6851/// appropriate vtable slot, and if not, it substitues a stub function
6852/// which tail-calls objc_msgSend. Both stubs adjust the selector
6853/// argument to correctly point to the selector.
6854RValue
6855CGObjCNonFragileABIMac::EmitVTableMessageSend(CodeGenFunction &CGF,
6856 ReturnValueSlot returnSlot,
6857 QualType resultType,
6858 Selector selector,
6859 llvm::Value *arg0,
6860 QualType arg0Type,
6861 bool isSuper,
6862 const CallArgList &formalArgs,
6863 const ObjCMethodDecl *method) {
John McCall234eac82011-05-13 23:16:18 +00006864 // Compute the actual arguments.
6865 CallArgList args;
6866
John McCall9e8bb002011-05-14 03:10:52 +00006867 // First argument: the receiver / super-call structure.
John McCall234eac82011-05-13 23:16:18 +00006868 if (!isSuper)
John McCall9e8bb002011-05-14 03:10:52 +00006869 arg0 = CGF.Builder.CreateBitCast(arg0, ObjCTypes.ObjectPtrTy);
6870 args.add(RValue::get(arg0), arg0Type);
John McCall234eac82011-05-13 23:16:18 +00006871
John McCall9e8bb002011-05-14 03:10:52 +00006872 // Second argument: a pointer to the message ref structure. Leave
6873 // the actual argument value blank for now.
Craig Topper8a13c412014-05-21 05:09:00 +00006874 args.add(RValue::get(nullptr), ObjCTypes.MessageRefCPtrTy);
John McCall234eac82011-05-13 23:16:18 +00006875
6876 args.insert(args.end(), formalArgs.begin(), formalArgs.end());
6877
John McCalla729c622012-02-17 03:33:10 +00006878 MessageSendInfo MSI = getMessageSendInfo(method, resultType, args);
John McCall234eac82011-05-13 23:16:18 +00006879
John McCall5880fb82011-05-14 21:12:11 +00006880 NullReturnState nullReturn;
6881
John McCall9e8bb002011-05-14 03:10:52 +00006882 // Find the function to call and the mangled name for the message
6883 // ref structure. Using a different mangled name wouldn't actually
6884 // be a problem; it would just be a waste.
6885 //
6886 // The runtime currently never uses vtable dispatch for anything
6887 // except normal, non-super message-sends.
6888 // FIXME: don't use this for that.
Craig Topper8a13c412014-05-21 05:09:00 +00006889 llvm::Constant *fn = nullptr;
John McCall234eac82011-05-13 23:16:18 +00006890 std::string messageRefName("\01l_");
Tim Northovere77cc392014-03-29 13:28:05 +00006891 if (CGM.ReturnSlotInterferesWithArgs(MSI.CallInfo)) {
John McCall234eac82011-05-13 23:16:18 +00006892 if (isSuper) {
6893 fn = ObjCTypes.getMessageSendSuper2StretFixupFn();
6894 messageRefName += "objc_msgSendSuper2_stret_fixup";
Chris Lattner396639d2010-08-18 16:09:06 +00006895 } else {
John McCall5880fb82011-05-14 21:12:11 +00006896 nullReturn.init(CGF, arg0);
John McCall234eac82011-05-13 23:16:18 +00006897 fn = ObjCTypes.getMessageSendStretFixupFn();
6898 messageRefName += "objc_msgSend_stret_fixup";
Chris Lattner396639d2010-08-18 16:09:06 +00006899 }
John McCall234eac82011-05-13 23:16:18 +00006900 } else if (!isSuper && CGM.ReturnTypeUsesFPRet(resultType)) {
6901 fn = ObjCTypes.getMessageSendFpretFixupFn();
6902 messageRefName += "objc_msgSend_fpret_fixup";
Mike Stump658fe022009-07-30 22:28:39 +00006903 } else {
John McCall234eac82011-05-13 23:16:18 +00006904 if (isSuper) {
6905 fn = ObjCTypes.getMessageSendSuper2FixupFn();
6906 messageRefName += "objc_msgSendSuper2_fixup";
Chris Lattner396639d2010-08-18 16:09:06 +00006907 } else {
John McCall234eac82011-05-13 23:16:18 +00006908 fn = ObjCTypes.getMessageSendFixupFn();
6909 messageRefName += "objc_msgSend_fixup";
Chris Lattner396639d2010-08-18 16:09:06 +00006910 }
Fariborz Jahaniane4dc35d2009-02-04 20:42:28 +00006911 }
John McCall234eac82011-05-13 23:16:18 +00006912 assert(fn && "CGObjCNonFragileABIMac::EmitMessageSend");
6913 messageRefName += '_';
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006914
John McCall234eac82011-05-13 23:16:18 +00006915 // Append the selector name, except use underscores anywhere we
6916 // would have used colons.
6917 appendSelectorForMessageRefTable(messageRefName, selector);
6918
6919 llvm::GlobalVariable *messageRef
6920 = CGM.getModule().getGlobalVariable(messageRefName);
6921 if (!messageRef) {
John McCall9e8bb002011-05-14 03:10:52 +00006922 // Build the message ref structure.
John McCall234eac82011-05-13 23:16:18 +00006923 llvm::Constant *values[] = { fn, GetMethodVarName(selector) };
Chris Lattnere64d7ba2011-06-20 04:01:35 +00006924 llvm::Constant *init = llvm::ConstantStruct::getAnon(values);
John McCall234eac82011-05-13 23:16:18 +00006925 messageRef = new llvm::GlobalVariable(CGM.getModule(),
6926 init->getType(),
6927 /*constant*/ false,
Rafael Espindola70efc5b2014-03-06 18:54:12 +00006928 llvm::GlobalValue::WeakAnyLinkage,
John McCall234eac82011-05-13 23:16:18 +00006929 init,
6930 messageRefName);
Rafael Espindola70efc5b2014-03-06 18:54:12 +00006931 messageRef->setVisibility(llvm::GlobalValue::HiddenVisibility);
John McCall234eac82011-05-13 23:16:18 +00006932 messageRef->setAlignment(16);
6933 messageRef->setSection("__DATA, __objc_msgrefs, coalesced");
6934 }
Rafael Espindola70efc5b2014-03-06 18:54:12 +00006935
Fariborz Jahanianc93fa982012-01-30 23:39:30 +00006936 bool requiresnullCheck = false;
David Blaikiebbafb8a2012-03-11 07:00:24 +00006937 if (CGM.getLangOpts().ObjCAutoRefCount && method)
David Majnemer59f77922016-06-24 04:05:48 +00006938 for (const auto *ParamDecl : method->parameters()) {
Fariborz Jahanianc93fa982012-01-30 23:39:30 +00006939 if (ParamDecl->hasAttr<NSConsumedAttr>()) {
6940 if (!nullReturn.NullBB)
6941 nullReturn.init(CGF, arg0);
6942 requiresnullCheck = true;
6943 break;
6944 }
6945 }
6946
John McCall7f416cc2015-09-08 08:05:57 +00006947 Address mref =
6948 Address(CGF.Builder.CreateBitCast(messageRef, ObjCTypes.MessageRefPtrTy),
6949 CGF.getPointerAlign());
John McCall234eac82011-05-13 23:16:18 +00006950
John McCall9e8bb002011-05-14 03:10:52 +00006951 // Update the message ref argument.
John McCall7f416cc2015-09-08 08:05:57 +00006952 args[1].RV = RValue::get(mref.getPointer());
John McCall234eac82011-05-13 23:16:18 +00006953
6954 // Load the function to call from the message ref table.
John McCall7f416cc2015-09-08 08:05:57 +00006955 Address calleeAddr =
6956 CGF.Builder.CreateStructGEP(mref, 0, CharUnits::Zero());
6957 llvm::Value *callee = CGF.Builder.CreateLoad(calleeAddr, "msgSend_fn");
John McCall234eac82011-05-13 23:16:18 +00006958
John McCalla729c622012-02-17 03:33:10 +00006959 callee = CGF.Builder.CreateBitCast(callee, MSI.MessengerType);
John McCall234eac82011-05-13 23:16:18 +00006960
John McCalla729c622012-02-17 03:33:10 +00006961 RValue result = CGF.EmitCall(MSI.CallInfo, callee, returnSlot, args);
Craig Topper8a13c412014-05-21 05:09:00 +00006962 return nullReturn.complete(CGF, result, resultType, formalArgs,
6963 requiresnullCheck ? method : nullptr);
Fariborz Jahanian3d9296e2009-02-04 00:22:57 +00006964}
6965
6966/// Generate code for a message send expression in the nonfragile abi.
Daniel Dunbaraff9fca2009-09-17 04:01:22 +00006967CodeGen::RValue
6968CGObjCNonFragileABIMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +00006969 ReturnValueSlot Return,
Daniel Dunbaraff9fca2009-09-17 04:01:22 +00006970 QualType ResultType,
6971 Selector Sel,
6972 llvm::Value *Receiver,
Daniel Dunbaraff9fca2009-09-17 04:01:22 +00006973 const CallArgList &CallArgs,
David Chisnall01aa4672010-04-28 19:33:36 +00006974 const ObjCInterfaceDecl *Class,
Daniel Dunbaraff9fca2009-09-17 04:01:22 +00006975 const ObjCMethodDecl *Method) {
John McCall9e8bb002011-05-14 03:10:52 +00006976 return isVTableDispatchedSelector(Sel)
6977 ? EmitVTableMessageSend(CGF, Return, ResultType, Sel,
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006978 Receiver, CGF.getContext().getObjCIdType(),
John McCall9e8bb002011-05-14 03:10:52 +00006979 false, CallArgs, Method)
6980 : EmitMessageSend(CGF, Return, ResultType,
John McCall882987f2013-02-28 19:01:20 +00006981 EmitSelector(CGF, Sel),
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006982 Receiver, CGF.getContext().getObjCIdType(),
John McCall1e3157b2015-09-10 22:27:50 +00006983 false, CallArgs, Method, Class, ObjCTypes);
Fariborz Jahanian3d9296e2009-02-04 00:22:57 +00006984}
6985
Daniel Dunbarc6928bb2009-03-01 04:40:10 +00006986llvm::GlobalVariable *
Benjamin Kramer0772c422016-02-13 13:42:54 +00006987CGObjCNonFragileABIMac::GetClassGlobal(StringRef Name, bool Weak) {
Rafael Espindola554256c2014-02-26 22:25:45 +00006988 llvm::GlobalValue::LinkageTypes L =
6989 Weak ? llvm::GlobalValue::ExternalWeakLinkage
6990 : llvm::GlobalValue::ExternalLinkage;
6991
Daniel Dunbarc6928bb2009-03-01 04:40:10 +00006992 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
6993
Rafael Espindola554256c2014-02-26 22:25:45 +00006994 if (!GV)
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006995 GV = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassnfABITy,
Craig Topper8a13c412014-05-21 05:09:00 +00006996 false, L, nullptr, Name);
Daniel Dunbarc6928bb2009-03-01 04:40:10 +00006997
Rafael Espindola554256c2014-02-26 22:25:45 +00006998 assert(GV->getLinkage() == L);
Daniel Dunbarc6928bb2009-03-01 04:40:10 +00006999 return GV;
7000}
7001
John McCall882987f2013-02-28 19:01:20 +00007002llvm::Value *CGObjCNonFragileABIMac::EmitClassRefFromId(CodeGenFunction &CGF,
Rafael Espindola554256c2014-02-26 22:25:45 +00007003 IdentifierInfo *II,
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00007004 bool Weak,
7005 const ObjCInterfaceDecl *ID) {
John McCall7f416cc2015-09-08 08:05:57 +00007006 CharUnits Align = CGF.getPointerAlign();
John McCall31168b02011-06-15 23:02:42 +00007007 llvm::GlobalVariable *&Entry = ClassReferences[II];
7008
Fariborz Jahanian33f66e62009-02-05 20:41:40 +00007009 if (!Entry) {
Saleem Abdulrasool1e6c4062016-05-16 05:06:49 +00007010 StringRef Name = ID ? ID->getObjCRuntimeNameAsString() : II->getName();
7011 std::string ClassName = (getClassSymbolPrefix() + Name).str();
Rafael Espindola554256c2014-02-26 22:25:45 +00007012 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName, Weak);
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00007013 Entry = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassnfABIPtrTy,
7014 false, llvm::GlobalValue::PrivateLinkage,
7015 ClassGV, "OBJC_CLASSLIST_REFERENCES_$_");
John McCall7f416cc2015-09-08 08:05:57 +00007016 Entry->setAlignment(Align.getQuantity());
Daniel Dunbar508a7dd2009-04-18 08:51:00 +00007017 Entry->setSection("__DATA, __objc_classrefs, regular, no_dead_strip");
Rafael Espindola060062a2014-03-06 22:15:10 +00007018 CGM.addCompilerUsedGlobal(Entry);
Daniel Dunbar508a7dd2009-04-18 08:51:00 +00007019 }
John McCall7f416cc2015-09-08 08:05:57 +00007020 return CGF.Builder.CreateAlignedLoad(Entry, Align);
Daniel Dunbar508a7dd2009-04-18 08:51:00 +00007021}
Fariborz Jahanian33f66e62009-02-05 20:41:40 +00007022
John McCall882987f2013-02-28 19:01:20 +00007023llvm::Value *CGObjCNonFragileABIMac::EmitClassRef(CodeGenFunction &CGF,
John McCall31168b02011-06-15 23:02:42 +00007024 const ObjCInterfaceDecl *ID) {
Douglas Gregor24ae22c2016-04-01 23:23:52 +00007025 // If the class has the objc_runtime_visible attribute, we need to
7026 // use the Objective-C runtime to get the class.
7027 if (ID->hasAttr<ObjCRuntimeVisibleAttr>())
7028 return EmitClassRefViaRuntime(CGF, ID, ObjCTypes);
7029
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00007030 return EmitClassRefFromId(CGF, ID->getIdentifier(), ID->isWeakImported(), ID);
John McCall31168b02011-06-15 23:02:42 +00007031}
7032
7033llvm::Value *CGObjCNonFragileABIMac::EmitNSAutoreleasePoolClassRef(
John McCall882987f2013-02-28 19:01:20 +00007034 CodeGenFunction &CGF) {
John McCall31168b02011-06-15 23:02:42 +00007035 IdentifierInfo *II = &CGM.getContext().Idents.get("NSAutoreleasePool");
Hans Wennborgdcfba332015-10-06 23:40:43 +00007036 return EmitClassRefFromId(CGF, II, false, nullptr);
John McCall31168b02011-06-15 23:02:42 +00007037}
7038
Daniel Dunbar508a7dd2009-04-18 08:51:00 +00007039llvm::Value *
John McCall882987f2013-02-28 19:01:20 +00007040CGObjCNonFragileABIMac::EmitSuperClassRef(CodeGenFunction &CGF,
Daniel Dunbar508a7dd2009-04-18 08:51:00 +00007041 const ObjCInterfaceDecl *ID) {
John McCall7f416cc2015-09-08 08:05:57 +00007042 CharUnits Align = CGF.getPointerAlign();
Daniel Dunbar508a7dd2009-04-18 08:51:00 +00007043 llvm::GlobalVariable *&Entry = SuperClassReferences[ID->getIdentifier()];
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007044
Daniel Dunbar508a7dd2009-04-18 08:51:00 +00007045 if (!Entry) {
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00007046 llvm::SmallString<64> ClassName(getClassSymbolPrefix());
7047 ClassName += ID->getObjCRuntimeNameAsString();
7048 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName.str(),
Fariborz Jahanianf322f2f2014-03-11 00:25:05 +00007049 ID->isWeakImported());
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00007050 Entry = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassnfABIPtrTy,
7051 false, llvm::GlobalValue::PrivateLinkage,
7052 ClassGV, "OBJC_CLASSLIST_SUP_REFS_$_");
John McCall7f416cc2015-09-08 08:05:57 +00007053 Entry->setAlignment(Align.getQuantity());
Daniel Dunbar508a7dd2009-04-18 08:51:00 +00007054 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Rafael Espindola060062a2014-03-06 22:15:10 +00007055 CGM.addCompilerUsedGlobal(Entry);
Fariborz Jahanian33f66e62009-02-05 20:41:40 +00007056 }
John McCall7f416cc2015-09-08 08:05:57 +00007057 return CGF.Builder.CreateAlignedLoad(Entry, Align);
Fariborz Jahanian33f66e62009-02-05 20:41:40 +00007058}
7059
Fariborz Jahanian6b7cd6e2009-02-06 20:09:23 +00007060/// EmitMetaClassRef - Return a Value * of the address of _class_t
7061/// meta-data
7062///
John McCall882987f2013-02-28 19:01:20 +00007063llvm::Value *CGObjCNonFragileABIMac::EmitMetaClassRef(CodeGenFunction &CGF,
Fariborz Jahanian0b3bc242014-06-10 17:08:04 +00007064 const ObjCInterfaceDecl *ID,
7065 bool Weak) {
John McCall7f416cc2015-09-08 08:05:57 +00007066 CharUnits Align = CGF.getPointerAlign();
Fariborz Jahanian6b7cd6e2009-02-06 20:09:23 +00007067 llvm::GlobalVariable * &Entry = MetaClassReferences[ID->getIdentifier()];
Rafael Espindola21039aa2014-02-27 16:26:32 +00007068 if (!Entry) {
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00007069 llvm::SmallString<64> MetaClassName(getMetaclassSymbolPrefix());
7070 MetaClassName += ID->getObjCRuntimeNameAsString();
Fariborz Jahanian0b3bc242014-06-10 17:08:04 +00007071 llvm::GlobalVariable *MetaClassGV =
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00007072 GetClassGlobal(MetaClassName.str(), Weak);
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00007073
Rafael Espindola21039aa2014-02-27 16:26:32 +00007074 Entry = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassnfABIPtrTy,
Rafael Espindola5179a4e2014-02-27 19:01:11 +00007075 false, llvm::GlobalValue::PrivateLinkage,
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00007076 MetaClassGV, "OBJC_CLASSLIST_SUP_REFS_$_");
John McCall7f416cc2015-09-08 08:05:57 +00007077 Entry->setAlignment(Align.getQuantity());
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007078
Rafael Espindola21039aa2014-02-27 16:26:32 +00007079 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Rafael Espindola060062a2014-03-06 22:15:10 +00007080 CGM.addCompilerUsedGlobal(Entry);
Rafael Espindola21039aa2014-02-27 16:26:32 +00007081 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007082
John McCall7f416cc2015-09-08 08:05:57 +00007083 return CGF.Builder.CreateAlignedLoad(Entry, Align);
Fariborz Jahanian6b7cd6e2009-02-06 20:09:23 +00007084}
7085
Fariborz Jahanian33f66e62009-02-05 20:41:40 +00007086/// GetClass - Return a reference to the class for the given interface
7087/// decl.
John McCall882987f2013-02-28 19:01:20 +00007088llvm::Value *CGObjCNonFragileABIMac::GetClass(CodeGenFunction &CGF,
Fariborz Jahanian33f66e62009-02-05 20:41:40 +00007089 const ObjCInterfaceDecl *ID) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00007090 if (ID->isWeakImported()) {
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00007091 llvm::SmallString<64> ClassName(getClassSymbolPrefix());
7092 ClassName += ID->getObjCRuntimeNameAsString();
7093 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName.str(), true);
Nick Lewycky9a441642014-02-27 00:36:00 +00007094 (void)ClassGV;
Rafael Espindolab3262952014-05-09 00:43:37 +00007095 assert(ClassGV->hasExternalWeakLinkage());
Fariborz Jahanian95ace552009-11-17 22:42:00 +00007096 }
7097
John McCall882987f2013-02-28 19:01:20 +00007098 return EmitClassRef(CGF, ID);
Fariborz Jahanian33f66e62009-02-05 20:41:40 +00007099}
7100
Fariborz Jahanian6b7cd6e2009-02-06 20:09:23 +00007101/// Generates a message send where the super is the receiver. This is
7102/// a message send to self with special delivery semantics indicating
7103/// which class's method should be called.
7104CodeGen::RValue
7105CGObjCNonFragileABIMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +00007106 ReturnValueSlot Return,
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007107 QualType ResultType,
7108 Selector Sel,
7109 const ObjCInterfaceDecl *Class,
7110 bool isCategoryImpl,
7111 llvm::Value *Receiver,
7112 bool IsClassMessage,
Daniel Dunbaraff9fca2009-09-17 04:01:22 +00007113 const CodeGen::CallArgList &CallArgs,
7114 const ObjCMethodDecl *Method) {
Fariborz Jahanian6b7cd6e2009-02-06 20:09:23 +00007115 // ...
7116 // Create and init a super structure; this is a (receiver, class)
7117 // pair we will pass to objc_msgSendSuper.
John McCall7f416cc2015-09-08 08:05:57 +00007118 Address ObjCSuper =
7119 CGF.CreateTempAlloca(ObjCTypes.SuperTy, CGF.getPointerAlign(),
7120 "objc_super");
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007121
Fariborz Jahanian6b7cd6e2009-02-06 20:09:23 +00007122 llvm::Value *ReceiverAsObject =
7123 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
David Blaikie1ed728c2015-04-05 22:45:47 +00007124 CGF.Builder.CreateStore(
7125 ReceiverAsObject,
John McCall7f416cc2015-09-08 08:05:57 +00007126 CGF.Builder.CreateStructGEP(ObjCSuper, 0, CharUnits::Zero()));
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007127
Fariborz Jahanian6b7cd6e2009-02-06 20:09:23 +00007128 // If this is a class message the metaclass is passed as the target.
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +00007129 llvm::Value *Target;
Fariborz Jahanian27678b02012-10-10 23:11:18 +00007130 if (IsClassMessage)
Fariborz Jahanian85b99da2014-08-28 17:05:17 +00007131 Target = EmitMetaClassRef(CGF, Class, Class->isWeakImported());
Fariborz Jahanian27678b02012-10-10 23:11:18 +00007132 else
John McCall882987f2013-02-28 19:01:20 +00007133 Target = EmitSuperClassRef(CGF, Class);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007134
Mike Stump18bb9282009-05-16 07:57:57 +00007135 // FIXME: We shouldn't need to do this cast, rectify the ASTContext and
7136 // ObjCTypes types.
Chris Lattner2192fe52011-07-18 04:24:23 +00007137 llvm::Type *ClassTy =
Fariborz Jahanian6b7cd6e2009-02-06 20:09:23 +00007138 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
7139 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
David Blaikie1ed728c2015-04-05 22:45:47 +00007140 CGF.Builder.CreateStore(
John McCall7f416cc2015-09-08 08:05:57 +00007141 Target, CGF.Builder.CreateStructGEP(ObjCSuper, 1, CGF.getPointerSize()));
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007142
John McCall9e8bb002011-05-14 03:10:52 +00007143 return (isVTableDispatchedSelector(Sel))
7144 ? EmitVTableMessageSend(CGF, Return, ResultType, Sel,
John McCall7f416cc2015-09-08 08:05:57 +00007145 ObjCSuper.getPointer(), ObjCTypes.SuperPtrCTy,
John McCall9e8bb002011-05-14 03:10:52 +00007146 true, CallArgs, Method)
7147 : EmitMessageSend(CGF, Return, ResultType,
John McCall882987f2013-02-28 19:01:20 +00007148 EmitSelector(CGF, Sel),
John McCall7f416cc2015-09-08 08:05:57 +00007149 ObjCSuper.getPointer(), ObjCTypes.SuperPtrCTy,
John McCall1e3157b2015-09-10 22:27:50 +00007150 true, CallArgs, Method, Class, ObjCTypes);
Fariborz Jahanian6b7cd6e2009-02-06 20:09:23 +00007151}
Fariborz Jahanian74b77222009-02-11 20:51:17 +00007152
John McCall882987f2013-02-28 19:01:20 +00007153llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00007154 Selector Sel) {
7155 Address Addr = EmitSelectorAddr(CGF, Sel);
7156
7157 llvm::LoadInst* LI = CGF.Builder.CreateLoad(Addr);
7158 LI->setMetadata(CGM.getModule().getMDKindID("invariant.load"),
7159 llvm::MDNode::get(VMContext, None));
7160 return LI;
7161}
7162
7163Address CGObjCNonFragileABIMac::EmitSelectorAddr(CodeGenFunction &CGF,
7164 Selector Sel) {
Fariborz Jahanian74b77222009-02-11 20:51:17 +00007165 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007166
John McCall7f416cc2015-09-08 08:05:57 +00007167 CharUnits Align = CGF.getPointerAlign();
Fariborz Jahanian74b77222009-02-11 20:51:17 +00007168 if (!Entry) {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007169 llvm::Constant *Casted =
7170 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
7171 ObjCTypes.SelectorPtrTy);
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00007172 Entry = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.SelectorPtrTy,
7173 false, llvm::GlobalValue::PrivateLinkage,
7174 Casted, "OBJC_SELECTOR_REFERENCES_");
Michael Gottesman5c205962013-02-05 23:08:45 +00007175 Entry->setExternallyInitialized(true);
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +00007176 Entry->setSection("__DATA, __objc_selrefs, literal_pointers, no_dead_strip");
John McCall7f416cc2015-09-08 08:05:57 +00007177 Entry->setAlignment(Align.getQuantity());
Rafael Espindola060062a2014-03-06 22:15:10 +00007178 CGM.addCompilerUsedGlobal(Entry);
Fariborz Jahanian74b77222009-02-11 20:51:17 +00007179 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007180
John McCall7f416cc2015-09-08 08:05:57 +00007181 return Address(Entry, Align);
Fariborz Jahanian74b77222009-02-11 20:51:17 +00007182}
John McCall7f416cc2015-09-08 08:05:57 +00007183
Fariborz Jahanian06292952009-02-16 22:52:32 +00007184/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00007185/// objc_assign_ivar (id src, id *dst, ptrdiff_t)
Fariborz Jahanian06292952009-02-16 22:52:32 +00007186///
7187void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +00007188 llvm::Value *src,
John McCall7f416cc2015-09-08 08:05:57 +00007189 Address dst,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00007190 llvm::Value *ivarOffset) {
Chris Lattner2192fe52011-07-18 04:24:23 +00007191 llvm::Type * SrcTy = src->getType();
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00007192 if (!isa<llvm::PointerType>(SrcTy)) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00007193 unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00007194 assert(Size <= 8 && "does not support size > 8");
7195 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
7196 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian1b074a32009-03-13 00:42:52 +00007197 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
7198 }
Fariborz Jahanian06292952009-02-16 22:52:32 +00007199 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
7200 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00007201 llvm::Value *args[] = { src, dst.getPointer(), ivarOffset };
John McCall882987f2013-02-28 19:01:20 +00007202 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignIvarFn(), args);
Fariborz Jahanian06292952009-02-16 22:52:32 +00007203}
7204
7205/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
7206/// objc_assign_strongCast (id src, id *dst)
7207///
7208void CGObjCNonFragileABIMac::EmitObjCStrongCastAssign(
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007209 CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00007210 llvm::Value *src, Address dst) {
Chris Lattner2192fe52011-07-18 04:24:23 +00007211 llvm::Type * SrcTy = src->getType();
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00007212 if (!isa<llvm::PointerType>(SrcTy)) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00007213 unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00007214 assert(Size <= 8 && "does not support size > 8");
7215 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007216 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian1b074a32009-03-13 00:42:52 +00007217 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
7218 }
Fariborz Jahanian06292952009-02-16 22:52:32 +00007219 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
7220 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00007221 llvm::Value *args[] = { src, dst.getPointer() };
John McCall882987f2013-02-28 19:01:20 +00007222 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignStrongCastFn(),
7223 args, "weakassign");
Fariborz Jahanian06292952009-02-16 22:52:32 +00007224}
7225
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00007226void CGObjCNonFragileABIMac::EmitGCMemmoveCollectable(
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007227 CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00007228 Address DestPtr,
7229 Address SrcPtr,
Fariborz Jahanian021510e2010-06-15 22:44:06 +00007230 llvm::Value *Size) {
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00007231 SrcPtr = CGF.Builder.CreateBitCast(SrcPtr, ObjCTypes.Int8PtrTy);
7232 DestPtr = CGF.Builder.CreateBitCast(DestPtr, ObjCTypes.Int8PtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00007233 llvm::Value *args[] = { DestPtr.getPointer(), SrcPtr.getPointer(), Size };
John McCall882987f2013-02-28 19:01:20 +00007234 CGF.EmitNounwindRuntimeCall(ObjCTypes.GcMemmoveCollectableFn(), args);
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00007235}
7236
Fariborz Jahanian06292952009-02-16 22:52:32 +00007237/// EmitObjCWeakRead - Code gen for loading value of a __weak
7238/// object: objc_read_weak (id *src)
7239///
7240llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead(
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007241 CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00007242 Address AddrWeakObj) {
7243 llvm::Type *DestTy = AddrWeakObj.getElementType();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007244 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
John McCall882987f2013-02-28 19:01:20 +00007245 llvm::Value *read_weak =
7246 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcReadWeakFn(),
John McCall7f416cc2015-09-08 08:05:57 +00007247 AddrWeakObj.getPointer(), "weakread");
Eli Friedmana374b682009-03-07 03:57:15 +00007248 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian06292952009-02-16 22:52:32 +00007249 return read_weak;
7250}
7251
7252/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
7253/// objc_assign_weak (id src, id *dst)
7254///
7255void CGObjCNonFragileABIMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00007256 llvm::Value *src, Address dst) {
Chris Lattner2192fe52011-07-18 04:24:23 +00007257 llvm::Type * SrcTy = src->getType();
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00007258 if (!isa<llvm::PointerType>(SrcTy)) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00007259 unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00007260 assert(Size <= 8 && "does not support size > 8");
7261 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
7262 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian1b074a32009-03-13 00:42:52 +00007263 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
7264 }
Fariborz Jahanian06292952009-02-16 22:52:32 +00007265 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
7266 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00007267 llvm::Value *args[] = { src, dst.getPointer() };
John McCall882987f2013-02-28 19:01:20 +00007268 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignWeakFn(),
7269 args, "weakassign");
Fariborz Jahanian06292952009-02-16 22:52:32 +00007270}
7271
7272/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
7273/// objc_assign_global (id src, id *dst)
7274///
7275void CGObjCNonFragileABIMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00007276 llvm::Value *src, Address dst,
Fariborz Jahanian217af242010-07-20 20:30:03 +00007277 bool threadlocal) {
Chris Lattner2192fe52011-07-18 04:24:23 +00007278 llvm::Type * SrcTy = src->getType();
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00007279 if (!isa<llvm::PointerType>(SrcTy)) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00007280 unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00007281 assert(Size <= 8 && "does not support size > 8");
7282 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
7283 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian1b074a32009-03-13 00:42:52 +00007284 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
7285 }
Fariborz Jahanian06292952009-02-16 22:52:32 +00007286 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
7287 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00007288 llvm::Value *args[] = { src, dst.getPointer() };
Fariborz Jahanian217af242010-07-20 20:30:03 +00007289 if (!threadlocal)
John McCall882987f2013-02-28 19:01:20 +00007290 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignGlobalFn(),
7291 args, "globalassign");
Fariborz Jahanian217af242010-07-20 20:30:03 +00007292 else
John McCall882987f2013-02-28 19:01:20 +00007293 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignThreadLocalFn(),
7294 args, "threadlocalassign");
Fariborz Jahanian06292952009-02-16 22:52:32 +00007295}
Fariborz Jahanian74b77222009-02-11 20:51:17 +00007296
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007297void
John McCallbd309292010-07-06 01:34:17 +00007298CGObjCNonFragileABIMac::EmitSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
7299 const ObjCAtSynchronizedStmt &S) {
David Chisnall3e575602011-03-25 17:46:35 +00007300 EmitAtSynchronizedStmt(CGF, S,
7301 cast<llvm::Function>(ObjCTypes.getSyncEnterFn()),
7302 cast<llvm::Function>(ObjCTypes.getSyncExitFn()));
John McCallbd309292010-07-06 01:34:17 +00007303}
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007304
John McCall2ca705e2010-07-24 00:37:23 +00007305llvm::Constant *
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +00007306CGObjCNonFragileABIMac::GetEHType(QualType T) {
John McCall2ca705e2010-07-24 00:37:23 +00007307 // There's a particular fixed type info for 'id'.
Saleem Abdulrasoole5f3eae2016-07-17 22:27:38 +00007308 if (T->isObjCIdType() || T->isObjCQualifiedIdType()) {
7309 auto *IDEHType = CGM.getModule().getGlobalVariable("OBJC_EHTYPE_id");
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00007310 if (!IDEHType) {
John McCall2ca705e2010-07-24 00:37:23 +00007311 IDEHType =
Saleem Abdulrasoole5f3eae2016-07-17 22:27:38 +00007312 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.EHTypeTy, false,
7313 llvm::GlobalValue::ExternalLinkage, nullptr,
7314 "OBJC_EHTYPE_id");
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00007315 if (CGM.getTriple().isOSBinFormatCOFF())
7316 IDEHType->setDLLStorageClass(getStorage(CGM, "OBJC_EHTYPE_id"));
7317 }
John McCall2ca705e2010-07-24 00:37:23 +00007318 return IDEHType;
7319 }
7320
7321 // All other types should be Objective-C interface pointer types.
Saleem Abdulrasoole5f3eae2016-07-17 22:27:38 +00007322 const ObjCObjectPointerType *PT = T->getAs<ObjCObjectPointerType>();
John McCall2ca705e2010-07-24 00:37:23 +00007323 assert(PT && "Invalid @catch type.");
Saleem Abdulrasoole5f3eae2016-07-17 22:27:38 +00007324
John McCall2ca705e2010-07-24 00:37:23 +00007325 const ObjCInterfaceType *IT = PT->getInterfaceType();
7326 assert(IT && "Invalid @catch type.");
Saleem Abdulrasoole5f3eae2016-07-17 22:27:38 +00007327
John McCall2ca705e2010-07-24 00:37:23 +00007328 return GetInterfaceEHType(IT->getDecl(), false);
Saleem Abdulrasoole5f3eae2016-07-17 22:27:38 +00007329}
John McCall2ca705e2010-07-24 00:37:23 +00007330
John McCallbd309292010-07-06 01:34:17 +00007331void CGObjCNonFragileABIMac::EmitTryStmt(CodeGen::CodeGenFunction &CGF,
7332 const ObjCAtTryStmt &S) {
David Chisnall3e575602011-03-25 17:46:35 +00007333 EmitTryCatchStmt(CGF, S,
7334 cast<llvm::Function>(ObjCTypes.getObjCBeginCatchFn()),
7335 cast<llvm::Function>(ObjCTypes.getObjCEndCatchFn()),
7336 cast<llvm::Function>(ObjCTypes.getExceptionRethrowFn()));
Daniel Dunbar0b0dcd92009-02-24 07:47:38 +00007337}
7338
Anders Carlsson9ab53d12009-02-16 22:59:18 +00007339/// EmitThrowStmt - Generate code for a throw statement.
7340void CGObjCNonFragileABIMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian1eab0522013-01-10 19:02:56 +00007341 const ObjCAtThrowStmt &S,
7342 bool ClearInsertionPoint) {
Anders Carlsson9ab53d12009-02-16 22:59:18 +00007343 if (const Expr *ThrowExpr = S.getThrowExpr()) {
John McCall248512a2011-10-01 10:32:24 +00007344 llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00007345 Exception = CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy);
John McCall882987f2013-02-28 19:01:20 +00007346 CGF.EmitRuntimeCallOrInvoke(ObjCTypes.getExceptionThrowFn(), Exception)
John McCall17afe452010-10-16 08:21:07 +00007347 .setDoesNotReturn();
Anders Carlsson9ab53d12009-02-16 22:59:18 +00007348 } else {
John McCall882987f2013-02-28 19:01:20 +00007349 CGF.EmitRuntimeCallOrInvoke(ObjCTypes.getExceptionRethrowFn())
John McCall17afe452010-10-16 08:21:07 +00007350 .setDoesNotReturn();
Anders Carlsson9ab53d12009-02-16 22:59:18 +00007351 }
7352
John McCall17afe452010-10-16 08:21:07 +00007353 CGF.Builder.CreateUnreachable();
Fariborz Jahanian1eab0522013-01-10 19:02:56 +00007354 if (ClearInsertionPoint)
7355 CGF.Builder.ClearInsertionPoint();
Anders Carlsson9ab53d12009-02-16 22:59:18 +00007356}
Daniel Dunbarb1559a42009-03-01 04:46:24 +00007357
John McCall2ca705e2010-07-24 00:37:23 +00007358llvm::Constant *
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007359CGObjCNonFragileABIMac::GetInterfaceEHType(const ObjCInterfaceDecl *ID,
Daniel Dunbar8f28d012009-04-08 04:21:03 +00007360 bool ForDefinition) {
Daniel Dunbarb1559a42009-03-01 04:46:24 +00007361 llvm::GlobalVariable * &Entry = EHTypeReferences[ID->getIdentifier()];
Saleem Abdulrasoole5f3eae2016-07-17 22:27:38 +00007362 StringRef ClassName = ID->getObjCRuntimeNameAsString();
Daniel Dunbarb1559a42009-03-01 04:46:24 +00007363
Daniel Dunbar8f28d012009-04-08 04:21:03 +00007364 // If we don't need a definition, return the entry if found or check
7365 // if we use an external reference.
7366 if (!ForDefinition) {
7367 if (Entry)
7368 return Entry;
Daniel Dunbard7beeea2009-04-07 06:43:45 +00007369
Daniel Dunbar8f28d012009-04-08 04:21:03 +00007370 // If this type (or a super class) has the __objc_exception__
7371 // attribute, emit an external reference.
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00007372 if (hasObjCExceptionAttribute(CGM.getContext(), ID)) {
7373 std::string EHTypeName = ("OBJC_EHTYPE_$_" + ClassName).str();
7374 Entry = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.EHTypeTy,
7375 false, llvm::GlobalValue::ExternalLinkage,
7376 nullptr, EHTypeName);
7377 if (CGM.getTriple().isOSBinFormatCOFF()) {
7378 if (ID->hasAttr<DLLExportAttr>())
7379 Entry->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
7380 else if (ID->hasAttr<DLLImportAttr>())
7381 Entry->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
7382 }
7383 return Entry;
7384 }
Daniel Dunbar8f28d012009-04-08 04:21:03 +00007385 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007386
Saleem Abdulrasoole5f3eae2016-07-17 22:27:38 +00007387 // Otherwise we need to either make a new entry or fill in the initializer.
Daniel Dunbar8f28d012009-04-08 04:21:03 +00007388 assert((!Entry || !Entry->hasInitializer()) && "Duplicate EHType definition");
Saleem Abdulrasoole5f3eae2016-07-17 22:27:38 +00007389
Daniel Dunbarb1559a42009-03-01 04:46:24 +00007390 std::string VTableName = "objc_ehtype_vtable";
Saleem Abdulrasoole5f3eae2016-07-17 22:27:38 +00007391 auto *VTableGV = CGM.getModule().getGlobalVariable(VTableName);
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00007392 if (!VTableGV) {
Saleem Abdulrasoole5f3eae2016-07-17 22:27:38 +00007393 VTableGV =
7394 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.Int8PtrTy, false,
7395 llvm::GlobalValue::ExternalLinkage, nullptr,
7396 VTableName);
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00007397 if (CGM.getTriple().isOSBinFormatCOFF())
7398 VTableGV->setDLLStorageClass(getStorage(CGM, VTableName));
7399 }
Daniel Dunbarb1559a42009-03-01 04:46:24 +00007400
Chris Lattnerece04092012-02-07 00:39:47 +00007401 llvm::Value *VTableIdx = llvm::ConstantInt::get(CGM.Int32Ty, 2);
Benjamin Kramer22d24c22011-10-15 12:20:02 +00007402 llvm::Constant *Values[] = {
David Blaikiee3b172a2015-04-02 18:55:21 +00007403 llvm::ConstantExpr::getGetElementPtr(VTableGV->getValueType(), VTableGV,
7404 VTableIdx),
7405 GetClassName(ID->getObjCRuntimeNameAsString()),
Saleem Abdulrasoole5f3eae2016-07-17 22:27:38 +00007406 GetClassGlobal((getClassSymbolPrefix() + ClassName).str()),
7407 };
7408 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.EHTypeTy, Values);
Daniel Dunbarb1559a42009-03-01 04:46:24 +00007409
Rafael Espindola554256c2014-02-26 22:25:45 +00007410 llvm::GlobalValue::LinkageTypes L = ForDefinition
7411 ? llvm::GlobalValue::ExternalLinkage
7412 : llvm::GlobalValue::WeakAnyLinkage;
Daniel Dunbar8f28d012009-04-08 04:21:03 +00007413 if (Entry) {
7414 Entry->setInitializer(Init);
7415 } else {
Saleem Abdulrasoole5f3eae2016-07-17 22:27:38 +00007416 Entry =
7417 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.EHTypeTy, false, L,
7418 Init, ("OBJC_EHTYPE_$_" + ClassName).str());
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00007419 if (CGM.getTriple().isOSBinFormatCOFF())
7420 if (hasObjCExceptionAttribute(CGM.getContext(), ID))
7421 if (ID->hasAttr<DLLExportAttr>())
7422 Entry->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
Daniel Dunbar8f28d012009-04-08 04:21:03 +00007423 }
Rafael Espindola554256c2014-02-26 22:25:45 +00007424 assert(Entry->getLinkage() == L);
Daniel Dunbar8f28d012009-04-08 04:21:03 +00007425
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00007426 if (!CGM.getTriple().isOSBinFormatCOFF())
7427 if (ID->getVisibility() == HiddenVisibility)
7428 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
Saleem Abdulrasoole5f3eae2016-07-17 22:27:38 +00007429
7430 const auto &DL = CGM.getDataLayout();
7431 Entry->setAlignment(DL.getABITypeAlignment(ObjCTypes.EHTypeTy));
Daniel Dunbar8f28d012009-04-08 04:21:03 +00007432
Rafael Espindola554256c2014-02-26 22:25:45 +00007433 if (ForDefinition)
Daniel Dunbar8f28d012009-04-08 04:21:03 +00007434 Entry->setSection("__DATA,__objc_const");
Daniel Dunbarb1559a42009-03-01 04:46:24 +00007435
7436 return Entry;
7437}
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007438
Daniel Dunbar8b8683f2008-08-12 00:12:39 +00007439/* *** */
7440
Daniel Dunbarb036db82008-08-13 03:21:16 +00007441CodeGen::CGObjCRuntime *
7442CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
John McCall5fb5df92012-06-20 06:18:46 +00007443 switch (CGM.getLangOpts().ObjCRuntime.getKind()) {
7444 case ObjCRuntime::FragileMacOSX:
Daniel Dunbar303e2c22008-08-11 02:45:11 +00007445 return new CGObjCMac(CGM);
John McCall5fb5df92012-06-20 06:18:46 +00007446
7447 case ObjCRuntime::MacOSX:
7448 case ObjCRuntime::iOS:
Tim Northover756447a2015-10-30 16:30:36 +00007449 case ObjCRuntime::WatchOS:
John McCall5fb5df92012-06-20 06:18:46 +00007450 return new CGObjCNonFragileABIMac(CGM);
7451
David Chisnallb601c962012-07-03 20:49:52 +00007452 case ObjCRuntime::GNUstep:
7453 case ObjCRuntime::GCC:
John McCall775086e2012-07-12 02:07:58 +00007454 case ObjCRuntime::ObjFW:
John McCall5fb5df92012-06-20 06:18:46 +00007455 llvm_unreachable("these runtimes are not Mac runtimes");
7456 }
7457 llvm_unreachable("bad runtime");
Daniel Dunbar303e2c22008-08-11 02:45:11 +00007458}