blob: 06b77a0914ff0aa31b31229992652ab5388b5551 [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 McCallb92ab1a2016-10-26 23:46:34 +00001981 CGCallee Callee = CGCallee::forDirect(Fn);
1982 RValue rvalue = CGF.EmitCall(MSI.CallInfo, Callee, Return, ActualArgs,
1983 &CallSite);
John McCall1e3157b2015-09-10 22:27:50 +00001984
1985 // Mark the call as noreturn if the method is marked noreturn and the
1986 // receiver cannot be null.
1987 if (Method && Method->hasAttr<NoReturnAttr>() && !ReceiverCanBeNull) {
1988 llvm::CallSite(CallSite).setDoesNotReturn();
1989 }
1990
Fariborz Jahanianf2bda692012-01-30 21:40:37 +00001991 return nullReturn.complete(CGF, rvalue, ResultType, CallArgs,
John McCall1e3157b2015-09-10 22:27:50 +00001992 RequiresNullCheck ? Method : nullptr);
Daniel Dunbar303e2c22008-08-11 02:45:11 +00001993}
1994
John McCall3fd13f062015-10-21 18:06:47 +00001995static Qualifiers::GC GetGCAttrTypeForType(ASTContext &Ctx, QualType FQT,
1996 bool pointee = false) {
1997 // Note that GC qualification applies recursively to C pointer types
1998 // that aren't otherwise decorated. This is weird, but it's probably
1999 // an intentional workaround to the unreliable placement of GC qualifiers.
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00002000 if (FQT.isObjCGCStrong())
2001 return Qualifiers::Strong;
John McCall3fd13f062015-10-21 18:06:47 +00002002
2003 if (FQT.isObjCGCWeak())
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00002004 return Qualifiers::Weak;
John McCall3fd13f062015-10-21 18:06:47 +00002005
2006 if (auto ownership = FQT.getObjCLifetime()) {
2007 // Ownership does not apply recursively to C pointer types.
2008 if (pointee) return Qualifiers::GCNone;
2009 switch (ownership) {
2010 case Qualifiers::OCL_Weak: return Qualifiers::Weak;
2011 case Qualifiers::OCL_Strong: return Qualifiers::Strong;
2012 case Qualifiers::OCL_ExplicitNone: return Qualifiers::GCNone;
2013 case Qualifiers::OCL_Autoreleasing: llvm_unreachable("autoreleasing ivar?");
2014 case Qualifiers::OCL_None: llvm_unreachable("known nonzero");
2015 }
2016 llvm_unreachable("bad objc ownership");
2017 }
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00002018
John McCall3fd13f062015-10-21 18:06:47 +00002019 // Treat unqualified retainable pointers as strong.
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00002020 if (FQT->isObjCObjectPointerType() || FQT->isBlockPointerType())
2021 return Qualifiers::Strong;
2022
John McCall3fd13f062015-10-21 18:06:47 +00002023 // Walk into C pointer types, but only in GC.
2024 if (Ctx.getLangOpts().getGC() != LangOptions::NonGC) {
2025 if (const PointerType *PT = FQT->getAs<PointerType>())
2026 return GetGCAttrTypeForType(Ctx, PT->getPointeeType(), /*pointee*/ true);
2027 }
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00002028
2029 return Qualifiers::GCNone;
2030}
2031
John McCall3fd13f062015-10-21 18:06:47 +00002032namespace {
2033 struct IvarInfo {
2034 CharUnits Offset;
2035 uint64_t SizeInWords;
2036 IvarInfo(CharUnits offset, uint64_t sizeInWords)
2037 : Offset(offset), SizeInWords(sizeInWords) {}
2038
2039 // Allow sorting based on byte pos.
2040 bool operator<(const IvarInfo &other) const {
2041 return Offset < other.Offset;
2042 }
2043 };
2044
2045 /// A helper class for building GC layout strings.
2046 class IvarLayoutBuilder {
2047 CodeGenModule &CGM;
2048
2049 /// The start of the layout. Offsets will be relative to this value,
2050 /// and entries less than this value will be silently discarded.
2051 CharUnits InstanceBegin;
2052
2053 /// The end of the layout. Offsets will never exceed this value.
2054 CharUnits InstanceEnd;
2055
2056 /// Whether we're generating the strong layout or the weak layout.
2057 bool ForStrongLayout;
2058
2059 /// Whether the offsets in IvarsInfo might be out-of-order.
2060 bool IsDisordered = false;
2061
2062 llvm::SmallVector<IvarInfo, 8> IvarsInfo;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00002063
John McCall3fd13f062015-10-21 18:06:47 +00002064 public:
2065 IvarLayoutBuilder(CodeGenModule &CGM, CharUnits instanceBegin,
2066 CharUnits instanceEnd, bool forStrongLayout)
2067 : CGM(CGM), InstanceBegin(instanceBegin), InstanceEnd(instanceEnd),
2068 ForStrongLayout(forStrongLayout) {
2069 }
2070
2071 void visitRecord(const RecordType *RT, CharUnits offset);
2072
2073 template <class Iterator, class GetOffsetFn>
2074 void visitAggregate(Iterator begin, Iterator end,
2075 CharUnits aggrOffset,
2076 const GetOffsetFn &getOffset);
2077
2078 void visitField(const FieldDecl *field, CharUnits offset);
2079
2080 /// Add the layout of a block implementation.
2081 void visitBlock(const CGBlockInfo &blockInfo);
2082
2083 /// Is there any information for an interesting bitmap?
2084 bool hasBitmapData() const { return !IvarsInfo.empty(); }
2085
2086 llvm::Constant *buildBitmap(CGObjCCommonMac &CGObjC,
2087 llvm::SmallVectorImpl<unsigned char> &buffer);
2088
2089 static void dump(ArrayRef<unsigned char> buffer) {
2090 const unsigned char *s = buffer.data();
2091 for (unsigned i = 0, e = buffer.size(); i < e; i++)
2092 if (!(s[i] & 0xf0))
2093 printf("0x0%x%s", s[i], s[i] != 0 ? ", " : "");
2094 else
2095 printf("0x%x%s", s[i], s[i] != 0 ? ", " : "");
2096 printf("\n");
2097 }
2098 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00002099} // end anonymous namespace
John McCall3fd13f062015-10-21 18:06:47 +00002100
John McCall351762c2011-02-07 10:33:21 +00002101llvm::Constant *CGObjCCommonMac::BuildGCBlockLayout(CodeGenModule &CGM,
2102 const CGBlockInfo &blockInfo) {
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +00002103
Chris Lattnerece04092012-02-07 00:39:47 +00002104 llvm::Constant *nullPtr = llvm::Constant::getNullValue(CGM.Int8PtrTy);
John McCall460ce582015-10-22 18:38:17 +00002105 if (CGM.getLangOpts().getGC() == LangOptions::NonGC)
John McCall351762c2011-02-07 10:33:21 +00002106 return nullPtr;
2107
John McCall3fd13f062015-10-21 18:06:47 +00002108 IvarLayoutBuilder builder(CGM, CharUnits::Zero(), blockInfo.BlockSize,
2109 /*for strong layout*/ true);
2110
2111 builder.visitBlock(blockInfo);
2112
2113 if (!builder.hasBitmapData())
2114 return nullPtr;
2115
2116 llvm::SmallVector<unsigned char, 32> buffer;
2117 llvm::Constant *C = builder.buildBitmap(*this, buffer);
John McCallf5ea0722015-10-29 23:36:14 +00002118 if (CGM.getLangOpts().ObjCGCBitmapPrint && !buffer.empty()) {
John McCall3fd13f062015-10-21 18:06:47 +00002119 printf("\n block variable layout for block: ");
2120 builder.dump(buffer);
2121 }
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00002122
John McCall3fd13f062015-10-21 18:06:47 +00002123 return C;
2124}
2125
2126void IvarLayoutBuilder::visitBlock(const CGBlockInfo &blockInfo) {
Fariborz Jahaniancfddabf2010-09-09 00:21:45 +00002127 // __isa is the first field in block descriptor and must assume by runtime's
2128 // convention that it is GC'able.
John McCall3fd13f062015-10-21 18:06:47 +00002129 IvarsInfo.push_back(IvarInfo(CharUnits::Zero(), 1));
John McCall351762c2011-02-07 10:33:21 +00002130
2131 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
2132
John McCall351762c2011-02-07 10:33:21 +00002133 // Ignore the optional 'this' capture: C++ objects are not assumed
2134 // to be GC'ed.
2135
John McCall3fd13f062015-10-21 18:06:47 +00002136 CharUnits lastFieldOffset;
2137
John McCall351762c2011-02-07 10:33:21 +00002138 // Walk the captured variables.
Aaron Ballman9371dd22014-03-14 18:34:04 +00002139 for (const auto &CI : blockDecl->captures()) {
2140 const VarDecl *variable = CI.getVariable();
John McCall351762c2011-02-07 10:33:21 +00002141 QualType type = variable->getType();
2142
2143 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
2144
2145 // Ignore constant captures.
2146 if (capture.isConstant()) continue;
2147
John McCall3fd13f062015-10-21 18:06:47 +00002148 CharUnits fieldOffset = capture.getOffset();
2149
2150 // Block fields are not necessarily ordered; if we detect that we're
2151 // adding them out-of-order, make sure we sort later.
2152 if (fieldOffset < lastFieldOffset)
2153 IsDisordered = true;
2154 lastFieldOffset = fieldOffset;
John McCall351762c2011-02-07 10:33:21 +00002155
2156 // __block variables are passed by their descriptor address.
Aaron Ballman9371dd22014-03-14 18:34:04 +00002157 if (CI.isByRef()) {
John McCall3fd13f062015-10-21 18:06:47 +00002158 IvarsInfo.push_back(IvarInfo(fieldOffset, /*size in words*/ 1));
Fariborz Jahanian933c6722010-09-11 01:27:29 +00002159 continue;
John McCall351762c2011-02-07 10:33:21 +00002160 }
2161
2162 assert(!type->isArrayType() && "array variable should not be caught");
2163 if (const RecordType *record = type->getAs<RecordType>()) {
John McCall3fd13f062015-10-21 18:06:47 +00002164 visitRecord(record, fieldOffset);
Fariborz Jahanian903aba32010-08-05 21:00:25 +00002165 continue;
2166 }
Fariborz Jahanianf95e3582010-08-06 16:28:55 +00002167
John McCall351762c2011-02-07 10:33:21 +00002168 Qualifiers::GC GCAttr = GetGCAttrTypeForType(CGM.getContext(), type);
John McCall351762c2011-02-07 10:33:21 +00002169
John McCall3fd13f062015-10-21 18:06:47 +00002170 if (GCAttr == Qualifiers::Strong) {
2171 assert(CGM.getContext().getTypeSize(type)
2172 == CGM.getTarget().getPointerWidth(0));
2173 IvarsInfo.push_back(IvarInfo(fieldOffset, /*size in words*/ 1));
2174 }
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00002175 }
Fariborz Jahanianc05349e2010-08-04 16:57:49 +00002176}
2177
Fariborz Jahanian2c96d302012-11-04 18:19:40 +00002178/// getBlockCaptureLifetime - This routine returns life time of the captured
2179/// block variable for the purpose of block layout meta-data generation. FQT is
2180/// the type of the variable captured in the block.
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002181Qualifiers::ObjCLifetime CGObjCCommonMac::getBlockCaptureLifetime(QualType FQT,
2182 bool ByrefLayout) {
John McCall460ce582015-10-22 18:38:17 +00002183 // If it has an ownership qualifier, we're done.
2184 if (auto lifetime = FQT.getObjCLifetime())
2185 return lifetime;
2186
2187 // If it doesn't, and this is ARC, it has no ownership.
Fariborz Jahanian2dd78192012-11-02 22:51:18 +00002188 if (CGM.getLangOpts().ObjCAutoRefCount)
John McCall460ce582015-10-22 18:38:17 +00002189 return Qualifiers::OCL_None;
Fariborz Jahanian2dd78192012-11-02 22:51:18 +00002190
John McCall460ce582015-10-22 18:38:17 +00002191 // In MRC, retainable pointers are owned by non-__block variables.
Fariborz Jahanian2dd78192012-11-02 22:51:18 +00002192 if (FQT->isObjCObjectPointerType() || FQT->isBlockPointerType())
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002193 return ByrefLayout ? Qualifiers::OCL_ExplicitNone : Qualifiers::OCL_Strong;
Fariborz Jahanian2dd78192012-11-02 22:51:18 +00002194
2195 return Qualifiers::OCL_None;
2196}
2197
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002198void CGObjCCommonMac::UpdateRunSkipBlockVars(bool IsByref,
2199 Qualifiers::ObjCLifetime LifeTime,
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002200 CharUnits FieldOffset,
2201 CharUnits FieldSize) {
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002202 // __block variables are passed by their descriptor address.
2203 if (IsByref)
2204 RunSkipBlockVars.push_back(RUN_SKIP(BLOCK_LAYOUT_BYREF, FieldOffset,
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002205 FieldSize));
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002206 else if (LifeTime == Qualifiers::OCL_Strong)
2207 RunSkipBlockVars.push_back(RUN_SKIP(BLOCK_LAYOUT_STRONG, FieldOffset,
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002208 FieldSize));
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002209 else if (LifeTime == Qualifiers::OCL_Weak)
2210 RunSkipBlockVars.push_back(RUN_SKIP(BLOCK_LAYOUT_WEAK, FieldOffset,
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002211 FieldSize));
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002212 else if (LifeTime == Qualifiers::OCL_ExplicitNone)
2213 RunSkipBlockVars.push_back(RUN_SKIP(BLOCK_LAYOUT_UNRETAINED, FieldOffset,
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002214 FieldSize));
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002215 else
2216 RunSkipBlockVars.push_back(RUN_SKIP(BLOCK_LAYOUT_NON_OBJECT_BYTES,
2217 FieldOffset,
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002218 FieldSize));
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002219}
2220
2221void CGObjCCommonMac::BuildRCRecordLayout(const llvm::StructLayout *RecLayout,
2222 const RecordDecl *RD,
2223 ArrayRef<const FieldDecl*> RecFields,
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002224 CharUnits BytePos, bool &HasUnion,
2225 bool ByrefLayout) {
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002226 bool IsUnion = (RD && RD->isUnion());
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002227 CharUnits MaxUnionSize = CharUnits::Zero();
Craig Topper8a13c412014-05-21 05:09:00 +00002228 const FieldDecl *MaxField = nullptr;
2229 const FieldDecl *LastFieldBitfieldOrUnnamed = nullptr;
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002230 CharUnits MaxFieldOffset = CharUnits::Zero();
2231 CharUnits LastBitfieldOrUnnamedOffset = CharUnits::Zero();
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002232
2233 if (RecFields.empty())
2234 return;
John McCallc8e01702013-04-16 22:48:15 +00002235 unsigned ByteSizeInBits = CGM.getTarget().getCharWidth();
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002236
2237 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
2238 const FieldDecl *Field = RecFields[i];
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002239 // Note that 'i' here is actually the field index inside RD of Field,
2240 // although this dependency is hidden.
2241 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002242 CharUnits FieldOffset =
2243 CGM.getContext().toCharUnitsFromBits(RL.getFieldOffset(i));
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002244
2245 // Skip over unnamed or bitfields
2246 if (!Field->getIdentifier() || Field->isBitField()) {
2247 LastFieldBitfieldOrUnnamed = Field;
2248 LastBitfieldOrUnnamedOffset = FieldOffset;
2249 continue;
2250 }
Craig Topper8a13c412014-05-21 05:09:00 +00002251
2252 LastFieldBitfieldOrUnnamed = nullptr;
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002253 QualType FQT = Field->getType();
2254 if (FQT->isRecordType() || FQT->isUnionType()) {
2255 if (FQT->isUnionType())
2256 HasUnion = true;
2257
2258 BuildRCBlockVarRecordLayout(FQT->getAs<RecordType>(),
2259 BytePos + FieldOffset, HasUnion);
2260 continue;
2261 }
2262
2263 if (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
2264 const ConstantArrayType *CArray =
2265 dyn_cast_or_null<ConstantArrayType>(Array);
2266 uint64_t ElCount = CArray->getSize().getZExtValue();
2267 assert(CArray && "only array with known element size is supported");
2268 FQT = CArray->getElementType();
2269 while (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
2270 const ConstantArrayType *CArray =
2271 dyn_cast_or_null<ConstantArrayType>(Array);
2272 ElCount *= CArray->getSize().getZExtValue();
2273 FQT = CArray->getElementType();
2274 }
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002275 if (FQT->isRecordType() && ElCount) {
2276 int OldIndex = RunSkipBlockVars.size() - 1;
2277 const RecordType *RT = FQT->getAs<RecordType>();
2278 BuildRCBlockVarRecordLayout(RT, BytePos + FieldOffset,
2279 HasUnion);
2280
2281 // Replicate layout information for each array element. Note that
2282 // one element is already done.
2283 uint64_t ElIx = 1;
2284 for (int FirstIndex = RunSkipBlockVars.size() - 1 ;ElIx < ElCount; ElIx++) {
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002285 CharUnits Size = CGM.getContext().getTypeSizeInChars(RT);
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002286 for (int i = OldIndex+1; i <= FirstIndex; ++i)
2287 RunSkipBlockVars.push_back(
2288 RUN_SKIP(RunSkipBlockVars[i].opcode,
2289 RunSkipBlockVars[i].block_var_bytepos + Size*ElIx,
2290 RunSkipBlockVars[i].block_var_size));
2291 }
2292 continue;
2293 }
2294 }
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002295 CharUnits FieldSize = CGM.getContext().getTypeSizeInChars(Field->getType());
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002296 if (IsUnion) {
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002297 CharUnits UnionIvarSize = FieldSize;
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002298 if (UnionIvarSize > MaxUnionSize) {
2299 MaxUnionSize = UnionIvarSize;
2300 MaxField = Field;
2301 MaxFieldOffset = FieldOffset;
2302 }
2303 } else {
2304 UpdateRunSkipBlockVars(false,
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002305 getBlockCaptureLifetime(FQT, ByrefLayout),
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002306 BytePos + FieldOffset,
2307 FieldSize);
2308 }
2309 }
2310
2311 if (LastFieldBitfieldOrUnnamed) {
2312 if (LastFieldBitfieldOrUnnamed->isBitField()) {
2313 // Last field was a bitfield. Must update the info.
2314 uint64_t BitFieldSize
2315 = LastFieldBitfieldOrUnnamed->getBitWidthValue(CGM.getContext());
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002316 unsigned UnsSize = (BitFieldSize / ByteSizeInBits) +
Eli Friedman8cbca202012-11-06 22:15:52 +00002317 ((BitFieldSize % ByteSizeInBits) != 0);
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002318 CharUnits Size = CharUnits::fromQuantity(UnsSize);
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002319 Size += LastBitfieldOrUnnamedOffset;
2320 UpdateRunSkipBlockVars(false,
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002321 getBlockCaptureLifetime(LastFieldBitfieldOrUnnamed->getType(),
2322 ByrefLayout),
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002323 BytePos + LastBitfieldOrUnnamedOffset,
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002324 Size);
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002325 } else {
2326 assert(!LastFieldBitfieldOrUnnamed->getIdentifier() &&"Expected unnamed");
2327 // Last field was unnamed. Must update skip info.
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002328 CharUnits FieldSize
2329 = CGM.getContext().getTypeSizeInChars(LastFieldBitfieldOrUnnamed->getType());
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002330 UpdateRunSkipBlockVars(false,
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002331 getBlockCaptureLifetime(LastFieldBitfieldOrUnnamed->getType(),
2332 ByrefLayout),
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002333 BytePos + LastBitfieldOrUnnamedOffset,
2334 FieldSize);
2335 }
2336 }
2337
2338 if (MaxField)
2339 UpdateRunSkipBlockVars(false,
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002340 getBlockCaptureLifetime(MaxField->getType(), ByrefLayout),
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002341 BytePos + MaxFieldOffset,
2342 MaxUnionSize);
2343}
2344
2345void CGObjCCommonMac::BuildRCBlockVarRecordLayout(const RecordType *RT,
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002346 CharUnits BytePos,
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002347 bool &HasUnion,
2348 bool ByrefLayout) {
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002349 const RecordDecl *RD = RT->getDecl();
Aaron Ballman62e47c42014-03-10 13:43:55 +00002350 SmallVector<const FieldDecl*, 16> Fields(RD->fields());
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002351 llvm::Type *Ty = CGM.getTypes().ConvertType(QualType(RT, 0));
2352 const llvm::StructLayout *RecLayout =
2353 CGM.getDataLayout().getStructLayout(cast<llvm::StructType>(Ty));
2354
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002355 BuildRCRecordLayout(RecLayout, RD, Fields, BytePos, HasUnion, ByrefLayout);
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002356}
2357
Fariborz Jahanian23290b02012-11-01 18:32:55 +00002358/// InlineLayoutInstruction - This routine produce an inline instruction for the
2359/// block variable layout if it can. If not, it returns 0. Rules are as follow:
2360/// If ((uintptr_t) layout) < (1 << 12), the layout is inline. In the 64bit world,
2361/// an inline layout of value 0x0000000000000xyz is interpreted as follows:
2362/// x captured object pointers of BLOCK_LAYOUT_STRONG. Followed by
2363/// y captured object of BLOCK_LAYOUT_BYREF. Followed by
2364/// z captured object of BLOCK_LAYOUT_WEAK. If any of the above is missing, zero
2365/// replaces it. For example, 0x00000x00 means x BLOCK_LAYOUT_STRONG and no
2366/// BLOCK_LAYOUT_BYREF and no BLOCK_LAYOUT_WEAK objects are captured.
2367uint64_t CGObjCCommonMac::InlineLayoutInstruction(
2368 SmallVectorImpl<unsigned char> &Layout) {
2369 uint64_t Result = 0;
2370 if (Layout.size() <= 3) {
2371 unsigned size = Layout.size();
2372 unsigned strong_word_count = 0, byref_word_count=0, weak_word_count=0;
2373 unsigned char inst;
2374 enum BLOCK_LAYOUT_OPCODE opcode ;
2375 switch (size) {
2376 case 3:
2377 inst = Layout[0];
2378 opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
2379 if (opcode == BLOCK_LAYOUT_STRONG)
2380 strong_word_count = (inst & 0xF)+1;
2381 else
2382 return 0;
2383 inst = Layout[1];
2384 opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
2385 if (opcode == BLOCK_LAYOUT_BYREF)
2386 byref_word_count = (inst & 0xF)+1;
2387 else
2388 return 0;
2389 inst = Layout[2];
2390 opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
2391 if (opcode == BLOCK_LAYOUT_WEAK)
2392 weak_word_count = (inst & 0xF)+1;
2393 else
2394 return 0;
2395 break;
2396
2397 case 2:
2398 inst = Layout[0];
2399 opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
2400 if (opcode == BLOCK_LAYOUT_STRONG) {
2401 strong_word_count = (inst & 0xF)+1;
2402 inst = Layout[1];
2403 opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
2404 if (opcode == BLOCK_LAYOUT_BYREF)
2405 byref_word_count = (inst & 0xF)+1;
2406 else if (opcode == BLOCK_LAYOUT_WEAK)
2407 weak_word_count = (inst & 0xF)+1;
2408 else
2409 return 0;
2410 }
2411 else if (opcode == BLOCK_LAYOUT_BYREF) {
2412 byref_word_count = (inst & 0xF)+1;
2413 inst = Layout[1];
2414 opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
2415 if (opcode == BLOCK_LAYOUT_WEAK)
2416 weak_word_count = (inst & 0xF)+1;
2417 else
2418 return 0;
2419 }
2420 else
2421 return 0;
2422 break;
2423
2424 case 1:
2425 inst = Layout[0];
2426 opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
2427 if (opcode == BLOCK_LAYOUT_STRONG)
2428 strong_word_count = (inst & 0xF)+1;
2429 else if (opcode == BLOCK_LAYOUT_BYREF)
2430 byref_word_count = (inst & 0xF)+1;
2431 else if (opcode == BLOCK_LAYOUT_WEAK)
2432 weak_word_count = (inst & 0xF)+1;
2433 else
2434 return 0;
2435 break;
2436
2437 default:
2438 return 0;
2439 }
2440
2441 // Cannot inline when any of the word counts is 15. Because this is one less
2442 // than the actual work count (so 15 means 16 actual word counts),
2443 // and we can only display 0 thru 15 word counts.
2444 if (strong_word_count == 16 || byref_word_count == 16 || weak_word_count == 16)
2445 return 0;
2446
2447 unsigned count =
2448 (strong_word_count != 0) + (byref_word_count != 0) + (weak_word_count != 0);
2449
2450 if (size == count) {
2451 if (strong_word_count)
2452 Result = strong_word_count;
2453 Result <<= 4;
2454 if (byref_word_count)
2455 Result += byref_word_count;
2456 Result <<= 4;
2457 if (weak_word_count)
2458 Result += weak_word_count;
2459 }
2460 }
2461 return Result;
2462}
2463
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002464llvm::Constant *CGObjCCommonMac::getBitmapBlockLayout(bool ComputeByrefLayout) {
2465 llvm::Constant *nullPtr = llvm::Constant::getNullValue(CGM.Int8PtrTy);
2466 if (RunSkipBlockVars.empty())
2467 return nullPtr;
John McCallc8e01702013-04-16 22:48:15 +00002468 unsigned WordSizeInBits = CGM.getTarget().getPointerWidth(0);
2469 unsigned ByteSizeInBits = CGM.getTarget().getCharWidth();
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002470 unsigned WordSizeInBytes = WordSizeInBits/ByteSizeInBits;
2471
2472 // Sort on byte position; captures might not be allocated in order,
2473 // and unions can do funny things.
2474 llvm::array_pod_sort(RunSkipBlockVars.begin(), RunSkipBlockVars.end());
2475 SmallVector<unsigned char, 16> Layout;
2476
2477 unsigned size = RunSkipBlockVars.size();
2478 for (unsigned i = 0; i < size; i++) {
2479 enum BLOCK_LAYOUT_OPCODE opcode = RunSkipBlockVars[i].opcode;
2480 CharUnits start_byte_pos = RunSkipBlockVars[i].block_var_bytepos;
2481 CharUnits end_byte_pos = start_byte_pos;
2482 unsigned j = i+1;
2483 while (j < size) {
2484 if (opcode == RunSkipBlockVars[j].opcode) {
2485 end_byte_pos = RunSkipBlockVars[j++].block_var_bytepos;
2486 i++;
2487 }
2488 else
2489 break;
2490 }
2491 CharUnits size_in_bytes =
2492 end_byte_pos - start_byte_pos + RunSkipBlockVars[j-1].block_var_size;
2493 if (j < size) {
2494 CharUnits gap =
2495 RunSkipBlockVars[j].block_var_bytepos -
2496 RunSkipBlockVars[j-1].block_var_bytepos - RunSkipBlockVars[j-1].block_var_size;
2497 size_in_bytes += gap;
2498 }
2499 CharUnits residue_in_bytes = CharUnits::Zero();
2500 if (opcode == BLOCK_LAYOUT_NON_OBJECT_BYTES) {
2501 residue_in_bytes = size_in_bytes % WordSizeInBytes;
2502 size_in_bytes -= residue_in_bytes;
2503 opcode = BLOCK_LAYOUT_NON_OBJECT_WORDS;
2504 }
2505
2506 unsigned size_in_words = size_in_bytes.getQuantity() / WordSizeInBytes;
2507 while (size_in_words >= 16) {
2508 // Note that value in imm. is one less that the actual
2509 // value. So, 0xf means 16 words follow!
2510 unsigned char inst = (opcode << 4) | 0xf;
2511 Layout.push_back(inst);
2512 size_in_words -= 16;
2513 }
2514 if (size_in_words > 0) {
2515 // Note that value in imm. is one less that the actual
2516 // value. So, we subtract 1 away!
2517 unsigned char inst = (opcode << 4) | (size_in_words-1);
2518 Layout.push_back(inst);
2519 }
2520 if (residue_in_bytes > CharUnits::Zero()) {
2521 unsigned char inst =
2522 (BLOCK_LAYOUT_NON_OBJECT_BYTES << 4) | (residue_in_bytes.getQuantity()-1);
2523 Layout.push_back(inst);
2524 }
2525 }
2526
John McCall7f416cc2015-09-08 08:05:57 +00002527 while (!Layout.empty()) {
2528 unsigned char inst = Layout.back();
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002529 enum BLOCK_LAYOUT_OPCODE opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
2530 if (opcode == BLOCK_LAYOUT_NON_OBJECT_BYTES || opcode == BLOCK_LAYOUT_NON_OBJECT_WORDS)
2531 Layout.pop_back();
2532 else
2533 break;
2534 }
2535
2536 uint64_t Result = InlineLayoutInstruction(Layout);
2537 if (Result != 0) {
2538 // Block variable layout instruction has been inlined.
2539 if (CGM.getLangOpts().ObjCGCBitmapPrint) {
2540 if (ComputeByrefLayout)
John McCall7f416cc2015-09-08 08:05:57 +00002541 printf("\n Inline BYREF variable layout: ");
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002542 else
John McCall7f416cc2015-09-08 08:05:57 +00002543 printf("\n Inline block variable layout: ");
2544 printf("0x0%" PRIx64 "", Result);
2545 if (auto numStrong = (Result & 0xF00) >> 8)
2546 printf(", BL_STRONG:%d", (int) numStrong);
2547 if (auto numByref = (Result & 0x0F0) >> 4)
2548 printf(", BL_BYREF:%d", (int) numByref);
2549 if (auto numWeak = (Result & 0x00F) >> 0)
2550 printf(", BL_WEAK:%d", (int) numWeak);
2551 printf(", BL_OPERATOR:0\n");
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002552 }
Vedant Kumar3ed0df02015-12-21 19:43:25 +00002553 return llvm::ConstantInt::get(CGM.IntPtrTy, Result);
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002554 }
2555
2556 unsigned char inst = (BLOCK_LAYOUT_OPERATOR << 4) | 0;
2557 Layout.push_back(inst);
2558 std::string BitMap;
2559 for (unsigned i = 0, e = Layout.size(); i != e; i++)
2560 BitMap += Layout[i];
2561
2562 if (CGM.getLangOpts().ObjCGCBitmapPrint) {
2563 if (ComputeByrefLayout)
John McCall7f416cc2015-09-08 08:05:57 +00002564 printf("\n Byref variable layout: ");
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002565 else
John McCall7f416cc2015-09-08 08:05:57 +00002566 printf("\n Block variable layout: ");
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002567 for (unsigned i = 0, e = BitMap.size(); i != e; i++) {
2568 unsigned char inst = BitMap[i];
2569 enum BLOCK_LAYOUT_OPCODE opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
2570 unsigned delta = 1;
2571 switch (opcode) {
2572 case BLOCK_LAYOUT_OPERATOR:
2573 printf("BL_OPERATOR:");
2574 delta = 0;
2575 break;
2576 case BLOCK_LAYOUT_NON_OBJECT_BYTES:
2577 printf("BL_NON_OBJECT_BYTES:");
2578 break;
2579 case BLOCK_LAYOUT_NON_OBJECT_WORDS:
2580 printf("BL_NON_OBJECT_WORD:");
2581 break;
2582 case BLOCK_LAYOUT_STRONG:
2583 printf("BL_STRONG:");
2584 break;
2585 case BLOCK_LAYOUT_BYREF:
2586 printf("BL_BYREF:");
2587 break;
2588 case BLOCK_LAYOUT_WEAK:
2589 printf("BL_WEAK:");
2590 break;
2591 case BLOCK_LAYOUT_UNRETAINED:
2592 printf("BL_UNRETAINED:");
2593 break;
2594 }
2595 // Actual value of word count is one more that what is in the imm.
2596 // field of the instruction
2597 printf("%d", (inst & 0xf) + delta);
2598 if (i < e-1)
2599 printf(", ");
2600 else
2601 printf("\n");
2602 }
2603 }
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00002604
Saleem Abdulrasool82f6add2016-09-20 18:38:54 +00002605 auto *Entry = CreateCStringLiteral(BitMap, ObjCLabelType::ClassName,
2606 /*ForceNonFragileABI=*/true,
2607 /*NullTerminate=*/false);
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002608 return getConstantGEP(VMContext, Entry, 0, 0);
2609}
2610
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +00002611llvm::Constant *CGObjCCommonMac::BuildRCBlockLayout(CodeGenModule &CGM,
2612 const CGBlockInfo &blockInfo) {
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +00002613 assert(CGM.getLangOpts().getGC() == LangOptions::NonGC);
2614
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +00002615 RunSkipBlockVars.clear();
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002616 bool hasUnion = false;
2617
John McCallc8e01702013-04-16 22:48:15 +00002618 unsigned WordSizeInBits = CGM.getTarget().getPointerWidth(0);
2619 unsigned ByteSizeInBits = CGM.getTarget().getCharWidth();
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +00002620 unsigned WordSizeInBytes = WordSizeInBits/ByteSizeInBits;
2621
2622 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
2623
2624 // Calculate the basic layout of the block structure.
2625 const llvm::StructLayout *layout =
2626 CGM.getDataLayout().getStructLayout(blockInfo.StructureType);
2627
2628 // Ignore the optional 'this' capture: C++ objects are not assumed
2629 // to be GC'ed.
Fariborz Jahanian4cf177e2012-12-04 17:20:57 +00002630 if (blockInfo.BlockHeaderForcedGapSize != CharUnits::Zero())
2631 UpdateRunSkipBlockVars(false, Qualifiers::OCL_None,
2632 blockInfo.BlockHeaderForcedGapOffset,
2633 blockInfo.BlockHeaderForcedGapSize);
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +00002634 // Walk the captured variables.
Aaron Ballman9371dd22014-03-14 18:34:04 +00002635 for (const auto &CI : blockDecl->captures()) {
2636 const VarDecl *variable = CI.getVariable();
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +00002637 QualType type = variable->getType();
2638
2639 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
2640
2641 // Ignore constant captures.
2642 if (capture.isConstant()) continue;
2643
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002644 CharUnits fieldOffset =
2645 CharUnits::fromQuantity(layout->getElementOffset(capture.getIndex()));
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +00002646
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002647 assert(!type->isArrayType() && "array variable should not be caught");
Aaron Ballman9371dd22014-03-14 18:34:04 +00002648 if (!CI.isByRef())
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002649 if (const RecordType *record = type->getAs<RecordType>()) {
2650 BuildRCBlockVarRecordLayout(record, fieldOffset, hasUnion);
2651 continue;
2652 }
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002653 CharUnits fieldSize;
Aaron Ballman9371dd22014-03-14 18:34:04 +00002654 if (CI.isByRef())
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002655 fieldSize = CharUnits::fromQuantity(WordSizeInBytes);
2656 else
2657 fieldSize = CGM.getContext().getTypeSizeInChars(type);
Aaron Ballman9371dd22014-03-14 18:34:04 +00002658 UpdateRunSkipBlockVars(CI.isByRef(), getBlockCaptureLifetime(type, false),
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002659 fieldOffset, fieldSize);
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +00002660 }
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002661 return getBitmapBlockLayout(false);
2662}
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +00002663
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002664llvm::Constant *CGObjCCommonMac::BuildByrefLayout(CodeGen::CodeGenModule &CGM,
2665 QualType T) {
2666 assert(CGM.getLangOpts().getGC() == LangOptions::NonGC);
2667 assert(!T->isArrayType() && "__block array variable should not be caught");
2668 CharUnits fieldOffset;
2669 RunSkipBlockVars.clear();
2670 bool hasUnion = false;
2671 if (const RecordType *record = T->getAs<RecordType>()) {
2672 BuildRCBlockVarRecordLayout(record, fieldOffset, hasUnion, true /*ByrefLayout */);
2673 llvm::Constant *Result = getBitmapBlockLayout(true);
Vedant Kumar2f5bb1152015-12-21 20:21:15 +00002674 if (isa<llvm::ConstantInt>(Result))
2675 Result = llvm::ConstantExpr::getIntToPtr(Result, CGM.Int8PtrTy);
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002676 return Result;
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +00002677 }
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002678 llvm::Constant *nullPtr = llvm::Constant::getNullValue(CGM.Int8PtrTy);
2679 return nullPtr;
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +00002680}
2681
John McCall882987f2013-02-28 19:01:20 +00002682llvm::Value *CGObjCMac::GenerateProtocolRef(CodeGenFunction &CGF,
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00002683 const ObjCProtocolDecl *PD) {
Daniel Dunbar7050c552008-09-04 04:33:15 +00002684 // FIXME: I don't understand why gcc generates this, or where it is
Mike Stump18bb9282009-05-16 07:57:57 +00002685 // resolved. Investigate. Its also wasteful to look this up over and over.
Daniel Dunbar7050c552008-09-04 04:33:15 +00002686 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
2687
Owen Andersonade90fd2009-07-29 18:54:39 +00002688 return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
Douglas Gregor020de322012-01-17 18:36:30 +00002689 ObjCTypes.getExternalProtocolPtrTy());
Daniel Dunbar303e2c22008-08-11 02:45:11 +00002690}
2691
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00002692void CGObjCCommonMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
Mike Stump18bb9282009-05-16 07:57:57 +00002693 // FIXME: We shouldn't need this, the protocol decl should contain enough
2694 // information to tell us whether this was a declaration or a definition.
Daniel Dunbarc475d422008-10-29 22:36:39 +00002695 DefinedProtocols.insert(PD->getIdentifier());
2696
2697 // If we have generated a forward reference to this protocol, emit
2698 // it now. Otherwise do nothing, the protocol objects are lazily
2699 // emitted.
Daniel Dunbar59e476b2009-08-03 17:06:42 +00002700 if (Protocols.count(PD->getIdentifier()))
Daniel Dunbarc475d422008-10-29 22:36:39 +00002701 GetOrEmitProtocol(PD);
2702}
2703
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00002704llvm::Constant *CGObjCCommonMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbarc475d422008-10-29 22:36:39 +00002705 if (DefinedProtocols.count(PD->getIdentifier()))
2706 return GetOrEmitProtocol(PD);
Douglas Gregora9d84932011-05-27 01:19:52 +00002707
Daniel Dunbarc475d422008-10-29 22:36:39 +00002708 return GetOrEmitProtocolRef(PD);
2709}
2710
Douglas Gregor24ae22c2016-04-01 23:23:52 +00002711llvm::Value *CGObjCCommonMac::EmitClassRefViaRuntime(
2712 CodeGenFunction &CGF,
2713 const ObjCInterfaceDecl *ID,
2714 ObjCCommonTypesHelper &ObjCTypes) {
2715 llvm::Constant *lookUpClassFn = ObjCTypes.getLookUpClassFn();
2716
2717 llvm::Value *className =
2718 CGF.CGM.GetAddrOfConstantCString(ID->getObjCRuntimeNameAsString())
2719 .getPointer();
2720 ASTContext &ctx = CGF.CGM.getContext();
2721 className =
2722 CGF.Builder.CreateBitCast(className,
2723 CGF.ConvertType(
2724 ctx.getPointerType(ctx.CharTy.withConst())));
2725 llvm::CallInst *call = CGF.Builder.CreateCall(lookUpClassFn, className);
2726 call->setDoesNotThrow();
2727 return call;
2728}
2729
Daniel Dunbarb036db82008-08-13 03:21:16 +00002730/*
Rafael Espindolaf9e1e5e2014-02-20 14:09:04 +00002731// Objective-C 1.0 extensions
Daniel Dunbar59e476b2009-08-03 17:06:42 +00002732struct _objc_protocol {
2733struct _objc_protocol_extension *isa;
2734char *protocol_name;
2735struct _objc_protocol_list *protocol_list;
2736struct _objc__method_prototype_list *instance_methods;
2737struct _objc__method_prototype_list *class_methods
2738};
Daniel Dunbarb036db82008-08-13 03:21:16 +00002739
Daniel Dunbar59e476b2009-08-03 17:06:42 +00002740See EmitProtocolExtension().
Daniel Dunbarb036db82008-08-13 03:21:16 +00002741*/
Daniel Dunbarc475d422008-10-29 22:36:39 +00002742llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
John McCallf9582a72012-03-30 21:29:05 +00002743 llvm::GlobalVariable *Entry = Protocols[PD->getIdentifier()];
Daniel Dunbarc475d422008-10-29 22:36:39 +00002744
2745 // Early exit if a defining object has already been generated.
2746 if (Entry && Entry->hasInitializer())
2747 return Entry;
2748
Douglas Gregora715bff2012-01-01 19:51:50 +00002749 // Use the protocol definition, if there is one.
2750 if (const ObjCProtocolDecl *Def = PD->getDefinition())
2751 PD = Def;
2752
Daniel Dunbarc61d0e92008-08-25 06:02:07 +00002753 // FIXME: I don't understand why gcc generates this, or where it is
Mike Stump18bb9282009-05-16 07:57:57 +00002754 // resolved. Investigate. Its also wasteful to look this up over and over.
Daniel Dunbarc61d0e92008-08-25 06:02:07 +00002755 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
2756
Daniel Dunbareb1f9a22008-08-27 02:31:56 +00002757 // Construct method lists.
2758 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
2759 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Bob Wilson5f4e3a72011-11-30 01:57:58 +00002760 std::vector<llvm::Constant*> MethodTypesExt, OptMethodTypesExt;
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002761 for (const auto *MD : PD->instance_methods()) {
Daniel Dunbareb1f9a22008-08-27 02:31:56 +00002762 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Douglas Gregora9d84932011-05-27 01:19:52 +00002763 if (!C)
2764 return GetOrEmitProtocolRef(PD);
2765
Daniel Dunbareb1f9a22008-08-27 02:31:56 +00002766 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
2767 OptInstanceMethods.push_back(C);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00002768 OptMethodTypesExt.push_back(GetMethodVarType(MD, true));
Daniel Dunbareb1f9a22008-08-27 02:31:56 +00002769 } else {
2770 InstanceMethods.push_back(C);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00002771 MethodTypesExt.push_back(GetMethodVarType(MD, true));
Daniel Dunbar59e476b2009-08-03 17:06:42 +00002772 }
Daniel Dunbareb1f9a22008-08-27 02:31:56 +00002773 }
2774
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002775 for (const auto *MD : PD->class_methods()) {
Daniel Dunbareb1f9a22008-08-27 02:31:56 +00002776 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Douglas Gregora9d84932011-05-27 01:19:52 +00002777 if (!C)
2778 return GetOrEmitProtocolRef(PD);
2779
Daniel Dunbareb1f9a22008-08-27 02:31:56 +00002780 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
2781 OptClassMethods.push_back(C);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00002782 OptMethodTypesExt.push_back(GetMethodVarType(MD, true));
Daniel Dunbareb1f9a22008-08-27 02:31:56 +00002783 } else {
2784 ClassMethods.push_back(C);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00002785 MethodTypesExt.push_back(GetMethodVarType(MD, true));
Daniel Dunbar59e476b2009-08-03 17:06:42 +00002786 }
Daniel Dunbareb1f9a22008-08-27 02:31:56 +00002787 }
2788
Bob Wilson5f4e3a72011-11-30 01:57:58 +00002789 MethodTypesExt.insert(MethodTypesExt.end(),
2790 OptMethodTypesExt.begin(), OptMethodTypesExt.end());
2791
Benjamin Kramer22d24c22011-10-15 12:20:02 +00002792 llvm::Constant *Values[] = {
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00002793 EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods,
2794 MethodTypesExt),
2795 GetClassName(PD->getObjCRuntimeNameAsString()),
2796 EmitProtocolList("OBJC_PROTOCOL_REFS_" + PD->getName(),
2797 PD->protocol_begin(), PD->protocol_end()),
2798 EmitMethodDescList("OBJC_PROTOCOL_INSTANCE_METHODS_" + PD->getName(),
2799 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
2800 InstanceMethods),
2801 EmitMethodDescList("OBJC_PROTOCOL_CLASS_METHODS_" + PD->getName(),
2802 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
2803 ClassMethods)};
Owen Anderson0e0189d2009-07-27 22:29:56 +00002804 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
Daniel Dunbarb036db82008-08-13 03:21:16 +00002805 Values);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00002806
Daniel Dunbarb036db82008-08-13 03:21:16 +00002807 if (Entry) {
Rafael Espindola5d117f32014-03-06 01:10:46 +00002808 // Already created, update the initializer.
Rafael Espindolab3262952014-05-09 00:43:37 +00002809 assert(Entry->hasPrivateLinkage());
Daniel Dunbarb036db82008-08-13 03:21:16 +00002810 Entry->setInitializer(Init);
2811 } else {
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00002812 Entry = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ProtocolTy,
2813 false, llvm::GlobalValue::PrivateLinkage,
2814 Init, "OBJC_PROTOCOL_" + PD->getName());
Daniel Dunbarb036db82008-08-13 03:21:16 +00002815 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbarb036db82008-08-13 03:21:16 +00002816 // FIXME: Is this necessary? Why only for protocol?
2817 Entry->setAlignment(4);
John McCallf9582a72012-03-30 21:29:05 +00002818
2819 Protocols[PD->getIdentifier()] = Entry;
Daniel Dunbarb036db82008-08-13 03:21:16 +00002820 }
Rafael Espindola060062a2014-03-06 22:15:10 +00002821 CGM.addCompilerUsedGlobal(Entry);
Daniel Dunbarc475d422008-10-29 22:36:39 +00002822
2823 return Entry;
Daniel Dunbarb036db82008-08-13 03:21:16 +00002824}
2825
Daniel Dunbarc475d422008-10-29 22:36:39 +00002826llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbarb036db82008-08-13 03:21:16 +00002827 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
2828
2829 if (!Entry) {
Daniel Dunbarc475d422008-10-29 22:36:39 +00002830 // We use the initializer as a marker of whether this is a forward
2831 // reference or not. At module finalization we add the empty
2832 // contents for protocols which were referenced but never defined.
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00002833 Entry = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ProtocolTy,
2834 false, llvm::GlobalValue::PrivateLinkage,
2835 nullptr, "OBJC_PROTOCOL_" + PD->getName());
Daniel Dunbarb036db82008-08-13 03:21:16 +00002836 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbarb036db82008-08-13 03:21:16 +00002837 // FIXME: Is this necessary? Why only for protocol?
2838 Entry->setAlignment(4);
2839 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00002840
Daniel Dunbarb036db82008-08-13 03:21:16 +00002841 return Entry;
2842}
2843
2844/*
2845 struct _objc_protocol_extension {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00002846 uint32_t size;
2847 struct objc_method_description_list *optional_instance_methods;
2848 struct objc_method_description_list *optional_class_methods;
2849 struct objc_property_list *instance_properties;
Bob Wilson5f4e3a72011-11-30 01:57:58 +00002850 const char ** extendedMethodTypes;
Manman Rence7bff52016-01-29 23:46:55 +00002851 struct objc_property_list *class_properties;
Daniel Dunbarb036db82008-08-13 03:21:16 +00002852 };
2853*/
Daniel Dunbareb1f9a22008-08-27 02:31:56 +00002854llvm::Constant *
2855CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
Bill Wendlingcb5b5ff2012-02-07 09:25:09 +00002856 ArrayRef<llvm::Constant*> OptInstanceMethods,
2857 ArrayRef<llvm::Constant*> OptClassMethods,
2858 ArrayRef<llvm::Constant*> MethodTypesExt) {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00002859 uint64_t Size =
Micah Villmowdd31ca12012-10-08 16:25:52 +00002860 CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ProtocolExtensionTy);
Benjamin Kramer22d24c22011-10-15 12:20:02 +00002861 llvm::Constant *Values[] = {
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00002862 llvm::ConstantInt::get(ObjCTypes.IntTy, Size),
2863 EmitMethodDescList("OBJC_PROTOCOL_INSTANCE_METHODS_OPT_" + PD->getName(),
2864 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
2865 OptInstanceMethods),
2866 EmitMethodDescList("OBJC_PROTOCOL_CLASS_METHODS_OPT_" + PD->getName(),
2867 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
2868 OptClassMethods),
2869 EmitPropertyList("OBJC_$_PROP_PROTO_LIST_" + PD->getName(), nullptr, PD,
Manman Renad0e7912016-01-29 19:22:54 +00002870 ObjCTypes, false),
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00002871 EmitProtocolMethodTypes("OBJC_PROTOCOL_METHOD_TYPES_" + PD->getName(),
Manman Rence7bff52016-01-29 23:46:55 +00002872 MethodTypesExt, ObjCTypes),
2873 EmitPropertyList("OBJC_$_CLASS_PROP_PROTO_LIST_" + PD->getName(), nullptr,
2874 PD, ObjCTypes, true)};
Daniel Dunbarb036db82008-08-13 03:21:16 +00002875
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00002876 // Return null if no extension bits are used.
Daniel Dunbar59e476b2009-08-03 17:06:42 +00002877 if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
Manman Rence7bff52016-01-29 23:46:55 +00002878 Values[3]->isNullValue() && Values[4]->isNullValue() &&
2879 Values[5]->isNullValue())
Owen Anderson0b75f232009-07-31 20:28:54 +00002880 return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
Daniel Dunbarb036db82008-08-13 03:21:16 +00002881
Daniel Dunbar59e476b2009-08-03 17:06:42 +00002882 llvm::Constant *Init =
Owen Anderson0e0189d2009-07-27 22:29:56 +00002883 llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
Daniel Dunbarb036db82008-08-13 03:21:16 +00002884
Daniel Dunbarc2d4b622009-03-09 21:49:58 +00002885 // No special section, but goes in llvm.used
Alp Toker541d5072014-06-07 23:30:53 +00002886 return CreateMetadataVar("\01l_OBJC_PROTOCOLEXT_" + PD->getName(), Init,
John McCall7f416cc2015-09-08 08:05:57 +00002887 StringRef(), CGM.getPointerAlign(), true);
Daniel Dunbarb036db82008-08-13 03:21:16 +00002888}
2889
2890/*
2891 struct objc_protocol_list {
Bill Wendlinga515b582012-02-09 22:16:49 +00002892 struct objc_protocol_list *next;
2893 long count;
2894 Protocol *list[];
Daniel Dunbarb036db82008-08-13 03:21:16 +00002895 };
2896*/
Daniel Dunbardec75f82008-08-21 21:57:41 +00002897llvm::Constant *
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002898CGObjCMac::EmitProtocolList(Twine Name,
Daniel Dunbardec75f82008-08-21 21:57:41 +00002899 ObjCProtocolDecl::protocol_iterator begin,
2900 ObjCProtocolDecl::protocol_iterator end) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002901 SmallVector<llvm::Constant *, 16> ProtocolRefs;
Daniel Dunbarb036db82008-08-13 03:21:16 +00002902
Daniel Dunbardec75f82008-08-21 21:57:41 +00002903 for (; begin != end; ++begin)
2904 ProtocolRefs.push_back(GetProtocolRef(*begin));
Daniel Dunbarb036db82008-08-13 03:21:16 +00002905
2906 // Just return null for empty protocol lists
Daniel Dunbar59e476b2009-08-03 17:06:42 +00002907 if (ProtocolRefs.empty())
Owen Anderson0b75f232009-07-31 20:28:54 +00002908 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
Daniel Dunbarb036db82008-08-13 03:21:16 +00002909
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00002910 // This list is null terminated.
Owen Anderson0b75f232009-07-31 20:28:54 +00002911 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
Daniel Dunbarb036db82008-08-13 03:21:16 +00002912
Chris Lattnere64d7ba2011-06-20 04:01:35 +00002913 llvm::Constant *Values[3];
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00002914 // This field is only used by the runtime.
Owen Anderson0b75f232009-07-31 20:28:54 +00002915 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00002916 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy,
Daniel Dunbar59e476b2009-08-03 17:06:42 +00002917 ProtocolRefs.size() - 1);
2918 Values[2] =
2919 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
2920 ProtocolRefs.size()),
Daniel Dunbarb036db82008-08-13 03:21:16 +00002921 ProtocolRefs);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00002922
Saleem Abdulrasool3c628af2016-10-25 21:43:28 +00002923 StringRef Section;
2924 if (CGM.getTriple().isOSBinFormatMachO())
2925 Section = "__OBJC,__cat_cls_meth,regular,no_dead_strip";
2926
Chris Lattnere64d7ba2011-06-20 04:01:35 +00002927 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00002928 llvm::GlobalVariable *GV =
Saleem Abdulrasool3c628af2016-10-25 21:43:28 +00002929 CreateMetadataVar(Name, Init, Section, CGM.getPointerAlign(), false);
Owen Andersonade90fd2009-07-29 18:54:39 +00002930 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
Daniel Dunbarb036db82008-08-13 03:21:16 +00002931}
2932
Bill Wendlingcb5b5ff2012-02-07 09:25:09 +00002933void CGObjCCommonMac::
2934PushProtocolProperties(llvm::SmallPtrSet<const IdentifierInfo*,16> &PropertySet,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002935 SmallVectorImpl<llvm::Constant *> &Properties,
Bill Wendlingcb5b5ff2012-02-07 09:25:09 +00002936 const Decl *Container,
Aaron Ballmandc4bea42014-03-13 18:47:37 +00002937 const ObjCProtocolDecl *Proto,
Manman Renad0e7912016-01-29 19:22:54 +00002938 const ObjCCommonTypesHelper &ObjCTypes,
2939 bool IsClassProperty) {
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00002940 for (const auto *P : Proto->protocols())
Manman Renad0e7912016-01-29 19:22:54 +00002941 PushProtocolProperties(PropertySet, Properties, Container, P, ObjCTypes,
2942 IsClassProperty);
2943
2944 for (const auto *PD : Proto->properties()) {
2945 if (IsClassProperty != PD->isClassProperty())
2946 continue;
David Blaikie82e95a32014-11-19 07:49:47 +00002947 if (!PropertySet.insert(PD->getIdentifier()).second)
Fariborz Jahanian751c1e72009-12-12 21:26:21 +00002948 continue;
Benjamin Kramer22d24c22011-10-15 12:20:02 +00002949 llvm::Constant *Prop[] = {
2950 GetPropertyName(PD->getIdentifier()),
2951 GetPropertyTypeString(PD, Container)
2952 };
Fariborz Jahanian751c1e72009-12-12 21:26:21 +00002953 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy, Prop));
2954 }
2955}
2956
Daniel Dunbarb036db82008-08-13 03:21:16 +00002957/*
Daniel Dunbar80a840b2008-08-23 00:19:03 +00002958 struct _objc_property {
Bill Wendlinga515b582012-02-09 22:16:49 +00002959 const char * const name;
2960 const char * const attributes;
Daniel Dunbar80a840b2008-08-23 00:19:03 +00002961 };
2962
2963 struct _objc_property_list {
Bill Wendlinga515b582012-02-09 22:16:49 +00002964 uint32_t entsize; // sizeof (struct _objc_property)
2965 uint32_t prop_count;
2966 struct _objc_property[prop_count];
Daniel Dunbar80a840b2008-08-23 00:19:03 +00002967 };
2968*/
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002969llvm::Constant *CGObjCCommonMac::EmitPropertyList(Twine Name,
Daniel Dunbar59e476b2009-08-03 17:06:42 +00002970 const Decl *Container,
2971 const ObjCContainerDecl *OCD,
Manman Renad0e7912016-01-29 19:22:54 +00002972 const ObjCCommonTypesHelper &ObjCTypes,
2973 bool IsClassProperty) {
Manman Ren01b705e2016-04-19 19:05:03 +00002974 if (IsClassProperty) {
2975 // Make this entry NULL for OS X with deployment target < 10.11, for iOS
2976 // with deployment target < 9.0.
2977 const llvm::Triple &Triple = CGM.getTarget().getTriple();
2978 if ((Triple.isMacOSX() && Triple.isMacOSXVersionLT(10, 11)) ||
2979 (Triple.isiOS() && Triple.isOSVersionLT(9)))
2980 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
2981 }
2982
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002983 SmallVector<llvm::Constant *, 16> Properties;
Fariborz Jahanian751c1e72009-12-12 21:26:21 +00002984 llvm::SmallPtrSet<const IdentifierInfo*, 16> PropertySet;
Nico Weber08c93332015-12-03 17:44:51 +00002985
2986 auto AddProperty = [&](const ObjCPropertyDecl *PD) {
2987 llvm::Constant *Prop[] = {GetPropertyName(PD->getIdentifier()),
2988 GetPropertyTypeString(PD, Container)};
2989 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy, Prop));
2990 };
2991 if (const ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(OCD))
2992 for (const ObjCCategoryDecl *ClassExt : OID->known_extensions())
Manman Renad0e7912016-01-29 19:22:54 +00002993 for (auto *PD : ClassExt->properties()) {
2994 if (IsClassProperty != PD->isClassProperty())
2995 continue;
Nico Weber08c93332015-12-03 17:44:51 +00002996 PropertySet.insert(PD->getIdentifier());
2997 AddProperty(PD);
2998 }
Manman Renad0e7912016-01-29 19:22:54 +00002999
3000 for (const auto *PD : OCD->properties()) {
3001 if (IsClassProperty != PD->isClassProperty())
3002 continue;
Nico Weber08c93332015-12-03 17:44:51 +00003003 // Don't emit duplicate metadata for properties that were already in a
3004 // class extension.
3005 if (!PropertySet.insert(PD->getIdentifier()).second)
3006 continue;
3007 AddProperty(PD);
Daniel Dunbar80a840b2008-08-23 00:19:03 +00003008 }
Nico Weber08c93332015-12-03 17:44:51 +00003009
Fariborz Jahanian7966aff2010-06-22 16:33:55 +00003010 if (const ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(OCD)) {
Aaron Ballmana9f49e32014-03-13 20:55:22 +00003011 for (const auto *P : OID->all_referenced_protocols())
Manman Renad0e7912016-01-29 19:22:54 +00003012 PushProtocolProperties(PropertySet, Properties, Container, P, ObjCTypes,
3013 IsClassProperty);
Fariborz Jahanian7966aff2010-06-22 16:33:55 +00003014 }
3015 else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(OCD)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00003016 for (const auto *P : CD->protocols())
Manman Renad0e7912016-01-29 19:22:54 +00003017 PushProtocolProperties(PropertySet, Properties, Container, P, ObjCTypes,
3018 IsClassProperty);
Fariborz Jahanian7966aff2010-06-22 16:33:55 +00003019 }
Daniel Dunbar80a840b2008-08-23 00:19:03 +00003020
3021 // Return null for empty list.
3022 if (Properties.empty())
Owen Anderson0b75f232009-07-31 20:28:54 +00003023 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
Daniel Dunbar80a840b2008-08-23 00:19:03 +00003024
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003025 unsigned PropertySize =
Micah Villmowdd31ca12012-10-08 16:25:52 +00003026 CGM.getDataLayout().getTypeAllocSize(ObjCTypes.PropertyTy);
Chris Lattnere64d7ba2011-06-20 04:01:35 +00003027 llvm::Constant *Values[3];
Owen Andersonb7a2fe62009-07-24 23:12:58 +00003028 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
3029 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003030 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
Daniel Dunbar80a840b2008-08-23 00:19:03 +00003031 Properties.size());
Owen Anderson47034e12009-07-28 18:33:04 +00003032 Values[2] = llvm::ConstantArray::get(AT, Properties);
Chris Lattnere64d7ba2011-06-20 04:01:35 +00003033 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
Daniel Dunbar80a840b2008-08-23 00:19:03 +00003034
Saleem Abdulrasool3c628af2016-10-25 21:43:28 +00003035 StringRef Section;
3036 if (CGM.getTriple().isOSBinFormatMachO())
3037 Section = (ObjCABI == 2) ? "__DATA, __objc_const"
3038 : "__OBJC,__property,regular,no_dead_strip";
3039
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003040 llvm::GlobalVariable *GV =
Saleem Abdulrasool3c628af2016-10-25 21:43:28 +00003041 CreateMetadataVar(Name, Init, Section, CGM.getPointerAlign(), true);
Owen Andersonade90fd2009-07-29 18:54:39 +00003042 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.PropertyListPtrTy);
Daniel Dunbar80a840b2008-08-23 00:19:03 +00003043}
3044
Bill Wendlingcb5b5ff2012-02-07 09:25:09 +00003045llvm::Constant *
3046CGObjCCommonMac::EmitProtocolMethodTypes(Twine Name,
3047 ArrayRef<llvm::Constant*> MethodTypes,
3048 const ObjCCommonTypesHelper &ObjCTypes) {
Bob Wilson5f4e3a72011-11-30 01:57:58 +00003049 // Return null for empty list.
3050 if (MethodTypes.empty())
3051 return llvm::Constant::getNullValue(ObjCTypes.Int8PtrPtrTy);
3052
3053 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
3054 MethodTypes.size());
3055 llvm::Constant *Init = llvm::ConstantArray::get(AT, MethodTypes);
3056
Saleem Abdulrasool3c628af2016-10-25 21:43:28 +00003057 StringRef Section;
3058 if (CGM.getTriple().isOSBinFormatMachO() && ObjCABI == 2)
3059 Section = "__DATA, __objc_const";
3060
3061 llvm::GlobalVariable *GV =
3062 CreateMetadataVar(Name, Init, Section, CGM.getPointerAlign(), true);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00003063 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.Int8PtrPtrTy);
3064}
3065
Daniel Dunbar80a840b2008-08-23 00:19:03 +00003066/*
Daniel Dunbarb036db82008-08-13 03:21:16 +00003067 struct objc_method_description_list {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003068 int count;
3069 struct objc_method_description list[];
Daniel Dunbarb036db82008-08-13 03:21:16 +00003070 };
3071*/
Daniel Dunbareb1f9a22008-08-27 02:31:56 +00003072llvm::Constant *
3073CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
Benjamin Kramer22d24c22011-10-15 12:20:02 +00003074 llvm::Constant *Desc[] = {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003075 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
Benjamin Kramer22d24c22011-10-15 12:20:02 +00003076 ObjCTypes.SelectorPtrTy),
3077 GetMethodVarType(MD)
3078 };
Douglas Gregora9d84932011-05-27 01:19:52 +00003079 if (!Desc[1])
Craig Topper8a13c412014-05-21 05:09:00 +00003080 return nullptr;
3081
Owen Anderson0e0189d2009-07-27 22:29:56 +00003082 return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
Daniel Dunbareb1f9a22008-08-27 02:31:56 +00003083 Desc);
3084}
Daniel Dunbarb036db82008-08-13 03:21:16 +00003085
Bill Wendlingcb5b5ff2012-02-07 09:25:09 +00003086llvm::Constant *
Saleem Abdulrasool1e6c4062016-05-16 05:06:49 +00003087CGObjCMac::EmitMethodDescList(Twine Name, StringRef Section,
3088 ArrayRef<llvm::Constant *> Methods) {
Daniel Dunbarb036db82008-08-13 03:21:16 +00003089 // Return null for empty list.
3090 if (Methods.empty())
Owen Anderson0b75f232009-07-31 20:28:54 +00003091 return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
Daniel Dunbarb036db82008-08-13 03:21:16 +00003092
Chris Lattnere64d7ba2011-06-20 04:01:35 +00003093 llvm::Constant *Values[2];
Owen Andersonb7a2fe62009-07-24 23:12:58 +00003094 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003095 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
Daniel Dunbarb036db82008-08-13 03:21:16 +00003096 Methods.size());
Owen Anderson47034e12009-07-28 18:33:04 +00003097 Values[1] = llvm::ConstantArray::get(AT, Methods);
Chris Lattnere64d7ba2011-06-20 04:01:35 +00003098 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
Daniel Dunbarb036db82008-08-13 03:21:16 +00003099
John McCall7f416cc2015-09-08 08:05:57 +00003100 llvm::GlobalVariable *GV =
3101 CreateMetadataVar(Name, Init, Section, CGM.getPointerAlign(), true);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003102 return llvm::ConstantExpr::getBitCast(GV,
Daniel Dunbarb036db82008-08-13 03:21:16 +00003103 ObjCTypes.MethodDescriptionListPtrTy);
Daniel Dunbar303e2c22008-08-11 02:45:11 +00003104}
3105
Daniel Dunbar938a77f2008-08-22 20:34:54 +00003106/*
3107 struct _objc_category {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003108 char *category_name;
3109 char *class_name;
3110 struct _objc_method_list *instance_methods;
3111 struct _objc_method_list *class_methods;
3112 struct _objc_protocol_list *protocols;
3113 uint32_t size; // <rdar://4585769>
3114 struct _objc_property_list *instance_properties;
Manman Ren96df0b32016-01-29 23:45:01 +00003115 struct _objc_property_list *class_properties;
Daniel Dunbar938a77f2008-08-22 20:34:54 +00003116 };
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003117*/
Daniel Dunbar92992502008-08-15 22:20:32 +00003118void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00003119 unsigned Size = CGM.getDataLayout().getTypeAllocSize(ObjCTypes.CategoryTy);
Daniel Dunbar938a77f2008-08-22 20:34:54 +00003120
Mike Stump18bb9282009-05-16 07:57:57 +00003121 // FIXME: This is poor design, the OCD should have a pointer to the category
3122 // decl. Additionally, note that Category can be null for the @implementation
3123 // w/o an @interface case. Sema should just create one for us as it does for
3124 // @implementation so everyone else can live life under a clear blue sky.
Daniel Dunbar938a77f2008-08-22 20:34:54 +00003125 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003126 const ObjCCategoryDecl *Category =
Daniel Dunbar28e76ca2008-08-26 23:03:11 +00003127 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Daniel Dunbar349e6fb2009-10-18 20:48:59 +00003128
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003129 SmallString<256> ExtName;
Daniel Dunbar349e6fb2009-10-18 20:48:59 +00003130 llvm::raw_svector_ostream(ExtName) << Interface->getName() << '_'
3131 << OCD->getName();
Daniel Dunbar938a77f2008-08-22 20:34:54 +00003132
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003133 SmallVector<llvm::Constant *, 16> InstanceMethods, ClassMethods;
Aaron Ballmanf26acce2014-03-13 19:50:17 +00003134 for (const auto *I : OCD->instance_methods())
Daniel Dunbar3c76cb52008-08-26 21:51:14 +00003135 // Instance methods should always be defined.
Aaron Ballmanf26acce2014-03-13 19:50:17 +00003136 InstanceMethods.push_back(GetMethodConstant(I));
3137
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00003138 for (const auto *I : OCD->class_methods())
Daniel Dunbar3c76cb52008-08-26 21:51:14 +00003139 // Class methods should always be defined.
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00003140 ClassMethods.push_back(GetMethodConstant(I));
Daniel Dunbar3c76cb52008-08-26 21:51:14 +00003141
Manman Ren96df0b32016-01-29 23:45:01 +00003142 llvm::Constant *Values[8];
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00003143 Values[0] = GetClassName(OCD->getName());
3144 Values[1] = GetClassName(Interface->getObjCRuntimeNameAsString());
Fariborz Jahaniane55f8662009-04-29 20:40:05 +00003145 LazySymbols.insert(Interface->getIdentifier());
Saleem Abdulrasoold48b0a32016-10-24 20:47:58 +00003146
3147 Values[2] = EmitMethodList(ExtName, MethodListType::CategoryInstanceMethods,
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00003148 InstanceMethods);
Saleem Abdulrasoold48b0a32016-10-24 20:47:58 +00003149 Values[3] = EmitMethodList(ExtName, MethodListType::CategoryClassMethods,
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00003150 ClassMethods);
Daniel Dunbareb1f9a22008-08-27 02:31:56 +00003151 if (Category) {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003152 Values[4] =
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00003153 EmitProtocolList("OBJC_CATEGORY_PROTOCOLS_" + ExtName.str(),
3154 Category->protocol_begin(), Category->protocol_end());
Daniel Dunbareb1f9a22008-08-27 02:31:56 +00003155 } else {
Owen Anderson0b75f232009-07-31 20:28:54 +00003156 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
Daniel Dunbareb1f9a22008-08-27 02:31:56 +00003157 }
Owen Andersonb7a2fe62009-07-24 23:12:58 +00003158 Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar28e76ca2008-08-26 23:03:11 +00003159
3160 // If there is no category @interface then there can be no properties.
3161 if (Category) {
Daniel Dunbar349e6fb2009-10-18 20:48:59 +00003162 Values[6] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ExtName.str(),
Manman Renad0e7912016-01-29 19:22:54 +00003163 OCD, Category, ObjCTypes, false);
Manman Ren96df0b32016-01-29 23:45:01 +00003164 Values[7] = EmitPropertyList("\01l_OBJC_$_CLASS_PROP_LIST_" + ExtName.str(),
3165 OCD, Category, ObjCTypes, true);
Daniel Dunbar28e76ca2008-08-26 23:03:11 +00003166 } else {
Owen Anderson0b75f232009-07-31 20:28:54 +00003167 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
Manman Ren96df0b32016-01-29 23:45:01 +00003168 Values[7] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
Daniel Dunbar28e76ca2008-08-26 23:03:11 +00003169 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003170
Owen Anderson0e0189d2009-07-27 22:29:56 +00003171 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
Daniel Dunbar938a77f2008-08-22 20:34:54 +00003172 Values);
3173
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003174 llvm::GlobalVariable *GV =
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00003175 CreateMetadataVar("OBJC_CATEGORY_" + ExtName.str(), Init,
John McCall7f416cc2015-09-08 08:05:57 +00003176 "__OBJC,__category,regular,no_dead_strip",
3177 CGM.getPointerAlign(), true);
Daniel Dunbar938a77f2008-08-22 20:34:54 +00003178 DefinedCategories.push_back(GV);
Justin Lebar5e83dfe2016-10-21 21:45:01 +00003179 DefinedCategoryNames.insert(llvm::CachedHashString(ExtName));
Fariborz Jahanianc0577942011-04-22 22:02:28 +00003180 // method definition entries must be clear for next implementation.
3181 MethodDefinitions.clear();
Daniel Dunbar303e2c22008-08-11 02:45:11 +00003182}
3183
John McCallef19dbb2012-10-17 04:53:23 +00003184enum FragileClassFlags {
John McCall460ce582015-10-22 18:38:17 +00003185 /// Apparently: is not a meta-class.
John McCallef19dbb2012-10-17 04:53:23 +00003186 FragileABI_Class_Factory = 0x00001,
John McCall460ce582015-10-22 18:38:17 +00003187
3188 /// Is a meta-class.
John McCallef19dbb2012-10-17 04:53:23 +00003189 FragileABI_Class_Meta = 0x00002,
John McCall460ce582015-10-22 18:38:17 +00003190
3191 /// Has a non-trivial constructor or destructor.
John McCallef19dbb2012-10-17 04:53:23 +00003192 FragileABI_Class_HasCXXStructors = 0x02000,
John McCall460ce582015-10-22 18:38:17 +00003193
3194 /// Has hidden visibility.
John McCall09ec1ec2015-10-21 22:06:03 +00003195 FragileABI_Class_Hidden = 0x20000,
John McCall460ce582015-10-22 18:38:17 +00003196
3197 /// Class implementation was compiled under ARC.
3198 FragileABI_Class_CompiledByARC = 0x04000000,
3199
3200 /// Class implementation was compiled under MRC and has MRC weak ivars.
3201 /// Exclusive with CompiledByARC.
3202 FragileABI_Class_HasMRCWeakIvars = 0x08000000,
John McCallef19dbb2012-10-17 04:53:23 +00003203};
3204
3205enum NonFragileClassFlags {
3206 /// Is a meta-class.
3207 NonFragileABI_Class_Meta = 0x00001,
3208
3209 /// Is a root class.
3210 NonFragileABI_Class_Root = 0x00002,
3211
John McCall460ce582015-10-22 18:38:17 +00003212 /// Has a non-trivial constructor or destructor.
John McCallef19dbb2012-10-17 04:53:23 +00003213 NonFragileABI_Class_HasCXXStructors = 0x00004,
3214
3215 /// Has hidden visibility.
3216 NonFragileABI_Class_Hidden = 0x00010,
3217
3218 /// Has the exception attribute.
3219 NonFragileABI_Class_Exception = 0x00020,
3220
3221 /// (Obsolete) ARC-specific: this class has a .release_ivars method
3222 NonFragileABI_Class_HasIvarReleaser = 0x00040,
3223
3224 /// Class implementation was compiled under ARC.
John McCall0d54a172012-10-17 04:53:31 +00003225 NonFragileABI_Class_CompiledByARC = 0x00080,
3226
3227 /// Class has non-trivial destructors, but zero-initialization is okay.
John McCall460ce582015-10-22 18:38:17 +00003228 NonFragileABI_Class_HasCXXDestructorOnly = 0x00100,
3229
3230 /// Class implementation was compiled under MRC and has MRC weak ivars.
3231 /// Exclusive with CompiledByARC.
3232 NonFragileABI_Class_HasMRCWeakIvars = 0x00200,
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003233};
3234
John McCall460ce582015-10-22 18:38:17 +00003235static bool hasWeakMember(QualType type) {
3236 if (type.getObjCLifetime() == Qualifiers::OCL_Weak) {
3237 return true;
3238 }
3239
3240 if (auto recType = type->getAs<RecordType>()) {
3241 for (auto field : recType->getDecl()->fields()) {
3242 if (hasWeakMember(field->getType()))
3243 return true;
3244 }
3245 }
3246
3247 return false;
3248}
3249
3250/// For compatibility, we only want to set the "HasMRCWeakIvars" flag
3251/// (and actually fill in a layout string) if we really do have any
3252/// __weak ivars.
3253static bool hasMRCWeakIvars(CodeGenModule &CGM,
3254 const ObjCImplementationDecl *ID) {
3255 if (!CGM.getLangOpts().ObjCWeak) return false;
3256 assert(CGM.getLangOpts().getGC() == LangOptions::NonGC);
3257
3258 for (const ObjCIvarDecl *ivar =
3259 ID->getClassInterface()->all_declared_ivar_begin();
3260 ivar; ivar = ivar->getNextIvar()) {
3261 if (hasWeakMember(ivar->getType()))
3262 return true;
3263 }
3264
3265 return false;
3266}
3267
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003268/*
3269 struct _objc_class {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003270 Class isa;
3271 Class super_class;
3272 const char *name;
3273 long version;
3274 long info;
3275 long instance_size;
3276 struct _objc_ivar_list *ivars;
3277 struct _objc_method_list *methods;
3278 struct _objc_cache *cache;
3279 struct _objc_protocol_list *protocols;
3280 // Objective-C 1.0 extensions (<rdr://4585769>)
3281 const char *ivar_layout;
3282 struct _objc_class_ext *ext;
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003283 };
3284
3285 See EmitClassExtension();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003286*/
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003287void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
Daniel Dunbarc61d0e92008-08-25 06:02:07 +00003288 DefinedSymbols.insert(ID->getIdentifier());
3289
Chris Lattner86d7d912008-11-24 03:54:41 +00003290 std::string ClassName = ID->getNameAsString();
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003291 // FIXME: Gross
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003292 ObjCInterfaceDecl *Interface =
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003293 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003294 llvm::Constant *Protocols =
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00003295 EmitProtocolList("OBJC_CLASS_PROTOCOLS_" + ID->getName(),
3296 Interface->all_referenced_protocol_begin(),
3297 Interface->all_referenced_protocol_end());
John McCallef19dbb2012-10-17 04:53:23 +00003298 unsigned Flags = FragileABI_Class_Factory;
John McCall0d54a172012-10-17 04:53:31 +00003299 if (ID->hasNonZeroConstructors() || ID->hasDestructors())
John McCallef19dbb2012-10-17 04:53:23 +00003300 Flags |= FragileABI_Class_HasCXXStructors;
John McCall09ec1ec2015-10-21 22:06:03 +00003301
John McCall460ce582015-10-22 18:38:17 +00003302 bool hasMRCWeak = false;
3303
John McCall09ec1ec2015-10-21 22:06:03 +00003304 if (CGM.getLangOpts().ObjCAutoRefCount)
3305 Flags |= FragileABI_Class_CompiledByARC;
John McCall460ce582015-10-22 18:38:17 +00003306 else if ((hasMRCWeak = hasMRCWeakIvars(CGM, ID)))
3307 Flags |= FragileABI_Class_HasMRCWeakIvars;
John McCall09ec1ec2015-10-21 22:06:03 +00003308
John McCall3fd13f062015-10-21 18:06:47 +00003309 CharUnits Size =
3310 CGM.getContext().getASTObjCImplementationLayout(ID).getSize();
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003311
3312 // FIXME: Set CXX-structors flag.
John McCall457a04e2010-10-22 21:05:15 +00003313 if (ID->getClassInterface()->getVisibility() == HiddenVisibility)
John McCallef19dbb2012-10-17 04:53:23 +00003314 Flags |= FragileABI_Class_Hidden;
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003315
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003316 SmallVector<llvm::Constant *, 16> InstanceMethods, ClassMethods;
Aaron Ballmanf26acce2014-03-13 19:50:17 +00003317 for (const auto *I : ID->instance_methods())
Daniel Dunbar3c76cb52008-08-26 21:51:14 +00003318 // Instance methods should always be defined.
Aaron Ballmanf26acce2014-03-13 19:50:17 +00003319 InstanceMethods.push_back(GetMethodConstant(I));
3320
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00003321 for (const auto *I : ID->class_methods())
Daniel Dunbar3c76cb52008-08-26 21:51:14 +00003322 // Class methods should always be defined.
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00003323 ClassMethods.push_back(GetMethodConstant(I));
Daniel Dunbar3c76cb52008-08-26 21:51:14 +00003324
Aaron Ballmand85eff42014-03-14 15:02:45 +00003325 for (const auto *PID : ID->property_impls()) {
Daniel Dunbar3c76cb52008-08-26 21:51:14 +00003326 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
3327 ObjCPropertyDecl *PD = PID->getPropertyDecl();
3328
3329 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
3330 if (llvm::Constant *C = GetMethodConstant(MD))
3331 InstanceMethods.push_back(C);
3332 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
3333 if (llvm::Constant *C = GetMethodConstant(MD))
3334 InstanceMethods.push_back(C);
3335 }
3336 }
3337
Chris Lattnere64d7ba2011-06-20 04:01:35 +00003338 llvm::Constant *Values[12];
Daniel Dunbarccf61832009-05-03 08:56:52 +00003339 Values[ 0] = EmitMetaClass(ID, Protocols, ClassMethods);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003340 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
Daniel Dunbarc61d0e92008-08-25 06:02:07 +00003341 // Record a reference to the super class.
3342 LazySymbols.insert(Super->getIdentifier());
3343
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003344 Values[ 1] =
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00003345 llvm::ConstantExpr::getBitCast(GetClassName(Super->getObjCRuntimeNameAsString()),
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003346 ObjCTypes.ClassPtrTy);
3347 } else {
Owen Anderson0b75f232009-07-31 20:28:54 +00003348 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003349 }
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00003350 Values[ 2] = GetClassName(ID->getObjCRuntimeNameAsString());
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003351 // Version is always 0.
Owen Andersonb7a2fe62009-07-24 23:12:58 +00003352 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
3353 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
John McCall3fd13f062015-10-21 18:06:47 +00003354 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size.getQuantity());
Fariborz Jahanianb042a592009-01-28 19:12:34 +00003355 Values[ 6] = EmitIvarList(ID, false);
Saleem Abdulrasoold48b0a32016-10-24 20:47:58 +00003356 Values[ 7] = EmitMethodList(ID->getName(), MethodListType::InstanceMethods,
3357 InstanceMethods);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003358 // cache is always NULL.
Owen Anderson0b75f232009-07-31 20:28:54 +00003359 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003360 Values[ 9] = Protocols;
John McCall460ce582015-10-22 18:38:17 +00003361 Values[10] = BuildStrongIvarLayout(ID, CharUnits::Zero(), Size);
Manman Renad0e7912016-01-29 19:22:54 +00003362 Values[11] = EmitClassExtension(ID, Size, hasMRCWeak,
3363 false/*isClassProperty*/);
Owen Anderson0e0189d2009-07-27 22:29:56 +00003364 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003365 Values);
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00003366 std::string Name("OBJC_CLASS_");
Fariborz Jahanianeb80c982009-11-12 20:14:24 +00003367 Name += ClassName;
3368 const char *Section = "__OBJC,__class,regular,no_dead_strip";
3369 // Check for a forward reference.
Rafael Espindola554256c2014-02-26 22:25:45 +00003370 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
Fariborz Jahanianeb80c982009-11-12 20:14:24 +00003371 if (GV) {
3372 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
3373 "Forward metaclass reference has incorrect type.");
Fariborz Jahanianeb80c982009-11-12 20:14:24 +00003374 GV->setInitializer(Init);
3375 GV->setSection(Section);
John McCall7f416cc2015-09-08 08:05:57 +00003376 GV->setAlignment(CGM.getPointerAlign().getQuantity());
Rafael Espindola060062a2014-03-06 22:15:10 +00003377 CGM.addCompilerUsedGlobal(GV);
Rafael Espindola21039aa2014-02-27 16:26:32 +00003378 } else
John McCall7f416cc2015-09-08 08:05:57 +00003379 GV = CreateMetadataVar(Name, Init, Section, CGM.getPointerAlign(), true);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003380 DefinedClasses.push_back(GV);
Fariborz Jahanianf322f2f2014-03-11 00:25:05 +00003381 ImplementedClasses.push_back(Interface);
Fariborz Jahanianc0577942011-04-22 22:02:28 +00003382 // method definition entries must be clear for next implementation.
3383 MethodDefinitions.clear();
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003384}
3385
3386llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
3387 llvm::Constant *Protocols,
Bill Wendlingcb5b5ff2012-02-07 09:25:09 +00003388 ArrayRef<llvm::Constant*> Methods) {
John McCallef19dbb2012-10-17 04:53:23 +00003389 unsigned Flags = FragileABI_Class_Meta;
Micah Villmowdd31ca12012-10-08 16:25:52 +00003390 unsigned Size = CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ClassTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003391
John McCall457a04e2010-10-22 21:05:15 +00003392 if (ID->getClassInterface()->getVisibility() == HiddenVisibility)
John McCallef19dbb2012-10-17 04:53:23 +00003393 Flags |= FragileABI_Class_Hidden;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003394
Chris Lattnere64d7ba2011-06-20 04:01:35 +00003395 llvm::Constant *Values[12];
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003396 // The isa for the metaclass is the root of the hierarchy.
3397 const ObjCInterfaceDecl *Root = ID->getClassInterface();
3398 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
3399 Root = Super;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003400 Values[ 0] =
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00003401 llvm::ConstantExpr::getBitCast(GetClassName(Root->getObjCRuntimeNameAsString()),
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003402 ObjCTypes.ClassPtrTy);
Daniel Dunbar938a77f2008-08-22 20:34:54 +00003403 // The super class for the metaclass is emitted as the name of the
3404 // super class. The runtime fixes this up to point to the
3405 // *metaclass* for the super class.
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003406 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003407 Values[ 1] =
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00003408 llvm::ConstantExpr::getBitCast(GetClassName(Super->getObjCRuntimeNameAsString()),
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003409 ObjCTypes.ClassPtrTy);
3410 } else {
Owen Anderson0b75f232009-07-31 20:28:54 +00003411 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003412 }
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00003413 Values[ 2] = GetClassName(ID->getObjCRuntimeNameAsString());
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003414 // Version is always 0.
Owen Andersonb7a2fe62009-07-24 23:12:58 +00003415 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
3416 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
3417 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanianb042a592009-01-28 19:12:34 +00003418 Values[ 6] = EmitIvarList(ID, true);
Saleem Abdulrasoold48b0a32016-10-24 20:47:58 +00003419 Values[ 7] = EmitMethodList(ID->getName(), MethodListType::ClassMethods,
3420 Methods);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003421 // cache is always NULL.
Owen Anderson0b75f232009-07-31 20:28:54 +00003422 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003423 Values[ 9] = Protocols;
3424 // ivar_layout for metaclass is always NULL.
Owen Anderson0b75f232009-07-31 20:28:54 +00003425 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Manman Renad0e7912016-01-29 19:22:54 +00003426 // The class extension is used to store class properties for metaclasses.
3427 Values[11] = EmitClassExtension(ID, CharUnits::Zero(), false/*hasMRCWeak*/,
3428 true/*isClassProperty*/);
Owen Anderson0e0189d2009-07-27 22:29:56 +00003429 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003430 Values);
3431
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00003432 std::string Name("OBJC_METACLASS_");
Benjamin Kramer1bbcbd02012-07-31 11:45:39 +00003433 Name += ID->getName();
Daniel Dunbarca8531a2008-08-25 08:19:24 +00003434
3435 // Check for a forward reference.
Rafael Espindola554256c2014-02-26 22:25:45 +00003436 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
Daniel Dunbarca8531a2008-08-25 08:19:24 +00003437 if (GV) {
3438 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
3439 "Forward metaclass reference has incorrect type.");
Daniel Dunbarca8531a2008-08-25 08:19:24 +00003440 GV->setInitializer(Init);
3441 } else {
Owen Andersonc10c8d32009-07-08 19:05:04 +00003442 GV = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassTy, false,
Rafael Espindola5179a4e2014-02-27 19:01:11 +00003443 llvm::GlobalValue::PrivateLinkage,
Owen Andersonc10c8d32009-07-08 19:05:04 +00003444 Init, Name);
Daniel Dunbarca8531a2008-08-25 08:19:24 +00003445 }
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003446 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
Daniel Dunbarae333842009-03-09 22:18:41 +00003447 GV->setAlignment(4);
Rafael Espindola060062a2014-03-06 22:15:10 +00003448 CGM.addCompilerUsedGlobal(GV);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003449
3450 return GV;
3451}
3452
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003453llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00003454 std::string Name = "OBJC_METACLASS_" + ID->getNameAsString();
Daniel Dunbarca8531a2008-08-25 08:19:24 +00003455
Mike Stump18bb9282009-05-16 07:57:57 +00003456 // FIXME: Should we look these up somewhere other than the module. Its a bit
3457 // silly since we only generate these while processing an implementation, so
3458 // exactly one pointer would work if know when we entered/exitted an
3459 // implementation block.
Daniel Dunbarca8531a2008-08-25 08:19:24 +00003460
3461 // Check for an existing forward reference.
Fariborz Jahanian475831b2009-01-07 20:11:22 +00003462 // Previously, metaclass with internal linkage may have been defined.
3463 // pass 'true' as 2nd argument so it is returned.
Rafael Espindola21039aa2014-02-27 16:26:32 +00003464 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
3465 if (!GV)
3466 GV = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassTy, false,
Craig Topper8a13c412014-05-21 05:09:00 +00003467 llvm::GlobalValue::PrivateLinkage, nullptr,
3468 Name);
Rafael Espindola21039aa2014-02-27 16:26:32 +00003469
3470 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
3471 "Forward metaclass reference has incorrect type.");
Rafael Espindola21039aa2014-02-27 16:26:32 +00003472 return GV;
Daniel Dunbarca8531a2008-08-25 08:19:24 +00003473}
3474
Fariborz Jahanianeb80c982009-11-12 20:14:24 +00003475llvm::Value *CGObjCMac::EmitSuperClassRef(const ObjCInterfaceDecl *ID) {
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00003476 std::string Name = "OBJC_CLASS_" + ID->getNameAsString();
Rafael Espindola21039aa2014-02-27 16:26:32 +00003477 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
3478
3479 if (!GV)
3480 GV = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassTy, false,
Craig Topper8a13c412014-05-21 05:09:00 +00003481 llvm::GlobalValue::PrivateLinkage, nullptr,
3482 Name);
Rafael Espindola21039aa2014-02-27 16:26:32 +00003483
3484 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
3485 "Forward class metadata reference has incorrect type.");
Rafael Espindola21039aa2014-02-27 16:26:32 +00003486 return GV;
Fariborz Jahanianeb80c982009-11-12 20:14:24 +00003487}
3488
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003489/*
John McCall3fd13f062015-10-21 18:06:47 +00003490 Emit a "class extension", which in this specific context means extra
3491 data that doesn't fit in the normal fragile-ABI class structure, and
3492 has nothing to do with the language concept of a class extension.
3493
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003494 struct objc_class_ext {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003495 uint32_t size;
3496 const char *weak_ivar_layout;
3497 struct _objc_property_list *properties;
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003498 };
3499*/
3500llvm::Constant *
John McCall3fd13f062015-10-21 18:06:47 +00003501CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID,
Manman Renad0e7912016-01-29 19:22:54 +00003502 CharUnits InstanceSize, bool hasMRCWeakIvars,
3503 bool isClassProperty) {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003504 uint64_t Size =
Micah Villmowdd31ca12012-10-08 16:25:52 +00003505 CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ClassExtensionTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003506
Chris Lattnere64d7ba2011-06-20 04:01:35 +00003507 llvm::Constant *Values[3];
Owen Andersonb7a2fe62009-07-24 23:12:58 +00003508 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Manman Ren92e0a712016-02-21 05:31:05 +00003509 if (isClassProperty) {
3510 llvm::Type *PtrTy = CGM.Int8PtrTy;
3511 Values[1] = llvm::Constant::getNullValue(PtrTy);
3512 } else
Manman Renad0e7912016-01-29 19:22:54 +00003513 Values[1] = BuildWeakIvarLayout(ID, CharUnits::Zero(), InstanceSize,
3514 hasMRCWeakIvars);
3515 if (isClassProperty)
3516 Values[2] = EmitPropertyList("\01l_OBJC_$_CLASS_PROP_LIST_" + ID->getName(),
3517 ID, ID->getClassInterface(), ObjCTypes, true);
3518 else
3519 Values[2] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ID->getName(),
3520 ID, ID->getClassInterface(), ObjCTypes, false);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003521
3522 // Return null if no extension bits are used.
Manman Renad0e7912016-01-29 19:22:54 +00003523 if ((!Values[1] || Values[1]->isNullValue()) && Values[2]->isNullValue())
Owen Anderson0b75f232009-07-31 20:28:54 +00003524 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003525
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003526 llvm::Constant *Init =
Owen Anderson0e0189d2009-07-27 22:29:56 +00003527 llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00003528 return CreateMetadataVar("OBJC_CLASSEXT_" + ID->getName(), Init,
John McCall7f416cc2015-09-08 08:05:57 +00003529 "__OBJC,__class_ext,regular,no_dead_strip",
3530 CGM.getPointerAlign(), true);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003531}
3532
3533/*
3534 struct objc_ivar {
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00003535 char *ivar_name;
3536 char *ivar_type;
3537 int ivar_offset;
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003538 };
3539
3540 struct objc_ivar_list {
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00003541 int ivar_count;
3542 struct objc_ivar list[count];
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003543 };
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003544*/
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003545llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanianb042a592009-01-28 19:12:34 +00003546 bool ForClass) {
Benjamin Kramer22d24c22011-10-15 12:20:02 +00003547 std::vector<llvm::Constant*> Ivars;
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003548
3549 // When emitting the root class GCC emits ivar entries for the
3550 // actual class structure. It is not clear if we need to follow this
3551 // behavior; for now lets try and get away with not doing it. If so,
3552 // the cleanest solution would be to make up an ObjCInterfaceDecl
3553 // for the class.
3554 if (ForClass)
Owen Anderson0b75f232009-07-31 20:28:54 +00003555 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003556
Jordy Rosea91768e2011-07-22 02:08:32 +00003557 const ObjCInterfaceDecl *OID = ID->getClassInterface();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003558
Jordy Rosea91768e2011-07-22 02:08:32 +00003559 for (const ObjCIvarDecl *IVD = OID->all_declared_ivar_begin();
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00003560 IVD; IVD = IVD->getNextIvar()) {
Fariborz Jahanian7c809592009-06-04 01:19:09 +00003561 // Ignore unnamed bit-fields.
3562 if (!IVD->getDeclName())
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003563 continue;
Benjamin Kramer22d24c22011-10-15 12:20:02 +00003564 llvm::Constant *Ivar[] = {
3565 GetMethodVarName(IVD->getIdentifier()),
3566 GetMethodVarType(IVD),
3567 llvm::ConstantInt::get(ObjCTypes.IntTy,
Eli Friedman8cbca202012-11-06 22:15:52 +00003568 ComputeIvarBaseOffset(CGM, OID, IVD))
Benjamin Kramer22d24c22011-10-15 12:20:02 +00003569 };
Owen Anderson0e0189d2009-07-27 22:29:56 +00003570 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003571 }
3572
3573 // Return null for empty list.
3574 if (Ivars.empty())
Owen Anderson0b75f232009-07-31 20:28:54 +00003575 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003576
Chris Lattnere64d7ba2011-06-20 04:01:35 +00003577 llvm::Constant *Values[2];
Owen Andersonb7a2fe62009-07-24 23:12:58 +00003578 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
Owen Anderson9793f0e2009-07-29 22:16:19 +00003579 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003580 Ivars.size());
Owen Anderson47034e12009-07-28 18:33:04 +00003581 Values[1] = llvm::ConstantArray::get(AT, Ivars);
Chris Lattnere64d7ba2011-06-20 04:01:35 +00003582 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003583
Daniel Dunbarc2d4b622009-03-09 21:49:58 +00003584 llvm::GlobalVariable *GV;
3585 if (ForClass)
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00003586 GV =
3587 CreateMetadataVar("OBJC_CLASS_VARIABLES_" + ID->getName(), Init,
John McCall7f416cc2015-09-08 08:05:57 +00003588 "__OBJC,__class_vars,regular,no_dead_strip",
3589 CGM.getPointerAlign(), true);
Daniel Dunbarc2d4b622009-03-09 21:49:58 +00003590 else
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00003591 GV = CreateMetadataVar("OBJC_INSTANCE_VARIABLES_" + ID->getName(), Init,
John McCall7f416cc2015-09-08 08:05:57 +00003592 "__OBJC,__instance_vars,regular,no_dead_strip",
3593 CGM.getPointerAlign(), true);
Owen Andersonade90fd2009-07-29 18:54:39 +00003594 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.IvarListPtrTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003595}
3596
3597/*
3598 struct objc_method {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003599 SEL method_name;
3600 char *method_types;
3601 void *method;
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003602 };
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003603
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003604 struct objc_method_list {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003605 struct objc_method_list *obsolete;
3606 int count;
3607 struct objc_method methods_list[count];
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003608 };
3609*/
Daniel Dunbar3c76cb52008-08-26 21:51:14 +00003610
3611/// GetMethodConstant - Return a struct objc_method constant for the
3612/// given method if it has been defined. The result is null if the
3613/// method has not been defined. The return value has type MethodPtrTy.
Daniel Dunbareb1f9a22008-08-27 02:31:56 +00003614llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
Argyrios Kyrtzidis13257c52010-08-09 10:54:20 +00003615 llvm::Function *Fn = GetMethodDefinition(MD);
Daniel Dunbar3c76cb52008-08-26 21:51:14 +00003616 if (!Fn)
Craig Topper8a13c412014-05-21 05:09:00 +00003617 return nullptr;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003618
Benjamin Kramer22d24c22011-10-15 12:20:02 +00003619 llvm::Constant *Method[] = {
Owen Andersonade90fd2009-07-29 18:54:39 +00003620 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
Benjamin Kramer22d24c22011-10-15 12:20:02 +00003621 ObjCTypes.SelectorPtrTy),
3622 GetMethodVarType(MD),
3623 llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy)
3624 };
Owen Anderson0e0189d2009-07-27 22:29:56 +00003625 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
Daniel Dunbar3c76cb52008-08-26 21:51:14 +00003626}
3627
Saleem Abdulrasoold48b0a32016-10-24 20:47:58 +00003628llvm::Constant *CGObjCMac::EmitMethodList(Twine Name, MethodListType MLT,
Saleem Abdulrasool1e6c4062016-05-16 05:06:49 +00003629 ArrayRef<llvm::Constant *> Methods) {
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003630 // Return null for empty list.
3631 if (Methods.empty())
Owen Anderson0b75f232009-07-31 20:28:54 +00003632 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003633
Chris Lattnere64d7ba2011-06-20 04:01:35 +00003634 llvm::Constant *Values[3];
Owen Anderson0b75f232009-07-31 20:28:54 +00003635 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00003636 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
Owen Anderson9793f0e2009-07-29 22:16:19 +00003637 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003638 Methods.size());
Owen Anderson47034e12009-07-28 18:33:04 +00003639 Values[2] = llvm::ConstantArray::get(AT, Methods);
Chris Lattnere64d7ba2011-06-20 04:01:35 +00003640 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003641
Saleem Abdulrasoold48b0a32016-10-24 20:47:58 +00003642 StringRef Prefix;
3643 StringRef Section;
3644 switch (MLT) {
3645 case MethodListType::CategoryInstanceMethods:
3646 Prefix = "OBJC_CATEGORY_INSTANCE_METHODS_";
3647 Section = "__OBJC,__cat_inst_meth,regular,no_dead_strip";
3648 break;
3649 case MethodListType::CategoryClassMethods:
3650 Prefix = "OBJC_CATEGORY_CLASS_METHODS_";
3651 Section = "__OBJC,__cat_cls_meth,regular,no_dead_strip";
3652 break;
3653 case MethodListType::InstanceMethods:
3654 Prefix = "OBJC_INSTANCE_METHODS_";
3655 Section = "__OBJC,__inst_meth,regular,no_dead_strip";
3656 break;
3657 case MethodListType::ClassMethods:
3658 Prefix = "OBJC_CLASS_METHODS_";
3659 Section = "__OBJC,__cls_meth,regular,no_dead_strip";
3660 break;
3661
3662 case MethodListType::ProtocolInstanceMethods:
3663 case MethodListType::ProtocolClassMethods:
3664 case MethodListType::OptionalProtocolInstanceMethods:
3665 case MethodListType::OptionalProtocolClassMethods:
3666 llvm_unreachable("unsupported method list type");
3667 }
3668
3669 llvm::GlobalVariable *GV = CreateMetadataVar(Prefix + Name, Init, Section,
3670 CGM.getPointerAlign(), true);
Chris Lattnere64d7ba2011-06-20 04:01:35 +00003671 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.MethodListPtrTy);
Daniel Dunbara94ecd22008-08-16 03:19:19 +00003672}
3673
Fariborz Jahanian99113fd2009-01-26 21:38:32 +00003674llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD,
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003675 const ObjCContainerDecl *CD) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003676 SmallString<256> Name;
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +00003677 GetNameForMethod(OMD, CD, Name);
Daniel Dunbara94ecd22008-08-16 03:19:19 +00003678
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +00003679 CodeGenTypes &Types = CGM.getTypes();
Chris Lattner2192fe52011-07-18 04:24:23 +00003680 llvm::FunctionType *MethodTy =
John McCalla729c622012-02-17 03:33:10 +00003681 Types.GetFunctionType(Types.arrangeObjCMethodDeclaration(OMD));
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003682 llvm::Function *Method =
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00003683 llvm::Function::Create(MethodTy,
Daniel Dunbara94ecd22008-08-16 03:19:19 +00003684 llvm::GlobalValue::InternalLinkage,
Daniel Dunbard2386812009-10-19 01:21:19 +00003685 Name.str(),
Daniel Dunbara94ecd22008-08-16 03:19:19 +00003686 &CGM.getModule());
Daniel Dunbar3c76cb52008-08-26 21:51:14 +00003687 MethodDefinitions.insert(std::make_pair(OMD, Method));
Daniel Dunbara94ecd22008-08-16 03:19:19 +00003688
Daniel Dunbara94ecd22008-08-16 03:19:19 +00003689 return Method;
Daniel Dunbar303e2c22008-08-11 02:45:11 +00003690}
3691
Alp Toker541d5072014-06-07 23:30:53 +00003692llvm::GlobalVariable *CGObjCCommonMac::CreateMetadataVar(Twine Name,
3693 llvm::Constant *Init,
3694 StringRef Section,
John McCall7f416cc2015-09-08 08:05:57 +00003695 CharUnits Align,
Alp Toker541d5072014-06-07 23:30:53 +00003696 bool AddToUsed) {
Chris Lattner2192fe52011-07-18 04:24:23 +00003697 llvm::Type *Ty = Init->getType();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003698 llvm::GlobalVariable *GV =
Owen Andersonc10c8d32009-07-08 19:05:04 +00003699 new llvm::GlobalVariable(CGM.getModule(), Ty, false,
Rafael Espindola5179a4e2014-02-27 19:01:11 +00003700 llvm::GlobalValue::PrivateLinkage, Init, Name);
Alp Toker541d5072014-06-07 23:30:53 +00003701 if (!Section.empty())
Daniel Dunbar30c65362009-03-09 20:09:19 +00003702 GV->setSection(Section);
John McCall7f416cc2015-09-08 08:05:57 +00003703 GV->setAlignment(Align.getQuantity());
Daniel Dunbar463cc8a2009-03-09 20:50:13 +00003704 if (AddToUsed)
Rafael Espindola060062a2014-03-06 22:15:10 +00003705 CGM.addCompilerUsedGlobal(GV);
Daniel Dunbar30c65362009-03-09 20:09:19 +00003706 return GV;
3707}
3708
Saleem Abdulrasool271106c2016-09-16 23:41:13 +00003709llvm::GlobalVariable *
Saleem Abdulrasool82f6add2016-09-20 18:38:54 +00003710CGObjCCommonMac::CreateCStringLiteral(StringRef Name, ObjCLabelType Type,
3711 bool ForceNonFragileABI,
3712 bool NullTerminate) {
Saleem Abdulrasool271106c2016-09-16 23:41:13 +00003713 StringRef Label;
3714 switch (Type) {
3715 case ObjCLabelType::ClassName: Label = "OBJC_CLASS_NAME_"; break;
3716 case ObjCLabelType::MethodVarName: Label = "OBJC_METH_VAR_NAME_"; break;
3717 case ObjCLabelType::MethodVarType: Label = "OBJC_METH_VAR_TYPE_"; break;
3718 case ObjCLabelType::PropertyName: Label = "OBJC_PROP_NAME_ATTR_"; break;
3719 }
3720
Saleem Abdulrasool82f6add2016-09-20 18:38:54 +00003721 bool NonFragile = ForceNonFragileABI || isNonFragileABI();
3722
Saleem Abdulrasool271106c2016-09-16 23:41:13 +00003723 StringRef Section;
3724 switch (Type) {
3725 case ObjCLabelType::ClassName:
Saleem Abdulrasool82f6add2016-09-20 18:38:54 +00003726 Section = NonFragile ? "__TEXT,__objc_classname,cstring_literals"
3727 : "__TEXT,__cstring,cstring_literals";
Saleem Abdulrasool271106c2016-09-16 23:41:13 +00003728 break;
3729 case ObjCLabelType::MethodVarName:
Saleem Abdulrasool82f6add2016-09-20 18:38:54 +00003730 Section = NonFragile ? "__TEXT,__objc_methname,cstring_literals"
3731 : "__TEXT,__cstring,cstring_literals";
Saleem Abdulrasool271106c2016-09-16 23:41:13 +00003732 break;
3733 case ObjCLabelType::MethodVarType:
Saleem Abdulrasool82f6add2016-09-20 18:38:54 +00003734 Section = NonFragile ? "__TEXT,__objc_methtype,cstring_literals"
3735 : "__TEXT,__cstring,cstring_literals";
Saleem Abdulrasool271106c2016-09-16 23:41:13 +00003736 break;
3737 case ObjCLabelType::PropertyName:
3738 Section = "__TEXT,__cstring,cstring_literals";
3739 break;
3740 }
3741
Saleem Abdulrasool82f6add2016-09-20 18:38:54 +00003742 llvm::Constant *Value =
3743 llvm::ConstantDataArray::getString(VMContext, Name, NullTerminate);
Saleem Abdulrasool271106c2016-09-16 23:41:13 +00003744 llvm::GlobalVariable *GV =
Saleem Abdulrasool0c54dc82016-09-18 16:12:04 +00003745 new llvm::GlobalVariable(CGM.getModule(), Value->getType(),
3746 /*isConstant=*/true,
Saleem Abdulrasool271106c2016-09-16 23:41:13 +00003747 llvm::GlobalValue::PrivateLinkage, Value, Label);
Saleem Abdulrasool3f307512016-09-18 16:12:14 +00003748 if (CGM.getTriple().isOSBinFormatMachO())
3749 GV->setSection(Section);
3750 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Saleem Abdulrasool271106c2016-09-16 23:41:13 +00003751 GV->setAlignment(CharUnits::One().getQuantity());
3752 CGM.addCompilerUsedGlobal(GV);
3753
3754 return GV;
3755}
3756
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003757llvm::Function *CGObjCMac::ModuleInitFunction() {
Daniel Dunbar3ad53482008-08-11 21:35:06 +00003758 // Abuse this interface function as a place to finalize.
3759 FinishModule();
Craig Topper8a13c412014-05-21 05:09:00 +00003760 return nullptr;
Daniel Dunbar303e2c22008-08-11 02:45:11 +00003761}
3762
Chris Lattnerd4808922009-03-22 21:03:39 +00003763llvm::Constant *CGObjCMac::GetPropertyGetFunction() {
Chris Lattnerce8754e2009-04-22 02:44:54 +00003764 return ObjCTypes.getGetPropertyFn();
Daniel Dunbara91c3e02008-09-24 03:38:44 +00003765}
3766
Chris Lattnerd4808922009-03-22 21:03:39 +00003767llvm::Constant *CGObjCMac::GetPropertySetFunction() {
Chris Lattnerce8754e2009-04-22 02:44:54 +00003768 return ObjCTypes.getSetPropertyFn();
Daniel Dunbara91c3e02008-09-24 03:38:44 +00003769}
3770
Ted Kremeneke65b0862012-03-06 20:05:56 +00003771llvm::Constant *CGObjCMac::GetOptimizedPropertySetFunction(bool atomic,
3772 bool copy) {
3773 return ObjCTypes.getOptimizedSetPropertyFn(atomic, copy);
3774}
3775
David Chisnall168b80f2010-12-26 22:13:16 +00003776llvm::Constant *CGObjCMac::GetGetStructFunction() {
3777 return ObjCTypes.getCopyStructFn();
3778}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00003779
David Chisnall168b80f2010-12-26 22:13:16 +00003780llvm::Constant *CGObjCMac::GetSetStructFunction() {
Fariborz Jahanian5a8c2032010-04-12 18:18:10 +00003781 return ObjCTypes.getCopyStructFn();
3782}
3783
David Chisnall0d75e062012-12-17 18:54:24 +00003784llvm::Constant *CGObjCMac::GetCppAtomicObjectGetFunction() {
3785 return ObjCTypes.getCppAtomicObjectFunction();
3786}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00003787
David Chisnall0d75e062012-12-17 18:54:24 +00003788llvm::Constant *CGObjCMac::GetCppAtomicObjectSetFunction() {
Fariborz Jahanian1e1b5492012-01-06 18:07:23 +00003789 return ObjCTypes.getCppAtomicObjectFunction();
3790}
3791
Chris Lattnerd4808922009-03-22 21:03:39 +00003792llvm::Constant *CGObjCMac::EnumerationMutationFunction() {
Chris Lattnerce8754e2009-04-22 02:44:54 +00003793 return ObjCTypes.getEnumerationMutationFn();
Anders Carlsson3f35a262008-08-31 04:05:03 +00003794}
3795
John McCallbd309292010-07-06 01:34:17 +00003796void CGObjCMac::EmitTryStmt(CodeGenFunction &CGF, const ObjCAtTryStmt &S) {
3797 return EmitTryOrSynchronizedStmt(CGF, S);
3798}
3799
3800void CGObjCMac::EmitSynchronizedStmt(CodeGenFunction &CGF,
3801 const ObjCAtSynchronizedStmt &S) {
3802 return EmitTryOrSynchronizedStmt(CGF, S);
3803}
3804
John McCall65bea082010-07-21 06:59:36 +00003805namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00003806 struct PerformFragileFinally final : EHScopeStack::Cleanup {
John McCall65bea082010-07-21 06:59:36 +00003807 const Stmt &S;
John McCall7f416cc2015-09-08 08:05:57 +00003808 Address SyncArgSlot;
3809 Address CallTryExitVar;
3810 Address ExceptionData;
John McCall65bea082010-07-21 06:59:36 +00003811 ObjCTypesHelper &ObjCTypes;
3812 PerformFragileFinally(const Stmt *S,
John McCall7f416cc2015-09-08 08:05:57 +00003813 Address SyncArgSlot,
3814 Address CallTryExitVar,
3815 Address ExceptionData,
John McCall65bea082010-07-21 06:59:36 +00003816 ObjCTypesHelper *ObjCTypes)
John McCall2dd7d442010-08-04 05:59:32 +00003817 : S(*S), SyncArgSlot(SyncArgSlot), CallTryExitVar(CallTryExitVar),
John McCall65bea082010-07-21 06:59:36 +00003818 ExceptionData(ExceptionData), ObjCTypes(*ObjCTypes) {}
3819
Craig Topper4f12f102014-03-12 06:41:41 +00003820 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall65bea082010-07-21 06:59:36 +00003821 // Check whether we need to call objc_exception_try_exit.
3822 // In optimized code, this branch will always be folded.
3823 llvm::BasicBlock *FinallyCallExit =
3824 CGF.createBasicBlock("finally.call_exit");
3825 llvm::BasicBlock *FinallyNoCallExit =
3826 CGF.createBasicBlock("finally.no_call_exit");
3827 CGF.Builder.CreateCondBr(CGF.Builder.CreateLoad(CallTryExitVar),
3828 FinallyCallExit, FinallyNoCallExit);
3829
3830 CGF.EmitBlock(FinallyCallExit);
John McCall882987f2013-02-28 19:01:20 +00003831 CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionTryExitFn(),
John McCall7f416cc2015-09-08 08:05:57 +00003832 ExceptionData.getPointer());
John McCall65bea082010-07-21 06:59:36 +00003833
3834 CGF.EmitBlock(FinallyNoCallExit);
3835
3836 if (isa<ObjCAtTryStmt>(S)) {
3837 if (const ObjCAtFinallyStmt* FinallyStmt =
John McCallcebe0ca2010-08-11 00:16:14 +00003838 cast<ObjCAtTryStmt>(S).getFinallyStmt()) {
John McCall638d4f52013-04-03 00:56:07 +00003839 // Don't try to do the @finally if this is an EH cleanup.
3840 if (flags.isForEHCleanup()) return;
3841
John McCallcebe0ca2010-08-11 00:16:14 +00003842 // Save the current cleanup destination in case there's
3843 // control flow inside the finally statement.
3844 llvm::Value *CurCleanupDest =
3845 CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot());
3846
John McCall65bea082010-07-21 06:59:36 +00003847 CGF.EmitStmt(FinallyStmt->getFinallyBody());
3848
John McCallcebe0ca2010-08-11 00:16:14 +00003849 if (CGF.HaveInsertPoint()) {
3850 CGF.Builder.CreateStore(CurCleanupDest,
3851 CGF.getNormalCleanupDestSlot());
3852 } else {
3853 // Currently, the end of the cleanup must always exist.
3854 CGF.EnsureInsertPoint();
3855 }
3856 }
John McCall65bea082010-07-21 06:59:36 +00003857 } else {
3858 // Emit objc_sync_exit(expr); as finally's sole statement for
3859 // @synchronized.
John McCall2dd7d442010-08-04 05:59:32 +00003860 llvm::Value *SyncArg = CGF.Builder.CreateLoad(SyncArgSlot);
John McCall882987f2013-02-28 19:01:20 +00003861 CGF.EmitNounwindRuntimeCall(ObjCTypes.getSyncExitFn(), SyncArg);
John McCall65bea082010-07-21 06:59:36 +00003862 }
3863 }
3864 };
John McCall42227ed2010-07-31 23:20:56 +00003865
3866 class FragileHazards {
3867 CodeGenFunction &CGF;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003868 SmallVector<llvm::Value*, 20> Locals;
John McCall42227ed2010-07-31 23:20:56 +00003869 llvm::DenseSet<llvm::BasicBlock*> BlocksBeforeTry;
3870
3871 llvm::InlineAsm *ReadHazard;
3872 llvm::InlineAsm *WriteHazard;
3873
3874 llvm::FunctionType *GetAsmFnType();
3875
3876 void collectLocals();
3877 void emitReadHazard(CGBuilderTy &Builder);
3878
3879 public:
3880 FragileHazards(CodeGenFunction &CGF);
John McCall2dd7d442010-08-04 05:59:32 +00003881
John McCall42227ed2010-07-31 23:20:56 +00003882 void emitWriteHazard();
John McCall2dd7d442010-08-04 05:59:32 +00003883 void emitHazardsInNewBlocks();
John McCall42227ed2010-07-31 23:20:56 +00003884 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00003885} // end anonymous namespace
John McCall42227ed2010-07-31 23:20:56 +00003886
3887/// Create the fragile-ABI read and write hazards based on the current
3888/// state of the function, which is presumed to be immediately prior
3889/// to a @try block. These hazards are used to maintain correct
3890/// semantics in the face of optimization and the fragile ABI's
3891/// cavalier use of setjmp/longjmp.
3892FragileHazards::FragileHazards(CodeGenFunction &CGF) : CGF(CGF) {
3893 collectLocals();
3894
3895 if (Locals.empty()) return;
3896
3897 // Collect all the blocks in the function.
3898 for (llvm::Function::iterator
3899 I = CGF.CurFn->begin(), E = CGF.CurFn->end(); I != E; ++I)
3900 BlocksBeforeTry.insert(&*I);
3901
3902 llvm::FunctionType *AsmFnTy = GetAsmFnType();
3903
3904 // Create a read hazard for the allocas. This inhibits dead-store
3905 // optimizations and forces the values to memory. This hazard is
3906 // inserted before any 'throwing' calls in the protected scope to
3907 // reflect the possibility that the variables might be read from the
3908 // catch block if the call throws.
3909 {
3910 std::string Constraint;
3911 for (unsigned I = 0, E = Locals.size(); I != E; ++I) {
3912 if (I) Constraint += ',';
3913 Constraint += "*m";
3914 }
3915
3916 ReadHazard = llvm::InlineAsm::get(AsmFnTy, "", Constraint, true, false);
3917 }
3918
3919 // Create a write hazard for the allocas. This inhibits folding
3920 // loads across the hazard. This hazard is inserted at the
3921 // beginning of the catch path to reflect the possibility that the
3922 // variables might have been written within the protected scope.
3923 {
3924 std::string Constraint;
3925 for (unsigned I = 0, E = Locals.size(); I != E; ++I) {
3926 if (I) Constraint += ',';
3927 Constraint += "=*m";
3928 }
3929
3930 WriteHazard = llvm::InlineAsm::get(AsmFnTy, "", Constraint, true, false);
3931 }
3932}
3933
3934/// Emit a write hazard at the current location.
3935void FragileHazards::emitWriteHazard() {
3936 if (Locals.empty()) return;
3937
John McCall882987f2013-02-28 19:01:20 +00003938 CGF.EmitNounwindRuntimeCall(WriteHazard, Locals);
John McCall42227ed2010-07-31 23:20:56 +00003939}
3940
John McCall42227ed2010-07-31 23:20:56 +00003941void FragileHazards::emitReadHazard(CGBuilderTy &Builder) {
3942 assert(!Locals.empty());
John McCall882987f2013-02-28 19:01:20 +00003943 llvm::CallInst *call = Builder.CreateCall(ReadHazard, Locals);
3944 call->setDoesNotThrow();
3945 call->setCallingConv(CGF.getRuntimeCC());
John McCall42227ed2010-07-31 23:20:56 +00003946}
3947
3948/// Emit read hazards in all the protected blocks, i.e. all the blocks
3949/// which have been inserted since the beginning of the try.
John McCall2dd7d442010-08-04 05:59:32 +00003950void FragileHazards::emitHazardsInNewBlocks() {
John McCall42227ed2010-07-31 23:20:56 +00003951 if (Locals.empty()) return;
3952
John McCall7f416cc2015-09-08 08:05:57 +00003953 CGBuilderTy Builder(CGF, CGF.getLLVMContext());
John McCall42227ed2010-07-31 23:20:56 +00003954
3955 // Iterate through all blocks, skipping those prior to the try.
3956 for (llvm::Function::iterator
3957 FI = CGF.CurFn->begin(), FE = CGF.CurFn->end(); FI != FE; ++FI) {
3958 llvm::BasicBlock &BB = *FI;
3959 if (BlocksBeforeTry.count(&BB)) continue;
3960
3961 // Walk through all the calls in the block.
3962 for (llvm::BasicBlock::iterator
3963 BI = BB.begin(), BE = BB.end(); BI != BE; ++BI) {
3964 llvm::Instruction &I = *BI;
3965
3966 // Ignore instructions that aren't non-intrinsic calls.
3967 // These are the only calls that can possibly call longjmp.
3968 if (!isa<llvm::CallInst>(I) && !isa<llvm::InvokeInst>(I)) continue;
3969 if (isa<llvm::IntrinsicInst>(I))
3970 continue;
3971
3972 // Ignore call sites marked nounwind. This may be questionable,
3973 // since 'nounwind' doesn't necessarily mean 'does not call longjmp'.
3974 llvm::CallSite CS(&I);
3975 if (CS.doesNotThrow()) continue;
3976
John McCall2dd7d442010-08-04 05:59:32 +00003977 // Insert a read hazard before the call. This will ensure that
3978 // any writes to the locals are performed before making the
3979 // call. If the call throws, then this is sufficient to
3980 // guarantee correctness as long as it doesn't also write to any
3981 // locals.
John McCall42227ed2010-07-31 23:20:56 +00003982 Builder.SetInsertPoint(&BB, BI);
3983 emitReadHazard(Builder);
3984 }
3985 }
3986}
3987
3988static void addIfPresent(llvm::DenseSet<llvm::Value*> &S, llvm::Value *V) {
3989 if (V) S.insert(V);
3990}
3991
John McCall7f416cc2015-09-08 08:05:57 +00003992static void addIfPresent(llvm::DenseSet<llvm::Value*> &S, Address V) {
3993 if (V.isValid()) S.insert(V.getPointer());
3994}
3995
John McCall42227ed2010-07-31 23:20:56 +00003996void FragileHazards::collectLocals() {
3997 // Compute a set of allocas to ignore.
3998 llvm::DenseSet<llvm::Value*> AllocasToIgnore;
3999 addIfPresent(AllocasToIgnore, CGF.ReturnValue);
4000 addIfPresent(AllocasToIgnore, CGF.NormalCleanupDest);
John McCall42227ed2010-07-31 23:20:56 +00004001
4002 // Collect all the allocas currently in the function. This is
4003 // probably way too aggressive.
4004 llvm::BasicBlock &Entry = CGF.CurFn->getEntryBlock();
4005 for (llvm::BasicBlock::iterator
4006 I = Entry.begin(), E = Entry.end(); I != E; ++I)
4007 if (isa<llvm::AllocaInst>(*I) && !AllocasToIgnore.count(&*I))
4008 Locals.push_back(&*I);
4009}
4010
4011llvm::FunctionType *FragileHazards::GetAsmFnType() {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004012 SmallVector<llvm::Type *, 16> tys(Locals.size());
John McCall9dc0db22011-05-15 01:53:33 +00004013 for (unsigned i = 0, e = Locals.size(); i != e; ++i)
4014 tys[i] = Locals[i]->getType();
4015 return llvm::FunctionType::get(CGF.VoidTy, tys, false);
John McCall65bea082010-07-21 06:59:36 +00004016}
4017
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004018/*
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004019
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004020 Objective-C setjmp-longjmp (sjlj) Exception Handling
4021 --
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004022
John McCallbd309292010-07-06 01:34:17 +00004023 A catch buffer is a setjmp buffer plus:
4024 - a pointer to the exception that was caught
4025 - a pointer to the previous exception data buffer
4026 - two pointers of reserved storage
4027 Therefore catch buffers form a stack, with a pointer to the top
4028 of the stack kept in thread-local storage.
4029
4030 objc_exception_try_enter pushes a catch buffer onto the EH stack.
4031 objc_exception_try_exit pops the given catch buffer, which is
4032 required to be the top of the EH stack.
4033 objc_exception_throw pops the top of the EH stack, writes the
4034 thrown exception into the appropriate field, and longjmps
4035 to the setjmp buffer. It crashes the process (with a printf
4036 and an abort()) if there are no catch buffers on the stack.
4037 objc_exception_extract just reads the exception pointer out of the
4038 catch buffer.
4039
4040 There's no reason an implementation couldn't use a light-weight
4041 setjmp here --- something like __builtin_setjmp, but API-compatible
4042 with the heavyweight setjmp. This will be more important if we ever
4043 want to implement correct ObjC/C++ exception interactions for the
4044 fragile ABI.
4045
4046 Note that for this use of setjmp/longjmp to be correct, we may need
4047 to mark some local variables volatile: if a non-volatile local
4048 variable is modified between the setjmp and the longjmp, it has
4049 indeterminate value. For the purposes of LLVM IR, it may be
4050 sufficient to make loads and stores within the @try (to variables
4051 declared outside the @try) volatile. This is necessary for
4052 optimized correctness, but is not currently being done; this is
4053 being tracked as rdar://problem/8160285
4054
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004055 The basic framework for a @try-catch-finally is as follows:
4056 {
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004057 objc_exception_data d;
4058 id _rethrow = null;
Anders Carlssonda0e4562009-02-07 21:26:04 +00004059 bool _call_try_exit = true;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004060
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004061 objc_exception_try_enter(&d);
4062 if (!setjmp(d.jmp_buf)) {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004063 ... try body ...
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004064 } else {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004065 // exception path
4066 id _caught = objc_exception_extract(&d);
4067
4068 // enter new try scope for handlers
4069 if (!setjmp(d.jmp_buf)) {
4070 ... match exception and execute catch blocks ...
4071
4072 // fell off end, rethrow.
4073 _rethrow = _caught;
4074 ... jump-through-finally to finally_rethrow ...
4075 } else {
4076 // exception in catch block
4077 _rethrow = objc_exception_extract(&d);
4078 _call_try_exit = false;
4079 ... jump-through-finally to finally_rethrow ...
4080 }
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004081 }
Daniel Dunbar2efd5382008-09-30 01:06:03 +00004082 ... jump-through-finally to finally_end ...
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004083
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004084 finally:
Anders Carlssonda0e4562009-02-07 21:26:04 +00004085 if (_call_try_exit)
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004086 objc_exception_try_exit(&d);
Anders Carlssonda0e4562009-02-07 21:26:04 +00004087
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004088 ... finally block ....
Daniel Dunbar2efd5382008-09-30 01:06:03 +00004089 ... dispatch to finally destination ...
4090
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004091 finally_rethrow:
Daniel Dunbar2efd5382008-09-30 01:06:03 +00004092 objc_exception_throw(_rethrow);
4093
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004094 finally_end:
4095 }
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004096
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004097 This framework differs slightly from the one gcc uses, in that gcc
4098 uses _rethrow to determine if objc_exception_try_exit should be called
4099 and if the object should be rethrown. This breaks in the face of
4100 throwing nil and introduces unnecessary branches.
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004101
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004102 We specialize this framework for a few particular circumstances:
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004103
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004104 - If there are no catch blocks, then we avoid emitting the second
4105 exception handling context.
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004106
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004107 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
4108 e)) we avoid emitting the code to rethrow an uncaught exception.
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004109
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004110 - FIXME: If there is no @finally block we can do a few more
4111 simplifications.
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004112
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004113 Rethrows and Jumps-Through-Finally
4114 --
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004115
John McCallbd309292010-07-06 01:34:17 +00004116 '@throw;' is supported by pushing the currently-caught exception
4117 onto ObjCEHStack while the @catch blocks are emitted.
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004118
John McCallbd309292010-07-06 01:34:17 +00004119 Branches through the @finally block are handled with an ordinary
4120 normal cleanup. We do not register an EH cleanup; fragile-ABI ObjC
4121 exceptions are not compatible with C++ exceptions, and this is
4122 hardly the only place where this will go wrong.
Daniel Dunbar2efd5382008-09-30 01:06:03 +00004123
John McCallbd309292010-07-06 01:34:17 +00004124 @synchronized(expr) { stmt; } is emitted as if it were:
4125 id synch_value = expr;
4126 objc_sync_enter(synch_value);
4127 @try { stmt; } @finally { objc_sync_exit(synch_value); }
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004128*/
4129
Fariborz Jahanianc2ad6dc2008-11-21 00:49:24 +00004130void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
4131 const Stmt &S) {
4132 bool isTry = isa<ObjCAtTryStmt>(S);
John McCallbd309292010-07-06 01:34:17 +00004133
4134 // A destination for the fall-through edges of the catch handlers to
4135 // jump to.
4136 CodeGenFunction::JumpDest FinallyEnd =
4137 CGF.getJumpDestInCurrentScope("finally.end");
4138
4139 // A destination for the rethrow edge of the catch handlers to jump
4140 // to.
4141 CodeGenFunction::JumpDest FinallyRethrow =
4142 CGF.getJumpDestInCurrentScope("finally.rethrow");
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004143
Daniel Dunbar94ceb612009-02-24 01:43:46 +00004144 // For @synchronized, call objc_sync_enter(sync.expr). The
4145 // evaluation of the expression must occur before we enter the
John McCall2dd7d442010-08-04 05:59:32 +00004146 // @synchronized. We can't avoid a temp here because we need the
4147 // value to be preserved. If the backend ever does liveness
4148 // correctly after setjmp, this will be unnecessary.
John McCall7f416cc2015-09-08 08:05:57 +00004149 Address SyncArgSlot = Address::invalid();
Daniel Dunbar94ceb612009-02-24 01:43:46 +00004150 if (!isTry) {
John McCall2dd7d442010-08-04 05:59:32 +00004151 llvm::Value *SyncArg =
Daniel Dunbar94ceb612009-02-24 01:43:46 +00004152 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
4153 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
John McCall882987f2013-02-28 19:01:20 +00004154 CGF.EmitNounwindRuntimeCall(ObjCTypes.getSyncEnterFn(), SyncArg);
John McCall2dd7d442010-08-04 05:59:32 +00004155
John McCall7f416cc2015-09-08 08:05:57 +00004156 SyncArgSlot = CGF.CreateTempAlloca(SyncArg->getType(),
4157 CGF.getPointerAlign(), "sync.arg");
John McCall2dd7d442010-08-04 05:59:32 +00004158 CGF.Builder.CreateStore(SyncArg, SyncArgSlot);
Daniel Dunbar94ceb612009-02-24 01:43:46 +00004159 }
Daniel Dunbar2efd5382008-09-30 01:06:03 +00004160
John McCall2dd7d442010-08-04 05:59:32 +00004161 // Allocate memory for the setjmp buffer. This needs to be kept
4162 // live throughout the try and catch blocks.
John McCall7f416cc2015-09-08 08:05:57 +00004163 Address ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
4164 CGF.getPointerAlign(),
4165 "exceptiondata.ptr");
John McCall2dd7d442010-08-04 05:59:32 +00004166
John McCall42227ed2010-07-31 23:20:56 +00004167 // Create the fragile hazards. Note that this will not capture any
4168 // of the allocas required for exception processing, but will
4169 // capture the current basic block (which extends all the way to the
4170 // setjmp call) as "before the @try".
4171 FragileHazards Hazards(CGF);
4172
John McCallbd309292010-07-06 01:34:17 +00004173 // Create a flag indicating whether the cleanup needs to call
4174 // objc_exception_try_exit. This is true except when
4175 // - no catches match and we're branching through the cleanup
4176 // just to rethrow the exception, or
4177 // - a catch matched and we're falling out of the catch handler.
John McCall2dd7d442010-08-04 05:59:32 +00004178 // The setjmp-safety rule here is that we should always store to this
4179 // variable in a place that dominates the branch through the cleanup
4180 // without passing through any setjmps.
John McCall7f416cc2015-09-08 08:05:57 +00004181 Address CallTryExitVar = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(),
4182 CharUnits::One(),
4183 "_call_try_exit");
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004184
John McCall9916e3f2010-10-04 23:42:51 +00004185 // A slot containing the exception to rethrow. Only needed when we
4186 // have both a @catch and a @finally.
John McCall7f416cc2015-09-08 08:05:57 +00004187 Address PropagatingExnVar = Address::invalid();
John McCall9916e3f2010-10-04 23:42:51 +00004188
John McCallbd309292010-07-06 01:34:17 +00004189 // Push a normal cleanup to leave the try scope.
John McCall638d4f52013-04-03 00:56:07 +00004190 CGF.EHStack.pushCleanup<PerformFragileFinally>(NormalAndEHCleanup, &S,
John McCall2dd7d442010-08-04 05:59:32 +00004191 SyncArgSlot,
John McCallcda666c2010-07-21 07:22:38 +00004192 CallTryExitVar,
4193 ExceptionData,
4194 &ObjCTypes);
John McCallbd309292010-07-06 01:34:17 +00004195
4196 // Enter a try block:
4197 // - Call objc_exception_try_enter to push ExceptionData on top of
4198 // the EH stack.
Nico Weber6307cf02015-02-26 20:43:00 +00004199 CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionTryEnterFn(),
John McCall7f416cc2015-09-08 08:05:57 +00004200 ExceptionData.getPointer());
John McCallbd309292010-07-06 01:34:17 +00004201
4202 // - Call setjmp on the exception data buffer.
4203 llvm::Constant *Zero = llvm::ConstantInt::get(CGF.Builder.getInt32Ty(), 0);
4204 llvm::Value *GEPIndexes[] = { Zero, Zero, Zero };
David Blaikie6b2a8302015-04-03 17:47:16 +00004205 llvm::Value *SetJmpBuffer = CGF.Builder.CreateGEP(
John McCall7f416cc2015-09-08 08:05:57 +00004206 ObjCTypes.ExceptionDataTy, ExceptionData.getPointer(), GEPIndexes,
4207 "setjmp_buffer");
Nico Weber6307cf02015-02-26 20:43:00 +00004208 llvm::CallInst *SetJmpResult = CGF.EmitNounwindRuntimeCall(
4209 ObjCTypes.getSetJmpFn(), SetJmpBuffer, "setjmp_result");
Bill Wendlingbd26cf92011-12-19 23:53:28 +00004210 SetJmpResult->setCanReturnTwice();
John McCallbd309292010-07-06 01:34:17 +00004211
4212 // If setjmp returned 0, enter the protected block; otherwise,
4213 // branch to the handler.
Daniel Dunbar75283ff2008-11-11 02:29:29 +00004214 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
4215 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
John McCallbd309292010-07-06 01:34:17 +00004216 llvm::Value *DidCatch =
John McCallcebe0ca2010-08-11 00:16:14 +00004217 CGF.Builder.CreateIsNotNull(SetJmpResult, "did_catch_exception");
4218 CGF.Builder.CreateCondBr(DidCatch, TryHandler, TryBlock);
Anders Carlsson4f1c7c32008-09-09 17:59:25 +00004219
John McCallbd309292010-07-06 01:34:17 +00004220 // Emit the protected block.
Anders Carlsson4f1c7c32008-09-09 17:59:25 +00004221 CGF.EmitBlock(TryBlock);
John McCall2dd7d442010-08-04 05:59:32 +00004222 CGF.Builder.CreateStore(CGF.Builder.getTrue(), CallTryExitVar);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004223 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
John McCallbd309292010-07-06 01:34:17 +00004224 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
John McCall2dd7d442010-08-04 05:59:32 +00004225
4226 CGBuilderTy::InsertPoint TryFallthroughIP = CGF.Builder.saveAndClearIP();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004227
John McCallbd309292010-07-06 01:34:17 +00004228 // Emit the exception handler block.
Daniel Dunbar7f086782008-09-27 23:30:04 +00004229 CGF.EmitBlock(TryHandler);
Daniel Dunbarb22ff592008-09-27 07:03:52 +00004230
John McCall42227ed2010-07-31 23:20:56 +00004231 // Don't optimize loads of the in-scope locals across this point.
4232 Hazards.emitWriteHazard();
4233
John McCallbd309292010-07-06 01:34:17 +00004234 // For a @synchronized (or a @try with no catches), just branch
4235 // through the cleanup to the rethrow block.
4236 if (!isTry || !cast<ObjCAtTryStmt>(S).getNumCatchStmts()) {
4237 // Tell the cleanup not to re-pop the exit.
John McCall2dd7d442010-08-04 05:59:32 +00004238 CGF.Builder.CreateStore(CGF.Builder.getFalse(), CallTryExitVar);
Anders Carlssonbfee7e92009-02-09 20:38:58 +00004239 CGF.EmitBranchThroughCleanup(FinallyRethrow);
John McCallbd309292010-07-06 01:34:17 +00004240
4241 // Otherwise, we have to match against the caught exceptions.
4242 } else {
John McCall2dd7d442010-08-04 05:59:32 +00004243 // Retrieve the exception object. We may emit multiple blocks but
4244 // nothing can cross this so the value is already in SSA form.
4245 llvm::CallInst *Caught =
John McCall882987f2013-02-28 19:01:20 +00004246 CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionExtractFn(),
John McCall7f416cc2015-09-08 08:05:57 +00004247 ExceptionData.getPointer(), "caught");
John McCall2dd7d442010-08-04 05:59:32 +00004248
John McCallbd309292010-07-06 01:34:17 +00004249 // Push the exception to rethrow onto the EH value stack for the
4250 // benefit of any @throws in the handlers.
4251 CGF.ObjCEHValueStack.push_back(Caught);
4252
Douglas Gregor96c79492010-04-23 22:50:49 +00004253 const ObjCAtTryStmt* AtTryStmt = cast<ObjCAtTryStmt>(&S);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004254
Craig Topper8a13c412014-05-21 05:09:00 +00004255 bool HasFinally = (AtTryStmt->getFinallyStmt() != nullptr);
John McCallbd309292010-07-06 01:34:17 +00004256
Craig Topper8a13c412014-05-21 05:09:00 +00004257 llvm::BasicBlock *CatchBlock = nullptr;
4258 llvm::BasicBlock *CatchHandler = nullptr;
John McCall2dd7d442010-08-04 05:59:32 +00004259 if (HasFinally) {
John McCall9916e3f2010-10-04 23:42:51 +00004260 // Save the currently-propagating exception before
4261 // objc_exception_try_enter clears the exception slot.
4262 PropagatingExnVar = CGF.CreateTempAlloca(Caught->getType(),
John McCall7f416cc2015-09-08 08:05:57 +00004263 CGF.getPointerAlign(),
John McCall9916e3f2010-10-04 23:42:51 +00004264 "propagating_exception");
4265 CGF.Builder.CreateStore(Caught, PropagatingExnVar);
4266
John McCall2dd7d442010-08-04 05:59:32 +00004267 // Enter a new exception try block (in case a @catch block
4268 // throws an exception).
John McCall882987f2013-02-28 19:01:20 +00004269 CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionTryEnterFn(),
John McCall7f416cc2015-09-08 08:05:57 +00004270 ExceptionData.getPointer());
Anders Carlsson4f1c7c32008-09-09 17:59:25 +00004271
John McCall2dd7d442010-08-04 05:59:32 +00004272 llvm::CallInst *SetJmpResult =
John McCall882987f2013-02-28 19:01:20 +00004273 CGF.EmitNounwindRuntimeCall(ObjCTypes.getSetJmpFn(),
4274 SetJmpBuffer, "setjmp.result");
Bill Wendlingbd26cf92011-12-19 23:53:28 +00004275 SetJmpResult->setCanReturnTwice();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004276
John McCall2dd7d442010-08-04 05:59:32 +00004277 llvm::Value *Threw =
4278 CGF.Builder.CreateIsNotNull(SetJmpResult, "did_catch_exception");
4279
4280 CatchBlock = CGF.createBasicBlock("catch");
4281 CatchHandler = CGF.createBasicBlock("catch_for_catch");
4282 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
4283
4284 CGF.EmitBlock(CatchBlock);
4285 }
4286
4287 CGF.Builder.CreateStore(CGF.Builder.getInt1(HasFinally), CallTryExitVar);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004288
Daniel Dunbarb22ff592008-09-27 07:03:52 +00004289 // Handle catch list. As a special case we check if everything is
4290 // matched and avoid generating code for falling off the end if
4291 // so.
4292 bool AllMatched = false;
Douglas Gregor96c79492010-04-23 22:50:49 +00004293 for (unsigned I = 0, N = AtTryStmt->getNumCatchStmts(); I != N; ++I) {
4294 const ObjCAtCatchStmt *CatchStmt = AtTryStmt->getCatchStmt(I);
Anders Carlsson4f1c7c32008-09-09 17:59:25 +00004295
Douglas Gregor46a572b2010-04-26 16:46:50 +00004296 const VarDecl *CatchParam = CatchStmt->getCatchParamDecl();
Craig Topper8a13c412014-05-21 05:09:00 +00004297 const ObjCObjectPointerType *OPT = nullptr;
Daniel Dunbar523208f2008-09-27 07:36:24 +00004298
Anders Carlsson4f1c7c32008-09-09 17:59:25 +00004299 // catch(...) always matches.
Daniel Dunbarb22ff592008-09-27 07:03:52 +00004300 if (!CatchParam) {
4301 AllMatched = true;
4302 } else {
John McCall9dd450b2009-09-21 23:43:11 +00004303 OPT = CatchParam->getType()->getAs<ObjCObjectPointerType>();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004304
John McCallbd309292010-07-06 01:34:17 +00004305 // catch(id e) always matches under this ABI, since only
4306 // ObjC exceptions end up here in the first place.
Daniel Dunbar86919f42008-09-27 22:21:14 +00004307 // FIXME: For the time being we also match id<X>; this should
4308 // be rejected by Sema instead.
Eli Friedman55179ca2009-07-11 00:57:02 +00004309 if (OPT && (OPT->isObjCIdType() || OPT->isObjCQualifiedIdType()))
Daniel Dunbarb22ff592008-09-27 07:03:52 +00004310 AllMatched = true;
Anders Carlsson4f1c7c32008-09-09 17:59:25 +00004311 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004312
John McCallbd309292010-07-06 01:34:17 +00004313 // If this is a catch-all, we don't need to test anything.
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004314 if (AllMatched) {
John McCallbd309292010-07-06 01:34:17 +00004315 CodeGenFunction::RunCleanupsScope CatchVarCleanups(CGF);
4316
Anders Carlsson9396a892008-09-11 09:15:33 +00004317 if (CatchParam) {
John McCall1c9c3fd2010-10-15 04:57:14 +00004318 CGF.EmitAutoVarDecl(*CatchParam);
Daniel Dunbar5c7e3932008-11-11 23:11:34 +00004319 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
John McCallbd309292010-07-06 01:34:17 +00004320
4321 // These types work out because ConvertType(id) == i8*.
John McCall17f02752015-10-30 00:56:02 +00004322 EmitInitOfCatchParam(CGF, Caught, CatchParam);
Anders Carlsson9396a892008-09-11 09:15:33 +00004323 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004324
Anders Carlsson9396a892008-09-11 09:15:33 +00004325 CGF.EmitStmt(CatchStmt->getCatchBody());
John McCallbd309292010-07-06 01:34:17 +00004326
4327 // The scope of the catch variable ends right here.
4328 CatchVarCleanups.ForceCleanup();
4329
Anders Carlssonbfee7e92009-02-09 20:38:58 +00004330 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson4f1c7c32008-09-09 17:59:25 +00004331 break;
4332 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004333
Steve Naroff7cae42b2009-07-10 23:34:53 +00004334 assert(OPT && "Unexpected non-object pointer type in @catch");
John McCall96fa4842010-05-17 21:00:27 +00004335 const ObjCObjectType *ObjTy = OPT->getObjectType();
John McCallbd309292010-07-06 01:34:17 +00004336
4337 // FIXME: @catch (Class c) ?
John McCall96fa4842010-05-17 21:00:27 +00004338 ObjCInterfaceDecl *IDecl = ObjTy->getInterface();
4339 assert(IDecl && "Catch parameter must have Objective-C type!");
Anders Carlsson4f1c7c32008-09-09 17:59:25 +00004340
4341 // Check if the @catch block matches the exception object.
John McCall882987f2013-02-28 19:01:20 +00004342 llvm::Value *Class = EmitClassRef(CGF, IDecl);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004343
John McCall882987f2013-02-28 19:01:20 +00004344 llvm::Value *matchArgs[] = { Class, Caught };
John McCallbd309292010-07-06 01:34:17 +00004345 llvm::CallInst *Match =
John McCall882987f2013-02-28 19:01:20 +00004346 CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionMatchFn(),
4347 matchArgs, "match");
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004348
John McCallbd309292010-07-06 01:34:17 +00004349 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("match");
4350 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch.next");
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004351
4352 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
Daniel Dunbar7f086782008-09-27 23:30:04 +00004353 MatchedBlock, NextCatchBlock);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004354
Anders Carlsson4f1c7c32008-09-09 17:59:25 +00004355 // Emit the @catch block.
4356 CGF.EmitBlock(MatchedBlock);
John McCallbd309292010-07-06 01:34:17 +00004357
4358 // Collect any cleanups for the catch variable. The scope lasts until
4359 // the end of the catch body.
John McCall2dd7d442010-08-04 05:59:32 +00004360 CodeGenFunction::RunCleanupsScope CatchVarCleanups(CGF);
John McCallbd309292010-07-06 01:34:17 +00004361
John McCall1c9c3fd2010-10-15 04:57:14 +00004362 CGF.EmitAutoVarDecl(*CatchParam);
Daniel Dunbar5c7e3932008-11-11 23:11:34 +00004363 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004364
John McCallbd309292010-07-06 01:34:17 +00004365 // Initialize the catch variable.
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004366 llvm::Value *Tmp =
4367 CGF.Builder.CreateBitCast(Caught,
Benjamin Kramer76399eb2011-09-27 21:06:10 +00004368 CGF.ConvertType(CatchParam->getType()));
John McCall17f02752015-10-30 00:56:02 +00004369 EmitInitOfCatchParam(CGF, Tmp, CatchParam);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004370
Anders Carlsson9396a892008-09-11 09:15:33 +00004371 CGF.EmitStmt(CatchStmt->getCatchBody());
John McCallbd309292010-07-06 01:34:17 +00004372
4373 // We're done with the catch variable.
4374 CatchVarCleanups.ForceCleanup();
4375
Anders Carlssonbfee7e92009-02-09 20:38:58 +00004376 CGF.EmitBranchThroughCleanup(FinallyEnd);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004377
Anders Carlsson4f1c7c32008-09-09 17:59:25 +00004378 CGF.EmitBlock(NextCatchBlock);
4379 }
4380
John McCallbd309292010-07-06 01:34:17 +00004381 CGF.ObjCEHValueStack.pop_back();
4382
John McCall2dd7d442010-08-04 05:59:32 +00004383 // If nothing wanted anything to do with the caught exception,
4384 // kill the extract call.
4385 if (Caught->use_empty())
4386 Caught->eraseFromParent();
4387
4388 if (!AllMatched)
4389 CGF.EmitBranchThroughCleanup(FinallyRethrow);
4390
4391 if (HasFinally) {
4392 // Emit the exception handler for the @catch blocks.
4393 CGF.EmitBlock(CatchHandler);
4394
4395 // In theory we might now need a write hazard, but actually it's
4396 // unnecessary because there's no local-accessing code between
4397 // the try's write hazard and here.
4398 //Hazards.emitWriteHazard();
4399
John McCall9916e3f2010-10-04 23:42:51 +00004400 // Extract the new exception and save it to the
4401 // propagating-exception slot.
John McCall7f416cc2015-09-08 08:05:57 +00004402 assert(PropagatingExnVar.isValid());
John McCall9916e3f2010-10-04 23:42:51 +00004403 llvm::CallInst *NewCaught =
John McCall882987f2013-02-28 19:01:20 +00004404 CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionExtractFn(),
John McCall7f416cc2015-09-08 08:05:57 +00004405 ExceptionData.getPointer(), "caught");
John McCall9916e3f2010-10-04 23:42:51 +00004406 CGF.Builder.CreateStore(NewCaught, PropagatingExnVar);
4407
John McCall2dd7d442010-08-04 05:59:32 +00004408 // Don't pop the catch handler; the throw already did.
4409 CGF.Builder.CreateStore(CGF.Builder.getFalse(), CallTryExitVar);
Anders Carlssonbfee7e92009-02-09 20:38:58 +00004410 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbarb22ff592008-09-27 07:03:52 +00004411 }
Anders Carlsson4f1c7c32008-09-09 17:59:25 +00004412 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004413
John McCall42227ed2010-07-31 23:20:56 +00004414 // Insert read hazards as required in the new blocks.
John McCall2dd7d442010-08-04 05:59:32 +00004415 Hazards.emitHazardsInNewBlocks();
John McCall42227ed2010-07-31 23:20:56 +00004416
John McCallbd309292010-07-06 01:34:17 +00004417 // Pop the cleanup.
John McCall2dd7d442010-08-04 05:59:32 +00004418 CGF.Builder.restoreIP(TryFallthroughIP);
4419 if (CGF.HaveInsertPoint())
4420 CGF.Builder.CreateStore(CGF.Builder.getTrue(), CallTryExitVar);
John McCallbd309292010-07-06 01:34:17 +00004421 CGF.PopCleanupBlock();
John McCall2dd7d442010-08-04 05:59:32 +00004422 CGF.EmitBlock(FinallyEnd.getBlock(), true);
Anders Carlssonbfee7e92009-02-09 20:38:58 +00004423
John McCallbd309292010-07-06 01:34:17 +00004424 // Emit the rethrow block.
John McCall42227ed2010-07-31 23:20:56 +00004425 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
John McCallad5d61e2010-07-23 21:56:41 +00004426 CGF.EmitBlock(FinallyRethrow.getBlock(), true);
John McCallbd309292010-07-06 01:34:17 +00004427 if (CGF.HaveInsertPoint()) {
John McCall9916e3f2010-10-04 23:42:51 +00004428 // If we have a propagating-exception variable, check it.
4429 llvm::Value *PropagatingExn;
John McCall7f416cc2015-09-08 08:05:57 +00004430 if (PropagatingExnVar.isValid()) {
John McCall9916e3f2010-10-04 23:42:51 +00004431 PropagatingExn = CGF.Builder.CreateLoad(PropagatingExnVar);
John McCall2dd7d442010-08-04 05:59:32 +00004432
John McCall9916e3f2010-10-04 23:42:51 +00004433 // Otherwise, just look in the buffer for the exception to throw.
4434 } else {
4435 llvm::CallInst *Caught =
John McCall882987f2013-02-28 19:01:20 +00004436 CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionExtractFn(),
John McCall7f416cc2015-09-08 08:05:57 +00004437 ExceptionData.getPointer());
John McCall9916e3f2010-10-04 23:42:51 +00004438 PropagatingExn = Caught;
4439 }
4440
John McCall882987f2013-02-28 19:01:20 +00004441 CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionThrowFn(),
4442 PropagatingExn);
John McCallbd309292010-07-06 01:34:17 +00004443 CGF.Builder.CreateUnreachable();
Fariborz Jahaniane2caaaa2008-11-21 19:21:53 +00004444 }
Anders Carlsson4f1c7c32008-09-09 17:59:25 +00004445
John McCall42227ed2010-07-31 23:20:56 +00004446 CGF.Builder.restoreIP(SavedIP);
Anders Carlsson1963b0c2008-09-09 10:04:29 +00004447}
4448
4449void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian1eab0522013-01-10 19:02:56 +00004450 const ObjCAtThrowStmt &S,
4451 bool ClearInsertionPoint) {
Anders Carlssone005aa12008-09-09 16:16:55 +00004452 llvm::Value *ExceptionAsObject;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004453
Anders Carlssone005aa12008-09-09 16:16:55 +00004454 if (const Expr *ThrowExpr = S.getThrowExpr()) {
John McCall248512a2011-10-01 10:32:24 +00004455 llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004456 ExceptionAsObject =
Benjamin Kramer76399eb2011-09-27 21:06:10 +00004457 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy);
Anders Carlssone005aa12008-09-09 16:16:55 +00004458 } else {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004459 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004460 "Unexpected rethrow outside @catch block.");
Anders Carlssonbf8a1be2009-02-07 21:37:21 +00004461 ExceptionAsObject = CGF.ObjCEHValueStack.back();
Anders Carlssone005aa12008-09-09 16:16:55 +00004462 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004463
John McCall882987f2013-02-28 19:01:20 +00004464 CGF.EmitRuntimeCall(ObjCTypes.getExceptionThrowFn(), ExceptionAsObject)
John McCallbd309292010-07-06 01:34:17 +00004465 ->setDoesNotReturn();
Anders Carlsson4f1c7c32008-09-09 17:59:25 +00004466 CGF.Builder.CreateUnreachable();
Daniel Dunbar5c7e3932008-11-11 23:11:34 +00004467
4468 // Clear the insertion point to indicate we are in unreachable code.
Fariborz Jahanian1eab0522013-01-10 19:02:56 +00004469 if (ClearInsertionPoint)
4470 CGF.Builder.ClearInsertionPoint();
Anders Carlsson1963b0c2008-09-09 10:04:29 +00004471}
4472
Fariborz Jahanian83f45b552008-11-18 22:37:34 +00004473/// EmitObjCWeakRead - Code gen for loading value of a __weak
Fariborz Jahanianf5125d12008-11-18 21:45:40 +00004474/// object: objc_read_weak (id *src)
4475///
Fariborz Jahanian83f45b552008-11-18 22:37:34 +00004476llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00004477 Address AddrWeakObj) {
4478 llvm::Type* DestTy = AddrWeakObj.getElementType();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004479 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj,
4480 ObjCTypes.PtrObjectPtrTy);
John McCall882987f2013-02-28 19:01:20 +00004481 llvm::Value *read_weak =
4482 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcReadWeakFn(),
John McCall7f416cc2015-09-08 08:05:57 +00004483 AddrWeakObj.getPointer(), "weakread");
Eli Friedmana374b682009-03-07 03:57:15 +00004484 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanianf5125d12008-11-18 21:45:40 +00004485 return read_weak;
4486}
4487
Fariborz Jahanian83f45b552008-11-18 22:37:34 +00004488/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
4489/// objc_assign_weak (id src, id *dst)
4490///
4491void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00004492 llvm::Value *src, Address dst) {
Chris Lattner2192fe52011-07-18 04:24:23 +00004493 llvm::Type * SrcTy = src->getType();
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00004494 if (!isa<llvm::PointerType>(SrcTy)) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00004495 unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00004496 assert(Size <= 8 && "does not support size > 8");
4497 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004498 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian1b074a32009-03-13 00:42:52 +00004499 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
4500 }
Fariborz Jahanian50a12702008-11-19 17:34:06 +00004501 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
4502 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00004503 llvm::Value *args[] = { src, dst.getPointer() };
John McCall882987f2013-02-28 19:01:20 +00004504 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignWeakFn(),
4505 args, "weakassign");
Fariborz Jahanian83f45b552008-11-18 22:37:34 +00004506}
4507
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00004508/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
4509/// objc_assign_global (id src, id *dst)
4510///
4511void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00004512 llvm::Value *src, Address dst,
Fariborz Jahanian217af242010-07-20 20:30:03 +00004513 bool threadlocal) {
Chris Lattner2192fe52011-07-18 04:24:23 +00004514 llvm::Type * SrcTy = src->getType();
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00004515 if (!isa<llvm::PointerType>(SrcTy)) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00004516 unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00004517 assert(Size <= 8 && "does not support size > 8");
4518 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004519 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian1b074a32009-03-13 00:42:52 +00004520 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
4521 }
Fariborz Jahanian50a12702008-11-19 17:34:06 +00004522 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
4523 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00004524 llvm::Value *args[] = { src, dst.getPointer() };
Fariborz Jahanian217af242010-07-20 20:30:03 +00004525 if (!threadlocal)
John McCall882987f2013-02-28 19:01:20 +00004526 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignGlobalFn(),
4527 args, "globalassign");
Fariborz Jahanian217af242010-07-20 20:30:03 +00004528 else
John McCall882987f2013-02-28 19:01:20 +00004529 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignThreadLocalFn(),
4530 args, "threadlocalassign");
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00004531}
4532
Fariborz Jahaniane881b532008-11-20 19:23:36 +00004533/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00004534/// objc_assign_ivar (id src, id *dst, ptrdiff_t ivaroffset)
Fariborz Jahaniane881b532008-11-20 19:23:36 +00004535///
4536void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00004537 llvm::Value *src, Address dst,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00004538 llvm::Value *ivarOffset) {
4539 assert(ivarOffset && "EmitObjCIvarAssign - ivarOffset is NULL");
Chris Lattner2192fe52011-07-18 04:24:23 +00004540 llvm::Type * SrcTy = src->getType();
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00004541 if (!isa<llvm::PointerType>(SrcTy)) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00004542 unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00004543 assert(Size <= 8 && "does not support size > 8");
4544 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004545 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian1b074a32009-03-13 00:42:52 +00004546 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
4547 }
Fariborz Jahaniane881b532008-11-20 19:23:36 +00004548 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
4549 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00004550 llvm::Value *args[] = { src, dst.getPointer(), ivarOffset };
John McCall882987f2013-02-28 19:01:20 +00004551 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignIvarFn(), args);
Fariborz Jahaniane881b532008-11-20 19:23:36 +00004552}
4553
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00004554/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
4555/// objc_assign_strongCast (id src, id *dst)
4556///
4557void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00004558 llvm::Value *src, Address dst) {
Chris Lattner2192fe52011-07-18 04:24:23 +00004559 llvm::Type * SrcTy = src->getType();
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00004560 if (!isa<llvm::PointerType>(SrcTy)) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00004561 unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00004562 assert(Size <= 8 && "does not support size > 8");
4563 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004564 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian1b074a32009-03-13 00:42:52 +00004565 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
4566 }
Fariborz Jahanian50a12702008-11-19 17:34:06 +00004567 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
4568 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00004569 llvm::Value *args[] = { src, dst.getPointer() };
John McCall882987f2013-02-28 19:01:20 +00004570 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignStrongCastFn(),
John McCall7f416cc2015-09-08 08:05:57 +00004571 args, "strongassign");
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00004572}
4573
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00004574void CGObjCMac::EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00004575 Address DestPtr,
4576 Address SrcPtr,
Fariborz Jahanian021510e2010-06-15 22:44:06 +00004577 llvm::Value *size) {
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00004578 SrcPtr = CGF.Builder.CreateBitCast(SrcPtr, ObjCTypes.Int8PtrTy);
4579 DestPtr = CGF.Builder.CreateBitCast(DestPtr, ObjCTypes.Int8PtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00004580 llvm::Value *args[] = { DestPtr.getPointer(), SrcPtr.getPointer(), size };
John McCall882987f2013-02-28 19:01:20 +00004581 CGF.EmitNounwindRuntimeCall(ObjCTypes.GcMemmoveCollectableFn(), args);
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00004582}
4583
Fariborz Jahanian9f84b782009-02-02 20:02:29 +00004584/// EmitObjCValueForIvar - Code Gen for ivar reference.
4585///
Fariborz Jahanian712bfa62009-02-03 19:03:09 +00004586LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
4587 QualType ObjectTy,
4588 llvm::Value *BaseValue,
4589 const ObjCIvarDecl *Ivar,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +00004590 unsigned CVRQualifiers) {
John McCall8b07ec22010-05-15 11:32:37 +00004591 const ObjCInterfaceDecl *ID =
4592 ObjectTy->getAs<ObjCObjectType>()->getInterface();
Daniel Dunbar9fd114d2009-04-22 07:32:20 +00004593 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
4594 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian9f84b782009-02-02 20:02:29 +00004595}
4596
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00004597llvm::Value *CGObjCMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar722f4242009-04-22 05:08:15 +00004598 const ObjCInterfaceDecl *Interface,
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00004599 const ObjCIvarDecl *Ivar) {
Eli Friedman8cbca202012-11-06 22:15:52 +00004600 uint64_t Offset = ComputeIvarBaseOffset(CGM, Interface, Ivar);
4601 return llvm::ConstantInt::get(
4602 CGM.getTypes().ConvertType(CGM.getContext().LongTy),
4603 Offset);
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00004604}
4605
Daniel Dunbar3ad53482008-08-11 21:35:06 +00004606/* *** Private Interface *** */
4607
4608/// EmitImageInfo - Emit the image info marker used to encode some module
4609/// level information.
4610///
4611/// See: <rdr://4810609&4810587&4810587>
4612/// struct IMAGE_INFO {
4613/// unsigned version;
4614/// unsigned flags;
4615/// };
4616enum ImageInfoFlags {
Fariborz Jahanian39c17a82014-01-14 22:01:08 +00004617 eImageInfo_FixAndContinue = (1 << 0), // This flag is no longer set by clang.
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004618 eImageInfo_GarbageCollected = (1 << 1),
4619 eImageInfo_GCOnly = (1 << 2),
Fariborz Jahanian39c17a82014-01-14 22:01:08 +00004620 eImageInfo_OptimizedByDyld = (1 << 3), // This flag is set by the dyld shared cache.
Daniel Dunbar75e909f2009-04-20 07:11:47 +00004621
Daniel Dunbar5e639272010-04-25 20:39:01 +00004622 // A flag indicating that the module has no instances of a @synthesize of a
4623 // superclass variable. <rdar://problem/6803242>
Fariborz Jahanian39c17a82014-01-14 22:01:08 +00004624 eImageInfo_CorrectedSynthesize = (1 << 4), // This flag is no longer set by clang.
Manman Ren96df0b32016-01-29 23:45:01 +00004625 eImageInfo_ImageIsSimulated = (1 << 5),
4626 eImageInfo_ClassProperties = (1 << 6)
Daniel Dunbar3ad53482008-08-11 21:35:06 +00004627};
4628
Daniel Dunbar5e639272010-04-25 20:39:01 +00004629void CGObjCCommonMac::EmitImageInfo() {
Daniel Dunbar3ad53482008-08-11 21:35:06 +00004630 unsigned version = 0; // Version is unused?
Bill Wendlingb6f795e2012-02-16 01:13:30 +00004631 const char *Section = (ObjCABI == 1) ?
4632 "__OBJC, __image_info,regular" :
4633 "__DATA, __objc_imageinfo, regular, no_dead_strip";
Daniel Dunbar3ad53482008-08-11 21:35:06 +00004634
Bill Wendlingb6f795e2012-02-16 01:13:30 +00004635 // Generate module-level named metadata to convey this information to the
4636 // linker and code-gen.
4637 llvm::Module &Mod = CGM.getModule();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004638
Bill Wendlingb6f795e2012-02-16 01:13:30 +00004639 // Add the ObjC ABI version to the module flags.
4640 Mod.addModuleFlag(llvm::Module::Error, "Objective-C Version", ObjCABI);
4641 Mod.addModuleFlag(llvm::Module::Error, "Objective-C Image Info Version",
4642 version);
4643 Mod.addModuleFlag(llvm::Module::Error, "Objective-C Image Info Section",
4644 llvm::MDString::get(VMContext,Section));
Daniel Dunbar3ad53482008-08-11 21:35:06 +00004645
David Blaikiebbafb8a2012-03-11 07:00:24 +00004646 if (CGM.getLangOpts().getGC() == LangOptions::NonGC) {
Bill Wendlingb6f795e2012-02-16 01:13:30 +00004647 // Non-GC overrides those files which specify GC.
4648 Mod.addModuleFlag(llvm::Module::Override,
4649 "Objective-C Garbage Collection", (uint32_t)0);
4650 } else {
4651 // Add the ObjC garbage collection value.
4652 Mod.addModuleFlag(llvm::Module::Error,
4653 "Objective-C Garbage Collection",
4654 eImageInfo_GarbageCollected);
Daniel Dunbarc2d4b622009-03-09 21:49:58 +00004655
David Blaikiebbafb8a2012-03-11 07:00:24 +00004656 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
Bill Wendlingb6f795e2012-02-16 01:13:30 +00004657 // Add the ObjC GC Only value.
4658 Mod.addModuleFlag(llvm::Module::Error, "Objective-C GC Only",
4659 eImageInfo_GCOnly);
4660
4661 // Require that GC be specified and set to eImageInfo_GarbageCollected.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00004662 llvm::Metadata *Ops[2] = {
4663 llvm::MDString::get(VMContext, "Objective-C Garbage Collection"),
4664 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
4665 llvm::Type::getInt32Ty(VMContext), eImageInfo_GarbageCollected))};
Bill Wendlingb6f795e2012-02-16 01:13:30 +00004666 Mod.addModuleFlag(llvm::Module::Require, "Objective-C GC Only",
4667 llvm::MDNode::get(VMContext, Ops));
4668 }
4669 }
Bill Wendling1e60a2c2012-04-24 11:04:57 +00004670
4671 // Indicate whether we're compiling this to run on a simulator.
4672 const llvm::Triple &Triple = CGM.getTarget().getTriple();
Tim Northover756447a2015-10-30 16:30:36 +00004673 if ((Triple.isiOS() || Triple.isWatchOS()) &&
Bill Wendling1e60a2c2012-04-24 11:04:57 +00004674 (Triple.getArch() == llvm::Triple::x86 ||
4675 Triple.getArch() == llvm::Triple::x86_64))
4676 Mod.addModuleFlag(llvm::Module::Error, "Objective-C Is Simulated",
4677 eImageInfo_ImageIsSimulated);
Manman Ren96df0b32016-01-29 23:45:01 +00004678
4679 // Indicate whether we are generating class properties.
4680 Mod.addModuleFlag(llvm::Module::Error, "Objective-C Class Properties",
4681 eImageInfo_ClassProperties);
Daniel Dunbar3ad53482008-08-11 21:35:06 +00004682}
4683
Daniel Dunbar7bd00bd2008-08-12 06:48:42 +00004684// struct objc_module {
4685// unsigned long version;
4686// unsigned long size;
4687// const char *name;
4688// Symtab symtab;
4689// };
4690
4691// FIXME: Get from somewhere
4692static const int ModuleVersion = 7;
4693
4694void CGObjCMac::EmitModuleInfo() {
Micah Villmowdd31ca12012-10-08 16:25:52 +00004695 uint64_t Size = CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ModuleTy);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004696
Benjamin Kramer22d24c22011-10-15 12:20:02 +00004697 llvm::Constant *Values[] = {
4698 llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion),
4699 llvm::ConstantInt::get(ObjCTypes.LongTy, Size),
4700 // This used to be the filename, now it is unused. <rdr://4327263>
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00004701 GetClassName(StringRef("")),
Benjamin Kramer22d24c22011-10-15 12:20:02 +00004702 EmitModuleSymbols()
4703 };
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00004704 CreateMetadataVar("OBJC_MODULES",
Owen Anderson0e0189d2009-07-27 22:29:56 +00004705 llvm::ConstantStruct::get(ObjCTypes.ModuleTy, Values),
John McCall7f416cc2015-09-08 08:05:57 +00004706 "__OBJC,__module_info,regular,no_dead_strip",
4707 CGM.getPointerAlign(), true);
Daniel Dunbar7bd00bd2008-08-12 06:48:42 +00004708}
4709
4710llvm::Constant *CGObjCMac::EmitModuleSymbols() {
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00004711 unsigned NumClasses = DefinedClasses.size();
4712 unsigned NumCategories = DefinedCategories.size();
4713
Daniel Dunbarc61d0e92008-08-25 06:02:07 +00004714 // Return null if no symbols were defined.
4715 if (!NumClasses && !NumCategories)
Owen Anderson0b75f232009-07-31 20:28:54 +00004716 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
Daniel Dunbarc61d0e92008-08-25 06:02:07 +00004717
Chris Lattnere64d7ba2011-06-20 04:01:35 +00004718 llvm::Constant *Values[5];
Owen Andersonb7a2fe62009-07-24 23:12:58 +00004719 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
Owen Anderson0b75f232009-07-31 20:28:54 +00004720 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00004721 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
4722 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00004723
Daniel Dunbar938a77f2008-08-22 20:34:54 +00004724 // The runtime expects exactly the list of defined classes followed
4725 // by the list of defined categories, in a single array.
Chris Lattner3def9ae2012-02-06 22:16:34 +00004726 SmallVector<llvm::Constant*, 8> Symbols(NumClasses + NumCategories);
Fariborz Jahanianf322f2f2014-03-11 00:25:05 +00004727 for (unsigned i=0; i<NumClasses; i++) {
4728 const ObjCInterfaceDecl *ID = ImplementedClasses[i];
4729 assert(ID);
4730 if (ObjCImplementationDecl *IMP = ID->getImplementation())
4731 // We are implementing a weak imported interface. Give it external linkage
4732 if (ID->isWeakImported() && !IMP->isWeakImported())
4733 DefinedClasses[i]->setLinkage(llvm::GlobalVariable::ExternalLinkage);
4734
Owen Andersonade90fd2009-07-29 18:54:39 +00004735 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
Daniel Dunbar938a77f2008-08-22 20:34:54 +00004736 ObjCTypes.Int8PtrTy);
Fariborz Jahanianf322f2f2014-03-11 00:25:05 +00004737 }
Daniel Dunbar938a77f2008-08-22 20:34:54 +00004738 for (unsigned i=0; i<NumCategories; i++)
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004739 Symbols[NumClasses + i] =
Owen Andersonade90fd2009-07-29 18:54:39 +00004740 llvm::ConstantExpr::getBitCast(DefinedCategories[i],
Daniel Dunbar938a77f2008-08-22 20:34:54 +00004741 ObjCTypes.Int8PtrTy);
4742
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004743 Values[4] =
Owen Anderson9793f0e2009-07-29 22:16:19 +00004744 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Chris Lattner3def9ae2012-02-06 22:16:34 +00004745 Symbols.size()),
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00004746 Symbols);
4747
Chris Lattnere64d7ba2011-06-20 04:01:35 +00004748 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00004749
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00004750 llvm::GlobalVariable *GV = CreateMetadataVar(
John McCall7f416cc2015-09-08 08:05:57 +00004751 "OBJC_SYMBOLS", Init, "__OBJC,__symbols,regular,no_dead_strip",
4752 CGM.getPointerAlign(), true);
Owen Andersonade90fd2009-07-29 18:54:39 +00004753 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00004754}
4755
John McCall882987f2013-02-28 19:01:20 +00004756llvm::Value *CGObjCMac::EmitClassRefFromId(CodeGenFunction &CGF,
4757 IdentifierInfo *II) {
John McCall31168b02011-06-15 23:02:42 +00004758 LazySymbols.insert(II);
4759
4760 llvm::GlobalVariable *&Entry = ClassReferences[II];
4761
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00004762 if (!Entry) {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004763 llvm::Constant *Casted =
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00004764 llvm::ConstantExpr::getBitCast(GetClassName(II->getName()),
John McCall31168b02011-06-15 23:02:42 +00004765 ObjCTypes.ClassPtrTy);
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00004766 Entry = CreateMetadataVar(
4767 "OBJC_CLASS_REFERENCES_", Casted,
John McCall7f416cc2015-09-08 08:05:57 +00004768 "__OBJC,__cls_refs,literal_pointers,no_dead_strip",
4769 CGM.getPointerAlign(), true);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00004770 }
John McCall31168b02011-06-15 23:02:42 +00004771
John McCall7f416cc2015-09-08 08:05:57 +00004772 return CGF.Builder.CreateAlignedLoad(Entry, CGF.getPointerAlign());
Daniel Dunbar7bd00bd2008-08-12 06:48:42 +00004773}
4774
John McCall882987f2013-02-28 19:01:20 +00004775llvm::Value *CGObjCMac::EmitClassRef(CodeGenFunction &CGF,
John McCall31168b02011-06-15 23:02:42 +00004776 const ObjCInterfaceDecl *ID) {
Douglas Gregor24ae22c2016-04-01 23:23:52 +00004777 // If the class has the objc_runtime_visible attribute, we need to
4778 // use the Objective-C runtime to get the class.
4779 if (ID->hasAttr<ObjCRuntimeVisibleAttr>())
4780 return EmitClassRefViaRuntime(CGF, ID, ObjCTypes);
4781
John McCall882987f2013-02-28 19:01:20 +00004782 return EmitClassRefFromId(CGF, ID->getIdentifier());
John McCall31168b02011-06-15 23:02:42 +00004783}
4784
John McCall882987f2013-02-28 19:01:20 +00004785llvm::Value *CGObjCMac::EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) {
John McCall31168b02011-06-15 23:02:42 +00004786 IdentifierInfo *II = &CGM.getContext().Idents.get("NSAutoreleasePool");
John McCall882987f2013-02-28 19:01:20 +00004787 return EmitClassRefFromId(CGF, II);
John McCall31168b02011-06-15 23:02:42 +00004788}
4789
John McCall7f416cc2015-09-08 08:05:57 +00004790llvm::Value *CGObjCMac::EmitSelector(CodeGenFunction &CGF, Selector Sel) {
4791 return CGF.Builder.CreateLoad(EmitSelectorAddr(CGF, Sel));
4792}
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004793
John McCall7f416cc2015-09-08 08:05:57 +00004794Address CGObjCMac::EmitSelectorAddr(CodeGenFunction &CGF, Selector Sel) {
4795 CharUnits Align = CGF.getPointerAlign();
4796
4797 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
Daniel Dunbarcb515c82008-08-12 03:39:23 +00004798 if (!Entry) {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004799 llvm::Constant *Casted =
Owen Andersonade90fd2009-07-29 18:54:39 +00004800 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
Daniel Dunbarcb515c82008-08-12 03:39:23 +00004801 ObjCTypes.SelectorPtrTy);
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00004802 Entry = CreateMetadataVar(
4803 "OBJC_SELECTOR_REFERENCES_", Casted,
John McCall7f416cc2015-09-08 08:05:57 +00004804 "__OBJC,__message_refs,literal_pointers,no_dead_strip", Align, true);
Michael Gottesman5c205962013-02-05 23:08:45 +00004805 Entry->setExternallyInitialized(true);
Daniel Dunbarcb515c82008-08-12 03:39:23 +00004806 }
4807
John McCall7f416cc2015-09-08 08:05:57 +00004808 return Address(Entry, Align);
Daniel Dunbarcb515c82008-08-12 03:39:23 +00004809}
4810
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00004811llvm::Constant *CGObjCCommonMac::GetClassName(StringRef RuntimeName) {
4812 llvm::GlobalVariable *&Entry = ClassNames[RuntimeName];
4813 if (!Entry)
Saleem Abdulrasool271106c2016-09-16 23:41:13 +00004814 Entry = CreateCStringLiteral(RuntimeName, ObjCLabelType::ClassName);
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00004815 return getConstantGEP(VMContext, Entry, 0, 0);
Daniel Dunbar7bd00bd2008-08-12 06:48:42 +00004816}
4817
Argyrios Kyrtzidis13257c52010-08-09 10:54:20 +00004818llvm::Function *CGObjCCommonMac::GetMethodDefinition(const ObjCMethodDecl *MD) {
4819 llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*>::iterator
4820 I = MethodDefinitions.find(MD);
4821 if (I != MethodDefinitions.end())
4822 return I->second;
4823
Craig Topper8a13c412014-05-21 05:09:00 +00004824 return nullptr;
Argyrios Kyrtzidis13257c52010-08-09 10:54:20 +00004825}
4826
Fariborz Jahanian01dff422009-03-05 19:17:31 +00004827/// GetIvarLayoutName - Returns a unique constant for the given
4828/// ivar layout bitmap.
4829llvm::Constant *CGObjCCommonMac::GetIvarLayoutName(IdentifierInfo *Ident,
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004830 const ObjCCommonTypesHelper &ObjCTypes) {
Owen Anderson0b75f232009-07-31 20:28:54 +00004831 return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Fariborz Jahanian01dff422009-03-05 19:17:31 +00004832}
4833
John McCall3fd13f062015-10-21 18:06:47 +00004834void IvarLayoutBuilder::visitRecord(const RecordType *RT,
4835 CharUnits offset) {
Daniel Dunbar15bd8882009-05-03 14:10:34 +00004836 const RecordDecl *RD = RT->getDecl();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004837
John McCall3fd13f062015-10-21 18:06:47 +00004838 // If this is a union, remember that we had one, because it might mess
4839 // up the ordering of layout entries.
4840 if (RD->isUnion())
4841 IsDisordered = true;
4842
4843 const ASTRecordLayout *recLayout = nullptr;
4844 visitAggregate(RD->field_begin(), RD->field_end(), offset,
4845 [&](const FieldDecl *field) -> CharUnits {
4846 if (!recLayout)
4847 recLayout = &CGM.getContext().getASTRecordLayout(RD);
4848 auto offsetInBits = recLayout->getFieldOffset(field->getFieldIndex());
4849 return CGM.getContext().toCharUnitsFromBits(offsetInBits);
4850 });
Daniel Dunbar15bd8882009-05-03 14:10:34 +00004851}
4852
John McCall3fd13f062015-10-21 18:06:47 +00004853template <class Iterator, class GetOffsetFn>
4854void IvarLayoutBuilder::visitAggregate(Iterator begin, Iterator end,
4855 CharUnits aggregateOffset,
4856 const GetOffsetFn &getOffset) {
4857 for (; begin != end; ++begin) {
4858 auto field = *begin;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004859
John McCall3fd13f062015-10-21 18:06:47 +00004860 // Skip over bitfields.
4861 if (field->isBitField()) {
4862 continue;
4863 }
4864
4865 // Compute the offset of the field within the aggregate.
4866 CharUnits fieldOffset = aggregateOffset + getOffset(field);
4867
4868 visitField(field, fieldOffset);
4869 }
4870}
4871
4872/// Collect layout information for the given fields into IvarsInfo.
4873void IvarLayoutBuilder::visitField(const FieldDecl *field,
4874 CharUnits fieldOffset) {
4875 QualType fieldType = field->getType();
4876
4877 // Drill down into arrays.
4878 uint64_t numElts = 1;
4879 while (auto arrayType = CGM.getContext().getAsConstantArrayType(fieldType)) {
4880 numElts *= arrayType->getSize().getZExtValue();
4881 fieldType = arrayType->getElementType();
4882 }
4883
4884 assert(!fieldType->isArrayType() && "ivar of non-constant array type?");
4885
4886 // If we ended up with a zero-sized array, we've done what we can do within
4887 // the limits of this layout encoding.
4888 if (numElts == 0) return;
4889
4890 // Recurse if the base element type is a record type.
4891 if (auto recType = fieldType->getAs<RecordType>()) {
4892 size_t oldEnd = IvarsInfo.size();
4893
4894 visitRecord(recType, fieldOffset);
4895
4896 // If we have an array, replicate the first entry's layout information.
4897 auto numEltEntries = IvarsInfo.size() - oldEnd;
4898 if (numElts != 1 && numEltEntries != 0) {
4899 CharUnits eltSize = CGM.getContext().getTypeSizeInChars(recType);
4900 for (uint64_t eltIndex = 1; eltIndex != numElts; ++eltIndex) {
4901 // Copy the last numEltEntries onto the end of the array, adjusting
4902 // each for the element size.
4903 for (size_t i = 0; i != numEltEntries; ++i) {
4904 auto firstEntry = IvarsInfo[oldEnd + i];
4905 IvarsInfo.push_back(IvarInfo(firstEntry.Offset + eltIndex * eltSize,
4906 firstEntry.SizeInWords));
4907 }
4908 }
4909 }
4910
Fariborz Jahanian524bb202009-03-10 16:22:08 +00004911 return;
Fariborz Jahanian3b0f8862009-03-11 00:07:04 +00004912 }
Daniel Dunbar15bd8882009-05-03 14:10:34 +00004913
John McCall3fd13f062015-10-21 18:06:47 +00004914 // Classify the element type.
4915 Qualifiers::GC GCAttr = GetGCAttrTypeForType(CGM.getContext(), fieldType);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004916
John McCall3fd13f062015-10-21 18:06:47 +00004917 // If it matches what we're looking for, add an entry.
4918 if ((ForStrongLayout && GCAttr == Qualifiers::Strong)
4919 || (!ForStrongLayout && GCAttr == Qualifiers::Weak)) {
4920 assert(CGM.getContext().getTypeSizeInChars(fieldType)
4921 == CGM.getPointerSize());
4922 IvarsInfo.push_back(IvarInfo(fieldOffset, numElts));
4923 }
Fariborz Jahanianc559f3f2009-03-05 22:39:55 +00004924}
4925
John McCall3fd13f062015-10-21 18:06:47 +00004926/// buildBitmap - This routine does the horsework of taking the offsets of
4927/// strong/weak references and creating a bitmap. The bitmap is also
4928/// returned in the given buffer, suitable for being passed to \c dump().
4929llvm::Constant *IvarLayoutBuilder::buildBitmap(CGObjCCommonMac &CGObjC,
4930 llvm::SmallVectorImpl<unsigned char> &buffer) {
4931 // The bitmap is a series of skip/scan instructions, aligned to word
4932 // boundaries. The skip is performed first.
4933 const unsigned char MaxNibble = 0xF;
4934 const unsigned char SkipMask = 0xF0, SkipShift = 4;
4935 const unsigned char ScanMask = 0x0F, ScanShift = 0;
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00004936
John McCall3fd13f062015-10-21 18:06:47 +00004937 assert(!IvarsInfo.empty() && "generating bitmap for no data");
4938
4939 // Sort the ivar info on byte position in case we encounterred a
4940 // union nested in the ivar list.
4941 if (IsDisordered) {
4942 // This isn't a stable sort, but our algorithm should handle it fine.
4943 llvm::array_pod_sort(IvarsInfo.begin(), IvarsInfo.end());
4944 } else {
Craig Toppera3467052016-01-03 19:43:20 +00004945 assert(std::is_sorted(IvarsInfo.begin(), IvarsInfo.end()));
John McCall3fd13f062015-10-21 18:06:47 +00004946 }
4947 assert(IvarsInfo.back().Offset < InstanceEnd);
4948
4949 assert(buffer.empty());
4950
4951 // Skip the next N words.
4952 auto skip = [&](unsigned numWords) {
4953 assert(numWords > 0);
4954
4955 // Try to merge into the previous byte. Since scans happen second, we
4956 // can't do this if it includes a scan.
4957 if (!buffer.empty() && !(buffer.back() & ScanMask)) {
4958 unsigned lastSkip = buffer.back() >> SkipShift;
4959 if (lastSkip < MaxNibble) {
4960 unsigned claimed = std::min(MaxNibble - lastSkip, numWords);
4961 numWords -= claimed;
4962 lastSkip += claimed;
4963 buffer.back() = (lastSkip << SkipShift);
4964 }
4965 }
4966
4967 while (numWords >= MaxNibble) {
4968 buffer.push_back(MaxNibble << SkipShift);
4969 numWords -= MaxNibble;
4970 }
4971 if (numWords) {
4972 buffer.push_back(numWords << SkipShift);
4973 }
4974 };
4975
4976 // Scan the next N words.
4977 auto scan = [&](unsigned numWords) {
4978 assert(numWords > 0);
4979
4980 // Try to merge into the previous byte. Since scans happen second, we can
4981 // do this even if it includes a skip.
4982 if (!buffer.empty()) {
4983 unsigned lastScan = (buffer.back() & ScanMask) >> ScanShift;
4984 if (lastScan < MaxNibble) {
4985 unsigned claimed = std::min(MaxNibble - lastScan, numWords);
4986 numWords -= claimed;
4987 lastScan += claimed;
4988 buffer.back() = (buffer.back() & SkipMask) | (lastScan << ScanShift);
4989 }
4990 }
4991
4992 while (numWords >= MaxNibble) {
4993 buffer.push_back(MaxNibble << ScanShift);
4994 numWords -= MaxNibble;
4995 }
4996 if (numWords) {
4997 buffer.push_back(numWords << ScanShift);
4998 }
4999 };
5000
5001 // One past the end of the last scan.
5002 unsigned endOfLastScanInWords = 0;
5003 const CharUnits WordSize = CGM.getPointerSize();
5004
5005 // Consider all the scan requests.
5006 for (auto &request : IvarsInfo) {
5007 CharUnits beginOfScan = request.Offset - InstanceBegin;
5008
5009 // Ignore scan requests that don't start at an even multiple of the
5010 // word size. We can't encode them.
5011 if ((beginOfScan % WordSize) != 0) continue;
5012
5013 // Ignore scan requests that start before the instance start.
5014 // This assumes that scans never span that boundary. The boundary
5015 // isn't the true start of the ivars, because in the fragile-ARC case
5016 // it's rounded up to word alignment, but the test above should leave
5017 // us ignoring that possibility.
5018 if (beginOfScan.isNegative()) {
5019 assert(request.Offset + request.SizeInWords * WordSize <= InstanceBegin);
5020 continue;
5021 }
5022
5023 unsigned beginOfScanInWords = beginOfScan / WordSize;
5024 unsigned endOfScanInWords = beginOfScanInWords + request.SizeInWords;
5025
5026 // If the scan starts some number of words after the last one ended,
5027 // skip forward.
5028 if (beginOfScanInWords > endOfLastScanInWords) {
5029 skip(beginOfScanInWords - endOfLastScanInWords);
5030
5031 // Otherwise, start scanning where the last left off.
5032 } else {
5033 beginOfScanInWords = endOfLastScanInWords;
5034
5035 // If that leaves us with nothing to scan, ignore this request.
5036 if (beginOfScanInWords >= endOfScanInWords) continue;
5037 }
5038
5039 // Scan to the end of the request.
5040 assert(beginOfScanInWords < endOfScanInWords);
5041 scan(endOfScanInWords - beginOfScanInWords);
5042 endOfLastScanInWords = endOfScanInWords;
5043 }
5044
John McCallf5ea0722015-10-29 23:36:14 +00005045 if (buffer.empty())
5046 return llvm::ConstantPointerNull::get(CGM.Int8PtrTy);
5047
John McCall3fd13f062015-10-21 18:06:47 +00005048 // For GC layouts, emit a skip to the end of the allocation so that we
5049 // have precise information about the entire thing. This isn't useful
5050 // or necessary for the ARC-style layout strings.
5051 if (CGM.getLangOpts().getGC() != LangOptions::NonGC) {
5052 unsigned lastOffsetInWords =
5053 (InstanceEnd - InstanceBegin + WordSize - CharUnits::One()) / WordSize;
5054 if (lastOffsetInWords > endOfLastScanInWords) {
5055 skip(lastOffsetInWords - endOfLastScanInWords);
5056 }
5057 }
5058
5059 // Null terminate the string.
5060 buffer.push_back(0);
5061
Saleem Abdulrasool271106c2016-09-16 23:41:13 +00005062 auto *Entry = CGObjC.CreateCStringLiteral(
5063 reinterpret_cast<char *>(buffer.data()), ObjCLabelType::ClassName);
John McCall3fd13f062015-10-21 18:06:47 +00005064 return getConstantGEP(CGM.getLLVMContext(), Entry, 0, 0);
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00005065}
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005066
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00005067/// BuildIvarLayout - Builds ivar layout bitmap for the class
5068/// implementation for the __strong or __weak case.
5069/// The layout map displays which words in ivar list must be skipped
5070/// and which must be scanned by GC (see below). String is built of bytes.
5071/// Each byte is divided up in two nibbles (4-bit each). Left nibble is count
5072/// of words to skip and right nibble is count of words to scan. So, each
5073/// nibble represents up to 15 workds to skip or scan. Skipping the rest is
5074/// represented by a 0x00 byte which also ends the string.
5075/// 1. when ForStrongLayout is true, following ivars are scanned:
5076/// - id, Class
5077/// - object *
5078/// - __strong anything
5079///
5080/// 2. When ForStrongLayout is false, following ivars are scanned:
5081/// - __weak anything
5082///
John McCall3fd13f062015-10-21 18:06:47 +00005083llvm::Constant *
5084CGObjCCommonMac::BuildIvarLayout(const ObjCImplementationDecl *OMD,
5085 CharUnits beginOffset, CharUnits endOffset,
John McCall460ce582015-10-22 18:38:17 +00005086 bool ForStrongLayout, bool HasMRCWeakIvars) {
5087 // If this is MRC, and we're either building a strong layout or there
5088 // are no weak ivars, bail out early.
Chris Lattnerece04092012-02-07 00:39:47 +00005089 llvm::Type *PtrTy = CGM.Int8PtrTy;
David Blaikiebbafb8a2012-03-11 07:00:24 +00005090 if (CGM.getLangOpts().getGC() == LangOptions::NonGC &&
John McCall460ce582015-10-22 18:38:17 +00005091 !CGM.getLangOpts().ObjCAutoRefCount &&
5092 (ForStrongLayout || !HasMRCWeakIvars))
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00005093 return llvm::Constant::getNullValue(PtrTy);
5094
Jordy Rosea91768e2011-07-22 02:08:32 +00005095 const ObjCInterfaceDecl *OI = OMD->getClassInterface();
John McCall3fd13f062015-10-21 18:06:47 +00005096 SmallVector<const ObjCIvarDecl*, 32> ivars;
5097
5098 // GC layout strings include the complete object layout, possibly
5099 // inaccurately in the non-fragile ABI; the runtime knows how to fix this
5100 // up.
5101 //
5102 // ARC layout strings only include the class's ivars. In non-fragile
John McCallf5ea0722015-10-29 23:36:14 +00005103 // runtimes, that means starting at InstanceStart, rounded up to word
5104 // alignment. In fragile runtimes, there's no InstanceStart, so it means
John McCalld80218f2015-11-19 02:27:55 +00005105 // starting at the offset of the first ivar, rounded up to word alignment.
John McCall460ce582015-10-22 18:38:17 +00005106 //
5107 // MRC weak layout strings follow the ARC style.
John McCall3fd13f062015-10-21 18:06:47 +00005108 CharUnits baseOffset;
John McCall460ce582015-10-22 18:38:17 +00005109 if (CGM.getLangOpts().getGC() == LangOptions::NonGC) {
Jordy Rosea91768e2011-07-22 02:08:32 +00005110 for (const ObjCIvarDecl *IVD = OI->all_declared_ivar_begin();
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00005111 IVD; IVD = IVD->getNextIvar())
John McCall3fd13f062015-10-21 18:06:47 +00005112 ivars.push_back(IVD);
5113
5114 if (isNonFragileABI()) {
5115 baseOffset = beginOffset; // InstanceStart
John McCalld80218f2015-11-19 02:27:55 +00005116 } else if (!ivars.empty()) {
5117 baseOffset =
5118 CharUnits::fromQuantity(ComputeIvarBaseOffset(CGM, OMD, ivars[0]));
John McCall3fd13f062015-10-21 18:06:47 +00005119 } else {
5120 baseOffset = CharUnits::Zero();
5121 }
John McCallf5ea0722015-10-29 23:36:14 +00005122
Rui Ueyama83aa9792016-01-14 21:00:27 +00005123 baseOffset = baseOffset.alignTo(CGM.getPointerAlign());
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00005124 }
5125 else {
John McCall3fd13f062015-10-21 18:06:47 +00005126 CGM.getContext().DeepCollectObjCIvars(OI, true, ivars);
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00005127
John McCall3fd13f062015-10-21 18:06:47 +00005128 baseOffset = CharUnits::Zero();
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00005129 }
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00005130
John McCall3fd13f062015-10-21 18:06:47 +00005131 if (ivars.empty())
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00005132 return llvm::Constant::getNullValue(PtrTy);
5133
John McCall3fd13f062015-10-21 18:06:47 +00005134 IvarLayoutBuilder builder(CGM, baseOffset, endOffset, ForStrongLayout);
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00005135
John McCall3fd13f062015-10-21 18:06:47 +00005136 builder.visitAggregate(ivars.begin(), ivars.end(), CharUnits::Zero(),
5137 [&](const ObjCIvarDecl *ivar) -> CharUnits {
5138 return CharUnits::fromQuantity(ComputeIvarBaseOffset(CGM, OMD, ivar));
5139 });
5140
5141 if (!builder.hasBitmapData())
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00005142 return llvm::Constant::getNullValue(PtrTy);
John McCall3fd13f062015-10-21 18:06:47 +00005143
5144 llvm::SmallVector<unsigned char, 4> buffer;
5145 llvm::Constant *C = builder.buildBitmap(*this, buffer);
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00005146
John McCallf5ea0722015-10-29 23:36:14 +00005147 if (CGM.getLangOpts().ObjCGCBitmapPrint && !buffer.empty()) {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005148 printf("\n%s ivar layout for class '%s': ",
Fariborz Jahanian80c9ce22009-04-20 22:03:45 +00005149 ForStrongLayout ? "strong" : "weak",
Ben Langmuire013bdc2014-07-11 00:43:47 +00005150 OMD->getClassInterface()->getName().str().c_str());
John McCall3fd13f062015-10-21 18:06:47 +00005151 builder.dump(buffer);
Fariborz Jahanian80c9ce22009-04-20 22:03:45 +00005152 }
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00005153 return C;
Fariborz Jahanianc559f3f2009-03-05 22:39:55 +00005154}
5155
Fariborz Jahanian0b1ccdc2009-01-21 23:34:32 +00005156llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) {
Daniel Dunbarcb515c82008-08-12 03:39:23 +00005157 llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
Chris Lattner3def9ae2012-02-06 22:16:34 +00005158 // FIXME: Avoid std::string in "Sel.getAsString()"
Daniel Dunbarc2d4b622009-03-09 21:49:58 +00005159 if (!Entry)
Saleem Abdulrasool271106c2016-09-16 23:41:13 +00005160 Entry = CreateCStringLiteral(Sel.getAsString(), ObjCLabelType::MethodVarName);
Owen Anderson170229f2009-07-14 23:10:40 +00005161 return getConstantGEP(VMContext, Entry, 0, 0);
Daniel Dunbarb036db82008-08-13 03:21:16 +00005162}
5163
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00005164// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian0b1ccdc2009-01-21 23:34:32 +00005165llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) {
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00005166 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
5167}
5168
Daniel Dunbarf5c18462009-04-20 06:54:31 +00005169llvm::Constant *CGObjCCommonMac::GetMethodVarType(const FieldDecl *Field) {
Devang Patel4b6e4bb2009-03-04 18:21:39 +00005170 std::string TypeStr;
5171 CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
5172
5173 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
Daniel Dunbarc2d4b622009-03-09 21:49:58 +00005174 if (!Entry)
Saleem Abdulrasool271106c2016-09-16 23:41:13 +00005175 Entry = CreateCStringLiteral(TypeStr, ObjCLabelType::MethodVarType);
Owen Anderson170229f2009-07-14 23:10:40 +00005176 return getConstantGEP(VMContext, Entry, 0, 0);
Daniel Dunbarcb515c82008-08-12 03:39:23 +00005177}
5178
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005179llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D,
5180 bool Extended) {
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00005181 std::string TypeStr;
Bill Wendlinge22bef72012-02-09 22:45:21 +00005182 if (CGM.getContext().getObjCEncodingForMethodDecl(D, TypeStr, Extended))
Craig Topper8a13c412014-05-21 05:09:00 +00005183 return nullptr;
Devang Patel4b6e4bb2009-03-04 18:21:39 +00005184
5185 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
Daniel Dunbar3241fae2009-04-14 23:14:47 +00005186 if (!Entry)
Saleem Abdulrasool271106c2016-09-16 23:41:13 +00005187 Entry = CreateCStringLiteral(TypeStr, ObjCLabelType::MethodVarType);
Owen Anderson170229f2009-07-14 23:10:40 +00005188 return getConstantGEP(VMContext, Entry, 0, 0);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00005189}
5190
Daniel Dunbar80a840b2008-08-23 00:19:03 +00005191// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian0b1ccdc2009-01-21 23:34:32 +00005192llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) {
Daniel Dunbar80a840b2008-08-23 00:19:03 +00005193 llvm::GlobalVariable *&Entry = PropertyNames[Ident];
Daniel Dunbarc2d4b622009-03-09 21:49:58 +00005194 if (!Entry)
Saleem Abdulrasool271106c2016-09-16 23:41:13 +00005195 Entry = CreateCStringLiteral(Ident->getName(), ObjCLabelType::PropertyName);
Owen Anderson170229f2009-07-14 23:10:40 +00005196 return getConstantGEP(VMContext, Entry, 0, 0);
Daniel Dunbar80a840b2008-08-23 00:19:03 +00005197}
5198
5199// FIXME: Merge into a single cstring creation function.
Daniel Dunbar4932b362008-08-28 04:38:10 +00005200// FIXME: This Decl should be more precise.
Daniel Dunbarc2d4b622009-03-09 21:49:58 +00005201llvm::Constant *
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005202CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
5203 const Decl *Container) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005204 std::string TypeStr;
5205 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
Daniel Dunbar80a840b2008-08-23 00:19:03 +00005206 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
5207}
5208
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005209void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D,
Fariborz Jahanian0b1ccdc2009-01-21 23:34:32 +00005210 const ObjCContainerDecl *CD,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005211 SmallVectorImpl<char> &Name) {
Daniel Dunbard2386812009-10-19 01:21:19 +00005212 llvm::raw_svector_ostream OS(Name);
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +00005213 assert (CD && "Missing container decl in GetNameForMethod");
Daniel Dunbard2386812009-10-19 01:21:19 +00005214 OS << '\01' << (D->isInstanceMethod() ? '-' : '+')
5215 << '[' << CD->getName();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005216 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbard2386812009-10-19 01:21:19 +00005217 dyn_cast<ObjCCategoryImplDecl>(D->getDeclContext()))
Benjamin Kramer2f569922012-02-07 11:57:45 +00005218 OS << '(' << *CID << ')';
Daniel Dunbard2386812009-10-19 01:21:19 +00005219 OS << ' ' << D->getSelector().getAsString() << ']';
Daniel Dunbara94ecd22008-08-16 03:19:19 +00005220}
5221
Daniel Dunbar3ad53482008-08-11 21:35:06 +00005222void CGObjCMac::FinishModule() {
Daniel Dunbar7bd00bd2008-08-12 06:48:42 +00005223 EmitModuleInfo();
5224
Daniel Dunbarc475d422008-10-29 22:36:39 +00005225 // Emit the dummy bodies for any protocols which were referenced but
5226 // never defined.
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005227 for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
Chris Lattnerf56501c2009-07-17 23:57:13 +00005228 I = Protocols.begin(), e = Protocols.end(); I != e; ++I) {
5229 if (I->second->hasInitializer())
Daniel Dunbarc475d422008-10-29 22:36:39 +00005230 continue;
Daniel Dunbar7bd00bd2008-08-12 06:48:42 +00005231
Benjamin Kramer22d24c22011-10-15 12:20:02 +00005232 llvm::Constant *Values[5];
Owen Anderson0b75f232009-07-31 20:28:54 +00005233 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00005234 Values[1] = GetClassName(I->first->getName());
Owen Anderson0b75f232009-07-31 20:28:54 +00005235 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
Daniel Dunbarc475d422008-10-29 22:36:39 +00005236 Values[3] = Values[4] =
Owen Anderson0b75f232009-07-31 20:28:54 +00005237 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
Owen Anderson0e0189d2009-07-27 22:29:56 +00005238 I->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
Daniel Dunbarc475d422008-10-29 22:36:39 +00005239 Values));
Rafael Espindola060062a2014-03-06 22:15:10 +00005240 CGM.addCompilerUsedGlobal(I->second);
Daniel Dunbarc475d422008-10-29 22:36:39 +00005241 }
5242
Daniel Dunbarc61d0e92008-08-25 06:02:07 +00005243 // Add assembler directives to add lazy undefined symbol references
5244 // for classes which are referenced but not defined. This is
5245 // important for correct linker interaction.
Daniel Dunbard027a922009-09-07 00:20:42 +00005246 //
5247 // FIXME: It would be nice if we had an LLVM construct for this.
Saleem Abdulrasool62c07eb2016-09-12 21:15:23 +00005248 if ((!LazySymbols.empty() || !DefinedSymbols.empty()) &&
5249 CGM.getTriple().isOSBinFormatMachO()) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00005250 SmallString<256> Asm;
Daniel Dunbard027a922009-09-07 00:20:42 +00005251 Asm += CGM.getModule().getModuleInlineAsm();
5252 if (!Asm.empty() && Asm.back() != '\n')
5253 Asm += '\n';
Daniel Dunbarc61d0e92008-08-25 06:02:07 +00005254
Daniel Dunbard027a922009-09-07 00:20:42 +00005255 llvm::raw_svector_ostream OS(Asm);
Saleem Abdulrasool39217d42016-09-16 14:24:26 +00005256 for (const auto *Sym : DefinedSymbols)
Saleem Abdulrasool62c07eb2016-09-12 21:15:23 +00005257 OS << "\t.objc_class_name_" << Sym->getName() << "=0\n"
5258 << "\t.globl .objc_class_name_" << Sym->getName() << "\n";
Saleem Abdulrasool39217d42016-09-16 14:24:26 +00005259 for (const auto *Sym : LazySymbols)
Saleem Abdulrasool62c07eb2016-09-12 21:15:23 +00005260 OS << "\t.lazy_reference .objc_class_name_" << Sym->getName() << "\n";
5261 for (const auto &Category : DefinedCategoryNames)
5262 OS << "\t.objc_category_name_" << Category << "=0\n"
5263 << "\t.globl .objc_category_name_" << Category << "\n";
Fariborz Jahanian9adb2e62010-06-21 22:05:18 +00005264
Daniel Dunbard027a922009-09-07 00:20:42 +00005265 CGM.getModule().setModuleInlineAsm(OS.str());
Daniel Dunbarc61d0e92008-08-25 06:02:07 +00005266 }
Daniel Dunbar3ad53482008-08-11 21:35:06 +00005267}
5268
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005269CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm)
Saleem Abdulrasool4f515a62016-07-13 02:58:44 +00005270 : CGObjCCommonMac(cgm), ObjCTypes(cgm), ObjCEmptyCacheVar(nullptr),
5271 ObjCEmptyVtableVar(nullptr) {
Fariborz Jahanian279eda62009-01-21 22:04:16 +00005272 ObjCABI = 2;
5273}
5274
Daniel Dunbar3ad53482008-08-11 21:35:06 +00005275/* *** */
5276
Fariborz Jahanian279eda62009-01-21 22:04:16 +00005277ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm)
Craig Topper8a13c412014-05-21 05:09:00 +00005278 : VMContext(cgm.getLLVMContext()), CGM(cgm), ExternalProtocolPtrTy(nullptr)
Douglas Gregora95f9aa2012-01-17 23:38:32 +00005279{
Daniel Dunbar7bd00bd2008-08-12 06:48:42 +00005280 CodeGen::CodeGenTypes &Types = CGM.getTypes();
5281 ASTContext &Ctx = CGM.getContext();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005282
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00005283 ShortTy = Types.ConvertType(Ctx.ShortTy);
Daniel Dunbarb036db82008-08-13 03:21:16 +00005284 IntTy = Types.ConvertType(Ctx.IntTy);
Daniel Dunbar7bd00bd2008-08-12 06:48:42 +00005285 LongTy = Types.ConvertType(Ctx.LongTy);
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00005286 LongLongTy = Types.ConvertType(Ctx.LongLongTy);
Chris Lattnerece04092012-02-07 00:39:47 +00005287 Int8PtrTy = CGM.Int8PtrTy;
5288 Int8PtrPtrTy = CGM.Int8PtrPtrTy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005289
Tim Northover238b5082014-03-29 13:42:40 +00005290 // arm64 targets use "int" ivar offset variables. All others,
5291 // including OS X x86_64 and Windows x86_64, use "long" ivar offsets.
Tim Northover40956e62014-07-23 12:32:58 +00005292 if (CGM.getTarget().getTriple().getArch() == llvm::Triple::aarch64)
Tim Northover238b5082014-03-29 13:42:40 +00005293 IvarOffsetVarTy = IntTy;
5294 else
5295 IvarOffsetVarTy = LongTy;
5296
Daniel Dunbar7bd00bd2008-08-12 06:48:42 +00005297 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
Owen Anderson9793f0e2009-07-29 22:16:19 +00005298 PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
Daniel Dunbar7bd00bd2008-08-12 06:48:42 +00005299 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005300
Fariborz Jahanian279eda62009-01-21 22:04:16 +00005301 // I'm not sure I like this. The implicit coordination is a bit
5302 // gross. We should solve this in a reasonable fashion because this
5303 // is a pretty common task (match some runtime data structure with
5304 // an LLVM data structure).
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005305
Fariborz Jahanian279eda62009-01-21 22:04:16 +00005306 // FIXME: This is leaked.
5307 // FIXME: Merge with rewriter code?
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005308
Fariborz Jahanian279eda62009-01-21 22:04:16 +00005309 // struct _objc_super {
5310 // id self;
5311 // Class cls;
5312 // }
Abramo Bagnara6150c882010-05-11 21:36:43 +00005313 RecordDecl *RD = RecordDecl::Create(Ctx, TTK_Struct,
Daniel Dunbar0c005372010-04-29 16:29:11 +00005314 Ctx.getTranslationUnitDecl(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00005315 SourceLocation(), SourceLocation(),
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005316 &Ctx.Idents.get("_objc_super"));
Craig Topper8a13c412014-05-21 05:09:00 +00005317 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), SourceLocation(),
5318 nullptr, Ctx.getObjCIdType(), nullptr, nullptr,
5319 false, ICIS_NoInit));
5320 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), SourceLocation(),
5321 nullptr, Ctx.getObjCClassType(), nullptr,
5322 nullptr, false, ICIS_NoInit));
Douglas Gregord5058122010-02-11 01:19:42 +00005323 RD->completeDefinition();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005324
Fariborz Jahanian279eda62009-01-21 22:04:16 +00005325 SuperCTy = Ctx.getTagDeclType(RD);
5326 SuperPtrCTy = Ctx.getPointerType(SuperCTy);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005327
Fariborz Jahanian279eda62009-01-21 22:04:16 +00005328 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005329 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
5330
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005331 // struct _prop_t {
5332 // char *name;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005333 // char *attributes;
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005334 // }
Chris Lattner5ec04a52011-08-12 17:43:31 +00005335 PropertyTy = llvm::StructType::create("struct._prop_t",
Reid Kleckneree7cf842014-12-01 22:02:27 +00005336 Int8PtrTy, Int8PtrTy, nullptr);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005337
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005338 // struct _prop_list_t {
Fariborz Jahanian0232c052009-01-23 01:46:23 +00005339 // uint32_t entsize; // sizeof(struct _prop_t)
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005340 // uint32_t count_of_properties;
Fariborz Jahanian0232c052009-01-23 01:46:23 +00005341 // struct _prop_t prop_list[count_of_properties];
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005342 // }
Chris Lattnera5f58b02011-07-09 17:41:47 +00005343 PropertyListTy =
Chris Lattner5ec04a52011-08-12 17:43:31 +00005344 llvm::StructType::create("struct._prop_list_t", IntTy, IntTy,
Reid Kleckneree7cf842014-12-01 22:02:27 +00005345 llvm::ArrayType::get(PropertyTy, 0), nullptr);
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005346 // struct _prop_list_t *
Owen Anderson9793f0e2009-07-29 22:16:19 +00005347 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005348
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005349 // struct _objc_method {
5350 // SEL _cmd;
5351 // char *method_type;
5352 // char *_imp;
5353 // }
Chris Lattner5ec04a52011-08-12 17:43:31 +00005354 MethodTy = llvm::StructType::create("struct._objc_method",
5355 SelectorPtrTy, Int8PtrTy, Int8PtrTy,
Reid Kleckneree7cf842014-12-01 22:02:27 +00005356 nullptr);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005357
Fariborz Jahanian0232c052009-01-23 01:46:23 +00005358 // struct _objc_cache *
Chris Lattner5ec04a52011-08-12 17:43:31 +00005359 CacheTy = llvm::StructType::create(VMContext, "struct._objc_cache");
Owen Anderson9793f0e2009-07-29 22:16:19 +00005360 CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
Fariborz Jahanian279eda62009-01-21 22:04:16 +00005361}
Daniel Dunbar7bd00bd2008-08-12 06:48:42 +00005362
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005363ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
Mike Stump11289f42009-09-09 15:08:12 +00005364 : ObjCCommonTypesHelper(cgm) {
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005365 // struct _objc_method_description {
5366 // SEL name;
5367 // char *types;
5368 // }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005369 MethodDescriptionTy =
Chris Lattner5ec04a52011-08-12 17:43:31 +00005370 llvm::StructType::create("struct._objc_method_description",
Reid Kleckneree7cf842014-12-01 22:02:27 +00005371 SelectorPtrTy, Int8PtrTy, nullptr);
Daniel Dunbarb036db82008-08-13 03:21:16 +00005372
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005373 // struct _objc_method_description_list {
5374 // int count;
5375 // struct _objc_method_description[1];
5376 // }
Reid Kleckneree7cf842014-12-01 22:02:27 +00005377 MethodDescriptionListTy = llvm::StructType::create(
5378 "struct._objc_method_description_list", IntTy,
5379 llvm::ArrayType::get(MethodDescriptionTy, 0), nullptr);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005380
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005381 // struct _objc_method_description_list *
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005382 MethodDescriptionListPtrTy =
Owen Anderson9793f0e2009-07-29 22:16:19 +00005383 llvm::PointerType::getUnqual(MethodDescriptionListTy);
Daniel Dunbarb036db82008-08-13 03:21:16 +00005384
Daniel Dunbarb036db82008-08-13 03:21:16 +00005385 // Protocol description structures
5386
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005387 // struct _objc_protocol_extension {
5388 // uint32_t size; // sizeof(struct _objc_protocol_extension)
5389 // struct _objc_method_description_list *optional_instance_methods;
5390 // struct _objc_method_description_list *optional_class_methods;
5391 // struct _objc_property_list *instance_properties;
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005392 // const char ** extendedMethodTypes;
Manman Rence7bff52016-01-29 23:46:55 +00005393 // struct _objc_property_list *class_properties;
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005394 // }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005395 ProtocolExtensionTy =
Chris Lattner5ec04a52011-08-12 17:43:31 +00005396 llvm::StructType::create("struct._objc_protocol_extension",
5397 IntTy, MethodDescriptionListPtrTy,
5398 MethodDescriptionListPtrTy, PropertyListPtrTy,
Manman Rence7bff52016-01-29 23:46:55 +00005399 Int8PtrPtrTy, PropertyListPtrTy, nullptr);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005400
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005401 // struct _objc_protocol_extension *
Owen Anderson9793f0e2009-07-29 22:16:19 +00005402 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
Daniel Dunbarb036db82008-08-13 03:21:16 +00005403
Daniel Dunbarc475d422008-10-29 22:36:39 +00005404 // Handle recursive construction of Protocol and ProtocolList types
Daniel Dunbarb036db82008-08-13 03:21:16 +00005405
Chris Lattnera5f58b02011-07-09 17:41:47 +00005406 ProtocolTy =
Chris Lattner5ec04a52011-08-12 17:43:31 +00005407 llvm::StructType::create(VMContext, "struct._objc_protocol");
Daniel Dunbarb036db82008-08-13 03:21:16 +00005408
Chris Lattnera5f58b02011-07-09 17:41:47 +00005409 ProtocolListTy =
Chris Lattner5ec04a52011-08-12 17:43:31 +00005410 llvm::StructType::create(VMContext, "struct._objc_protocol_list");
Chris Lattnera5f58b02011-07-09 17:41:47 +00005411 ProtocolListTy->setBody(llvm::PointerType::getUnqual(ProtocolListTy),
Fariborz Jahanian279eda62009-01-21 22:04:16 +00005412 LongTy,
Chris Lattnera5f58b02011-07-09 17:41:47 +00005413 llvm::ArrayType::get(ProtocolTy, 0),
Reid Kleckneree7cf842014-12-01 22:02:27 +00005414 nullptr);
Daniel Dunbarb036db82008-08-13 03:21:16 +00005415
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005416 // struct _objc_protocol {
5417 // struct _objc_protocol_extension *isa;
5418 // char *protocol_name;
5419 // struct _objc_protocol **_objc_protocol_list;
5420 // struct _objc_method_description_list *instance_methods;
5421 // struct _objc_method_description_list *class_methods;
5422 // }
Chris Lattnera5f58b02011-07-09 17:41:47 +00005423 ProtocolTy->setBody(ProtocolExtensionPtrTy, Int8PtrTy,
5424 llvm::PointerType::getUnqual(ProtocolListTy),
5425 MethodDescriptionListPtrTy,
5426 MethodDescriptionListPtrTy,
Reid Kleckneree7cf842014-12-01 22:02:27 +00005427 nullptr);
Daniel Dunbarb036db82008-08-13 03:21:16 +00005428
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005429 // struct _objc_protocol_list *
Owen Anderson9793f0e2009-07-29 22:16:19 +00005430 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
Daniel Dunbarb036db82008-08-13 03:21:16 +00005431
Owen Anderson9793f0e2009-07-29 22:16:19 +00005432 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00005433
5434 // Class description structures
5435
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005436 // struct _objc_ivar {
5437 // char *ivar_name;
5438 // char *ivar_type;
5439 // int ivar_offset;
5440 // }
Chris Lattner5ec04a52011-08-12 17:43:31 +00005441 IvarTy = llvm::StructType::create("struct._objc_ivar",
Reid Kleckneree7cf842014-12-01 22:02:27 +00005442 Int8PtrTy, Int8PtrTy, IntTy, nullptr);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00005443
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005444 // struct _objc_ivar_list *
Chris Lattnera5f58b02011-07-09 17:41:47 +00005445 IvarListTy =
Chris Lattner5ec04a52011-08-12 17:43:31 +00005446 llvm::StructType::create(VMContext, "struct._objc_ivar_list");
Owen Anderson9793f0e2009-07-29 22:16:19 +00005447 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00005448
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005449 // struct _objc_method_list *
Chris Lattnera5f58b02011-07-09 17:41:47 +00005450 MethodListTy =
Chris Lattner5ec04a52011-08-12 17:43:31 +00005451 llvm::StructType::create(VMContext, "struct._objc_method_list");
Owen Anderson9793f0e2009-07-29 22:16:19 +00005452 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00005453
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005454 // struct _objc_class_extension *
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005455 ClassExtensionTy =
Chris Lattner5ec04a52011-08-12 17:43:31 +00005456 llvm::StructType::create("struct._objc_class_extension",
Reid Kleckneree7cf842014-12-01 22:02:27 +00005457 IntTy, Int8PtrTy, PropertyListPtrTy, nullptr);
Owen Anderson9793f0e2009-07-29 22:16:19 +00005458 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00005459
Chris Lattner5ec04a52011-08-12 17:43:31 +00005460 ClassTy = llvm::StructType::create(VMContext, "struct._objc_class");
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00005461
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005462 // struct _objc_class {
5463 // Class isa;
5464 // Class super_class;
5465 // char *name;
5466 // long version;
5467 // long info;
5468 // long instance_size;
5469 // struct _objc_ivar_list *ivars;
5470 // struct _objc_method_list *methods;
5471 // struct _objc_cache *cache;
5472 // struct _objc_protocol_list *protocols;
5473 // char *ivar_layout;
5474 // struct _objc_class_ext *ext;
5475 // };
Chris Lattnera5f58b02011-07-09 17:41:47 +00005476 ClassTy->setBody(llvm::PointerType::getUnqual(ClassTy),
5477 llvm::PointerType::getUnqual(ClassTy),
5478 Int8PtrTy,
5479 LongTy,
5480 LongTy,
5481 LongTy,
5482 IvarListPtrTy,
5483 MethodListPtrTy,
5484 CachePtrTy,
5485 ProtocolListPtrTy,
5486 Int8PtrTy,
5487 ClassExtensionPtrTy,
Reid Kleckneree7cf842014-12-01 22:02:27 +00005488 nullptr);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005489
Owen Anderson9793f0e2009-07-29 22:16:19 +00005490 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00005491
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005492 // struct _objc_category {
5493 // char *category_name;
5494 // char *class_name;
5495 // struct _objc_method_list *instance_method;
5496 // struct _objc_method_list *class_method;
Manman Renb3736772016-01-25 22:37:47 +00005497 // struct _objc_protocol_list *protocols;
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005498 // uint32_t size; // sizeof(struct _objc_category)
5499 // struct _objc_property_list *instance_properties;// category's @property
Manman Ren96df0b32016-01-29 23:45:01 +00005500 // struct _objc_property_list *class_properties;
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005501 // }
Chris Lattnera5f58b02011-07-09 17:41:47 +00005502 CategoryTy =
Chris Lattner5ec04a52011-08-12 17:43:31 +00005503 llvm::StructType::create("struct._objc_category",
5504 Int8PtrTy, Int8PtrTy, MethodListPtrTy,
5505 MethodListPtrTy, ProtocolListPtrTy,
Manman Ren96df0b32016-01-29 23:45:01 +00005506 IntTy, PropertyListPtrTy, PropertyListPtrTy,
5507 nullptr);
Daniel Dunbar938a77f2008-08-22 20:34:54 +00005508
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00005509 // Global metadata structures
5510
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005511 // struct _objc_symtab {
5512 // long sel_ref_cnt;
5513 // SEL *refs;
5514 // short cls_def_cnt;
5515 // short cat_def_cnt;
5516 // char *defs[cls_def_cnt + cat_def_cnt];
5517 // }
Chris Lattnera5f58b02011-07-09 17:41:47 +00005518 SymtabTy =
Chris Lattner5ec04a52011-08-12 17:43:31 +00005519 llvm::StructType::create("struct._objc_symtab",
5520 LongTy, SelectorPtrTy, ShortTy, ShortTy,
Reid Kleckneree7cf842014-12-01 22:02:27 +00005521 llvm::ArrayType::get(Int8PtrTy, 0), nullptr);
Owen Anderson9793f0e2009-07-29 22:16:19 +00005522 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00005523
Fariborz Jahanianeee54df2009-01-22 00:37:21 +00005524 // struct _objc_module {
5525 // long version;
5526 // long size; // sizeof(struct _objc_module)
5527 // char *name;
5528 // struct _objc_symtab* symtab;
5529 // }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005530 ModuleTy =
Chris Lattner5ec04a52011-08-12 17:43:31 +00005531 llvm::StructType::create("struct._objc_module",
Reid Kleckneree7cf842014-12-01 22:02:27 +00005532 LongTy, LongTy, Int8PtrTy, SymtabPtrTy, nullptr);
Daniel Dunbar97ff50d2008-08-23 09:25:55 +00005533
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005534
Mike Stump18bb9282009-05-16 07:57:57 +00005535 // FIXME: This is the size of the setjmp buffer and should be target
5536 // specific. 18 is what's used on 32-bit X86.
Anders Carlsson9ff22482008-09-09 10:10:21 +00005537 uint64_t SetJmpBufferSize = 18;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005538
Anders Carlsson9ff22482008-09-09 10:10:21 +00005539 // Exceptions
Chris Lattnerece04092012-02-07 00:39:47 +00005540 llvm::Type *StackPtrTy = llvm::ArrayType::get(CGM.Int8PtrTy, 4);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005541
5542 ExceptionDataTy =
Chris Lattner5ec04a52011-08-12 17:43:31 +00005543 llvm::StructType::create("struct._objc_exception_data",
Chris Lattnerece04092012-02-07 00:39:47 +00005544 llvm::ArrayType::get(CGM.Int32Ty,SetJmpBufferSize),
Reid Kleckneree7cf842014-12-01 22:02:27 +00005545 StackPtrTy, nullptr);
Daniel Dunbar8b8683f2008-08-12 00:12:39 +00005546}
5547
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005548ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm)
Mike Stump11289f42009-09-09 15:08:12 +00005549 : ObjCCommonTypesHelper(cgm) {
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005550 // struct _method_list_t {
5551 // uint32_t entsize; // sizeof(struct _objc_method)
5552 // uint32_t method_count;
5553 // struct _objc_method method_list[method_count];
5554 // }
Chris Lattnera5f58b02011-07-09 17:41:47 +00005555 MethodListnfABITy =
Chris Lattner5ec04a52011-08-12 17:43:31 +00005556 llvm::StructType::create("struct.__method_list_t", IntTy, IntTy,
Reid Kleckneree7cf842014-12-01 22:02:27 +00005557 llvm::ArrayType::get(MethodTy, 0), nullptr);
Fariborz Jahanian0232c052009-01-23 01:46:23 +00005558 // struct method_list_t *
Owen Anderson9793f0e2009-07-29 22:16:19 +00005559 MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005560
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005561 // struct _protocol_t {
5562 // id isa; // NULL
5563 // const char * const protocol_name;
Fariborz Jahanian0232c052009-01-23 01:46:23 +00005564 // const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005565 // const struct method_list_t * const instance_methods;
5566 // const struct method_list_t * const class_methods;
5567 // const struct method_list_t *optionalInstanceMethods;
5568 // const struct method_list_t *optionalClassMethods;
Fariborz Jahanian0232c052009-01-23 01:46:23 +00005569 // const struct _prop_list_t * properties;
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005570 // const uint32_t size; // sizeof(struct _protocol_t)
5571 // const uint32_t flags; // = 0
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005572 // const char ** extendedMethodTypes;
Fariborz Jahanian6a9c46b2015-03-31 22:22:40 +00005573 // const char *demangledName;
Manman Rence7bff52016-01-29 23:46:55 +00005574 // const struct _prop_list_t * class_properties;
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005575 // }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005576
Fariborz Jahanian0232c052009-01-23 01:46:23 +00005577 // Holder for struct _protocol_list_t *
Chris Lattnera5f58b02011-07-09 17:41:47 +00005578 ProtocolListnfABITy =
Chris Lattner5ec04a52011-08-12 17:43:31 +00005579 llvm::StructType::create(VMContext, "struct._objc_protocol_list");
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005580
Chris Lattnera5f58b02011-07-09 17:41:47 +00005581 ProtocolnfABITy =
Chris Lattner5ec04a52011-08-12 17:43:31 +00005582 llvm::StructType::create("struct._protocol_t", ObjectPtrTy, Int8PtrTy,
5583 llvm::PointerType::getUnqual(ProtocolListnfABITy),
5584 MethodListnfABIPtrTy, MethodListnfABIPtrTy,
5585 MethodListnfABIPtrTy, MethodListnfABIPtrTy,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005586 PropertyListPtrTy, IntTy, IntTy, Int8PtrPtrTy,
Manman Rence7bff52016-01-29 23:46:55 +00005587 Int8PtrTy, PropertyListPtrTy,
Reid Kleckneree7cf842014-12-01 22:02:27 +00005588 nullptr);
Daniel Dunbar8de90f02009-02-15 07:36:20 +00005589
5590 // struct _protocol_t*
Owen Anderson9793f0e2009-07-29 22:16:19 +00005591 ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005592
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00005593 // struct _protocol_list_t {
Fariborz Jahanian0232c052009-01-23 01:46:23 +00005594 // long protocol_count; // Note, this is 32/64 bit
Daniel Dunbar8de90f02009-02-15 07:36:20 +00005595 // struct _protocol_t *[protocol_count];
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005596 // }
Chris Lattnera5f58b02011-07-09 17:41:47 +00005597 ProtocolListnfABITy->setBody(LongTy,
5598 llvm::ArrayType::get(ProtocolnfABIPtrTy, 0),
Reid Kleckneree7cf842014-12-01 22:02:27 +00005599 nullptr);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005600
Fariborz Jahanian0232c052009-01-23 01:46:23 +00005601 // struct _objc_protocol_list*
Owen Anderson9793f0e2009-07-29 22:16:19 +00005602 ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005603
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005604 // struct _ivar_t {
Tim Northover238b5082014-03-29 13:42:40 +00005605 // unsigned [long] int *offset; // pointer to ivar offset location
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005606 // char *name;
5607 // char *type;
5608 // uint32_t alignment;
5609 // uint32_t size;
5610 // }
Tim Northover238b5082014-03-29 13:42:40 +00005611 IvarnfABITy = llvm::StructType::create(
5612 "struct._ivar_t", llvm::PointerType::getUnqual(IvarOffsetVarTy),
Reid Kleckneree7cf842014-12-01 22:02:27 +00005613 Int8PtrTy, Int8PtrTy, IntTy, IntTy, nullptr);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005614
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005615 // struct _ivar_list_t {
5616 // uint32 entsize; // sizeof(struct _ivar_t)
5617 // uint32 count;
5618 // struct _iver_t list[count];
5619 // }
Chris Lattnera5f58b02011-07-09 17:41:47 +00005620 IvarListnfABITy =
Chris Lattner5ec04a52011-08-12 17:43:31 +00005621 llvm::StructType::create("struct._ivar_list_t", IntTy, IntTy,
Reid Kleckneree7cf842014-12-01 22:02:27 +00005622 llvm::ArrayType::get(IvarnfABITy, 0), nullptr);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005623
Owen Anderson9793f0e2009-07-29 22:16:19 +00005624 IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005625
Fariborz Jahanian0232c052009-01-23 01:46:23 +00005626 // struct _class_ro_t {
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005627 // uint32_t const flags;
5628 // uint32_t const instanceStart;
5629 // uint32_t const instanceSize;
5630 // uint32_t const reserved; // only when building for 64bit targets
5631 // const uint8_t * const ivarLayout;
5632 // const char *const name;
5633 // const struct _method_list_t * const baseMethods;
5634 // const struct _objc_protocol_list *const baseProtocols;
5635 // const struct _ivar_list_t *const ivars;
5636 // const uint8_t * const weakIvarLayout;
5637 // const struct _prop_list_t * const properties;
5638 // }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005639
Fariborz Jahanian0232c052009-01-23 01:46:23 +00005640 // FIXME. Add 'reserved' field in 64bit abi mode!
Chris Lattner5ec04a52011-08-12 17:43:31 +00005641 ClassRonfABITy = llvm::StructType::create("struct._class_ro_t",
5642 IntTy, IntTy, IntTy, Int8PtrTy,
5643 Int8PtrTy, MethodListnfABIPtrTy,
5644 ProtocolListnfABIPtrTy,
5645 IvarListnfABIPtrTy,
Reid Kleckneree7cf842014-12-01 22:02:27 +00005646 Int8PtrTy, PropertyListPtrTy,
5647 nullptr);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005648
Fariborz Jahanian0232c052009-01-23 01:46:23 +00005649 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
Chris Lattnera5f58b02011-07-09 17:41:47 +00005650 llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy };
John McCall9dc0db22011-05-15 01:53:33 +00005651 ImpnfABITy = llvm::FunctionType::get(ObjectPtrTy, params, false)
5652 ->getPointerTo();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005653
Fariborz Jahanian0232c052009-01-23 01:46:23 +00005654 // struct _class_t {
5655 // struct _class_t *isa;
5656 // struct _class_t * const superclass;
5657 // void *cache;
5658 // IMP *vtable;
5659 // struct class_ro_t *ro;
5660 // }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005661
Chris Lattner5ec04a52011-08-12 17:43:31 +00005662 ClassnfABITy = llvm::StructType::create(VMContext, "struct._class_t");
Chris Lattnera5f58b02011-07-09 17:41:47 +00005663 ClassnfABITy->setBody(llvm::PointerType::getUnqual(ClassnfABITy),
5664 llvm::PointerType::getUnqual(ClassnfABITy),
5665 CachePtrTy,
5666 llvm::PointerType::getUnqual(ImpnfABITy),
5667 llvm::PointerType::getUnqual(ClassRonfABITy),
Reid Kleckneree7cf842014-12-01 22:02:27 +00005668 nullptr);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005669
Fariborz Jahanian71394042009-01-23 23:53:38 +00005670 // LLVM for struct _class_t *
Owen Anderson9793f0e2009-07-29 22:16:19 +00005671 ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005672
Fariborz Jahanian0232c052009-01-23 01:46:23 +00005673 // struct _category_t {
5674 // const char * const name;
5675 // struct _class_t *const cls;
5676 // const struct _method_list_t * const instance_methods;
5677 // const struct _method_list_t * const class_methods;
5678 // const struct _protocol_list_t * const protocols;
5679 // const struct _prop_list_t * const properties;
Manman Ren96df0b32016-01-29 23:45:01 +00005680 // const struct _prop_list_t * const class_properties;
Manman Ren42ff3902016-02-24 17:49:50 +00005681 // const uint32_t size;
Fariborz Jahanian5a63e4c2009-01-23 17:41:22 +00005682 // }
Chris Lattner5ec04a52011-08-12 17:43:31 +00005683 CategorynfABITy = llvm::StructType::create("struct._category_t",
5684 Int8PtrTy, ClassnfABIPtrTy,
5685 MethodListnfABIPtrTy,
5686 MethodListnfABIPtrTy,
5687 ProtocolListnfABIPtrTy,
5688 PropertyListPtrTy,
Manman Ren96df0b32016-01-29 23:45:01 +00005689 PropertyListPtrTy,
Manman Ren42ff3902016-02-24 17:49:50 +00005690 IntTy,
Reid Kleckneree7cf842014-12-01 22:02:27 +00005691 nullptr);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005692
Fariborz Jahanian82c72e12009-02-03 23:49:23 +00005693 // New types for nonfragile abi messaging.
Fariborz Jahaniane4dc35d2009-02-04 20:42:28 +00005694 CodeGen::CodeGenTypes &Types = CGM.getTypes();
5695 ASTContext &Ctx = CGM.getContext();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005696
Fariborz Jahanian82c72e12009-02-03 23:49:23 +00005697 // MessageRefTy - LLVM for:
5698 // struct _message_ref_t {
5699 // IMP messenger;
5700 // SEL name;
5701 // };
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005702
Fariborz Jahaniane4dc35d2009-02-04 20:42:28 +00005703 // First the clang type for struct _message_ref_t
Abramo Bagnara6150c882010-05-11 21:36:43 +00005704 RecordDecl *RD = RecordDecl::Create(Ctx, TTK_Struct,
Daniel Dunbar0c005372010-04-29 16:29:11 +00005705 Ctx.getTranslationUnitDecl(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00005706 SourceLocation(), SourceLocation(),
Fariborz Jahaniane4dc35d2009-02-04 20:42:28 +00005707 &Ctx.Idents.get("_message_ref_t"));
Craig Topper8a13c412014-05-21 05:09:00 +00005708 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), SourceLocation(),
5709 nullptr, Ctx.VoidPtrTy, nullptr, nullptr, false,
Richard Smith2b013182012-06-10 03:12:00 +00005710 ICIS_NoInit));
Craig Topper8a13c412014-05-21 05:09:00 +00005711 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), SourceLocation(),
5712 nullptr, Ctx.getObjCSelType(), nullptr, nullptr,
5713 false, ICIS_NoInit));
Douglas Gregord5058122010-02-11 01:19:42 +00005714 RD->completeDefinition();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005715
Fariborz Jahaniane4dc35d2009-02-04 20:42:28 +00005716 MessageRefCTy = Ctx.getTagDeclType(RD);
5717 MessageRefCPtrTy = Ctx.getPointerType(MessageRefCTy);
5718 MessageRefTy = cast<llvm::StructType>(Types.ConvertType(MessageRefCTy));
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005719
Fariborz Jahanian82c72e12009-02-03 23:49:23 +00005720 // MessageRefPtrTy - LLVM for struct _message_ref_t*
Owen Anderson9793f0e2009-07-29 22:16:19 +00005721 MessageRefPtrTy = llvm::PointerType::getUnqual(MessageRefTy);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005722
Fariborz Jahanian82c72e12009-02-03 23:49:23 +00005723 // SuperMessageRefTy - LLVM for:
5724 // struct _super_message_ref_t {
5725 // SUPER_IMP messenger;
5726 // SEL name;
5727 // };
Chris Lattnera5f58b02011-07-09 17:41:47 +00005728 SuperMessageRefTy =
Chris Lattner5ec04a52011-08-12 17:43:31 +00005729 llvm::StructType::create("struct._super_message_ref_t",
Reid Kleckneree7cf842014-12-01 22:02:27 +00005730 ImpnfABITy, SelectorPtrTy, nullptr);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005731
Fariborz Jahanian82c72e12009-02-03 23:49:23 +00005732 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005733 SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy);
Fariborz Jahanian0a3cfcc2011-06-22 20:21:51 +00005734
Daniel Dunbarb1559a42009-03-01 04:46:24 +00005735
5736 // struct objc_typeinfo {
5737 // const void** vtable; // objc_ehtype_vtable + 2
5738 // const char* name; // c++ typeinfo string
5739 // Class cls;
5740 // };
Chris Lattnera5f58b02011-07-09 17:41:47 +00005741 EHTypeTy =
Chris Lattner5ec04a52011-08-12 17:43:31 +00005742 llvm::StructType::create("struct._objc_typeinfo",
5743 llvm::PointerType::getUnqual(Int8PtrTy),
Reid Kleckneree7cf842014-12-01 22:02:27 +00005744 Int8PtrTy, ClassnfABIPtrTy, nullptr);
Owen Anderson9793f0e2009-07-29 22:16:19 +00005745 EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy);
Daniel Dunbar8b8683f2008-08-12 00:12:39 +00005746}
5747
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005748llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() {
Fariborz Jahanian71394042009-01-23 23:53:38 +00005749 FinishNonFragileABIModule();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005750
Craig Topper8a13c412014-05-21 05:09:00 +00005751 return nullptr;
Fariborz Jahanian71394042009-01-23 23:53:38 +00005752}
5753
Saleem Abdulrasool1e6c4062016-05-16 05:06:49 +00005754void CGObjCNonFragileABIMac::AddModuleClassList(
5755 ArrayRef<llvm::GlobalValue *> Container, StringRef SymbolName,
5756 StringRef SectionName) {
Daniel Dunbar19573e72009-05-15 21:48:48 +00005757 unsigned NumClasses = Container.size();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005758
Daniel Dunbar19573e72009-05-15 21:48:48 +00005759 if (!NumClasses)
5760 return;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005761
Chris Lattner3def9ae2012-02-06 22:16:34 +00005762 SmallVector<llvm::Constant*, 8> Symbols(NumClasses);
Daniel Dunbar19573e72009-05-15 21:48:48 +00005763 for (unsigned i=0; i<NumClasses; i++)
Owen Andersonade90fd2009-07-29 18:54:39 +00005764 Symbols[i] = llvm::ConstantExpr::getBitCast(Container[i],
Daniel Dunbar19573e72009-05-15 21:48:48 +00005765 ObjCTypes.Int8PtrTy);
Chris Lattner3def9ae2012-02-06 22:16:34 +00005766 llvm::Constant *Init =
Owen Anderson9793f0e2009-07-29 22:16:19 +00005767 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Chris Lattner3def9ae2012-02-06 22:16:34 +00005768 Symbols.size()),
Daniel Dunbar19573e72009-05-15 21:48:48 +00005769 Symbols);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005770
Daniel Dunbar19573e72009-05-15 21:48:48 +00005771 llvm::GlobalVariable *GV =
Owen Andersonc10c8d32009-07-08 19:05:04 +00005772 new llvm::GlobalVariable(CGM.getModule(), Init->getType(), false,
Rafael Espindola5179a4e2014-02-27 19:01:11 +00005773 llvm::GlobalValue::PrivateLinkage,
Daniel Dunbar19573e72009-05-15 21:48:48 +00005774 Init,
Owen Andersonc10c8d32009-07-08 19:05:04 +00005775 SymbolName);
Micah Villmowdd31ca12012-10-08 16:25:52 +00005776 GV->setAlignment(CGM.getDataLayout().getABITypeAlignment(Init->getType()));
Daniel Dunbar19573e72009-05-15 21:48:48 +00005777 GV->setSection(SectionName);
Rafael Espindola060062a2014-03-06 22:15:10 +00005778 CGM.addCompilerUsedGlobal(GV);
Daniel Dunbar19573e72009-05-15 21:48:48 +00005779}
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005780
Fariborz Jahanian71394042009-01-23 23:53:38 +00005781void CGObjCNonFragileABIMac::FinishNonFragileABIModule() {
5782 // nonfragile abi has no module definition.
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005783
Daniel Dunbar19573e72009-05-15 21:48:48 +00005784 // Build list of all implemented class addresses in array
Fariborz Jahanian279abd32009-01-30 20:55:31 +00005785 // L_OBJC_LABEL_CLASS_$.
Fariborz Jahanianf322f2f2014-03-11 00:25:05 +00005786
5787 for (unsigned i=0, NumClasses=ImplementedClasses.size(); i<NumClasses; i++) {
5788 const ObjCInterfaceDecl *ID = ImplementedClasses[i];
5789 assert(ID);
5790 if (ObjCImplementationDecl *IMP = ID->getImplementation())
5791 // We are implementing a weak imported interface. Give it external linkage
Fariborz Jahanianbc94c942014-07-15 17:14:34 +00005792 if (ID->isWeakImported() && !IMP->isWeakImported()) {
Fariborz Jahanianf322f2f2014-03-11 00:25:05 +00005793 DefinedClasses[i]->setLinkage(llvm::GlobalVariable::ExternalLinkage);
Fariborz Jahanianbc94c942014-07-15 17:14:34 +00005794 DefinedMetaClasses[i]->setLinkage(llvm::GlobalVariable::ExternalLinkage);
5795 }
Fariborz Jahanianf322f2f2014-03-11 00:25:05 +00005796 }
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00005797
5798 AddModuleClassList(DefinedClasses, "OBJC_LABEL_CLASS_$",
Daniel Dunbar19573e72009-05-15 21:48:48 +00005799 "__DATA, __objc_classlist, regular, no_dead_strip");
Rafael Espindola554256c2014-02-26 22:25:45 +00005800
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00005801 AddModuleClassList(DefinedNonLazyClasses, "OBJC_LABEL_NONLAZY_CLASS_$",
Daniel Dunbar9a017d72009-05-15 22:33:15 +00005802 "__DATA, __objc_nlclslist, regular, no_dead_strip");
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005803
Fariborz Jahanian279abd32009-01-30 20:55:31 +00005804 // Build list of all implemented category addresses in array
5805 // L_OBJC_LABEL_CATEGORY_$.
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00005806 AddModuleClassList(DefinedCategories, "OBJC_LABEL_CATEGORY_$",
Daniel Dunbar19573e72009-05-15 21:48:48 +00005807 "__DATA, __objc_catlist, regular, no_dead_strip");
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00005808 AddModuleClassList(DefinedNonLazyCategories, "OBJC_LABEL_NONLAZY_CATEGORY_$",
Daniel Dunbar9a017d72009-05-15 22:33:15 +00005809 "__DATA, __objc_nlcatlist, regular, no_dead_strip");
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005810
Daniel Dunbar5e639272010-04-25 20:39:01 +00005811 EmitImageInfo();
Fariborz Jahanian71394042009-01-23 23:53:38 +00005812}
5813
John McCall9e8bb002011-05-14 03:10:52 +00005814/// isVTableDispatchedSelector - Returns true if SEL is not in the list of
5815/// VTableDispatchMethods; false otherwise. What this means is that
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005816/// except for the 19 selectors in the list, we generate 32bit-style
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +00005817/// message dispatch call for all the rest.
John McCall9e8bb002011-05-14 03:10:52 +00005818bool CGObjCNonFragileABIMac::isVTableDispatchedSelector(Selector Sel) {
5819 // At various points we've experimented with using vtable-based
5820 // dispatch for all methods.
Daniel Dunbarfca18c1b42010-04-24 17:56:46 +00005821 switch (CGM.getCodeGenOpts().getObjCDispatchMethod()) {
Daniel Dunbarfca18c1b42010-04-24 17:56:46 +00005822 case CodeGenOptions::Legacy:
Fariborz Jahaniandfb39832010-04-19 17:53:30 +00005823 return false;
John McCall9e8bb002011-05-14 03:10:52 +00005824 case CodeGenOptions::NonLegacy:
5825 return true;
Daniel Dunbarfca18c1b42010-04-24 17:56:46 +00005826 case CodeGenOptions::Mixed:
5827 break;
5828 }
5829
5830 // If so, see whether this selector is in the white-list of things which must
5831 // use the new dispatch convention. We lazily build a dense set for this.
John McCall9e8bb002011-05-14 03:10:52 +00005832 if (VTableDispatchMethods.empty()) {
5833 VTableDispatchMethods.insert(GetNullarySelector("alloc"));
5834 VTableDispatchMethods.insert(GetNullarySelector("class"));
5835 VTableDispatchMethods.insert(GetNullarySelector("self"));
5836 VTableDispatchMethods.insert(GetNullarySelector("isFlipped"));
5837 VTableDispatchMethods.insert(GetNullarySelector("length"));
5838 VTableDispatchMethods.insert(GetNullarySelector("count"));
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005839
John McCall9e8bb002011-05-14 03:10:52 +00005840 // These are vtable-based if GC is disabled.
5841 // Optimistically use vtable dispatch for hybrid compiles.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005842 if (CGM.getLangOpts().getGC() != LangOptions::GCOnly) {
John McCall9e8bb002011-05-14 03:10:52 +00005843 VTableDispatchMethods.insert(GetNullarySelector("retain"));
5844 VTableDispatchMethods.insert(GetNullarySelector("release"));
5845 VTableDispatchMethods.insert(GetNullarySelector("autorelease"));
5846 }
5847
5848 VTableDispatchMethods.insert(GetUnarySelector("allocWithZone"));
5849 VTableDispatchMethods.insert(GetUnarySelector("isKindOfClass"));
5850 VTableDispatchMethods.insert(GetUnarySelector("respondsToSelector"));
5851 VTableDispatchMethods.insert(GetUnarySelector("objectForKey"));
5852 VTableDispatchMethods.insert(GetUnarySelector("objectAtIndex"));
5853 VTableDispatchMethods.insert(GetUnarySelector("isEqualToString"));
5854 VTableDispatchMethods.insert(GetUnarySelector("isEqual"));
5855
5856 // These are vtable-based if GC is enabled.
5857 // Optimistically use vtable dispatch for hybrid compiles.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005858 if (CGM.getLangOpts().getGC() != LangOptions::NonGC) {
John McCall9e8bb002011-05-14 03:10:52 +00005859 VTableDispatchMethods.insert(GetNullarySelector("hash"));
5860 VTableDispatchMethods.insert(GetUnarySelector("addObject"));
5861
5862 // "countByEnumeratingWithState:objects:count"
5863 IdentifierInfo *KeyIdents[] = {
5864 &CGM.getContext().Idents.get("countByEnumeratingWithState"),
5865 &CGM.getContext().Idents.get("objects"),
5866 &CGM.getContext().Idents.get("count")
5867 };
5868 VTableDispatchMethods.insert(
5869 CGM.getContext().Selectors.getSelector(3, KeyIdents));
5870 }
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +00005871 }
Daniel Dunbarfca18c1b42010-04-24 17:56:46 +00005872
John McCall9e8bb002011-05-14 03:10:52 +00005873 return VTableDispatchMethods.count(Sel);
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +00005874}
5875
Fariborz Jahanian9e3ad522009-01-24 20:21:50 +00005876/// BuildClassRoTInitializer - generate meta-data for:
5877/// struct _class_ro_t {
5878/// uint32_t const flags;
5879/// uint32_t const instanceStart;
5880/// uint32_t const instanceSize;
5881/// uint32_t const reserved; // only when building for 64bit targets
5882/// const uint8_t * const ivarLayout;
5883/// const char *const name;
5884/// const struct _method_list_t * const baseMethods;
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00005885/// const struct _protocol_list_t *const baseProtocols;
Fariborz Jahanian9e3ad522009-01-24 20:21:50 +00005886/// const struct _ivar_list_t *const ivars;
5887/// const uint8_t * const weakIvarLayout;
5888/// const struct _prop_list_t * const properties;
5889/// }
5890///
5891llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer(
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005892 unsigned flags,
5893 unsigned InstanceStart,
5894 unsigned InstanceSize,
5895 const ObjCImplementationDecl *ID) {
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00005896 std::string ClassName = ID->getObjCRuntimeNameAsString();
Benjamin Kramer22d24c22011-10-15 12:20:02 +00005897 llvm::Constant *Values[10]; // 11 for 64bit targets!
John McCall31168b02011-06-15 23:02:42 +00005898
John McCall3fd13f062015-10-21 18:06:47 +00005899 CharUnits beginInstance = CharUnits::fromQuantity(InstanceStart);
5900 CharUnits endInstance = CharUnits::fromQuantity(InstanceSize);
5901
John McCall460ce582015-10-22 18:38:17 +00005902 bool hasMRCWeak = false;
David Blaikiebbafb8a2012-03-11 07:00:24 +00005903 if (CGM.getLangOpts().ObjCAutoRefCount)
John McCallef19dbb2012-10-17 04:53:23 +00005904 flags |= NonFragileABI_Class_CompiledByARC;
John McCall460ce582015-10-22 18:38:17 +00005905 else if ((hasMRCWeak = hasMRCWeakIvars(CGM, ID)))
5906 flags |= NonFragileABI_Class_HasMRCWeakIvars;
John McCall31168b02011-06-15 23:02:42 +00005907
Owen Andersonb7a2fe62009-07-24 23:12:58 +00005908 Values[ 0] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
5909 Values[ 1] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceStart);
5910 Values[ 2] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceSize);
Fariborz Jahanian9e3ad522009-01-24 20:21:50 +00005911 // FIXME. For 64bit targets add 0 here.
John McCallef19dbb2012-10-17 04:53:23 +00005912 Values[ 3] = (flags & NonFragileABI_Class_Meta)
Craig Topper8a13c412014-05-21 05:09:00 +00005913 ? GetIvarLayoutName(nullptr, ObjCTypes)
John McCall460ce582015-10-22 18:38:17 +00005914 : BuildStrongIvarLayout(ID, beginInstance, endInstance);
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00005915 Values[ 4] = GetClassName(ID->getObjCRuntimeNameAsString());
Fariborz Jahanian99113fd2009-01-26 21:38:32 +00005916 // const struct _method_list_t * const baseMethods;
5917 std::vector<llvm::Constant*> Methods;
John McCallef19dbb2012-10-17 04:53:23 +00005918 if (flags & NonFragileABI_Class_Meta) {
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00005919 for (const auto *I : ID->class_methods())
Fariborz Jahanian99113fd2009-01-26 21:38:32 +00005920 // Class methods should always be defined.
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00005921 Methods.push_back(GetMethodConstant(I));
Fariborz Jahanian99113fd2009-01-26 21:38:32 +00005922 } else {
Aaron Ballmanf26acce2014-03-13 19:50:17 +00005923 for (const auto *I : ID->instance_methods())
Fariborz Jahanian99113fd2009-01-26 21:38:32 +00005924 // Instance methods should always be defined.
Aaron Ballmanf26acce2014-03-13 19:50:17 +00005925 Methods.push_back(GetMethodConstant(I));
5926
Aaron Ballmand85eff42014-03-14 15:02:45 +00005927 for (const auto *PID : ID->property_impls()) {
Fariborz Jahaniand27a8202009-01-28 22:46:49 +00005928 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize){
5929 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005930
Fariborz Jahaniand27a8202009-01-28 22:46:49 +00005931 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
5932 if (llvm::Constant *C = GetMethodConstant(MD))
5933 Methods.push_back(C);
5934 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
5935 if (llvm::Constant *C = GetMethodConstant(MD))
5936 Methods.push_back(C);
5937 }
5938 }
Fariborz Jahanian99113fd2009-01-26 21:38:32 +00005939 }
Saleem Abdulrasoold48b0a32016-10-24 20:47:58 +00005940
5941 Values[ 5] = EmitMethodList(ID->getObjCRuntimeNameAsString(),
5942 (flags & NonFragileABI_Class_Meta)
5943 ? MethodListType::ClassMethods
5944 : MethodListType::InstanceMethods,
5945 Methods);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005946
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00005947 const ObjCInterfaceDecl *OID = ID->getClassInterface();
5948 assert(OID && "CGObjCNonFragileABIMac::BuildClassRoTInitializer");
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005949 Values[ 6] = EmitProtocolList("\01l_OBJC_CLASS_PROTOCOLS_$_"
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00005950 + OID->getObjCRuntimeNameAsString(),
Ted Kremenek0ef508d2010-09-01 01:21:15 +00005951 OID->all_referenced_protocol_begin(),
5952 OID->all_referenced_protocol_end());
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005953
John McCallef19dbb2012-10-17 04:53:23 +00005954 if (flags & NonFragileABI_Class_Meta) {
Owen Anderson0b75f232009-07-31 20:28:54 +00005955 Values[ 7] = llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
Craig Topper8a13c412014-05-21 05:09:00 +00005956 Values[ 8] = GetIvarLayoutName(nullptr, ObjCTypes);
Manman Renad0e7912016-01-29 19:22:54 +00005957 Values[ 9] = EmitPropertyList(
5958 "\01l_OBJC_$_CLASS_PROP_LIST_" + ID->getObjCRuntimeNameAsString(),
5959 ID, ID->getClassInterface(), ObjCTypes, true);
John McCallef19dbb2012-10-17 04:53:23 +00005960 } else {
5961 Values[ 7] = EmitIvarList(ID);
John McCall460ce582015-10-22 18:38:17 +00005962 Values[ 8] = BuildWeakIvarLayout(ID, beginInstance, endInstance,
5963 hasMRCWeak);
Manman Renad0e7912016-01-29 19:22:54 +00005964 Values[ 9] = EmitPropertyList(
5965 "\01l_OBJC_$_PROP_LIST_" + ID->getObjCRuntimeNameAsString(),
5966 ID, ID->getClassInterface(), ObjCTypes, false);
John McCallef19dbb2012-10-17 04:53:23 +00005967 }
Owen Anderson0e0189d2009-07-27 22:29:56 +00005968 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassRonfABITy,
Fariborz Jahanian9e3ad522009-01-24 20:21:50 +00005969 Values);
Saleem Abdulrasool3c628af2016-10-25 21:43:28 +00005970
5971 llvm::SmallString<64> ROLabel;
5972 llvm::raw_svector_ostream(ROLabel)
5973 << ((flags & NonFragileABI_Class_Meta) ? "\01l_OBJC_METACLASS_RO_$_"
5974 : "\01l_OBJC_CLASS_RO_$_")
5975 << ClassName;
5976
Fariborz Jahanian9e3ad522009-01-24 20:21:50 +00005977 llvm::GlobalVariable *CLASS_RO_GV =
Saleem Abdulrasool3c628af2016-10-25 21:43:28 +00005978 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassRonfABITy, false,
5979 llvm::GlobalValue::PrivateLinkage, Init, ROLabel);
Fariborz Jahanianc22f2362009-01-31 02:43:27 +00005980 CLASS_RO_GV->setAlignment(
Micah Villmowdd31ca12012-10-08 16:25:52 +00005981 CGM.getDataLayout().getABITypeAlignment(ObjCTypes.ClassRonfABITy));
Saleem Abdulrasool3c628af2016-10-25 21:43:28 +00005982 if (CGM.getTriple().isOSBinFormatMachO())
5983 CLASS_RO_GV->setSection("__DATA, __objc_const");
Fariborz Jahanian9e3ad522009-01-24 20:21:50 +00005984 return CLASS_RO_GV;
5985}
5986
5987/// BuildClassMetaData - This routine defines that to-level meta-data
5988/// for the given ClassName for:
5989/// struct _class_t {
5990/// struct _class_t *isa;
5991/// struct _class_t * const superclass;
5992/// void *cache;
5993/// IMP *vtable;
5994/// struct class_ro_t *ro;
5995/// }
5996///
Rafael Espindola554256c2014-02-26 22:25:45 +00005997llvm::GlobalVariable *CGObjCNonFragileABIMac::BuildClassMetaData(
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00005998 const std::string &ClassName, llvm::Constant *IsAGV, llvm::Constant *SuperClassGV,
Rafael Espindola554256c2014-02-26 22:25:45 +00005999 llvm::Constant *ClassRoGV, bool HiddenVisibility, bool Weak) {
Benjamin Kramer22d24c22011-10-15 12:20:02 +00006000 llvm::Constant *Values[] = {
6001 IsAGV,
6002 SuperClassGV,
6003 ObjCEmptyCacheVar, // &ObjCEmptyCacheVar
6004 ObjCEmptyVtableVar, // &ObjCEmptyVtableVar
6005 ClassRoGV // &CLASS_RO_GV
6006 };
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006007 if (!Values[1])
6008 Values[1] = llvm::Constant::getNullValue(ObjCTypes.ClassnfABIPtrTy);
Fariborz Jahanian42d49552013-10-24 17:40:28 +00006009 if (!Values[3])
6010 Values[3] = llvm::Constant::getNullValue(
6011 llvm::PointerType::getUnqual(ObjCTypes.ImpnfABITy));
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006012 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassnfABITy,
Fariborz Jahanian9e3ad522009-01-24 20:21:50 +00006013 Values);
Rafael Espindola554256c2014-02-26 22:25:45 +00006014 llvm::GlobalVariable *GV = GetClassGlobal(ClassName, Weak);
Daniel Dunbarc6928bb2009-03-01 04:40:10 +00006015 GV->setInitializer(Init);
Saleem Abdulrasool3c628af2016-10-25 21:43:28 +00006016 if (CGM.getTriple().isOSBinFormatMachO())
6017 GV->setSection("__DATA, __objc_data");
Fariborz Jahanianc22f2362009-01-31 02:43:27 +00006018 GV->setAlignment(
Saleem Abdulrasool3c628af2016-10-25 21:43:28 +00006019 CGM.getDataLayout().getABITypeAlignment(ObjCTypes.ClassnfABITy));
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00006020 if (!CGM.getTriple().isOSBinFormatCOFF())
6021 if (HiddenVisibility)
6022 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahanian4723fb72009-01-24 21:21:53 +00006023 return GV;
Fariborz Jahanian9e3ad522009-01-24 20:21:50 +00006024}
6025
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006026bool
Fariborz Jahaniana6bed832009-05-21 01:03:45 +00006027CGObjCNonFragileABIMac::ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
Craig Topper8a13c412014-05-21 05:09:00 +00006028 return OD->getClassMethod(GetNullarySelector("load")) != nullptr;
Daniel Dunbar9a017d72009-05-15 22:33:15 +00006029}
6030
Daniel Dunbar961202372009-05-03 12:57:56 +00006031void CGObjCNonFragileABIMac::GetClassSizeInfo(const ObjCImplementationDecl *OID,
Daniel Dunbar554fd792009-04-19 23:41:48 +00006032 uint32_t &InstanceStart,
6033 uint32_t &InstanceSize) {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006034 const ASTRecordLayout &RL =
Daniel Dunbar9252ee12009-05-04 21:26:30 +00006035 CGM.getContext().getASTObjCImplementationLayout(OID);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006036
Daniel Dunbar9b042e02009-05-04 23:23:09 +00006037 // InstanceSize is really instance end.
Ken Dyckd5090c12011-02-11 02:20:09 +00006038 InstanceSize = RL.getDataSize().getQuantity();
Daniel Dunbar9b042e02009-05-04 23:23:09 +00006039
6040 // If there are no fields, the start is the same as the end.
6041 if (!RL.getFieldCount())
6042 InstanceStart = InstanceSize;
6043 else
Ken Dyckc5ca8762011-04-14 00:43:09 +00006044 InstanceStart = RL.getFieldOffset(0) / CGM.getContext().getCharWidth();
Daniel Dunbar554fd792009-04-19 23:41:48 +00006045}
6046
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00006047static llvm::GlobalValue::DLLStorageClassTypes getStorage(CodeGenModule &CGM,
6048 StringRef Name) {
6049 IdentifierInfo &II = CGM.getContext().Idents.get(Name);
6050 TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
6051 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
6052
6053 const VarDecl *VD = nullptr;
6054 for (const auto &Result : DC->lookup(&II))
6055 if ((VD = dyn_cast<VarDecl>(Result)))
6056 break;
6057
6058 if (!VD)
6059 return llvm::GlobalValue::DLLImportStorageClass;
6060 if (VD->hasAttr<DLLExportAttr>())
6061 return llvm::GlobalValue::DLLExportStorageClass;
6062 if (VD->hasAttr<DLLImportAttr>())
6063 return llvm::GlobalValue::DLLImportStorageClass;
6064 return llvm::GlobalValue::DefaultStorageClass;
6065}
6066
Fariborz Jahanian71394042009-01-23 23:53:38 +00006067void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) {
Fariborz Jahanian71394042009-01-23 23:53:38 +00006068 if (!ObjCEmptyCacheVar) {
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00006069 ObjCEmptyCacheVar =
6070 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.CacheTy, false,
6071 llvm::GlobalValue::ExternalLinkage, nullptr,
6072 "_objc_empty_cache");
6073 if (CGM.getTriple().isOSBinFormatCOFF())
6074 ObjCEmptyCacheVar->setDLLStorageClass(getStorage(CGM, "_objc_empty_cache"));
Craig Topper8a13c412014-05-21 05:09:00 +00006075
Saleem Abdulrasool4f515a62016-07-13 02:58:44 +00006076 // Only OS X with deployment version <10.9 use the empty vtable symbol
Fariborz Jahanian42d49552013-10-24 17:40:28 +00006077 const llvm::Triple &Triple = CGM.getTarget().getTriple();
Saleem Abdulrasool4f515a62016-07-13 02:58:44 +00006078 if (Triple.isMacOSX() && Triple.isMacOSXVersionLT(10, 9))
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00006079 ObjCEmptyVtableVar =
6080 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ImpnfABITy, false,
6081 llvm::GlobalValue::ExternalLinkage, nullptr,
6082 "_objc_empty_vtable");
Fariborz Jahanian71394042009-01-23 23:53:38 +00006083 }
Saleem Abdulrasoolbc2d9992016-07-16 22:42:04 +00006084
Daniel Dunbare3f5cfc2009-04-20 20:18:54 +00006085 // FIXME: Is this correct (that meta class size is never computed)?
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006086 uint32_t InstanceStart =
Micah Villmowdd31ca12012-10-08 16:25:52 +00006087 CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ClassnfABITy);
Fariborz Jahanian9e3ad522009-01-24 20:21:50 +00006088 uint32_t InstanceSize = InstanceStart;
John McCallef19dbb2012-10-17 04:53:23 +00006089 uint32_t flags = NonFragileABI_Class_Meta;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006090
Fariborz Jahanian9e3ad522009-01-24 20:21:50 +00006091 llvm::GlobalVariable *SuperClassGV, *IsAGV;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006092
Saleem Abdulrasool10fd1ff2016-07-16 22:42:06 +00006093 StringRef ClassName = ID->getObjCRuntimeNameAsString();
Saleem Abdulrasoolbc2d9992016-07-16 22:42:04 +00006094 const auto *CI = ID->getClassInterface();
6095 assert(CI && "CGObjCNonFragileABIMac::GenerateClass - class is 0");
6096
John McCall0d54a172012-10-17 04:53:31 +00006097 // Build the flags for the metaclass.
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00006098 bool classIsHidden = (CGM.getTriple().isOSBinFormatCOFF())
6099 ? !CI->hasAttr<DLLExportAttr>()
6100 : CI->getVisibility() == HiddenVisibility;
Fariborz Jahanian82208252009-01-31 00:59:10 +00006101 if (classIsHidden)
John McCallef19dbb2012-10-17 04:53:23 +00006102 flags |= NonFragileABI_Class_Hidden;
John McCall0d54a172012-10-17 04:53:31 +00006103
6104 // FIXME: why is this flag set on the metaclass?
6105 // ObjC metaclasses have no fields and don't really get constructed.
6106 if (ID->hasNonZeroConstructors() || ID->hasDestructors()) {
John McCallef19dbb2012-10-17 04:53:23 +00006107 flags |= NonFragileABI_Class_HasCXXStructors;
John McCall0d54a172012-10-17 04:53:31 +00006108 if (!ID->hasNonZeroConstructors())
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00006109 flags |= NonFragileABI_Class_HasCXXDestructorOnly;
John McCall0d54a172012-10-17 04:53:31 +00006110 }
6111
Saleem Abdulrasoolbc2d9992016-07-16 22:42:04 +00006112 if (!CI->getSuperClass()) {
Fariborz Jahanian9e3ad522009-01-24 20:21:50 +00006113 // class is root
John McCallef19dbb2012-10-17 04:53:23 +00006114 flags |= NonFragileABI_Class_Root;
Saleem Abdulrasoolbc2d9992016-07-16 22:42:04 +00006115
Saleem Abdulrasool10fd1ff2016-07-16 22:42:06 +00006116 SuperClassGV = GetClassGlobal((getClassSymbolPrefix() + ClassName).str(),
6117 CI->isWeakImported());
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00006118 if (CGM.getTriple().isOSBinFormatCOFF())
6119 if (CI->hasAttr<DLLImportAttr>())
6120 SuperClassGV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
Saleem Abdulrasoolbc2d9992016-07-16 22:42:04 +00006121
Saleem Abdulrasool10fd1ff2016-07-16 22:42:06 +00006122 IsAGV = GetClassGlobal((getMetaclassSymbolPrefix() + ClassName).str(),
6123 CI->isWeakImported());
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00006124 if (CGM.getTriple().isOSBinFormatCOFF())
6125 if (CI->hasAttr<DLLImportAttr>())
6126 IsAGV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
Fariborz Jahanian9e3ad522009-01-24 20:21:50 +00006127 } else {
Fariborz Jahanian4723fb72009-01-24 21:21:53 +00006128 // Has a root. Current class is not a root.
Fariborz Jahanian03b300b2009-02-26 18:23:47 +00006129 const ObjCInterfaceDecl *Root = ID->getClassInterface();
6130 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
6131 Root = Super;
Saleem Abdulrasoolbc2d9992016-07-16 22:42:04 +00006132
6133 const auto *Super = CI->getSuperClass();
Saleem Abdulrasool10fd1ff2016-07-16 22:42:06 +00006134 StringRef RootClassName = Root->getObjCRuntimeNameAsString();
6135 StringRef SuperClassName = Super->getObjCRuntimeNameAsString();
Saleem Abdulrasoolbc2d9992016-07-16 22:42:04 +00006136
Saleem Abdulrasool10fd1ff2016-07-16 22:42:06 +00006137 IsAGV = GetClassGlobal((getMetaclassSymbolPrefix() + RootClassName).str(),
6138 Root->isWeakImported());
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00006139 if (CGM.getTriple().isOSBinFormatCOFF())
6140 if (Root->hasAttr<DLLImportAttr>())
6141 IsAGV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006142
Fariborz Jahanian03b300b2009-02-26 18:23:47 +00006143 // work on super class metadata symbol.
Saleem Abdulrasool10fd1ff2016-07-16 22:42:06 +00006144 SuperClassGV =
6145 GetClassGlobal((getMetaclassSymbolPrefix() + SuperClassName).str(),
6146 Super->isWeakImported());
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00006147 if (CGM.getTriple().isOSBinFormatCOFF())
6148 if (Super->hasAttr<DLLImportAttr>())
6149 SuperClassGV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
Fariborz Jahanian9e3ad522009-01-24 20:21:50 +00006150 }
Saleem Abdulrasoolbc2d9992016-07-16 22:42:04 +00006151
6152 llvm::GlobalVariable *CLASS_RO_GV =
6153 BuildClassRoTInitializer(flags, InstanceStart, InstanceSize, ID);
6154
Saleem Abdulrasoolbc2d9992016-07-16 22:42:04 +00006155 llvm::GlobalVariable *MetaTClass =
Saleem Abdulrasool10fd1ff2016-07-16 22:42:06 +00006156 BuildClassMetaData((getMetaclassSymbolPrefix() + ClassName).str(), IsAGV,
6157 SuperClassGV, CLASS_RO_GV, classIsHidden,
6158 CI->isWeakImported());
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00006159 if (CGM.getTriple().isOSBinFormatCOFF())
6160 if (CI->hasAttr<DLLExportAttr>())
6161 MetaTClass->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
Fariborz Jahanian67260552009-11-17 21:37:35 +00006162 DefinedMetaClasses.push_back(MetaTClass);
Daniel Dunbar15894b72009-04-07 05:48:37 +00006163
Fariborz Jahanian4723fb72009-01-24 21:21:53 +00006164 // Metadata for the class
John McCallef19dbb2012-10-17 04:53:23 +00006165 flags = 0;
Fariborz Jahanian82208252009-01-31 00:59:10 +00006166 if (classIsHidden)
John McCallef19dbb2012-10-17 04:53:23 +00006167 flags |= NonFragileABI_Class_Hidden;
John McCall0d54a172012-10-17 04:53:31 +00006168
6169 if (ID->hasNonZeroConstructors() || ID->hasDestructors()) {
John McCallef19dbb2012-10-17 04:53:23 +00006170 flags |= NonFragileABI_Class_HasCXXStructors;
Daniel Dunbar8f28d012009-04-08 04:21:03 +00006171
John McCall0d54a172012-10-17 04:53:31 +00006172 // Set a flag to enable a runtime optimization when a class has
6173 // fields that require destruction but which don't require
6174 // anything except zero-initialization during construction. This
6175 // is most notably true of __strong and __weak types, but you can
6176 // also imagine there being C++ types with non-trivial default
6177 // constructors that merely set all fields to null.
6178 if (!ID->hasNonZeroConstructors())
6179 flags |= NonFragileABI_Class_HasCXXDestructorOnly;
6180 }
6181
Saleem Abdulrasoolbc2d9992016-07-16 22:42:04 +00006182 if (hasObjCExceptionAttribute(CGM.getContext(), CI))
John McCallef19dbb2012-10-17 04:53:23 +00006183 flags |= NonFragileABI_Class_Exception;
Daniel Dunbar8f28d012009-04-08 04:21:03 +00006184
Saleem Abdulrasoolbc2d9992016-07-16 22:42:04 +00006185 if (!CI->getSuperClass()) {
John McCallef19dbb2012-10-17 04:53:23 +00006186 flags |= NonFragileABI_Class_Root;
Craig Topper8a13c412014-05-21 05:09:00 +00006187 SuperClassGV = nullptr;
Chris Lattnerb433b272009-04-19 06:02:28 +00006188 } else {
Fariborz Jahanian4723fb72009-01-24 21:21:53 +00006189 // Has a root. Current class is not a root.
Saleem Abdulrasoolbc2d9992016-07-16 22:42:04 +00006190 const auto *Super = CI->getSuperClass();
Saleem Abdulrasool10fd1ff2016-07-16 22:42:06 +00006191 StringRef SuperClassName = Super->getObjCRuntimeNameAsString();
Saleem Abdulrasoolbc2d9992016-07-16 22:42:04 +00006192
Saleem Abdulrasool10fd1ff2016-07-16 22:42:06 +00006193 SuperClassGV =
6194 GetClassGlobal((getClassSymbolPrefix() + SuperClassName).str(),
6195 Super->isWeakImported());
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00006196 if (CGM.getTriple().isOSBinFormatCOFF())
6197 if (Super->hasAttr<DLLImportAttr>())
6198 SuperClassGV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
Fariborz Jahanian4723fb72009-01-24 21:21:53 +00006199 }
Saleem Abdulrasoolbc2d9992016-07-16 22:42:04 +00006200
Daniel Dunbar961202372009-05-03 12:57:56 +00006201 GetClassSizeInfo(ID, InstanceStart, InstanceSize);
Saleem Abdulrasoolbc2d9992016-07-16 22:42:04 +00006202 CLASS_RO_GV =
6203 BuildClassRoTInitializer(flags, InstanceStart, InstanceSize, ID);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006204
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006205 llvm::GlobalVariable *ClassMD =
Saleem Abdulrasool10fd1ff2016-07-16 22:42:06 +00006206 BuildClassMetaData((getClassSymbolPrefix() + ClassName).str(), MetaTClass,
6207 SuperClassGV, CLASS_RO_GV, classIsHidden,
6208 CI->isWeakImported());
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00006209 if (CGM.getTriple().isOSBinFormatCOFF())
6210 if (CI->hasAttr<DLLExportAttr>())
6211 ClassMD->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
Fariborz Jahanian279abd32009-01-30 20:55:31 +00006212 DefinedClasses.push_back(ClassMD);
Saleem Abdulrasoolbc2d9992016-07-16 22:42:04 +00006213 ImplementedClasses.push_back(CI);
Daniel Dunbar8f28d012009-04-08 04:21:03 +00006214
Daniel Dunbar9a017d72009-05-15 22:33:15 +00006215 // Determine if this class is also "non-lazy".
6216 if (ImplementationIsNonLazy(ID))
6217 DefinedNonLazyClasses.push_back(ClassMD);
6218
Daniel Dunbar8f28d012009-04-08 04:21:03 +00006219 // Force the definition of the EHType if necessary.
John McCallef19dbb2012-10-17 04:53:23 +00006220 if (flags & NonFragileABI_Class_Exception)
Saleem Abdulrasoolbc2d9992016-07-16 22:42:04 +00006221 GetInterfaceEHType(CI, true);
Fariborz Jahanianc0577942011-04-22 22:02:28 +00006222 // Make sure method definition entries are all clear for next implementation.
6223 MethodDefinitions.clear();
Fariborz Jahanian71394042009-01-23 23:53:38 +00006224}
6225
Fariborz Jahanian097feda2009-01-30 18:58:59 +00006226/// GenerateProtocolRef - This routine is called to generate code for
6227/// a protocol reference expression; as in:
6228/// @code
6229/// @protocol(Proto1);
6230/// @endcode
6231/// It generates a weak reference to l_OBJC_PROTOCOL_REFERENCE_$_Proto1
6232/// which will hold address of the protocol meta-data.
6233///
John McCall882987f2013-02-28 19:01:20 +00006234llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CodeGenFunction &CGF,
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006235 const ObjCProtocolDecl *PD) {
6236
Fariborz Jahanian464423d2009-04-10 18:47:34 +00006237 // This routine is called for @protocol only. So, we must build definition
6238 // of protocol's meta-data (not a reference to it!)
6239 //
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006240 llvm::Constant *Init =
6241 llvm::ConstantExpr::getBitCast(GetOrEmitProtocol(PD),
Douglas Gregor020de322012-01-17 18:36:30 +00006242 ObjCTypes.getExternalProtocolPtrTy());
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006243
Fariborz Jahanian097feda2009-01-30 18:58:59 +00006244 std::string ProtocolName("\01l_OBJC_PROTOCOL_REFERENCE_$_");
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006245 ProtocolName += PD->getObjCRuntimeNameAsString();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006246
John McCall7f416cc2015-09-08 08:05:57 +00006247 CharUnits Align = CGF.getPointerAlign();
6248
Fariborz Jahanian097feda2009-01-30 18:58:59 +00006249 llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName);
6250 if (PTGV)
John McCall7f416cc2015-09-08 08:05:57 +00006251 return CGF.Builder.CreateAlignedLoad(PTGV, Align);
Fariborz Jahanian097feda2009-01-30 18:58:59 +00006252 PTGV = new llvm::GlobalVariable(
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006253 CGM.getModule(),
6254 Init->getType(), false,
Rafael Espindola70efc5b2014-03-06 18:54:12 +00006255 llvm::GlobalValue::WeakAnyLinkage,
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006256 Init,
6257 ProtocolName);
Fariborz Jahanian097feda2009-01-30 18:58:59 +00006258 PTGV->setSection("__DATA, __objc_protorefs, coalesced, no_dead_strip");
Rafael Espindola70efc5b2014-03-06 18:54:12 +00006259 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
John McCall7f416cc2015-09-08 08:05:57 +00006260 PTGV->setAlignment(Align.getQuantity());
Rafael Espindola060062a2014-03-06 22:15:10 +00006261 CGM.addCompilerUsedGlobal(PTGV);
John McCall7f416cc2015-09-08 08:05:57 +00006262 return CGF.Builder.CreateAlignedLoad(PTGV, Align);
Fariborz Jahanian097feda2009-01-30 18:58:59 +00006263}
6264
Fariborz Jahanian0c8d0602009-01-26 18:32:24 +00006265/// GenerateCategory - Build metadata for a category implementation.
6266/// struct _category_t {
6267/// const char * const name;
6268/// struct _class_t *const cls;
6269/// const struct _method_list_t * const instance_methods;
6270/// const struct _method_list_t * const class_methods;
6271/// const struct _protocol_list_t * const protocols;
6272/// const struct _prop_list_t * const properties;
Manman Ren96df0b32016-01-29 23:45:01 +00006273/// const struct _prop_list_t * const class_properties;
Manman Ren42ff3902016-02-24 17:49:50 +00006274/// const uint32_t size;
Fariborz Jahanian0c8d0602009-01-26 18:32:24 +00006275/// }
6276///
Daniel Dunbar9a017d72009-05-15 22:33:15 +00006277void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Fariborz Jahanian0c8d0602009-01-26 18:32:24 +00006278 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Fariborz Jahanian2612e142009-01-26 22:58:07 +00006279 const char *Prefix = "\01l_OBJC_$_CATEGORY_";
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006280
6281 llvm::SmallString<64> ExtCatName(Prefix);
6282 ExtCatName += Interface->getObjCRuntimeNameAsString();
6283 ExtCatName += "_$_";
6284 ExtCatName += OCD->getNameAsString();
6285
6286 llvm::SmallString<64> ExtClassName(getClassSymbolPrefix());
6287 ExtClassName += Interface->getObjCRuntimeNameAsString();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006288
Manman Ren42ff3902016-02-24 17:49:50 +00006289 llvm::Constant *Values[8];
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006290 Values[0] = GetClassName(OCD->getIdentifier()->getName());
Fariborz Jahanian0c8d0602009-01-26 18:32:24 +00006291 // meta-class entry symbol
Rafael Espindola554256c2014-02-26 22:25:45 +00006292 llvm::GlobalVariable *ClassGV =
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006293 GetClassGlobal(ExtClassName.str(), Interface->isWeakImported());
Rafael Espindola554256c2014-02-26 22:25:45 +00006294
Fariborz Jahanian0c8d0602009-01-26 18:32:24 +00006295 Values[1] = ClassGV;
Fariborz Jahanian2612e142009-01-26 22:58:07 +00006296 std::vector<llvm::Constant*> Methods;
Saleem Abdulrasool209150a2016-10-24 21:25:57 +00006297 std::string ListName =
6298 (Interface->getObjCRuntimeNameAsString() + "_$_" + OCD->getName()).str();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006299
Aaron Ballmanf26acce2014-03-13 19:50:17 +00006300 for (const auto *I : OCD->instance_methods())
Fariborz Jahanian2612e142009-01-26 22:58:07 +00006301 // Instance methods should always be defined.
Aaron Ballmanf26acce2014-03-13 19:50:17 +00006302 Methods.push_back(GetMethodConstant(I));
Saleem Abdulrasoold48b0a32016-10-24 20:47:58 +00006303 Values[2] = EmitMethodList(ListName, MethodListType::CategoryInstanceMethods,
Fariborz Jahanian2612e142009-01-26 22:58:07 +00006304 Methods);
6305
Fariborz Jahanian2612e142009-01-26 22:58:07 +00006306 Methods.clear();
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00006307 for (const auto *I : OCD->class_methods())
Fariborz Jahanian2612e142009-01-26 22:58:07 +00006308 // Class methods should always be defined.
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00006309 Methods.push_back(GetMethodConstant(I));
Saleem Abdulrasoold48b0a32016-10-24 20:47:58 +00006310 Values[3] =
6311 EmitMethodList(ListName, MethodListType::CategoryClassMethods, Methods);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006312
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006313 const ObjCCategoryDecl *Category =
Fariborz Jahanian066347e2009-01-28 22:18:42 +00006314 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Fariborz Jahaniand8fc1052009-02-13 17:52:22 +00006315 if (Category) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00006316 SmallString<256> ExtName;
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006317 llvm::raw_svector_ostream(ExtName) << Interface->getObjCRuntimeNameAsString() << "_$_"
Daniel Dunbar349e6fb2009-10-18 20:48:59 +00006318 << OCD->getName();
Fariborz Jahaniand8fc1052009-02-13 17:52:22 +00006319 Values[4] = EmitProtocolList("\01l_OBJC_CATEGORY_PROTOCOLS_$_"
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006320 + Interface->getObjCRuntimeNameAsString() + "_$_"
6321 + Category->getName(),
6322 Category->protocol_begin(),
6323 Category->protocol_end());
Daniel Dunbar349e6fb2009-10-18 20:48:59 +00006324 Values[5] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ExtName.str(),
Manman Renad0e7912016-01-29 19:22:54 +00006325 OCD, Category, ObjCTypes, false);
Manman Ren96df0b32016-01-29 23:45:01 +00006326 Values[6] = EmitPropertyList("\01l_OBJC_$_CLASS_PROP_LIST_" + ExtName.str(),
6327 OCD, Category, ObjCTypes, true);
Mike Stump658fe022009-07-30 22:28:39 +00006328 } else {
Owen Anderson0b75f232009-07-31 20:28:54 +00006329 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
6330 Values[5] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
Manman Ren96df0b32016-01-29 23:45:01 +00006331 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
Fariborz Jahaniand8fc1052009-02-13 17:52:22 +00006332 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006333
Manman Ren42ff3902016-02-24 17:49:50 +00006334 unsigned Size = CGM.getDataLayout().getTypeAllocSize(ObjCTypes.CategorynfABITy);
6335 Values[7] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
6336
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006337 llvm::Constant *Init =
6338 llvm::ConstantStruct::get(ObjCTypes.CategorynfABITy,
Fariborz Jahanian0c8d0602009-01-26 18:32:24 +00006339 Values);
6340 llvm::GlobalVariable *GCATV
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006341 = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.CategorynfABITy,
Fariborz Jahanian0c8d0602009-01-26 18:32:24 +00006342 false,
Rafael Espindola5179a4e2014-02-27 19:01:11 +00006343 llvm::GlobalValue::PrivateLinkage,
Fariborz Jahanian0c8d0602009-01-26 18:32:24 +00006344 Init,
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006345 ExtCatName.str());
Fariborz Jahanianc22f2362009-01-31 02:43:27 +00006346 GCATV->setAlignment(
Micah Villmowdd31ca12012-10-08 16:25:52 +00006347 CGM.getDataLayout().getABITypeAlignment(ObjCTypes.CategorynfABITy));
Saleem Abdulrasool3c628af2016-10-25 21:43:28 +00006348 if (CGM.getTriple().isOSBinFormatMachO())
6349 GCATV->setSection("__DATA, __objc_const");
Rafael Espindola060062a2014-03-06 22:15:10 +00006350 CGM.addCompilerUsedGlobal(GCATV);
Fariborz Jahanian0c8d0602009-01-26 18:32:24 +00006351 DefinedCategories.push_back(GCATV);
Daniel Dunbar9a017d72009-05-15 22:33:15 +00006352
6353 // Determine if this category is also "non-lazy".
6354 if (ImplementationIsNonLazy(OCD))
6355 DefinedNonLazyCategories.push_back(GCATV);
Fariborz Jahanianc0577942011-04-22 22:02:28 +00006356 // method definition entries must be clear for next implementation.
6357 MethodDefinitions.clear();
Fariborz Jahanian0c8d0602009-01-26 18:32:24 +00006358}
Fariborz Jahanian99113fd2009-01-26 21:38:32 +00006359
6360/// GetMethodConstant - Return a struct objc_method constant for the
6361/// given method if it has been defined. The result is null if the
6362/// method has not been defined. The return value has type MethodPtrTy.
6363llvm::Constant *CGObjCNonFragileABIMac::GetMethodConstant(
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006364 const ObjCMethodDecl *MD) {
Argyrios Kyrtzidis13257c52010-08-09 10:54:20 +00006365 llvm::Function *Fn = GetMethodDefinition(MD);
Fariborz Jahanian99113fd2009-01-26 21:38:32 +00006366 if (!Fn)
Craig Topper8a13c412014-05-21 05:09:00 +00006367 return nullptr;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006368
Benjamin Kramer22d24c22011-10-15 12:20:02 +00006369 llvm::Constant *Method[] = {
Owen Andersonade90fd2009-07-29 18:54:39 +00006370 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
Benjamin Kramer22d24c22011-10-15 12:20:02 +00006371 ObjCTypes.SelectorPtrTy),
6372 GetMethodVarType(MD),
6373 llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy)
6374 };
Owen Anderson0e0189d2009-07-27 22:29:56 +00006375 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
Fariborz Jahanian99113fd2009-01-26 21:38:32 +00006376}
6377
6378/// EmitMethodList - Build meta-data for method declarations
6379/// struct _method_list_t {
6380/// uint32_t entsize; // sizeof(struct _objc_method)
6381/// uint32_t method_count;
6382/// struct _objc_method method_list[method_count];
6383/// }
6384///
Bill Wendlingcb5b5ff2012-02-07 09:25:09 +00006385llvm::Constant *
Saleem Abdulrasoold48b0a32016-10-24 20:47:58 +00006386CGObjCNonFragileABIMac::EmitMethodList(Twine Name, MethodListType MLT,
Saleem Abdulrasool1e6c4062016-05-16 05:06:49 +00006387 ArrayRef<llvm::Constant *> Methods) {
Fariborz Jahanian99113fd2009-01-26 21:38:32 +00006388 // Return null for empty list.
6389 if (Methods.empty())
Owen Anderson0b75f232009-07-31 20:28:54 +00006390 return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006391
Chris Lattnere64d7ba2011-06-20 04:01:35 +00006392 llvm::Constant *Values[3];
Fariborz Jahanian99113fd2009-01-26 21:38:32 +00006393 // sizeof(struct _objc_method)
Micah Villmowdd31ca12012-10-08 16:25:52 +00006394 unsigned Size = CGM.getDataLayout().getTypeAllocSize(ObjCTypes.MethodTy);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00006395 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Fariborz Jahanian99113fd2009-01-26 21:38:32 +00006396 // method_count
Owen Andersonb7a2fe62009-07-24 23:12:58 +00006397 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
Owen Anderson9793f0e2009-07-29 22:16:19 +00006398 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
Fariborz Jahanian99113fd2009-01-26 21:38:32 +00006399 Methods.size());
Owen Anderson47034e12009-07-28 18:33:04 +00006400 Values[2] = llvm::ConstantArray::get(AT, Methods);
Chris Lattnere64d7ba2011-06-20 04:01:35 +00006401 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006402
Saleem Abdulrasoold48b0a32016-10-24 20:47:58 +00006403 StringRef Prefix;
6404 switch (MLT) {
6405 case MethodListType::CategoryInstanceMethods:
6406 Prefix = "\01l_OBJC_$_CATEGORY_INSTANCE_METHODS_";
6407 break;
6408 case MethodListType::CategoryClassMethods:
6409 Prefix = "\01l_OBJC_$_CATEGORY_CLASS_METHODS_";
6410 break;
6411 case MethodListType::InstanceMethods:
6412 Prefix = "\01l_OBJC_$_INSTANCE_METHODS_";
6413 break;
6414 case MethodListType::ClassMethods:
6415 Prefix = "\01l_OBJC_$_CLASS_METHODS_";
6416 break;
6417
6418 case MethodListType::ProtocolInstanceMethods:
6419 Prefix = "\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_";
6420 break;
6421 case MethodListType::ProtocolClassMethods:
6422 Prefix = "\01l_OBJC_$_PROTOCOL_CLASS_METHODS_";
6423 break;
6424 case MethodListType::OptionalProtocolInstanceMethods:
6425 Prefix = "\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_";
6426 break;
6427 case MethodListType::OptionalProtocolClassMethods:
6428 Prefix = "\01l_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_";
6429 break;
6430 }
6431
6432 auto *GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(), false,
6433 llvm::GlobalValue::PrivateLinkage, Init,
6434 Prefix + Name);
Micah Villmowdd31ca12012-10-08 16:25:52 +00006435 GV->setAlignment(CGM.getDataLayout().getABITypeAlignment(Init->getType()));
Saleem Abdulrasool3c628af2016-10-25 21:43:28 +00006436 if (CGM.getTriple().isOSBinFormatMachO())
6437 GV->setSection("__DATA, __objc_const");
Rafael Espindola060062a2014-03-06 22:15:10 +00006438 CGM.addCompilerUsedGlobal(GV);
Chris Lattnere64d7ba2011-06-20 04:01:35 +00006439 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.MethodListnfABIPtrTy);
Fariborz Jahanian99113fd2009-01-26 21:38:32 +00006440}
Fariborz Jahanian7415caa2009-01-27 19:38:51 +00006441
Fariborz Jahanian4e7ae062009-02-10 20:21:06 +00006442/// ObjCIvarOffsetVariable - Returns the ivar offset variable for
6443/// the given ivar.
Daniel Dunbar8c7f9812010-04-02 21:14:02 +00006444llvm::GlobalVariable *
6445CGObjCNonFragileABIMac::ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
6446 const ObjCIvarDecl *Ivar) {
6447 const ObjCInterfaceDecl *Container = Ivar->getContainingInterface();
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006448 llvm::SmallString<64> Name("OBJC_IVAR_$_");
6449 Name += Container->getObjCRuntimeNameAsString();
6450 Name += ".";
6451 Name += Ivar->getName();
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00006452 llvm::GlobalVariable *IvarOffsetGV = CGM.getModule().getGlobalVariable(Name);
6453 if (!IvarOffsetGV) {
6454 IvarOffsetGV =
6455 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.IvarOffsetVarTy,
6456 false, llvm::GlobalValue::ExternalLinkage,
6457 nullptr, Name.str());
6458 if (CGM.getTriple().isOSBinFormatCOFF()) {
6459 bool IsPrivateOrPackage =
6460 Ivar->getAccessControl() == ObjCIvarDecl::Private ||
6461 Ivar->getAccessControl() == ObjCIvarDecl::Package;
6462
6463 if (ID->hasAttr<DLLExportAttr>() && !IsPrivateOrPackage)
6464 IvarOffsetGV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
6465 else if (ID->hasAttr<DLLImportAttr>())
6466 IvarOffsetGV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
6467 }
6468 }
Fariborz Jahanian4e7ae062009-02-10 20:21:06 +00006469 return IvarOffsetGV;
6470}
6471
Daniel Dunbar8c7f9812010-04-02 21:14:02 +00006472llvm::Constant *
6473CGObjCNonFragileABIMac::EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,
6474 const ObjCIvarDecl *Ivar,
Eli Friedman8cbca202012-11-06 22:15:52 +00006475 unsigned long int Offset) {
Daniel Dunbarbf90b332009-04-19 00:44:02 +00006476 llvm::GlobalVariable *IvarOffsetGV = ObjCIvarOffsetVariable(ID, Ivar);
Tim Northover238b5082014-03-29 13:42:40 +00006477 IvarOffsetGV->setInitializer(
6478 llvm::ConstantInt::get(ObjCTypes.IvarOffsetVarTy, Offset));
Fariborz Jahanianc22f2362009-01-31 02:43:27 +00006479 IvarOffsetGV->setAlignment(
Tim Northover238b5082014-03-29 13:42:40 +00006480 CGM.getDataLayout().getABITypeAlignment(ObjCTypes.IvarOffsetVarTy));
Daniel Dunbarbf90b332009-04-19 00:44:02 +00006481
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00006482 if (!CGM.getTriple().isOSBinFormatCOFF()) {
6483 // FIXME: This matches gcc, but shouldn't the visibility be set on the use
6484 // as well (i.e., in ObjCIvarOffsetVariable).
6485 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
6486 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
6487 ID->getVisibility() == HiddenVisibility)
6488 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
6489 else
6490 IvarOffsetGV->setVisibility(llvm::GlobalValue::DefaultVisibility);
6491 }
6492
Saleem Abdulrasool3c628af2016-10-25 21:43:28 +00006493 if (CGM.getTriple().isOSBinFormatMachO())
6494 IvarOffsetGV->setSection("__DATA, __objc_ivar");
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00006495 return IvarOffsetGV;
Fariborz Jahanian40a4bcd2009-01-28 01:05:23 +00006496}
6497
Fariborz Jahanian7415caa2009-01-27 19:38:51 +00006498/// EmitIvarList - Emit the ivar list for the given
Daniel Dunbar508a7dd2009-04-18 08:51:00 +00006499/// implementation. The return value has type
Fariborz Jahanian7415caa2009-01-27 19:38:51 +00006500/// IvarListnfABIPtrTy.
6501/// struct _ivar_t {
Tim Northover238b5082014-03-29 13:42:40 +00006502/// unsigned [long] int *offset; // pointer to ivar offset location
Fariborz Jahanian7415caa2009-01-27 19:38:51 +00006503/// char *name;
6504/// char *type;
6505/// uint32_t alignment;
6506/// uint32_t size;
6507/// }
6508/// struct _ivar_list_t {
6509/// uint32 entsize; // sizeof(struct _ivar_t)
6510/// uint32 count;
6511/// struct _iver_t list[count];
6512/// }
6513///
Daniel Dunbarf5c18462009-04-20 06:54:31 +00006514
Fariborz Jahanian7415caa2009-01-27 19:38:51 +00006515llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList(
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006516 const ObjCImplementationDecl *ID) {
6517
Benjamin Kramer22d24c22011-10-15 12:20:02 +00006518 std::vector<llvm::Constant*> Ivars;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006519
Jordy Rosea91768e2011-07-22 02:08:32 +00006520 const ObjCInterfaceDecl *OID = ID->getClassInterface();
Fariborz Jahanian7415caa2009-01-27 19:38:51 +00006521 assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface");
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006522
Fariborz Jahanian40a4bcd2009-01-28 01:05:23 +00006523 // FIXME. Consolidate this with similar code in GenerateClass.
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006524
Jordy Rosea91768e2011-07-22 02:08:32 +00006525 for (const ObjCIvarDecl *IVD = OID->all_declared_ivar_begin();
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00006526 IVD; IVD = IVD->getNextIvar()) {
Fariborz Jahanian7c809592009-06-04 01:19:09 +00006527 // Ignore unnamed bit-fields.
6528 if (!IVD->getDeclName())
6529 continue;
Benjamin Kramer22d24c22011-10-15 12:20:02 +00006530 llvm::Constant *Ivar[5];
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006531 Ivar[0] = EmitIvarOffsetVar(ID->getClassInterface(), IVD,
Daniel Dunbar961202372009-05-03 12:57:56 +00006532 ComputeIvarBaseOffset(CGM, ID, IVD));
Daniel Dunbar725dc2c2009-04-22 08:22:17 +00006533 Ivar[1] = GetMethodVarName(IVD->getIdentifier());
6534 Ivar[2] = GetMethodVarType(IVD);
Chris Lattner2192fe52011-07-18 04:24:23 +00006535 llvm::Type *FieldTy =
Daniel Dunbar725dc2c2009-04-22 08:22:17 +00006536 CGM.getTypes().ConvertTypeForMem(IVD->getType());
Micah Villmowdd31ca12012-10-08 16:25:52 +00006537 unsigned Size = CGM.getDataLayout().getTypeAllocSize(FieldTy);
Fariborz Jahanian7415caa2009-01-27 19:38:51 +00006538 unsigned Align = CGM.getContext().getPreferredTypeAlign(
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006539 IVD->getType().getTypePtr()) >> 3;
Fariborz Jahanian7415caa2009-01-27 19:38:51 +00006540 Align = llvm::Log2_32(Align);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00006541 Ivar[3] = llvm::ConstantInt::get(ObjCTypes.IntTy, Align);
Daniel Dunbarae032262009-04-20 00:33:43 +00006542 // NOTE. Size of a bitfield does not match gcc's, because of the
6543 // way bitfields are treated special in each. But I am told that
6544 // 'size' for bitfield ivars is ignored by the runtime so it does
6545 // not matter. If it matters, there is enough info to get the
6546 // bitfield right!
Owen Andersonb7a2fe62009-07-24 23:12:58 +00006547 Ivar[4] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Owen Anderson0e0189d2009-07-27 22:29:56 +00006548 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarnfABITy, Ivar));
Fariborz Jahanian7415caa2009-01-27 19:38:51 +00006549 }
6550 // Return null for empty list.
6551 if (Ivars.empty())
Owen Anderson0b75f232009-07-31 20:28:54 +00006552 return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
Chris Lattnere64d7ba2011-06-20 04:01:35 +00006553
6554 llvm::Constant *Values[3];
Micah Villmowdd31ca12012-10-08 16:25:52 +00006555 unsigned Size = CGM.getDataLayout().getTypeAllocSize(ObjCTypes.IvarnfABITy);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00006556 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
6557 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
Owen Anderson9793f0e2009-07-29 22:16:19 +00006558 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarnfABITy,
Fariborz Jahanian7415caa2009-01-27 19:38:51 +00006559 Ivars.size());
Owen Anderson47034e12009-07-28 18:33:04 +00006560 Values[2] = llvm::ConstantArray::get(AT, Ivars);
Chris Lattnere64d7ba2011-06-20 04:01:35 +00006561 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
Fariborz Jahanian7415caa2009-01-27 19:38:51 +00006562 const char *Prefix = "\01l_OBJC_$_INSTANCE_VARIABLES_";
6563 llvm::GlobalVariable *GV =
Owen Andersonc10c8d32009-07-08 19:05:04 +00006564 new llvm::GlobalVariable(CGM.getModule(), Init->getType(), false,
Rafael Espindola5179a4e2014-02-27 19:01:11 +00006565 llvm::GlobalValue::PrivateLinkage,
Fariborz Jahanian7415caa2009-01-27 19:38:51 +00006566 Init,
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006567 Prefix + OID->getObjCRuntimeNameAsString());
Fariborz Jahanianc22f2362009-01-31 02:43:27 +00006568 GV->setAlignment(
Micah Villmowdd31ca12012-10-08 16:25:52 +00006569 CGM.getDataLayout().getABITypeAlignment(Init->getType()));
Saleem Abdulrasool3c628af2016-10-25 21:43:28 +00006570 if (CGM.getTriple().isOSBinFormatMachO())
6571 GV->setSection("__DATA, __objc_const");
Rafael Espindola060062a2014-03-06 22:15:10 +00006572 CGM.addCompilerUsedGlobal(GV);
Owen Andersonade90fd2009-07-29 18:54:39 +00006573 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.IvarListnfABIPtrTy);
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006574}
6575
6576llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef(
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006577 const ObjCProtocolDecl *PD) {
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006578 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006579
Saleem Abdulrasool9ccc7ad2016-10-25 14:50:44 +00006580 if (!Entry) {
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006581 // We use the initializer as a marker of whether this is a forward
6582 // reference or not. At module finalization we add the empty
6583 // contents for protocols which were referenced but never defined.
Saleem Abdulrasool9ccc7ad2016-10-25 14:50:44 +00006584 llvm::SmallString<64> Protocol;
6585 llvm::raw_svector_ostream(Protocol) << "\01l_OBJC_PROTOCOL_$_"
6586 << PD->getObjCRuntimeNameAsString();
6587
6588 Entry = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ProtocolnfABITy,
6589 false, llvm::GlobalValue::ExternalLinkage,
6590 nullptr, Protocol);
6591 if (!CGM.getTriple().isOSBinFormatMachO())
6592 Entry->setComdat(CGM.getModule().getOrInsertComdat(Protocol));
6593 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006594
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006595 return Entry;
6596}
6597
6598/// GetOrEmitProtocol - Generate the protocol meta-data:
6599/// @code
6600/// struct _protocol_t {
6601/// id isa; // NULL
6602/// const char * const protocol_name;
6603/// const struct _protocol_list_t * protocol_list; // super protocols
6604/// const struct method_list_t * const instance_methods;
6605/// const struct method_list_t * const class_methods;
6606/// const struct method_list_t *optionalInstanceMethods;
6607/// const struct method_list_t *optionalClassMethods;
6608/// const struct _prop_list_t * properties;
6609/// const uint32_t size; // sizeof(struct _protocol_t)
6610/// const uint32_t flags; // = 0
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006611/// const char ** extendedMethodTypes;
Fariborz Jahanian6a9c46b2015-03-31 22:22:40 +00006612/// const char *demangledName;
Manman Rence7bff52016-01-29 23:46:55 +00006613/// const struct _prop_list_t * class_properties;
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006614/// }
6615/// @endcode
6616///
6617
6618llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol(
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006619 const ObjCProtocolDecl *PD) {
John McCallf9582a72012-03-30 21:29:05 +00006620 llvm::GlobalVariable *Entry = Protocols[PD->getIdentifier()];
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006621
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006622 // Early exit if a defining object has already been generated.
6623 if (Entry && Entry->hasInitializer())
6624 return Entry;
6625
Douglas Gregora715bff2012-01-01 19:51:50 +00006626 // Use the protocol definition, if there is one.
6627 if (const ObjCProtocolDecl *Def = PD->getDefinition())
6628 PD = Def;
6629
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006630 // Construct method lists.
6631 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
6632 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006633 std::vector<llvm::Constant*> MethodTypesExt, OptMethodTypesExt;
Aaron Ballmanf26acce2014-03-13 19:50:17 +00006634 for (const auto *MD : PD->instance_methods()) {
Fariborz Jahaniand9c28b82009-01-30 00:46:37 +00006635 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Douglas Gregora9d84932011-05-27 01:19:52 +00006636 if (!C)
6637 return GetOrEmitProtocolRef(PD);
6638
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006639 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6640 OptInstanceMethods.push_back(C);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006641 OptMethodTypesExt.push_back(GetMethodVarType(MD, true));
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006642 } else {
6643 InstanceMethods.push_back(C);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006644 MethodTypesExt.push_back(GetMethodVarType(MD, true));
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006645 }
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006646 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006647
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00006648 for (const auto *MD : PD->class_methods()) {
Fariborz Jahaniand9c28b82009-01-30 00:46:37 +00006649 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Douglas Gregora9d84932011-05-27 01:19:52 +00006650 if (!C)
6651 return GetOrEmitProtocolRef(PD);
6652
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006653 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6654 OptClassMethods.push_back(C);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006655 OptMethodTypesExt.push_back(GetMethodVarType(MD, true));
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006656 } else {
6657 ClassMethods.push_back(C);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006658 MethodTypesExt.push_back(GetMethodVarType(MD, true));
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006659 }
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006660 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006661
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006662 MethodTypesExt.insert(MethodTypesExt.end(),
6663 OptMethodTypesExt.begin(), OptMethodTypesExt.end());
6664
Manman Rence7bff52016-01-29 23:46:55 +00006665 llvm::Constant *Values[13];
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006666 // isa is NULL
Owen Anderson0b75f232009-07-31 20:28:54 +00006667 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ObjectPtrTy);
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006668 Values[1] = GetClassName(PD->getObjCRuntimeNameAsString());
6669 Values[2] = EmitProtocolList("\01l_OBJC_$_PROTOCOL_REFS_" + PD->getObjCRuntimeNameAsString(),
Daniel Dunbar349e6fb2009-10-18 20:48:59 +00006670 PD->protocol_begin(),
6671 PD->protocol_end());
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006672
Saleem Abdulrasoold48b0a32016-10-24 20:47:58 +00006673 Values[3] =
6674 EmitMethodList(PD->getObjCRuntimeNameAsString(),
6675 MethodListType::ProtocolInstanceMethods, InstanceMethods);
6676 Values[4] =
6677 EmitMethodList(PD->getObjCRuntimeNameAsString(),
6678 MethodListType::ProtocolClassMethods, ClassMethods);
6679 Values[5] = EmitMethodList(PD->getObjCRuntimeNameAsString(),
6680 MethodListType::OptionalProtocolInstanceMethods,
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006681 OptInstanceMethods);
Saleem Abdulrasoold48b0a32016-10-24 20:47:58 +00006682 Values[6] = EmitMethodList(PD->getObjCRuntimeNameAsString(),
6683 MethodListType::OptionalProtocolClassMethods,
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006684 OptClassMethods);
Saleem Abdulrasoold48b0a32016-10-24 20:47:58 +00006685
Manman Renad0e7912016-01-29 19:22:54 +00006686 Values[7] = EmitPropertyList(
6687 "\01l_OBJC_$_PROP_LIST_" + PD->getObjCRuntimeNameAsString(),
6688 nullptr, PD, ObjCTypes, false);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006689 uint32_t Size =
Micah Villmowdd31ca12012-10-08 16:25:52 +00006690 CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ProtocolnfABITy);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00006691 Values[8] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Owen Anderson0b75f232009-07-31 20:28:54 +00006692 Values[9] = llvm::Constant::getNullValue(ObjCTypes.IntTy);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006693 Values[10] = EmitProtocolMethodTypes("\01l_OBJC_$_PROTOCOL_METHOD_TYPES_"
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006694 + PD->getObjCRuntimeNameAsString(),
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006695 MethodTypesExt, ObjCTypes);
Fariborz Jahanian6a9c46b2015-03-31 22:22:40 +00006696 // const char *demangledName;
6697 Values[11] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Manman Rence7bff52016-01-29 23:46:55 +00006698
6699 Values[12] = EmitPropertyList(
6700 "\01l_OBJC_$_CLASS_PROP_LIST_" + PD->getObjCRuntimeNameAsString(),
6701 nullptr, PD, ObjCTypes, true);
Fariborz Jahanian6a9c46b2015-03-31 22:22:40 +00006702
Owen Anderson0e0189d2009-07-27 22:29:56 +00006703 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolnfABITy,
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006704 Values);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006705
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006706 if (Entry) {
Rafael Espindola24615092014-09-12 20:14:20 +00006707 // Already created, fix the linkage and update the initializer.
6708 Entry->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006709 Entry->setInitializer(Init);
6710 } else {
Saleem Abdulrasool9ccc7ad2016-10-25 14:50:44 +00006711 llvm::SmallString<64> Protocol;
6712 llvm::raw_svector_ostream(Protocol) << "\01l_OBJC_PROTOCOL_$_"
6713 << PD->getObjCRuntimeNameAsString();
6714
6715 Entry = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ProtocolnfABITy,
6716 false, llvm::GlobalValue::WeakAnyLinkage,
6717 Init, Protocol);
6718 if (!CGM.getTriple().isOSBinFormatMachO())
6719 Entry->setComdat(CGM.getModule().getOrInsertComdat(Protocol));
6720
Fariborz Jahanianc22f2362009-01-31 02:43:27 +00006721 Entry->setAlignment(
Micah Villmowdd31ca12012-10-08 16:25:52 +00006722 CGM.getDataLayout().getABITypeAlignment(ObjCTypes.ProtocolnfABITy));
John McCallf9582a72012-03-30 21:29:05 +00006723
6724 Protocols[PD->getIdentifier()] = Entry;
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006725 }
Rafael Espindola70efc5b2014-03-06 18:54:12 +00006726 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
Rafael Espindola060062a2014-03-06 22:15:10 +00006727 CGM.addCompilerUsedGlobal(Entry);
Chris Lattnerf56501c2009-07-17 23:57:13 +00006728
Fariborz Jahanian61cd4b52009-01-29 20:10:59 +00006729 // Use this protocol meta-data to build protocol list table in section
6730 // __DATA, __objc_protolist
Saleem Abdulrasool9ccc7ad2016-10-25 14:50:44 +00006731 llvm::SmallString<64> ProtocolRef;
6732 llvm::raw_svector_ostream(ProtocolRef) << "\01l_OBJC_LABEL_PROTOCOL_$_"
6733 << PD->getObjCRuntimeNameAsString();
6734
Daniel Dunbar349e6fb2009-10-18 20:48:59 +00006735 llvm::GlobalVariable *PTGV =
6736 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ProtocolnfABIPtrTy,
Rafael Espindola70efc5b2014-03-06 18:54:12 +00006737 false, llvm::GlobalValue::WeakAnyLinkage, Entry,
Saleem Abdulrasool9ccc7ad2016-10-25 14:50:44 +00006738 ProtocolRef);
6739 if (!CGM.getTriple().isOSBinFormatMachO())
6740 PTGV->setComdat(CGM.getModule().getOrInsertComdat(ProtocolRef));
Fariborz Jahanianc22f2362009-01-31 02:43:27 +00006741 PTGV->setAlignment(
Micah Villmowdd31ca12012-10-08 16:25:52 +00006742 CGM.getDataLayout().getABITypeAlignment(ObjCTypes.ProtocolnfABIPtrTy));
Saleem Abdulrasool9ccc7ad2016-10-25 14:50:44 +00006743 if (CGM.getTriple().isOSBinFormatMachO())
6744 PTGV->setSection("__DATA, __objc_protolist, coalesced, no_dead_strip");
Rafael Espindola70efc5b2014-03-06 18:54:12 +00006745 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Rafael Espindola060062a2014-03-06 22:15:10 +00006746 CGM.addCompilerUsedGlobal(PTGV);
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006747 return Entry;
6748}
6749
6750/// EmitProtocolList - Generate protocol list meta-data:
6751/// @code
6752/// struct _protocol_list_t {
6753/// long protocol_count; // Note, this is 32/64 bit
6754/// struct _protocol_t[protocol_count];
6755/// }
6756/// @endcode
6757///
6758llvm::Constant *
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006759CGObjCNonFragileABIMac::EmitProtocolList(Twine Name,
Daniel Dunbar349e6fb2009-10-18 20:48:59 +00006760 ObjCProtocolDecl::protocol_iterator begin,
6761 ObjCProtocolDecl::protocol_iterator end) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006762 SmallVector<llvm::Constant *, 16> ProtocolRefs;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006763
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006764 // Just return null for empty protocol lists
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006765 if (begin == end)
Owen Anderson0b75f232009-07-31 20:28:54 +00006766 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006767
Daniel Dunbar8de90f02009-02-15 07:36:20 +00006768 // FIXME: We shouldn't need to do this lookup here, should we?
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00006769 SmallString<256> TmpName;
Daniel Dunbar349e6fb2009-10-18 20:48:59 +00006770 Name.toVector(TmpName);
6771 llvm::GlobalVariable *GV =
6772 CGM.getModule().getGlobalVariable(TmpName.str(), true);
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006773 if (GV)
Daniel Dunbar349e6fb2009-10-18 20:48:59 +00006774 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListnfABIPtrTy);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006775
Daniel Dunbar8de90f02009-02-15 07:36:20 +00006776 for (; begin != end; ++begin)
6777 ProtocolRefs.push_back(GetProtocolRef(*begin)); // Implemented???
6778
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006779 // This list is null terminated.
Owen Anderson0b75f232009-07-31 20:28:54 +00006780 ProtocolRefs.push_back(llvm::Constant::getNullValue(
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006781 ObjCTypes.ProtocolnfABIPtrTy));
6782
Chris Lattnere64d7ba2011-06-20 04:01:35 +00006783 llvm::Constant *Values[2];
Owen Anderson170229f2009-07-14 23:10:40 +00006784 Values[0] =
Owen Andersonb7a2fe62009-07-24 23:12:58 +00006785 llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006786 Values[1] =
Bill Wendlinga515b582012-02-09 22:16:49 +00006787 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolnfABIPtrTy,
6788 ProtocolRefs.size()),
6789 ProtocolRefs);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006790
Chris Lattnere64d7ba2011-06-20 04:01:35 +00006791 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
Owen Andersonc10c8d32009-07-08 19:05:04 +00006792 GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(), false,
Rafael Espindola5179a4e2014-02-27 19:01:11 +00006793 llvm::GlobalValue::PrivateLinkage,
Chris Lattnere64d7ba2011-06-20 04:01:35 +00006794 Init, Name);
Saleem Abdulrasool3c628af2016-10-25 21:43:28 +00006795 GV->setAlignment(CGM.getDataLayout().getABITypeAlignment(Init->getType()));
6796 if (CGM.getTriple().isOSBinFormatMachO())
6797 GV->setSection("__DATA, __objc_const");
Rafael Espindola060062a2014-03-06 22:15:10 +00006798 CGM.addCompilerUsedGlobal(GV);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006799 return llvm::ConstantExpr::getBitCast(GV,
Daniel Dunbar8de90f02009-02-15 07:36:20 +00006800 ObjCTypes.ProtocolListnfABIPtrTy);
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006801}
6802
Fariborz Jahaniand9c28b82009-01-30 00:46:37 +00006803/// GetMethodDescriptionConstant - This routine build following meta-data:
6804/// struct _objc_method {
6805/// SEL _cmd;
6806/// char *method_type;
6807/// char *_imp;
6808/// }
6809
6810llvm::Constant *
6811CGObjCNonFragileABIMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
Benjamin Kramer22d24c22011-10-15 12:20:02 +00006812 llvm::Constant *Desc[3];
Owen Anderson170229f2009-07-14 23:10:40 +00006813 Desc[0] =
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006814 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
6815 ObjCTypes.SelectorPtrTy);
Fariborz Jahaniand9c28b82009-01-30 00:46:37 +00006816 Desc[1] = GetMethodVarType(MD);
Douglas Gregora9d84932011-05-27 01:19:52 +00006817 if (!Desc[1])
Craig Topper8a13c412014-05-21 05:09:00 +00006818 return nullptr;
6819
Fariborz Jahanian097feda2009-01-30 18:58:59 +00006820 // Protocol methods have no implementation. So, this entry is always NULL.
Owen Anderson0b75f232009-07-31 20:28:54 +00006821 Desc[2] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Owen Anderson0e0189d2009-07-27 22:29:56 +00006822 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Desc);
Fariborz Jahaniand9c28b82009-01-30 00:46:37 +00006823}
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00006824
6825/// EmitObjCValueForIvar - Code Gen for nonfragile ivar reference.
6826/// This code gen. amounts to generating code for:
6827/// @code
6828/// (type *)((char *)base + _OBJC_IVAR_$_.ivar;
6829/// @encode
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006830///
Fariborz Jahanian712bfa62009-02-03 19:03:09 +00006831LValue CGObjCNonFragileABIMac::EmitObjCValueForIvar(
John McCall96fa4842010-05-17 21:00:27 +00006832 CodeGen::CodeGenFunction &CGF,
6833 QualType ObjectTy,
6834 llvm::Value *BaseValue,
6835 const ObjCIvarDecl *Ivar,
6836 unsigned CVRQualifiers) {
6837 ObjCInterfaceDecl *ID = ObjectTy->getAs<ObjCObjectType>()->getInterface();
Fariborz Jahaniancaabf1b2012-02-20 22:42:22 +00006838 llvm::Value *Offset = EmitIvarOffset(CGF, ID, Ivar);
Daniel Dunbar9fd114d2009-04-22 07:32:20 +00006839 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
Fariborz Jahaniancaabf1b2012-02-20 22:42:22 +00006840 Offset);
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00006841}
6842
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00006843llvm::Value *CGObjCNonFragileABIMac::EmitIvarOffset(
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006844 CodeGen::CodeGenFunction &CGF,
6845 const ObjCInterfaceDecl *Interface,
6846 const ObjCIvarDecl *Ivar) {
Tim Northover238b5082014-03-29 13:42:40 +00006847 llvm::Value *IvarOffsetValue = ObjCIvarOffsetVariable(Interface, Ivar);
John McCall7f416cc2015-09-08 08:05:57 +00006848 IvarOffsetValue = CGF.Builder.CreateAlignedLoad(IvarOffsetValue,
6849 CGF.getSizeAlign(), "ivar");
Tim Northover238b5082014-03-29 13:42:40 +00006850 if (IsIvarOffsetKnownIdempotent(CGF, Ivar))
6851 cast<llvm::LoadInst>(IvarOffsetValue)
6852 ->setMetadata(CGM.getModule().getMDKindID("invariant.load"),
Craig Topper5fc8fc22014-08-27 06:28:36 +00006853 llvm::MDNode::get(VMContext, None));
Tim Northover238b5082014-03-29 13:42:40 +00006854
6855 // This could be 32bit int or 64bit integer depending on the architecture.
6856 // Cast it to 64bit integer value, if it is a 32bit integer ivar offset value
6857 // as this is what caller always expectes.
6858 if (ObjCTypes.IvarOffsetVarTy == ObjCTypes.IntTy)
6859 IvarOffsetValue = CGF.Builder.CreateIntCast(
6860 IvarOffsetValue, ObjCTypes.LongTy, true, "ivar.conv");
6861 return IvarOffsetValue;
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00006862}
6863
John McCall234eac82011-05-13 23:16:18 +00006864static void appendSelectorForMessageRefTable(std::string &buffer,
6865 Selector selector) {
6866 if (selector.isUnarySelector()) {
6867 buffer += selector.getNameForSlot(0);
6868 return;
6869 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006870
John McCall234eac82011-05-13 23:16:18 +00006871 for (unsigned i = 0, e = selector.getNumArgs(); i != e; ++i) {
6872 buffer += selector.getNameForSlot(i);
6873 buffer += '_';
6874 }
6875}
6876
Eric Christopherd160c502016-01-29 01:35:53 +00006877/// Emit a "vtable" message send. We emit a weak hidden-visibility
John McCall9e8bb002011-05-14 03:10:52 +00006878/// struct, initially containing the selector pointer and a pointer to
6879/// a "fixup" variant of the appropriate objc_msgSend. To call, we
6880/// load and call the function pointer, passing the address of the
6881/// struct as the second parameter. The runtime determines whether
6882/// the selector is currently emitted using vtable dispatch; if so, it
6883/// substitutes a stub function which simply tail-calls through the
6884/// appropriate vtable slot, and if not, it substitues a stub function
6885/// which tail-calls objc_msgSend. Both stubs adjust the selector
6886/// argument to correctly point to the selector.
6887RValue
6888CGObjCNonFragileABIMac::EmitVTableMessageSend(CodeGenFunction &CGF,
6889 ReturnValueSlot returnSlot,
6890 QualType resultType,
6891 Selector selector,
6892 llvm::Value *arg0,
6893 QualType arg0Type,
6894 bool isSuper,
6895 const CallArgList &formalArgs,
6896 const ObjCMethodDecl *method) {
John McCall234eac82011-05-13 23:16:18 +00006897 // Compute the actual arguments.
6898 CallArgList args;
6899
John McCall9e8bb002011-05-14 03:10:52 +00006900 // First argument: the receiver / super-call structure.
John McCall234eac82011-05-13 23:16:18 +00006901 if (!isSuper)
John McCall9e8bb002011-05-14 03:10:52 +00006902 arg0 = CGF.Builder.CreateBitCast(arg0, ObjCTypes.ObjectPtrTy);
6903 args.add(RValue::get(arg0), arg0Type);
John McCall234eac82011-05-13 23:16:18 +00006904
John McCall9e8bb002011-05-14 03:10:52 +00006905 // Second argument: a pointer to the message ref structure. Leave
6906 // the actual argument value blank for now.
Craig Topper8a13c412014-05-21 05:09:00 +00006907 args.add(RValue::get(nullptr), ObjCTypes.MessageRefCPtrTy);
John McCall234eac82011-05-13 23:16:18 +00006908
6909 args.insert(args.end(), formalArgs.begin(), formalArgs.end());
6910
John McCalla729c622012-02-17 03:33:10 +00006911 MessageSendInfo MSI = getMessageSendInfo(method, resultType, args);
John McCall234eac82011-05-13 23:16:18 +00006912
John McCall5880fb82011-05-14 21:12:11 +00006913 NullReturnState nullReturn;
6914
John McCall9e8bb002011-05-14 03:10:52 +00006915 // Find the function to call and the mangled name for the message
6916 // ref structure. Using a different mangled name wouldn't actually
6917 // be a problem; it would just be a waste.
6918 //
6919 // The runtime currently never uses vtable dispatch for anything
6920 // except normal, non-super message-sends.
6921 // FIXME: don't use this for that.
Craig Topper8a13c412014-05-21 05:09:00 +00006922 llvm::Constant *fn = nullptr;
John McCall234eac82011-05-13 23:16:18 +00006923 std::string messageRefName("\01l_");
Tim Northovere77cc392014-03-29 13:28:05 +00006924 if (CGM.ReturnSlotInterferesWithArgs(MSI.CallInfo)) {
John McCall234eac82011-05-13 23:16:18 +00006925 if (isSuper) {
6926 fn = ObjCTypes.getMessageSendSuper2StretFixupFn();
6927 messageRefName += "objc_msgSendSuper2_stret_fixup";
Chris Lattner396639d2010-08-18 16:09:06 +00006928 } else {
John McCall5880fb82011-05-14 21:12:11 +00006929 nullReturn.init(CGF, arg0);
John McCall234eac82011-05-13 23:16:18 +00006930 fn = ObjCTypes.getMessageSendStretFixupFn();
6931 messageRefName += "objc_msgSend_stret_fixup";
Chris Lattner396639d2010-08-18 16:09:06 +00006932 }
John McCall234eac82011-05-13 23:16:18 +00006933 } else if (!isSuper && CGM.ReturnTypeUsesFPRet(resultType)) {
6934 fn = ObjCTypes.getMessageSendFpretFixupFn();
6935 messageRefName += "objc_msgSend_fpret_fixup";
Mike Stump658fe022009-07-30 22:28:39 +00006936 } else {
John McCall234eac82011-05-13 23:16:18 +00006937 if (isSuper) {
6938 fn = ObjCTypes.getMessageSendSuper2FixupFn();
6939 messageRefName += "objc_msgSendSuper2_fixup";
Chris Lattner396639d2010-08-18 16:09:06 +00006940 } else {
John McCall234eac82011-05-13 23:16:18 +00006941 fn = ObjCTypes.getMessageSendFixupFn();
6942 messageRefName += "objc_msgSend_fixup";
Chris Lattner396639d2010-08-18 16:09:06 +00006943 }
Fariborz Jahaniane4dc35d2009-02-04 20:42:28 +00006944 }
John McCall234eac82011-05-13 23:16:18 +00006945 assert(fn && "CGObjCNonFragileABIMac::EmitMessageSend");
6946 messageRefName += '_';
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006947
John McCall234eac82011-05-13 23:16:18 +00006948 // Append the selector name, except use underscores anywhere we
6949 // would have used colons.
6950 appendSelectorForMessageRefTable(messageRefName, selector);
6951
6952 llvm::GlobalVariable *messageRef
6953 = CGM.getModule().getGlobalVariable(messageRefName);
6954 if (!messageRef) {
John McCall9e8bb002011-05-14 03:10:52 +00006955 // Build the message ref structure.
John McCall234eac82011-05-13 23:16:18 +00006956 llvm::Constant *values[] = { fn, GetMethodVarName(selector) };
Chris Lattnere64d7ba2011-06-20 04:01:35 +00006957 llvm::Constant *init = llvm::ConstantStruct::getAnon(values);
John McCall234eac82011-05-13 23:16:18 +00006958 messageRef = new llvm::GlobalVariable(CGM.getModule(),
6959 init->getType(),
6960 /*constant*/ false,
Rafael Espindola70efc5b2014-03-06 18:54:12 +00006961 llvm::GlobalValue::WeakAnyLinkage,
John McCall234eac82011-05-13 23:16:18 +00006962 init,
6963 messageRefName);
Rafael Espindola70efc5b2014-03-06 18:54:12 +00006964 messageRef->setVisibility(llvm::GlobalValue::HiddenVisibility);
John McCall234eac82011-05-13 23:16:18 +00006965 messageRef->setAlignment(16);
6966 messageRef->setSection("__DATA, __objc_msgrefs, coalesced");
6967 }
Rafael Espindola70efc5b2014-03-06 18:54:12 +00006968
Fariborz Jahanianc93fa982012-01-30 23:39:30 +00006969 bool requiresnullCheck = false;
David Blaikiebbafb8a2012-03-11 07:00:24 +00006970 if (CGM.getLangOpts().ObjCAutoRefCount && method)
David Majnemer59f77922016-06-24 04:05:48 +00006971 for (const auto *ParamDecl : method->parameters()) {
Fariborz Jahanianc93fa982012-01-30 23:39:30 +00006972 if (ParamDecl->hasAttr<NSConsumedAttr>()) {
6973 if (!nullReturn.NullBB)
6974 nullReturn.init(CGF, arg0);
6975 requiresnullCheck = true;
6976 break;
6977 }
6978 }
6979
John McCall7f416cc2015-09-08 08:05:57 +00006980 Address mref =
6981 Address(CGF.Builder.CreateBitCast(messageRef, ObjCTypes.MessageRefPtrTy),
6982 CGF.getPointerAlign());
John McCall234eac82011-05-13 23:16:18 +00006983
John McCall9e8bb002011-05-14 03:10:52 +00006984 // Update the message ref argument.
John McCall7f416cc2015-09-08 08:05:57 +00006985 args[1].RV = RValue::get(mref.getPointer());
John McCall234eac82011-05-13 23:16:18 +00006986
6987 // Load the function to call from the message ref table.
John McCall7f416cc2015-09-08 08:05:57 +00006988 Address calleeAddr =
6989 CGF.Builder.CreateStructGEP(mref, 0, CharUnits::Zero());
John McCallb92ab1a2016-10-26 23:46:34 +00006990 llvm::Value *calleePtr = CGF.Builder.CreateLoad(calleeAddr, "msgSend_fn");
John McCall234eac82011-05-13 23:16:18 +00006991
John McCallb92ab1a2016-10-26 23:46:34 +00006992 calleePtr = CGF.Builder.CreateBitCast(calleePtr, MSI.MessengerType);
6993 CGCallee callee(CGCalleeInfo(), calleePtr);
John McCall234eac82011-05-13 23:16:18 +00006994
John McCalla729c622012-02-17 03:33:10 +00006995 RValue result = CGF.EmitCall(MSI.CallInfo, callee, returnSlot, args);
Craig Topper8a13c412014-05-21 05:09:00 +00006996 return nullReturn.complete(CGF, result, resultType, formalArgs,
6997 requiresnullCheck ? method : nullptr);
Fariborz Jahanian3d9296e2009-02-04 00:22:57 +00006998}
6999
7000/// Generate code for a message send expression in the nonfragile abi.
Daniel Dunbaraff9fca2009-09-17 04:01:22 +00007001CodeGen::RValue
7002CGObjCNonFragileABIMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +00007003 ReturnValueSlot Return,
Daniel Dunbaraff9fca2009-09-17 04:01:22 +00007004 QualType ResultType,
7005 Selector Sel,
7006 llvm::Value *Receiver,
Daniel Dunbaraff9fca2009-09-17 04:01:22 +00007007 const CallArgList &CallArgs,
David Chisnall01aa4672010-04-28 19:33:36 +00007008 const ObjCInterfaceDecl *Class,
Daniel Dunbaraff9fca2009-09-17 04:01:22 +00007009 const ObjCMethodDecl *Method) {
John McCall9e8bb002011-05-14 03:10:52 +00007010 return isVTableDispatchedSelector(Sel)
7011 ? EmitVTableMessageSend(CGF, Return, ResultType, Sel,
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007012 Receiver, CGF.getContext().getObjCIdType(),
John McCall9e8bb002011-05-14 03:10:52 +00007013 false, CallArgs, Method)
7014 : EmitMessageSend(CGF, Return, ResultType,
John McCall882987f2013-02-28 19:01:20 +00007015 EmitSelector(CGF, Sel),
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007016 Receiver, CGF.getContext().getObjCIdType(),
John McCall1e3157b2015-09-10 22:27:50 +00007017 false, CallArgs, Method, Class, ObjCTypes);
Fariborz Jahanian3d9296e2009-02-04 00:22:57 +00007018}
7019
Daniel Dunbarc6928bb2009-03-01 04:40:10 +00007020llvm::GlobalVariable *
Benjamin Kramer0772c422016-02-13 13:42:54 +00007021CGObjCNonFragileABIMac::GetClassGlobal(StringRef Name, bool Weak) {
Rafael Espindola554256c2014-02-26 22:25:45 +00007022 llvm::GlobalValue::LinkageTypes L =
7023 Weak ? llvm::GlobalValue::ExternalWeakLinkage
7024 : llvm::GlobalValue::ExternalLinkage;
7025
Daniel Dunbarc6928bb2009-03-01 04:40:10 +00007026 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
7027
Rafael Espindola554256c2014-02-26 22:25:45 +00007028 if (!GV)
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007029 GV = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassnfABITy,
Craig Topper8a13c412014-05-21 05:09:00 +00007030 false, L, nullptr, Name);
Daniel Dunbarc6928bb2009-03-01 04:40:10 +00007031
Rafael Espindola554256c2014-02-26 22:25:45 +00007032 assert(GV->getLinkage() == L);
Daniel Dunbarc6928bb2009-03-01 04:40:10 +00007033 return GV;
7034}
7035
John McCall882987f2013-02-28 19:01:20 +00007036llvm::Value *CGObjCNonFragileABIMac::EmitClassRefFromId(CodeGenFunction &CGF,
Rafael Espindola554256c2014-02-26 22:25:45 +00007037 IdentifierInfo *II,
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00007038 bool Weak,
7039 const ObjCInterfaceDecl *ID) {
John McCall7f416cc2015-09-08 08:05:57 +00007040 CharUnits Align = CGF.getPointerAlign();
John McCall31168b02011-06-15 23:02:42 +00007041 llvm::GlobalVariable *&Entry = ClassReferences[II];
7042
Fariborz Jahanian33f66e62009-02-05 20:41:40 +00007043 if (!Entry) {
Saleem Abdulrasool1e6c4062016-05-16 05:06:49 +00007044 StringRef Name = ID ? ID->getObjCRuntimeNameAsString() : II->getName();
7045 std::string ClassName = (getClassSymbolPrefix() + Name).str();
Rafael Espindola554256c2014-02-26 22:25:45 +00007046 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName, Weak);
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00007047 Entry = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassnfABIPtrTy,
7048 false, llvm::GlobalValue::PrivateLinkage,
7049 ClassGV, "OBJC_CLASSLIST_REFERENCES_$_");
John McCall7f416cc2015-09-08 08:05:57 +00007050 Entry->setAlignment(Align.getQuantity());
Daniel Dunbar508a7dd2009-04-18 08:51:00 +00007051 Entry->setSection("__DATA, __objc_classrefs, regular, no_dead_strip");
Rafael Espindola060062a2014-03-06 22:15:10 +00007052 CGM.addCompilerUsedGlobal(Entry);
Daniel Dunbar508a7dd2009-04-18 08:51:00 +00007053 }
John McCall7f416cc2015-09-08 08:05:57 +00007054 return CGF.Builder.CreateAlignedLoad(Entry, Align);
Daniel Dunbar508a7dd2009-04-18 08:51:00 +00007055}
Fariborz Jahanian33f66e62009-02-05 20:41:40 +00007056
John McCall882987f2013-02-28 19:01:20 +00007057llvm::Value *CGObjCNonFragileABIMac::EmitClassRef(CodeGenFunction &CGF,
John McCall31168b02011-06-15 23:02:42 +00007058 const ObjCInterfaceDecl *ID) {
Douglas Gregor24ae22c2016-04-01 23:23:52 +00007059 // If the class has the objc_runtime_visible attribute, we need to
7060 // use the Objective-C runtime to get the class.
7061 if (ID->hasAttr<ObjCRuntimeVisibleAttr>())
7062 return EmitClassRefViaRuntime(CGF, ID, ObjCTypes);
7063
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00007064 return EmitClassRefFromId(CGF, ID->getIdentifier(), ID->isWeakImported(), ID);
John McCall31168b02011-06-15 23:02:42 +00007065}
7066
7067llvm::Value *CGObjCNonFragileABIMac::EmitNSAutoreleasePoolClassRef(
John McCall882987f2013-02-28 19:01:20 +00007068 CodeGenFunction &CGF) {
John McCall31168b02011-06-15 23:02:42 +00007069 IdentifierInfo *II = &CGM.getContext().Idents.get("NSAutoreleasePool");
Hans Wennborgdcfba332015-10-06 23:40:43 +00007070 return EmitClassRefFromId(CGF, II, false, nullptr);
John McCall31168b02011-06-15 23:02:42 +00007071}
7072
Daniel Dunbar508a7dd2009-04-18 08:51:00 +00007073llvm::Value *
John McCall882987f2013-02-28 19:01:20 +00007074CGObjCNonFragileABIMac::EmitSuperClassRef(CodeGenFunction &CGF,
Daniel Dunbar508a7dd2009-04-18 08:51:00 +00007075 const ObjCInterfaceDecl *ID) {
John McCall7f416cc2015-09-08 08:05:57 +00007076 CharUnits Align = CGF.getPointerAlign();
Daniel Dunbar508a7dd2009-04-18 08:51:00 +00007077 llvm::GlobalVariable *&Entry = SuperClassReferences[ID->getIdentifier()];
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007078
Daniel Dunbar508a7dd2009-04-18 08:51:00 +00007079 if (!Entry) {
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00007080 llvm::SmallString<64> ClassName(getClassSymbolPrefix());
7081 ClassName += ID->getObjCRuntimeNameAsString();
7082 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName.str(),
Fariborz Jahanianf322f2f2014-03-11 00:25:05 +00007083 ID->isWeakImported());
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00007084 Entry = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassnfABIPtrTy,
7085 false, llvm::GlobalValue::PrivateLinkage,
7086 ClassGV, "OBJC_CLASSLIST_SUP_REFS_$_");
John McCall7f416cc2015-09-08 08:05:57 +00007087 Entry->setAlignment(Align.getQuantity());
Daniel Dunbar508a7dd2009-04-18 08:51:00 +00007088 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Rafael Espindola060062a2014-03-06 22:15:10 +00007089 CGM.addCompilerUsedGlobal(Entry);
Fariborz Jahanian33f66e62009-02-05 20:41:40 +00007090 }
John McCall7f416cc2015-09-08 08:05:57 +00007091 return CGF.Builder.CreateAlignedLoad(Entry, Align);
Fariborz Jahanian33f66e62009-02-05 20:41:40 +00007092}
7093
Fariborz Jahanian6b7cd6e2009-02-06 20:09:23 +00007094/// EmitMetaClassRef - Return a Value * of the address of _class_t
7095/// meta-data
7096///
John McCall882987f2013-02-28 19:01:20 +00007097llvm::Value *CGObjCNonFragileABIMac::EmitMetaClassRef(CodeGenFunction &CGF,
Fariborz Jahanian0b3bc242014-06-10 17:08:04 +00007098 const ObjCInterfaceDecl *ID,
7099 bool Weak) {
John McCall7f416cc2015-09-08 08:05:57 +00007100 CharUnits Align = CGF.getPointerAlign();
Fariborz Jahanian6b7cd6e2009-02-06 20:09:23 +00007101 llvm::GlobalVariable * &Entry = MetaClassReferences[ID->getIdentifier()];
Rafael Espindola21039aa2014-02-27 16:26:32 +00007102 if (!Entry) {
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00007103 llvm::SmallString<64> MetaClassName(getMetaclassSymbolPrefix());
7104 MetaClassName += ID->getObjCRuntimeNameAsString();
Fariborz Jahanian0b3bc242014-06-10 17:08:04 +00007105 llvm::GlobalVariable *MetaClassGV =
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00007106 GetClassGlobal(MetaClassName.str(), Weak);
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00007107
Rafael Espindola21039aa2014-02-27 16:26:32 +00007108 Entry = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassnfABIPtrTy,
Rafael Espindola5179a4e2014-02-27 19:01:11 +00007109 false, llvm::GlobalValue::PrivateLinkage,
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00007110 MetaClassGV, "OBJC_CLASSLIST_SUP_REFS_$_");
John McCall7f416cc2015-09-08 08:05:57 +00007111 Entry->setAlignment(Align.getQuantity());
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007112
Rafael Espindola21039aa2014-02-27 16:26:32 +00007113 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Rafael Espindola060062a2014-03-06 22:15:10 +00007114 CGM.addCompilerUsedGlobal(Entry);
Rafael Espindola21039aa2014-02-27 16:26:32 +00007115 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007116
John McCall7f416cc2015-09-08 08:05:57 +00007117 return CGF.Builder.CreateAlignedLoad(Entry, Align);
Fariborz Jahanian6b7cd6e2009-02-06 20:09:23 +00007118}
7119
Fariborz Jahanian33f66e62009-02-05 20:41:40 +00007120/// GetClass - Return a reference to the class for the given interface
7121/// decl.
John McCall882987f2013-02-28 19:01:20 +00007122llvm::Value *CGObjCNonFragileABIMac::GetClass(CodeGenFunction &CGF,
Fariborz Jahanian33f66e62009-02-05 20:41:40 +00007123 const ObjCInterfaceDecl *ID) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00007124 if (ID->isWeakImported()) {
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00007125 llvm::SmallString<64> ClassName(getClassSymbolPrefix());
7126 ClassName += ID->getObjCRuntimeNameAsString();
7127 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName.str(), true);
Nick Lewycky9a441642014-02-27 00:36:00 +00007128 (void)ClassGV;
Rafael Espindolab3262952014-05-09 00:43:37 +00007129 assert(ClassGV->hasExternalWeakLinkage());
Fariborz Jahanian95ace552009-11-17 22:42:00 +00007130 }
7131
John McCall882987f2013-02-28 19:01:20 +00007132 return EmitClassRef(CGF, ID);
Fariborz Jahanian33f66e62009-02-05 20:41:40 +00007133}
7134
Fariborz Jahanian6b7cd6e2009-02-06 20:09:23 +00007135/// Generates a message send where the super is the receiver. This is
7136/// a message send to self with special delivery semantics indicating
7137/// which class's method should be called.
7138CodeGen::RValue
7139CGObjCNonFragileABIMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +00007140 ReturnValueSlot Return,
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007141 QualType ResultType,
7142 Selector Sel,
7143 const ObjCInterfaceDecl *Class,
7144 bool isCategoryImpl,
7145 llvm::Value *Receiver,
7146 bool IsClassMessage,
Daniel Dunbaraff9fca2009-09-17 04:01:22 +00007147 const CodeGen::CallArgList &CallArgs,
7148 const ObjCMethodDecl *Method) {
Fariborz Jahanian6b7cd6e2009-02-06 20:09:23 +00007149 // ...
7150 // Create and init a super structure; this is a (receiver, class)
7151 // pair we will pass to objc_msgSendSuper.
John McCall7f416cc2015-09-08 08:05:57 +00007152 Address ObjCSuper =
7153 CGF.CreateTempAlloca(ObjCTypes.SuperTy, CGF.getPointerAlign(),
7154 "objc_super");
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007155
Fariborz Jahanian6b7cd6e2009-02-06 20:09:23 +00007156 llvm::Value *ReceiverAsObject =
7157 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
David Blaikie1ed728c2015-04-05 22:45:47 +00007158 CGF.Builder.CreateStore(
7159 ReceiverAsObject,
John McCall7f416cc2015-09-08 08:05:57 +00007160 CGF.Builder.CreateStructGEP(ObjCSuper, 0, CharUnits::Zero()));
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007161
Fariborz Jahanian6b7cd6e2009-02-06 20:09:23 +00007162 // If this is a class message the metaclass is passed as the target.
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +00007163 llvm::Value *Target;
Fariborz Jahanian27678b02012-10-10 23:11:18 +00007164 if (IsClassMessage)
Fariborz Jahanian85b99da2014-08-28 17:05:17 +00007165 Target = EmitMetaClassRef(CGF, Class, Class->isWeakImported());
Fariborz Jahanian27678b02012-10-10 23:11:18 +00007166 else
John McCall882987f2013-02-28 19:01:20 +00007167 Target = EmitSuperClassRef(CGF, Class);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007168
Mike Stump18bb9282009-05-16 07:57:57 +00007169 // FIXME: We shouldn't need to do this cast, rectify the ASTContext and
7170 // ObjCTypes types.
Chris Lattner2192fe52011-07-18 04:24:23 +00007171 llvm::Type *ClassTy =
Fariborz Jahanian6b7cd6e2009-02-06 20:09:23 +00007172 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
7173 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
David Blaikie1ed728c2015-04-05 22:45:47 +00007174 CGF.Builder.CreateStore(
John McCall7f416cc2015-09-08 08:05:57 +00007175 Target, CGF.Builder.CreateStructGEP(ObjCSuper, 1, CGF.getPointerSize()));
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007176
John McCall9e8bb002011-05-14 03:10:52 +00007177 return (isVTableDispatchedSelector(Sel))
7178 ? EmitVTableMessageSend(CGF, Return, ResultType, Sel,
John McCall7f416cc2015-09-08 08:05:57 +00007179 ObjCSuper.getPointer(), ObjCTypes.SuperPtrCTy,
John McCall9e8bb002011-05-14 03:10:52 +00007180 true, CallArgs, Method)
7181 : EmitMessageSend(CGF, Return, ResultType,
John McCall882987f2013-02-28 19:01:20 +00007182 EmitSelector(CGF, Sel),
John McCall7f416cc2015-09-08 08:05:57 +00007183 ObjCSuper.getPointer(), ObjCTypes.SuperPtrCTy,
John McCall1e3157b2015-09-10 22:27:50 +00007184 true, CallArgs, Method, Class, ObjCTypes);
Fariborz Jahanian6b7cd6e2009-02-06 20:09:23 +00007185}
Fariborz Jahanian74b77222009-02-11 20:51:17 +00007186
John McCall882987f2013-02-28 19:01:20 +00007187llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00007188 Selector Sel) {
7189 Address Addr = EmitSelectorAddr(CGF, Sel);
7190
7191 llvm::LoadInst* LI = CGF.Builder.CreateLoad(Addr);
7192 LI->setMetadata(CGM.getModule().getMDKindID("invariant.load"),
7193 llvm::MDNode::get(VMContext, None));
7194 return LI;
7195}
7196
7197Address CGObjCNonFragileABIMac::EmitSelectorAddr(CodeGenFunction &CGF,
7198 Selector Sel) {
Fariborz Jahanian74b77222009-02-11 20:51:17 +00007199 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007200
John McCall7f416cc2015-09-08 08:05:57 +00007201 CharUnits Align = CGF.getPointerAlign();
Fariborz Jahanian74b77222009-02-11 20:51:17 +00007202 if (!Entry) {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007203 llvm::Constant *Casted =
7204 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
7205 ObjCTypes.SelectorPtrTy);
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00007206 Entry = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.SelectorPtrTy,
7207 false, llvm::GlobalValue::PrivateLinkage,
7208 Casted, "OBJC_SELECTOR_REFERENCES_");
Michael Gottesman5c205962013-02-05 23:08:45 +00007209 Entry->setExternallyInitialized(true);
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +00007210 Entry->setSection("__DATA, __objc_selrefs, literal_pointers, no_dead_strip");
John McCall7f416cc2015-09-08 08:05:57 +00007211 Entry->setAlignment(Align.getQuantity());
Rafael Espindola060062a2014-03-06 22:15:10 +00007212 CGM.addCompilerUsedGlobal(Entry);
Fariborz Jahanian74b77222009-02-11 20:51:17 +00007213 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007214
John McCall7f416cc2015-09-08 08:05:57 +00007215 return Address(Entry, Align);
Fariborz Jahanian74b77222009-02-11 20:51:17 +00007216}
John McCall7f416cc2015-09-08 08:05:57 +00007217
Fariborz Jahanian06292952009-02-16 22:52:32 +00007218/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00007219/// objc_assign_ivar (id src, id *dst, ptrdiff_t)
Fariborz Jahanian06292952009-02-16 22:52:32 +00007220///
7221void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +00007222 llvm::Value *src,
John McCall7f416cc2015-09-08 08:05:57 +00007223 Address dst,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00007224 llvm::Value *ivarOffset) {
Chris Lattner2192fe52011-07-18 04:24:23 +00007225 llvm::Type * SrcTy = src->getType();
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00007226 if (!isa<llvm::PointerType>(SrcTy)) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00007227 unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00007228 assert(Size <= 8 && "does not support size > 8");
7229 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
7230 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian1b074a32009-03-13 00:42:52 +00007231 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
7232 }
Fariborz Jahanian06292952009-02-16 22:52:32 +00007233 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
7234 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00007235 llvm::Value *args[] = { src, dst.getPointer(), ivarOffset };
John McCall882987f2013-02-28 19:01:20 +00007236 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignIvarFn(), args);
Fariborz Jahanian06292952009-02-16 22:52:32 +00007237}
7238
7239/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
7240/// objc_assign_strongCast (id src, id *dst)
7241///
7242void CGObjCNonFragileABIMac::EmitObjCStrongCastAssign(
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007243 CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00007244 llvm::Value *src, Address dst) {
Chris Lattner2192fe52011-07-18 04:24:23 +00007245 llvm::Type * SrcTy = src->getType();
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00007246 if (!isa<llvm::PointerType>(SrcTy)) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00007247 unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00007248 assert(Size <= 8 && "does not support size > 8");
7249 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007250 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian1b074a32009-03-13 00:42:52 +00007251 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
7252 }
Fariborz Jahanian06292952009-02-16 22:52:32 +00007253 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
7254 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00007255 llvm::Value *args[] = { src, dst.getPointer() };
John McCall882987f2013-02-28 19:01:20 +00007256 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignStrongCastFn(),
7257 args, "weakassign");
Fariborz Jahanian06292952009-02-16 22:52:32 +00007258}
7259
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00007260void CGObjCNonFragileABIMac::EmitGCMemmoveCollectable(
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007261 CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00007262 Address DestPtr,
7263 Address SrcPtr,
Fariborz Jahanian021510e2010-06-15 22:44:06 +00007264 llvm::Value *Size) {
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00007265 SrcPtr = CGF.Builder.CreateBitCast(SrcPtr, ObjCTypes.Int8PtrTy);
7266 DestPtr = CGF.Builder.CreateBitCast(DestPtr, ObjCTypes.Int8PtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00007267 llvm::Value *args[] = { DestPtr.getPointer(), SrcPtr.getPointer(), Size };
John McCall882987f2013-02-28 19:01:20 +00007268 CGF.EmitNounwindRuntimeCall(ObjCTypes.GcMemmoveCollectableFn(), args);
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00007269}
7270
Fariborz Jahanian06292952009-02-16 22:52:32 +00007271/// EmitObjCWeakRead - Code gen for loading value of a __weak
7272/// object: objc_read_weak (id *src)
7273///
7274llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead(
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007275 CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00007276 Address AddrWeakObj) {
7277 llvm::Type *DestTy = AddrWeakObj.getElementType();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007278 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
John McCall882987f2013-02-28 19:01:20 +00007279 llvm::Value *read_weak =
7280 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcReadWeakFn(),
John McCall7f416cc2015-09-08 08:05:57 +00007281 AddrWeakObj.getPointer(), "weakread");
Eli Friedmana374b682009-03-07 03:57:15 +00007282 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian06292952009-02-16 22:52:32 +00007283 return read_weak;
7284}
7285
7286/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
7287/// objc_assign_weak (id src, id *dst)
7288///
7289void CGObjCNonFragileABIMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00007290 llvm::Value *src, Address dst) {
Chris Lattner2192fe52011-07-18 04:24:23 +00007291 llvm::Type * SrcTy = src->getType();
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00007292 if (!isa<llvm::PointerType>(SrcTy)) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00007293 unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00007294 assert(Size <= 8 && "does not support size > 8");
7295 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
7296 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian1b074a32009-03-13 00:42:52 +00007297 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
7298 }
Fariborz Jahanian06292952009-02-16 22:52:32 +00007299 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
7300 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00007301 llvm::Value *args[] = { src, dst.getPointer() };
John McCall882987f2013-02-28 19:01:20 +00007302 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignWeakFn(),
7303 args, "weakassign");
Fariborz Jahanian06292952009-02-16 22:52:32 +00007304}
7305
7306/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
7307/// objc_assign_global (id src, id *dst)
7308///
7309void CGObjCNonFragileABIMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00007310 llvm::Value *src, Address dst,
Fariborz Jahanian217af242010-07-20 20:30:03 +00007311 bool threadlocal) {
Chris Lattner2192fe52011-07-18 04:24:23 +00007312 llvm::Type * SrcTy = src->getType();
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00007313 if (!isa<llvm::PointerType>(SrcTy)) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00007314 unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00007315 assert(Size <= 8 && "does not support size > 8");
7316 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
7317 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian1b074a32009-03-13 00:42:52 +00007318 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
7319 }
Fariborz Jahanian06292952009-02-16 22:52:32 +00007320 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
7321 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00007322 llvm::Value *args[] = { src, dst.getPointer() };
Fariborz Jahanian217af242010-07-20 20:30:03 +00007323 if (!threadlocal)
John McCall882987f2013-02-28 19:01:20 +00007324 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignGlobalFn(),
7325 args, "globalassign");
Fariborz Jahanian217af242010-07-20 20:30:03 +00007326 else
John McCall882987f2013-02-28 19:01:20 +00007327 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignThreadLocalFn(),
7328 args, "threadlocalassign");
Fariborz Jahanian06292952009-02-16 22:52:32 +00007329}
Fariborz Jahanian74b77222009-02-11 20:51:17 +00007330
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007331void
John McCallbd309292010-07-06 01:34:17 +00007332CGObjCNonFragileABIMac::EmitSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
7333 const ObjCAtSynchronizedStmt &S) {
David Chisnall3e575602011-03-25 17:46:35 +00007334 EmitAtSynchronizedStmt(CGF, S,
7335 cast<llvm::Function>(ObjCTypes.getSyncEnterFn()),
7336 cast<llvm::Function>(ObjCTypes.getSyncExitFn()));
John McCallbd309292010-07-06 01:34:17 +00007337}
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007338
John McCall2ca705e2010-07-24 00:37:23 +00007339llvm::Constant *
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +00007340CGObjCNonFragileABIMac::GetEHType(QualType T) {
John McCall2ca705e2010-07-24 00:37:23 +00007341 // There's a particular fixed type info for 'id'.
Saleem Abdulrasoole5f3eae2016-07-17 22:27:38 +00007342 if (T->isObjCIdType() || T->isObjCQualifiedIdType()) {
7343 auto *IDEHType = CGM.getModule().getGlobalVariable("OBJC_EHTYPE_id");
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00007344 if (!IDEHType) {
John McCall2ca705e2010-07-24 00:37:23 +00007345 IDEHType =
Saleem Abdulrasoole5f3eae2016-07-17 22:27:38 +00007346 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.EHTypeTy, false,
7347 llvm::GlobalValue::ExternalLinkage, nullptr,
7348 "OBJC_EHTYPE_id");
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00007349 if (CGM.getTriple().isOSBinFormatCOFF())
7350 IDEHType->setDLLStorageClass(getStorage(CGM, "OBJC_EHTYPE_id"));
7351 }
John McCall2ca705e2010-07-24 00:37:23 +00007352 return IDEHType;
7353 }
7354
7355 // All other types should be Objective-C interface pointer types.
Saleem Abdulrasoole5f3eae2016-07-17 22:27:38 +00007356 const ObjCObjectPointerType *PT = T->getAs<ObjCObjectPointerType>();
John McCall2ca705e2010-07-24 00:37:23 +00007357 assert(PT && "Invalid @catch type.");
Saleem Abdulrasoole5f3eae2016-07-17 22:27:38 +00007358
John McCall2ca705e2010-07-24 00:37:23 +00007359 const ObjCInterfaceType *IT = PT->getInterfaceType();
7360 assert(IT && "Invalid @catch type.");
Saleem Abdulrasoole5f3eae2016-07-17 22:27:38 +00007361
John McCall2ca705e2010-07-24 00:37:23 +00007362 return GetInterfaceEHType(IT->getDecl(), false);
Saleem Abdulrasoole5f3eae2016-07-17 22:27:38 +00007363}
John McCall2ca705e2010-07-24 00:37:23 +00007364
John McCallbd309292010-07-06 01:34:17 +00007365void CGObjCNonFragileABIMac::EmitTryStmt(CodeGen::CodeGenFunction &CGF,
7366 const ObjCAtTryStmt &S) {
David Chisnall3e575602011-03-25 17:46:35 +00007367 EmitTryCatchStmt(CGF, S,
7368 cast<llvm::Function>(ObjCTypes.getObjCBeginCatchFn()),
7369 cast<llvm::Function>(ObjCTypes.getObjCEndCatchFn()),
7370 cast<llvm::Function>(ObjCTypes.getExceptionRethrowFn()));
Daniel Dunbar0b0dcd92009-02-24 07:47:38 +00007371}
7372
Anders Carlsson9ab53d12009-02-16 22:59:18 +00007373/// EmitThrowStmt - Generate code for a throw statement.
7374void CGObjCNonFragileABIMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian1eab0522013-01-10 19:02:56 +00007375 const ObjCAtThrowStmt &S,
7376 bool ClearInsertionPoint) {
Anders Carlsson9ab53d12009-02-16 22:59:18 +00007377 if (const Expr *ThrowExpr = S.getThrowExpr()) {
John McCall248512a2011-10-01 10:32:24 +00007378 llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00007379 Exception = CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy);
John McCall882987f2013-02-28 19:01:20 +00007380 CGF.EmitRuntimeCallOrInvoke(ObjCTypes.getExceptionThrowFn(), Exception)
John McCall17afe452010-10-16 08:21:07 +00007381 .setDoesNotReturn();
Anders Carlsson9ab53d12009-02-16 22:59:18 +00007382 } else {
John McCall882987f2013-02-28 19:01:20 +00007383 CGF.EmitRuntimeCallOrInvoke(ObjCTypes.getExceptionRethrowFn())
John McCall17afe452010-10-16 08:21:07 +00007384 .setDoesNotReturn();
Anders Carlsson9ab53d12009-02-16 22:59:18 +00007385 }
7386
John McCall17afe452010-10-16 08:21:07 +00007387 CGF.Builder.CreateUnreachable();
Fariborz Jahanian1eab0522013-01-10 19:02:56 +00007388 if (ClearInsertionPoint)
7389 CGF.Builder.ClearInsertionPoint();
Anders Carlsson9ab53d12009-02-16 22:59:18 +00007390}
Daniel Dunbarb1559a42009-03-01 04:46:24 +00007391
John McCall2ca705e2010-07-24 00:37:23 +00007392llvm::Constant *
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007393CGObjCNonFragileABIMac::GetInterfaceEHType(const ObjCInterfaceDecl *ID,
Daniel Dunbar8f28d012009-04-08 04:21:03 +00007394 bool ForDefinition) {
Daniel Dunbarb1559a42009-03-01 04:46:24 +00007395 llvm::GlobalVariable * &Entry = EHTypeReferences[ID->getIdentifier()];
Saleem Abdulrasoole5f3eae2016-07-17 22:27:38 +00007396 StringRef ClassName = ID->getObjCRuntimeNameAsString();
Daniel Dunbarb1559a42009-03-01 04:46:24 +00007397
Daniel Dunbar8f28d012009-04-08 04:21:03 +00007398 // If we don't need a definition, return the entry if found or check
7399 // if we use an external reference.
7400 if (!ForDefinition) {
7401 if (Entry)
7402 return Entry;
Daniel Dunbard7beeea2009-04-07 06:43:45 +00007403
Daniel Dunbar8f28d012009-04-08 04:21:03 +00007404 // If this type (or a super class) has the __objc_exception__
7405 // attribute, emit an external reference.
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00007406 if (hasObjCExceptionAttribute(CGM.getContext(), ID)) {
7407 std::string EHTypeName = ("OBJC_EHTYPE_$_" + ClassName).str();
7408 Entry = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.EHTypeTy,
7409 false, llvm::GlobalValue::ExternalLinkage,
7410 nullptr, EHTypeName);
7411 if (CGM.getTriple().isOSBinFormatCOFF()) {
7412 if (ID->hasAttr<DLLExportAttr>())
7413 Entry->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
7414 else if (ID->hasAttr<DLLImportAttr>())
7415 Entry->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
7416 }
7417 return Entry;
7418 }
Daniel Dunbar8f28d012009-04-08 04:21:03 +00007419 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007420
Saleem Abdulrasoole5f3eae2016-07-17 22:27:38 +00007421 // Otherwise we need to either make a new entry or fill in the initializer.
Daniel Dunbar8f28d012009-04-08 04:21:03 +00007422 assert((!Entry || !Entry->hasInitializer()) && "Duplicate EHType definition");
Saleem Abdulrasoole5f3eae2016-07-17 22:27:38 +00007423
Daniel Dunbarb1559a42009-03-01 04:46:24 +00007424 std::string VTableName = "objc_ehtype_vtable";
Saleem Abdulrasoole5f3eae2016-07-17 22:27:38 +00007425 auto *VTableGV = CGM.getModule().getGlobalVariable(VTableName);
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00007426 if (!VTableGV) {
Saleem Abdulrasoole5f3eae2016-07-17 22:27:38 +00007427 VTableGV =
7428 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.Int8PtrTy, false,
7429 llvm::GlobalValue::ExternalLinkage, nullptr,
7430 VTableName);
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00007431 if (CGM.getTriple().isOSBinFormatCOFF())
7432 VTableGV->setDLLStorageClass(getStorage(CGM, VTableName));
7433 }
Daniel Dunbarb1559a42009-03-01 04:46:24 +00007434
Chris Lattnerece04092012-02-07 00:39:47 +00007435 llvm::Value *VTableIdx = llvm::ConstantInt::get(CGM.Int32Ty, 2);
Benjamin Kramer22d24c22011-10-15 12:20:02 +00007436 llvm::Constant *Values[] = {
David Blaikiee3b172a2015-04-02 18:55:21 +00007437 llvm::ConstantExpr::getGetElementPtr(VTableGV->getValueType(), VTableGV,
7438 VTableIdx),
7439 GetClassName(ID->getObjCRuntimeNameAsString()),
Saleem Abdulrasoole5f3eae2016-07-17 22:27:38 +00007440 GetClassGlobal((getClassSymbolPrefix() + ClassName).str()),
7441 };
7442 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.EHTypeTy, Values);
Daniel Dunbarb1559a42009-03-01 04:46:24 +00007443
Rafael Espindola554256c2014-02-26 22:25:45 +00007444 llvm::GlobalValue::LinkageTypes L = ForDefinition
7445 ? llvm::GlobalValue::ExternalLinkage
7446 : llvm::GlobalValue::WeakAnyLinkage;
Daniel Dunbar8f28d012009-04-08 04:21:03 +00007447 if (Entry) {
7448 Entry->setInitializer(Init);
7449 } else {
Saleem Abdulrasoole5f3eae2016-07-17 22:27:38 +00007450 Entry =
7451 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.EHTypeTy, false, L,
7452 Init, ("OBJC_EHTYPE_$_" + ClassName).str());
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00007453 if (CGM.getTriple().isOSBinFormatCOFF())
7454 if (hasObjCExceptionAttribute(CGM.getContext(), ID))
7455 if (ID->hasAttr<DLLExportAttr>())
7456 Entry->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
Daniel Dunbar8f28d012009-04-08 04:21:03 +00007457 }
Rafael Espindola554256c2014-02-26 22:25:45 +00007458 assert(Entry->getLinkage() == L);
Daniel Dunbar8f28d012009-04-08 04:21:03 +00007459
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00007460 if (!CGM.getTriple().isOSBinFormatCOFF())
7461 if (ID->getVisibility() == HiddenVisibility)
7462 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
Saleem Abdulrasoole5f3eae2016-07-17 22:27:38 +00007463
7464 const auto &DL = CGM.getDataLayout();
7465 Entry->setAlignment(DL.getABITypeAlignment(ObjCTypes.EHTypeTy));
Daniel Dunbar8f28d012009-04-08 04:21:03 +00007466
Rafael Espindola554256c2014-02-26 22:25:45 +00007467 if (ForDefinition)
Saleem Abdulrasool3c628af2016-10-25 21:43:28 +00007468 if (CGM.getTriple().isOSBinFormatMachO())
7469 Entry->setSection("__DATA,__objc_const");
Daniel Dunbarb1559a42009-03-01 04:46:24 +00007470
7471 return Entry;
7472}
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007473
Daniel Dunbar8b8683f2008-08-12 00:12:39 +00007474/* *** */
7475
Daniel Dunbarb036db82008-08-13 03:21:16 +00007476CodeGen::CGObjCRuntime *
7477CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
John McCall5fb5df92012-06-20 06:18:46 +00007478 switch (CGM.getLangOpts().ObjCRuntime.getKind()) {
7479 case ObjCRuntime::FragileMacOSX:
Daniel Dunbar303e2c22008-08-11 02:45:11 +00007480 return new CGObjCMac(CGM);
John McCall5fb5df92012-06-20 06:18:46 +00007481
7482 case ObjCRuntime::MacOSX:
7483 case ObjCRuntime::iOS:
Tim Northover756447a2015-10-30 16:30:36 +00007484 case ObjCRuntime::WatchOS:
John McCall5fb5df92012-06-20 06:18:46 +00007485 return new CGObjCNonFragileABIMac(CGM);
7486
David Chisnallb601c962012-07-03 20:49:52 +00007487 case ObjCRuntime::GNUstep:
7488 case ObjCRuntime::GCC:
John McCall775086e2012-07-12 02:07:58 +00007489 case ObjCRuntime::ObjFW:
John McCall5fb5df92012-06-20 06:18:46 +00007490 llvm_unreachable("these runtimes are not Mac runtimes");
7491 }
7492 llvm_unreachable("bad runtime");
Daniel Dunbar303e2c22008-08-11 02:45:11 +00007493}