blob: dd55e655ce3f040a181eccd95c87e48b9827c195 [file] [log] [blame]
Daniel Dunbarc17a4d32008-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//
10// This provides Objective-C code generation targetting the Apple runtime.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CGObjCRuntime.h"
Daniel Dunbarf77ac862008-08-11 21:35:06 +000015
16#include "CodeGenModule.h"
Daniel Dunbarb7ec2462008-08-16 03:19:19 +000017#include "CodeGenFunction.h"
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000018#include "clang/AST/ASTContext.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000019#include "clang/AST/Decl.h"
Daniel Dunbar6efc0c52008-08-13 03:21:16 +000020#include "clang/AST/DeclObjC.h"
Daniel Dunbarf77ac862008-08-11 21:35:06 +000021#include "clang/Basic/LangOptions.h"
22
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +000023#include "llvm/Intrinsics.h"
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000024#include "llvm/Module.h"
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +000025#include "llvm/ADT/DenseSet.h"
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +000026#include "llvm/Target/TargetData.h"
Daniel Dunbarb7ec2462008-08-16 03:19:19 +000027#include <sstream>
Daniel Dunbarc17a4d32008-08-11 02:45:11 +000028
29using namespace clang;
Daniel Dunbar46f45b92008-09-09 01:06:48 +000030using namespace CodeGen;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +000031
32namespace {
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000033
Daniel Dunbarae226fa2008-08-27 02:31:56 +000034 typedef std::vector<llvm::Constant*> ConstantVector;
35
Daniel Dunbar6efc0c52008-08-13 03:21:16 +000036 // FIXME: We should find a nicer way to make the labels for
37 // metadata, string concatenation is lame.
38
Fariborz Jahanianee0af742009-01-21 22:04:16 +000039class ObjCCommonTypesHelper {
40protected:
41 CodeGen::CodeGenModule &CGM;
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000042
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000043public:
Fariborz Jahanian0a855d02009-03-23 19:10:40 +000044 const llvm::Type *ShortTy, *IntTy, *LongTy, *LongLongTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +000045 const llvm::Type *Int8PtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +000046
Daniel Dunbar2bedbf82008-08-12 05:28:47 +000047 /// ObjectPtrTy - LLVM type for object handles (typeof(id))
48 const llvm::Type *ObjectPtrTy;
Fariborz Jahanian6d657c42008-11-18 20:18:11 +000049
50 /// PtrObjectPtrTy - LLVM type for id *
51 const llvm::Type *PtrObjectPtrTy;
52
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +000053 /// SelectorPtrTy - LLVM type for selector handles (typeof(SEL))
Daniel Dunbar2bedbf82008-08-12 05:28:47 +000054 const llvm::Type *SelectorPtrTy;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +000055 /// ProtocolPtrTy - LLVM type for external protocol handles
56 /// (typeof(Protocol))
57 const llvm::Type *ExternalProtocolPtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +000058
Daniel Dunbar19cd87e2008-08-30 03:02:31 +000059 // SuperCTy - clang type for struct objc_super.
60 QualType SuperCTy;
61 // SuperPtrCTy - clang type for struct objc_super *.
62 QualType SuperPtrCTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +000063
Daniel Dunbare8b470d2008-08-23 04:28:29 +000064 /// SuperTy - LLVM type for struct objc_super.
65 const llvm::StructType *SuperTy;
Daniel Dunbar14c80b72008-08-23 09:25:55 +000066 /// SuperPtrTy - LLVM type for struct objc_super *.
67 const llvm::Type *SuperPtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +000068
Fariborz Jahanian30bc5712009-01-22 23:02:58 +000069 /// PropertyTy - LLVM type for struct objc_property (struct _prop_t
70 /// in GCC parlance).
71 const llvm::StructType *PropertyTy;
72
73 /// PropertyListTy - LLVM type for struct objc_property_list
74 /// (_prop_list_t in GCC parlance).
75 const llvm::StructType *PropertyListTy;
76 /// PropertyListPtrTy - LLVM type for struct objc_property_list*.
77 const llvm::Type *PropertyListPtrTy;
78
79 // MethodTy - LLVM type for struct objc_method.
80 const llvm::StructType *MethodTy;
81
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +000082 /// CacheTy - LLVM type for struct objc_cache.
83 const llvm::Type *CacheTy;
84 /// CachePtrTy - LLVM type for struct objc_cache *.
85 const llvm::Type *CachePtrTy;
86
Chris Lattner74391b42009-03-22 21:03:39 +000087 llvm::Constant *GetPropertyFn, *SetPropertyFn;
Fariborz Jahaniandb286862009-01-22 00:37:21 +000088
Chris Lattner74391b42009-03-22 21:03:39 +000089 llvm::Constant *EnumerationMutationFn;
Fariborz Jahaniandb286862009-01-22 00:37:21 +000090
91 /// GcReadWeakFn -- LLVM objc_read_weak (id *src) function.
Chris Lattner74391b42009-03-22 21:03:39 +000092 llvm::Constant *GcReadWeakFn;
Fariborz Jahaniandb286862009-01-22 00:37:21 +000093
94 /// GcAssignWeakFn -- LLVM objc_assign_weak function.
Chris Lattner74391b42009-03-22 21:03:39 +000095 llvm::Constant *GcAssignWeakFn;
Fariborz Jahaniandb286862009-01-22 00:37:21 +000096
97 /// GcAssignGlobalFn -- LLVM objc_assign_global function.
Chris Lattner74391b42009-03-22 21:03:39 +000098 llvm::Constant *GcAssignGlobalFn;
Fariborz Jahaniandb286862009-01-22 00:37:21 +000099
100 /// GcAssignIvarFn -- LLVM objc_assign_ivar function.
Chris Lattner74391b42009-03-22 21:03:39 +0000101 llvm::Constant *GcAssignIvarFn;
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000102
103 /// GcAssignStrongCastFn -- LLVM objc_assign_strongCast function.
Chris Lattner74391b42009-03-22 21:03:39 +0000104 llvm::Constant *GcAssignStrongCastFn;
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000105
106 /// ExceptionThrowFn - LLVM objc_exception_throw function.
Chris Lattner74391b42009-03-22 21:03:39 +0000107 llvm::Constant *ExceptionThrowFn;
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000108
Daniel Dunbar1c566672009-02-24 01:43:46 +0000109 /// SyncEnterFn - LLVM object_sync_enter function.
Chris Lattnerb02e53b2009-04-06 16:53:45 +0000110 llvm::Constant *getSyncEnterFn() {
111 // void objc_sync_enter (id)
112 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
113 llvm::FunctionType *FTy =
114 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
115 return CGM.CreateRuntimeFunction(FTy, "objc_sync_enter");
116 }
Daniel Dunbar1c566672009-02-24 01:43:46 +0000117
118 /// SyncExitFn - LLVM object_sync_exit function.
Chris Lattner74391b42009-03-22 21:03:39 +0000119 llvm::Constant *SyncExitFn;
Daniel Dunbar1c566672009-02-24 01:43:46 +0000120
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000121 ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm);
122 ~ObjCCommonTypesHelper(){}
123};
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000124
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000125/// ObjCTypesHelper - Helper class that encapsulates lazy
126/// construction of varies types used during ObjC generation.
127class ObjCTypesHelper : public ObjCCommonTypesHelper {
128private:
129
Chris Lattner74391b42009-03-22 21:03:39 +0000130 llvm::Constant *MessageSendFn, *MessageSendStretFn, *MessageSendFpretFn;
131 llvm::Constant *MessageSendSuperFn, *MessageSendSuperStretFn,
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000132 *MessageSendSuperFpretFn;
133
134public:
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000135 /// SymtabTy - LLVM type for struct objc_symtab.
136 const llvm::StructType *SymtabTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000137 /// SymtabPtrTy - LLVM type for struct objc_symtab *.
138 const llvm::Type *SymtabPtrTy;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000139 /// ModuleTy - LLVM type for struct objc_module.
140 const llvm::StructType *ModuleTy;
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000141
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000142 /// ProtocolTy - LLVM type for struct objc_protocol.
143 const llvm::StructType *ProtocolTy;
144 /// ProtocolPtrTy - LLVM type for struct objc_protocol *.
145 const llvm::Type *ProtocolPtrTy;
146 /// ProtocolExtensionTy - LLVM type for struct
147 /// objc_protocol_extension.
148 const llvm::StructType *ProtocolExtensionTy;
149 /// ProtocolExtensionTy - LLVM type for struct
150 /// objc_protocol_extension *.
151 const llvm::Type *ProtocolExtensionPtrTy;
152 /// MethodDescriptionTy - LLVM type for struct
153 /// objc_method_description.
154 const llvm::StructType *MethodDescriptionTy;
155 /// MethodDescriptionListTy - LLVM type for struct
156 /// objc_method_description_list.
157 const llvm::StructType *MethodDescriptionListTy;
158 /// MethodDescriptionListPtrTy - LLVM type for struct
159 /// objc_method_description_list *.
160 const llvm::Type *MethodDescriptionListPtrTy;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000161 /// ProtocolListTy - LLVM type for struct objc_property_list.
162 const llvm::Type *ProtocolListTy;
163 /// ProtocolListPtrTy - LLVM type for struct objc_property_list*.
164 const llvm::Type *ProtocolListPtrTy;
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000165 /// CategoryTy - LLVM type for struct objc_category.
166 const llvm::StructType *CategoryTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000167 /// ClassTy - LLVM type for struct objc_class.
168 const llvm::StructType *ClassTy;
169 /// ClassPtrTy - LLVM type for struct objc_class *.
170 const llvm::Type *ClassPtrTy;
171 /// ClassExtensionTy - LLVM type for struct objc_class_ext.
172 const llvm::StructType *ClassExtensionTy;
173 /// ClassExtensionPtrTy - LLVM type for struct objc_class_ext *.
174 const llvm::Type *ClassExtensionPtrTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000175 // IvarTy - LLVM type for struct objc_ivar.
176 const llvm::StructType *IvarTy;
177 /// IvarListTy - LLVM type for struct objc_ivar_list.
178 const llvm::Type *IvarListTy;
179 /// IvarListPtrTy - LLVM type for struct objc_ivar_list *.
180 const llvm::Type *IvarListPtrTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000181 /// MethodListTy - LLVM type for struct objc_method_list.
182 const llvm::Type *MethodListTy;
183 /// MethodListPtrTy - LLVM type for struct objc_method_list *.
184 const llvm::Type *MethodListPtrTy;
Anders Carlsson124526b2008-09-09 10:10:21 +0000185
186 /// ExceptionDataTy - LLVM type for struct _objc_exception_data.
187 const llvm::Type *ExceptionDataTy;
188
Anders Carlsson124526b2008-09-09 10:10:21 +0000189 /// ExceptionTryEnterFn - LLVM objc_exception_try_enter function.
Chris Lattner74391b42009-03-22 21:03:39 +0000190 llvm::Constant *ExceptionTryEnterFn;
Anders Carlsson124526b2008-09-09 10:10:21 +0000191
192 /// ExceptionTryExitFn - LLVM objc_exception_try_exit function.
Chris Lattner74391b42009-03-22 21:03:39 +0000193 llvm::Constant *ExceptionTryExitFn;
Anders Carlsson124526b2008-09-09 10:10:21 +0000194
195 /// ExceptionExtractFn - LLVM objc_exception_extract function.
Chris Lattner74391b42009-03-22 21:03:39 +0000196 llvm::Constant *ExceptionExtractFn;
Anders Carlsson124526b2008-09-09 10:10:21 +0000197
198 /// ExceptionMatchFn - LLVM objc_exception_match function.
Chris Lattner74391b42009-03-22 21:03:39 +0000199 llvm::Constant *ExceptionMatchFn;
Anders Carlsson124526b2008-09-09 10:10:21 +0000200
201 /// SetJmpFn - LLVM _setjmp function.
Chris Lattner74391b42009-03-22 21:03:39 +0000202 llvm::Constant *SetJmpFn;
Chris Lattner10cac6f2008-11-15 21:26:17 +0000203
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000204public:
205 ObjCTypesHelper(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000206 ~ObjCTypesHelper() {}
Daniel Dunbar5669e572008-10-17 03:24:53 +0000207
208
Chris Lattner74391b42009-03-22 21:03:39 +0000209 llvm::Constant *getSendFn(bool IsSuper) {
Daniel Dunbar5669e572008-10-17 03:24:53 +0000210 return IsSuper ? MessageSendSuperFn : MessageSendFn;
211 }
212
Chris Lattner74391b42009-03-22 21:03:39 +0000213 llvm::Constant *getSendStretFn(bool IsSuper) {
Daniel Dunbar5669e572008-10-17 03:24:53 +0000214 return IsSuper ? MessageSendSuperStretFn : MessageSendStretFn;
215 }
216
Chris Lattner74391b42009-03-22 21:03:39 +0000217 llvm::Constant *getSendFpretFn(bool IsSuper) {
Daniel Dunbar5669e572008-10-17 03:24:53 +0000218 return IsSuper ? MessageSendSuperFpretFn : MessageSendFpretFn;
219 }
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000220};
221
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000222/// ObjCNonFragileABITypesHelper - will have all types needed by objective-c's
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000223/// modern abi
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000224class ObjCNonFragileABITypesHelper : public ObjCCommonTypesHelper {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000225public:
Chris Lattner74391b42009-03-22 21:03:39 +0000226 llvm::Constant *MessageSendFixupFn, *MessageSendFpretFixupFn,
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000227 *MessageSendStretFixupFn, *MessageSendIdFixupFn,
228 *MessageSendIdStretFixupFn, *MessageSendSuper2FixupFn,
229 *MessageSendSuper2StretFixupFn;
230
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000231 // MethodListnfABITy - LLVM for struct _method_list_t
232 const llvm::StructType *MethodListnfABITy;
233
234 // MethodListnfABIPtrTy - LLVM for struct _method_list_t*
235 const llvm::Type *MethodListnfABIPtrTy;
236
237 // ProtocolnfABITy = LLVM for struct _protocol_t
238 const llvm::StructType *ProtocolnfABITy;
239
Daniel Dunbar948e2582009-02-15 07:36:20 +0000240 // ProtocolnfABIPtrTy = LLVM for struct _protocol_t*
241 const llvm::Type *ProtocolnfABIPtrTy;
242
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000243 // ProtocolListnfABITy - LLVM for struct _objc_protocol_list
244 const llvm::StructType *ProtocolListnfABITy;
245
246 // ProtocolListnfABIPtrTy - LLVM for struct _objc_protocol_list*
247 const llvm::Type *ProtocolListnfABIPtrTy;
248
249 // ClassnfABITy - LLVM for struct _class_t
250 const llvm::StructType *ClassnfABITy;
251
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000252 // ClassnfABIPtrTy - LLVM for struct _class_t*
253 const llvm::Type *ClassnfABIPtrTy;
254
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000255 // IvarnfABITy - LLVM for struct _ivar_t
256 const llvm::StructType *IvarnfABITy;
257
258 // IvarListnfABITy - LLVM for struct _ivar_list_t
259 const llvm::StructType *IvarListnfABITy;
260
261 // IvarListnfABIPtrTy = LLVM for struct _ivar_list_t*
262 const llvm::Type *IvarListnfABIPtrTy;
263
264 // ClassRonfABITy - LLVM for struct _class_ro_t
265 const llvm::StructType *ClassRonfABITy;
266
267 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
268 const llvm::Type *ImpnfABITy;
269
270 // CategorynfABITy - LLVM for struct _category_t
271 const llvm::StructType *CategorynfABITy;
272
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000273 // New types for nonfragile abi messaging.
274
275 // MessageRefTy - LLVM for:
276 // struct _message_ref_t {
277 // IMP messenger;
278 // SEL name;
279 // };
280 const llvm::StructType *MessageRefTy;
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000281 // MessageRefCTy - clang type for struct _message_ref_t
282 QualType MessageRefCTy;
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000283
284 // MessageRefPtrTy - LLVM for struct _message_ref_t*
285 const llvm::Type *MessageRefPtrTy;
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000286 // MessageRefCPtrTy - clang type for struct _message_ref_t*
287 QualType MessageRefCPtrTy;
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000288
Fariborz Jahanianef163782009-02-05 01:13:09 +0000289 // MessengerTy - Type of the messenger (shown as IMP above)
290 const llvm::FunctionType *MessengerTy;
291
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000292 // SuperMessageRefTy - LLVM for:
293 // struct _super_message_ref_t {
294 // SUPER_IMP messenger;
295 // SEL name;
296 // };
297 const llvm::StructType *SuperMessageRefTy;
298
299 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
300 const llvm::Type *SuperMessageRefPtrTy;
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000301
302 /// EHPersonalityPtr - LLVM value for an i8* to the Objective-C
303 /// exception personality function.
Chris Lattnerb02e53b2009-04-06 16:53:45 +0000304 llvm::Value *getEHPersonalityPtr() {
305 llvm::Constant *Personality =
306 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
307 std::vector<const llvm::Type*>(),
308 true),
309 "__objc_personality_v0");
310 return llvm::ConstantExpr::getBitCast(Personality, Int8PtrTy);
311 }
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000312
Chris Lattner74391b42009-03-22 21:03:39 +0000313 llvm::Constant *UnwindResumeOrRethrowFn, *ObjCBeginCatchFn, *ObjCEndCatchFn;
Daniel Dunbare588b992009-03-01 04:46:24 +0000314
315 const llvm::StructType *EHTypeTy;
316 const llvm::Type *EHTypePtrTy;
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000317
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000318 ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm);
319 ~ObjCNonFragileABITypesHelper(){}
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000320};
321
322class CGObjCCommonMac : public CodeGen::CGObjCRuntime {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000323public:
324 // FIXME - accessibility
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000325 class GC_IVAR {
Fariborz Jahanian820e0202009-03-11 00:07:04 +0000326 public:
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000327 unsigned int ivar_bytepos;
328 unsigned int ivar_size;
329 GC_IVAR() : ivar_bytepos(0), ivar_size(0) {}
330 };
331
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000332 class SKIP_SCAN {
333 public:
334 unsigned int skip;
335 unsigned int scan;
336 SKIP_SCAN() : skip(0), scan(0) {}
337 };
338
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000339protected:
340 CodeGen::CodeGenModule &CGM;
341 // FIXME! May not be needing this after all.
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000342 unsigned ObjCABI;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000343
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000344 // gc ivar layout bitmap calculation helper caches.
345 llvm::SmallVector<GC_IVAR, 16> SkipIvars;
346 llvm::SmallVector<GC_IVAR, 16> IvarsInfo;
347 llvm::SmallVector<SKIP_SCAN, 32> SkipScanIvars;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000348
Daniel Dunbar242d4dc2008-08-25 06:02:07 +0000349 /// LazySymbols - Symbols to generate a lazy reference for. See
350 /// DefinedSymbols and FinishModule().
351 std::set<IdentifierInfo*> LazySymbols;
352
353 /// DefinedSymbols - External symbols which are defined by this
354 /// module. The symbols in this list and LazySymbols are used to add
355 /// special linker symbols which ensure that Objective-C modules are
356 /// linked properly.
357 std::set<IdentifierInfo*> DefinedSymbols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000358
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000359 /// ClassNames - uniqued class names.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000360 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000361
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000362 /// MethodVarNames - uniqued method variable names.
363 llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000364
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000365 /// MethodVarTypes - uniqued method type signatures. We have to use
366 /// a StringMap here because have no other unique reference.
367 llvm::StringMap<llvm::GlobalVariable*> MethodVarTypes;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000368
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000369 /// MethodDefinitions - map of methods which have been defined in
370 /// this translation unit.
371 llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> MethodDefinitions;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000372
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000373 /// PropertyNames - uniqued method variable names.
374 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000375
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000376 /// ClassReferences - uniqued class references.
377 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000378
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000379 /// SelectorReferences - uniqued selector references.
380 llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000381
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000382 /// Protocols - Protocols for which an objc_protocol structure has
383 /// been emitted. Forward declarations are handled by creating an
384 /// empty structure whose initializer is filled in when/if defined.
385 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> Protocols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000386
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000387 /// DefinedProtocols - Protocols which have actually been
388 /// defined. We should not need this, see FIXME in GenerateProtocol.
389 llvm::DenseSet<IdentifierInfo*> DefinedProtocols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000390
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000391 /// DefinedClasses - List of defined classes.
392 std::vector<llvm::GlobalValue*> DefinedClasses;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000393
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000394 /// DefinedCategories - List of defined categories.
395 std::vector<llvm::GlobalValue*> DefinedCategories;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000396
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000397 /// UsedGlobals - List of globals to pack into the llvm.used metadata
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000398 /// to prevent them from being clobbered.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000399 std::vector<llvm::GlobalVariable*> UsedGlobals;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000400
Fariborz Jahanian56210f72009-01-21 23:34:32 +0000401 /// GetNameForMethod - Return a name for the given method.
402 /// \param[out] NameOut - The return value.
403 void GetNameForMethod(const ObjCMethodDecl *OMD,
404 const ObjCContainerDecl *CD,
405 std::string &NameOut);
406
407 /// GetMethodVarName - Return a unique constant for the given
408 /// selector's name. The return value has type char *.
409 llvm::Constant *GetMethodVarName(Selector Sel);
410 llvm::Constant *GetMethodVarName(IdentifierInfo *Ident);
411 llvm::Constant *GetMethodVarName(const std::string &Name);
412
413 /// GetMethodVarType - Return a unique constant for the given
414 /// selector's name. The return value has type char *.
415
416 // FIXME: This is a horrible name.
417 llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D);
Devang Patel7794bb82009-03-04 18:21:39 +0000418 llvm::Constant *GetMethodVarType(FieldDecl *D);
Fariborz Jahanian56210f72009-01-21 23:34:32 +0000419
420 /// GetPropertyName - Return a unique constant for the given
421 /// name. The return value has type char *.
422 llvm::Constant *GetPropertyName(IdentifierInfo *Ident);
423
424 // FIXME: This can be dropped once string functions are unified.
425 llvm::Constant *GetPropertyTypeString(const ObjCPropertyDecl *PD,
426 const Decl *Container);
427
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000428 /// GetClassName - Return a unique constant for the given selector's
429 /// name. The return value has type char *.
430 llvm::Constant *GetClassName(IdentifierInfo *Ident);
431
Fariborz Jahanian21e6f172009-03-11 21:42:00 +0000432 /// GetInterfaceDeclStructLayout - Get layout for ivars of given
433 /// interface declaration.
434 const llvm::StructLayout *GetInterfaceDeclStructLayout(
435 const ObjCInterfaceDecl *ID) const;
436
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000437 /// BuildIvarLayout - Builds ivar layout bitmap for the class
438 /// implementation for the __strong or __weak case.
439 ///
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000440 llvm::Constant *BuildIvarLayout(const ObjCImplementationDecl *OI,
441 bool ForStrongLayout);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000442
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000443 void BuildAggrIvarLayout(const ObjCInterfaceDecl *OI,
444 const llvm::StructLayout *Layout,
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000445 const RecordDecl *RD,
Chris Lattnerf1690852009-03-31 08:48:01 +0000446 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000447 unsigned int BytePos, bool ForStrongLayout,
448 int &Index, int &SkIndex, bool &HasUnion);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000449
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +0000450 /// GetIvarLayoutName - Returns a unique constant for the given
451 /// ivar layout bitmap.
452 llvm::Constant *GetIvarLayoutName(IdentifierInfo *Ident,
453 const ObjCCommonTypesHelper &ObjCTypes);
454
Fariborz Jahanian46b86c62009-01-28 19:12:34 +0000455 const RecordDecl *GetFirstIvarInRecord(const ObjCInterfaceDecl *OID,
456 RecordDecl::field_iterator &FIV,
457 RecordDecl::field_iterator &PIV);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +0000458 /// EmitPropertyList - Emit the given property list. The return
459 /// value has type PropertyListPtrTy.
460 llvm::Constant *EmitPropertyList(const std::string &Name,
461 const Decl *Container,
462 const ObjCContainerDecl *OCD,
463 const ObjCCommonTypesHelper &ObjCTypes);
464
Fariborz Jahanianda320092009-01-29 19:24:30 +0000465 /// GetProtocolRef - Return a reference to the internal protocol
466 /// description, creating an empty one if it has not been
467 /// defined. The return value has type ProtocolPtrTy.
468 llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +0000469
470 /// GetIvarBaseOffset - returns ivars byte offset.
471 uint64_t GetIvarBaseOffset(const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +0000472 const FieldDecl *Field);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000473
Chris Lattnercd0ee142009-03-31 08:33:16 +0000474 /// GetFieldBaseOffset - return's field byte offset.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000475 uint64_t GetFieldBaseOffset(const ObjCInterfaceDecl *OI,
476 const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +0000477 const FieldDecl *Field);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000478
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000479 /// CreateMetadataVar - Create a global variable with internal
480 /// linkage for use by the Objective-C runtime.
481 ///
482 /// This is a convenience wrapper which not only creates the
483 /// variable, but also sets the section and alignment and adds the
484 /// global to the UsedGlobals list.
Daniel Dunbar35bd7632009-03-09 20:50:13 +0000485 ///
486 /// \param Name - The variable name.
487 /// \param Init - The variable initializer; this is also used to
488 /// define the type of the variable.
489 /// \param Section - The section the variable should go into, or 0.
490 /// \param Align - The alignment for the variable, or 0.
491 /// \param AddToUsed - Whether the variable should be added to
Daniel Dunbarc1583062009-04-14 17:42:51 +0000492 /// "llvm.used".
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000493 llvm::GlobalVariable *CreateMetadataVar(const std::string &Name,
494 llvm::Constant *Init,
495 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +0000496 unsigned Align,
497 bool AddToUsed);
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000498
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000499public:
500 CGObjCCommonMac(CodeGen::CodeGenModule &cgm) : CGM(cgm)
501 { }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000502
Steve Naroff33fdb732009-03-31 16:53:37 +0000503 virtual llvm::Constant *GenerateConstantString(const ObjCStringLiteral *SL);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000504
505 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
506 const ObjCContainerDecl *CD=0);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000507
508 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
509
510 /// GetOrEmitProtocol - Get the protocol object for the given
511 /// declaration, emitting it if necessary. The return value has type
512 /// ProtocolPtrTy.
513 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD)=0;
514
515 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
516 /// object for the given declaration, emitting it if needed. These
517 /// forward references will be filled in with empty bodies if no
518 /// definition is seen. The return value has type ProtocolPtrTy.
519 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD)=0;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000520};
521
522class CGObjCMac : public CGObjCCommonMac {
523private:
524 ObjCTypesHelper ObjCTypes;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000525 /// EmitImageInfo - Emit the image info marker used to encode some module
526 /// level information.
527 void EmitImageInfo();
528
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000529 /// EmitModuleInfo - Another marker encoding module level
530 /// information.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000531 void EmitModuleInfo();
532
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000533 /// EmitModuleSymols - Emit module symbols, the list of defined
534 /// classes and categories. The result has type SymtabPtrTy.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000535 llvm::Constant *EmitModuleSymbols();
536
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000537 /// FinishModule - Write out global data structures at the end of
538 /// processing a translation unit.
539 void FinishModule();
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000540
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000541 /// EmitClassExtension - Generate the class extension structure used
542 /// to store the weak ivar layout and properties. The return value
543 /// has type ClassExtensionPtrTy.
544 llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID);
545
546 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
547 /// for the given class.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000548 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000549 const ObjCInterfaceDecl *ID);
550
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000551 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000552 QualType ResultType,
553 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000554 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000555 QualType Arg0Ty,
556 bool IsSuper,
557 const CallArgList &CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000558
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000559 /// EmitIvarList - Emit the ivar list for the given
560 /// implementation. If ForClass is true the list of class ivars
561 /// (i.e. metaclass ivars) is emitted, otherwise the list of
562 /// interface ivars will be emitted. The return value has type
563 /// IvarListPtrTy.
564 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +0000565 bool ForClass);
566
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000567 /// EmitMetaClass - Emit a forward reference to the class structure
568 /// for the metaclass of the given interface. The return value has
569 /// type ClassPtrTy.
570 llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
571
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000572 /// EmitMetaClass - Emit a class structure for the metaclass of the
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000573 /// given implementation. The return value has type ClassPtrTy.
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000574 llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
575 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000576 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000577 const ConstantVector &Methods);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000578
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000579 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000580
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000581 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000582
583 /// EmitMethodList - Emit the method list for the given
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000584 /// implementation. The return value has type MethodListPtrTy.
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000585 llvm::Constant *EmitMethodList(const std::string &Name,
586 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000587 const ConstantVector &Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000588
589 /// EmitMethodDescList - Emit a method description list for a list of
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000590 /// method declarations.
591 /// - TypeName: The name for the type containing the methods.
592 /// - IsProtocol: True iff these methods are for a protocol.
593 /// - ClassMethds: True iff these are class methods.
594 /// - Required: When true, only "required" methods are
595 /// listed. Similarly, when false only "optional" methods are
596 /// listed. For classes this should always be true.
597 /// - begin, end: The method list to output.
598 ///
599 /// The return value has type MethodDescriptionListPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000600 llvm::Constant *EmitMethodDescList(const std::string &Name,
601 const char *Section,
602 const ConstantVector &Methods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000603
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000604 /// GetOrEmitProtocol - Get the protocol object for the given
605 /// declaration, emitting it if necessary. The return value has type
606 /// ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +0000607 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000608
609 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
610 /// object for the given declaration, emitting it if needed. These
611 /// forward references will be filled in with empty bodies if no
612 /// definition is seen. The return value has type ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +0000613 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000614
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000615 /// EmitProtocolExtension - Generate the protocol extension
616 /// structure used to store optional instance and class methods, and
617 /// protocol properties. The return value has type
618 /// ProtocolExtensionPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000619 llvm::Constant *
620 EmitProtocolExtension(const ObjCProtocolDecl *PD,
621 const ConstantVector &OptInstanceMethods,
622 const ConstantVector &OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000623
624 /// EmitProtocolList - Generate the list of referenced
625 /// protocols. The return value has type ProtocolListPtrTy.
Daniel Dunbardbc933702008-08-21 21:57:41 +0000626 llvm::Constant *EmitProtocolList(const std::string &Name,
627 ObjCProtocolDecl::protocol_iterator begin,
628 ObjCProtocolDecl::protocol_iterator end);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000629
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000630 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
631 /// for the given selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000632 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000633
Fariborz Jahanianda320092009-01-29 19:24:30 +0000634 public:
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000635 CGObjCMac(CodeGen::CodeGenModule &cgm);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000636
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000637 virtual llvm::Function *ModuleInitFunction();
638
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000639 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000640 QualType ResultType,
641 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000642 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000643 bool IsClassMessage,
644 const CallArgList &CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000645
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000646 virtual CodeGen::RValue
647 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000648 QualType ResultType,
649 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000650 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000651 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000652 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000653 bool IsClassMessage,
654 const CallArgList &CallArgs);
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000655
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000656 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000657 const ObjCInterfaceDecl *ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000658
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000659 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000660
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000661 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000662
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000663 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000664
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000665 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000666 const ObjCProtocolDecl *PD);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000667
Chris Lattner74391b42009-03-22 21:03:39 +0000668 virtual llvm::Constant *GetPropertyGetFunction();
669 virtual llvm::Constant *GetPropertySetFunction();
670 virtual llvm::Constant *EnumerationMutationFunction();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000671
Fariborz Jahanianbd71be42008-11-21 00:49:24 +0000672 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
673 const Stmt &S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000674 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
675 const ObjCAtThrowStmt &S);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000676 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +0000677 llvm::Value *AddrWeakObj);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000678 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
679 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000680 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
681 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian7eda8362008-11-20 19:23:36 +0000682 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
683 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000684 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
685 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian0bb20362009-02-02 20:02:29 +0000686
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000687 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
688 QualType ObjectTy,
689 llvm::Value *BaseValue,
690 const ObjCIvarDecl *Ivar,
691 const FieldDecl *Field,
692 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000693 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
694 ObjCInterfaceDecl *Interface,
695 const ObjCIvarDecl *Ivar);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000696};
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000697
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000698class CGObjCNonFragileABIMac : public CGObjCCommonMac {
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000699private:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000700 ObjCNonFragileABITypesHelper ObjCTypes;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000701 llvm::GlobalVariable* ObjCEmptyCacheVar;
702 llvm::GlobalVariable* ObjCEmptyVtableVar;
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000703
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000704 /// MetaClassReferences - uniqued meta class references.
705 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> MetaClassReferences;
Daniel Dunbare588b992009-03-01 04:46:24 +0000706
707 /// EHTypeReferences - uniqued class ehtype references.
708 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> EHTypeReferences;
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000709
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000710 /// FinishNonFragileABIModule - Write out global data structures at the end of
711 /// processing a translation unit.
712 void FinishNonFragileABIModule();
Daniel Dunbar8158a2f2009-04-08 04:21:03 +0000713
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000714 llvm::GlobalVariable * BuildClassRoTInitializer(unsigned flags,
715 unsigned InstanceStart,
716 unsigned InstanceSize,
717 const ObjCImplementationDecl *ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +0000718 llvm::GlobalVariable * BuildClassMetaData(std::string &ClassName,
719 llvm::Constant *IsAGV,
720 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +0000721 llvm::Constant *ClassRoGV,
722 bool HiddenVisibility);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000723
724 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
725
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +0000726 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
727
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000728 /// EmitMethodList - Emit the method list for the given
729 /// implementation. The return value has type MethodListnfABITy.
730 llvm::Constant *EmitMethodList(const std::string &Name,
731 const char *Section,
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +0000732 const ConstantVector &Methods);
733 /// EmitIvarList - Emit the ivar list for the given
734 /// implementation. If ForClass is true the list of class ivars
735 /// (i.e. metaclass ivars) is emitted, otherwise the list of
736 /// interface ivars will be emitted. The return value has type
737 /// IvarListnfABIPtrTy.
738 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000739
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000740 llvm::Constant *EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +0000741 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +0000742 unsigned long int offset);
743
Fariborz Jahanianda320092009-01-29 19:24:30 +0000744 /// GetOrEmitProtocol - Get the protocol object for the given
745 /// declaration, emitting it if necessary. The return value has type
746 /// ProtocolPtrTy.
747 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
748
749 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
750 /// object for the given declaration, emitting it if needed. These
751 /// forward references will be filled in with empty bodies if no
752 /// definition is seen. The return value has type ProtocolPtrTy.
753 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
754
755 /// EmitProtocolList - Generate the list of referenced
756 /// protocols. The return value has type ProtocolListPtrTy.
757 llvm::Constant *EmitProtocolList(const std::string &Name,
758 ObjCProtocolDecl::protocol_iterator begin,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000759 ObjCProtocolDecl::protocol_iterator end);
760
761 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
762 QualType ResultType,
763 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000764 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000765 QualType Arg0Ty,
766 bool IsSuper,
767 const CallArgList &CallArgs);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +0000768
769 /// GetClassGlobal - Return the global variable for the Objective-C
770 /// class of the given name.
Fariborz Jahanian0f902942009-04-14 18:41:56 +0000771 llvm::GlobalVariable *GetClassGlobal(const std::string &Name);
772
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000773 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
774 /// for the given class.
775 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000776 const ObjCInterfaceDecl *ID,
777 bool IsSuper = false);
778
779 /// EmitMetaClassRef - Return a Value * of the address of _class_t
780 /// meta-data
781 llvm::Value *EmitMetaClassRef(CGBuilderTy &Builder,
782 const ObjCInterfaceDecl *ID);
783
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000784 /// ObjCIvarOffsetVariable - Returns the ivar offset variable for
785 /// the given ivar.
786 ///
787 llvm::GlobalVariable * ObjCIvarOffsetVariable(std::string &Name,
Fariborz Jahanian01a0c362009-02-12 18:51:23 +0000788 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000789 const ObjCIvarDecl *Ivar);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000790
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +0000791 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
792 /// for the given selector.
793 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbare588b992009-03-01 04:46:24 +0000794
Daniel Dunbar8158a2f2009-04-08 04:21:03 +0000795 /// GetInterfaceEHType - Get the cached ehtype for the given Objective-C
Daniel Dunbare588b992009-03-01 04:46:24 +0000796 /// interface. The return value has type EHTypePtrTy.
Daniel Dunbar8158a2f2009-04-08 04:21:03 +0000797 llvm::Value *GetInterfaceEHType(const ObjCInterfaceDecl *ID,
798 bool ForDefinition);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +0000799
800 const char *getMetaclassSymbolPrefix() const {
801 return "OBJC_METACLASS_$_";
802 }
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000803
Daniel Dunbar6ab187a2009-04-07 05:48:37 +0000804 const char *getClassSymbolPrefix() const {
805 return "OBJC_CLASS_$_";
806 }
807
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000808public:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000809 CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000810 // FIXME. All stubs for now!
811 virtual llvm::Function *ModuleInitFunction();
812
813 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
814 QualType ResultType,
815 Selector Sel,
816 llvm::Value *Receiver,
817 bool IsClassMessage,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000818 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000819
820 virtual CodeGen::RValue
821 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
822 QualType ResultType,
823 Selector Sel,
824 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000825 bool isCategoryImpl,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000826 llvm::Value *Receiver,
827 bool IsClassMessage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000828 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000829
830 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000831 const ObjCInterfaceDecl *ID);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000832
833 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel)
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +0000834 { return EmitSelector(Builder, Sel); }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000835
Fariborz Jahanianeb062d92009-01-26 18:32:24 +0000836 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000837
838 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000839 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +0000840 const ObjCProtocolDecl *PD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000841
Chris Lattner74391b42009-03-22 21:03:39 +0000842 virtual llvm::Constant *GetPropertyGetFunction() {
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000843 return ObjCTypes.GetPropertyFn;
844 }
Chris Lattner74391b42009-03-22 21:03:39 +0000845 virtual llvm::Constant *GetPropertySetFunction() {
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000846 return ObjCTypes.SetPropertyFn;
847 }
Chris Lattner74391b42009-03-22 21:03:39 +0000848 virtual llvm::Constant *EnumerationMutationFunction() {
Daniel Dunbar28ed0842009-02-16 18:48:45 +0000849 return ObjCTypes.EnumerationMutationFn;
850 }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000851
852 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000853 const Stmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000854 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000855 const ObjCAtThrowStmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000856 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000857 llvm::Value *AddrWeakObj);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000858 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000859 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000860 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000861 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000862 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000863 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000864 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000865 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000866 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
867 QualType ObjectTy,
868 llvm::Value *BaseValue,
869 const ObjCIvarDecl *Ivar,
870 const FieldDecl *Field,
871 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000872 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
873 ObjCInterfaceDecl *Interface,
874 const ObjCIvarDecl *Ivar);
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000875};
876
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000877} // end anonymous namespace
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000878
879/* *** Helper Functions *** */
880
881/// getConstantGEP() - Help routine to construct simple GEPs.
882static llvm::Constant *getConstantGEP(llvm::Constant *C,
883 unsigned idx0,
884 unsigned idx1) {
885 llvm::Value *Idxs[] = {
886 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx0),
887 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx1)
888 };
889 return llvm::ConstantExpr::getGetElementPtr(C, Idxs, 2);
890}
891
Daniel Dunbar8158a2f2009-04-08 04:21:03 +0000892/// hasObjCExceptionAttribute - Return true if this class or any super
893/// class has the __objc_exception__ attribute.
894static bool hasObjCExceptionAttribute(const ObjCInterfaceDecl *OID) {
Daniel Dunbarb11fa0d2009-04-13 21:08:27 +0000895 if (OID->hasAttr<ObjCExceptionAttr>())
Daniel Dunbar8158a2f2009-04-08 04:21:03 +0000896 return true;
897 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
898 return hasObjCExceptionAttribute(Super);
899 return false;
900}
901
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000902/* *** CGObjCMac Public Interface *** */
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000903
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000904CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm),
905 ObjCTypes(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000906{
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000907 ObjCABI = 1;
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000908 EmitImageInfo();
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000909}
910
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000911/// GetClass - Return a reference to the class for the given interface
912/// decl.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000913llvm::Value *CGObjCMac::GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000914 const ObjCInterfaceDecl *ID) {
915 return EmitClassRef(Builder, ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000916}
917
918/// GetSelector - Return the pointer to the unique'd string for this selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000919llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000920 return EmitSelector(Builder, Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000921}
922
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000923/// Generate a constant CFString object.
924/*
925 struct __builtin_CFString {
926 const int *isa; // point to __CFConstantStringClassReference
927 int flags;
928 const char *str;
929 long length;
930 };
931*/
932
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000933llvm::Constant *CGObjCCommonMac::GenerateConstantString(
Steve Naroff33fdb732009-03-31 16:53:37 +0000934 const ObjCStringLiteral *SL) {
Steve Naroff8d4141f2009-04-01 13:55:36 +0000935 return CGM.GetAddrOfConstantCFString(SL->getString());
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000936}
937
938/// Generates a message send where the super is the receiver. This is
939/// a message send to self with special delivery semantics indicating
940/// which class's method should be called.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000941CodeGen::RValue
942CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000943 QualType ResultType,
944 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000945 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000946 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000947 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000948 bool IsClassMessage,
Daniel Dunbar46f45b92008-09-09 01:06:48 +0000949 const CodeGen::CallArgList &CallArgs) {
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000950 // Create and init a super structure; this is a (receiver, class)
951 // pair we will pass to objc_msgSendSuper.
952 llvm::Value *ObjCSuper =
953 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
954 llvm::Value *ReceiverAsObject =
955 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
956 CGF.Builder.CreateStore(ReceiverAsObject,
957 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000958
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000959 // If this is a class message the metaclass is passed as the target.
960 llvm::Value *Target;
961 if (IsClassMessage) {
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000962 if (isCategoryImpl) {
963 // Message sent to 'super' in a class method defined in a category
964 // implementation requires an odd treatment.
965 // If we are in a class method, we must retrieve the
966 // _metaclass_ for the current class, pointed at by
967 // the class's "isa" pointer. The following assumes that
968 // isa" is the first ivar in a class (which it must be).
969 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
970 Target = CGF.Builder.CreateStructGEP(Target, 0);
971 Target = CGF.Builder.CreateLoad(Target);
972 }
973 else {
974 llvm::Value *MetaClassPtr = EmitMetaClassRef(Class);
975 llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1);
976 llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr);
977 Target = Super;
978 }
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000979 } else {
980 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
981 }
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000982 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
983 // and ObjCTypes types.
984 const llvm::Type *ClassTy =
985 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000986 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000987 CGF.Builder.CreateStore(Target,
988 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
989
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000990 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000991 ObjCSuper, ObjCTypes.SuperPtrCTy,
992 true, CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000993}
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000994
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000995/// Generate code for a message send expression.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000996CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000997 QualType ResultType,
998 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000999 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001000 bool IsClassMessage,
1001 const CallArgList &CallArgs) {
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001002 llvm::Value *Arg0 =
1003 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy, "tmp");
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001004 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001005 Arg0, CGF.getContext().getObjCIdType(),
1006 false, CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001007}
1008
1009CodeGen::RValue CGObjCMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001010 QualType ResultType,
1011 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001012 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001013 QualType Arg0Ty,
1014 bool IsSuper,
1015 const CallArgList &CallArgs) {
1016 CallArgList ActualArgs;
Daniel Dunbar46f45b92008-09-09 01:06:48 +00001017 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
1018 ActualArgs.push_back(std::make_pair(RValue::get(EmitSelector(CGF.Builder,
1019 Sel)),
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001020 CGF.getContext().getObjCSelType()));
1021 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001022
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001023 CodeGenTypes &Types = CGM.getTypes();
1024 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs);
1025 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo, false);
Daniel Dunbar5669e572008-10-17 03:24:53 +00001026
1027 llvm::Constant *Fn;
Daniel Dunbar88b53962009-02-02 22:03:45 +00001028 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Daniel Dunbar5669e572008-10-17 03:24:53 +00001029 Fn = ObjCTypes.getSendStretFn(IsSuper);
1030 } else if (ResultType->isFloatingType()) {
1031 // FIXME: Sadly, this is wrong. This actually depends on the
1032 // architecture. This happens to be right for x86-32 though.
1033 Fn = ObjCTypes.getSendFpretFn(IsSuper);
1034 } else {
1035 Fn = ObjCTypes.getSendFn(IsSuper);
1036 }
Daniel Dunbar62d5c1b2008-09-10 07:00:50 +00001037 Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy));
Daniel Dunbar88b53962009-02-02 22:03:45 +00001038 return CGF.EmitCall(FnInfo, Fn, ActualArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001039}
1040
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001041llvm::Value *CGObjCMac::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001042 const ObjCProtocolDecl *PD) {
Daniel Dunbarc67876d2008-09-04 04:33:15 +00001043 // FIXME: I don't understand why gcc generates this, or where it is
1044 // resolved. Investigate. Its also wasteful to look this up over and
1045 // over.
1046 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1047
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001048 return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
1049 ObjCTypes.ExternalProtocolPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001050}
1051
Fariborz Jahanianda320092009-01-29 19:24:30 +00001052void CGObjCCommonMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001053 // FIXME: We shouldn't need this, the protocol decl should contain
1054 // enough information to tell us whether this was a declaration or a
1055 // definition.
1056 DefinedProtocols.insert(PD->getIdentifier());
1057
1058 // If we have generated a forward reference to this protocol, emit
1059 // it now. Otherwise do nothing, the protocol objects are lazily
1060 // emitted.
1061 if (Protocols.count(PD->getIdentifier()))
1062 GetOrEmitProtocol(PD);
1063}
1064
Fariborz Jahanianda320092009-01-29 19:24:30 +00001065llvm::Constant *CGObjCCommonMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001066 if (DefinedProtocols.count(PD->getIdentifier()))
1067 return GetOrEmitProtocol(PD);
1068 return GetOrEmitProtocolRef(PD);
1069}
1070
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001071/*
1072 // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions
1073 struct _objc_protocol {
1074 struct _objc_protocol_extension *isa;
1075 char *protocol_name;
1076 struct _objc_protocol_list *protocol_list;
1077 struct _objc__method_prototype_list *instance_methods;
1078 struct _objc__method_prototype_list *class_methods
1079 };
1080
1081 See EmitProtocolExtension().
1082*/
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001083llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
1084 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1085
1086 // Early exit if a defining object has already been generated.
1087 if (Entry && Entry->hasInitializer())
1088 return Entry;
1089
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001090 // FIXME: I don't understand why gcc generates this, or where it is
1091 // resolved. Investigate. Its also wasteful to look this up over and
1092 // over.
1093 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1094
Chris Lattner8ec03f52008-11-24 03:54:41 +00001095 const char *ProtocolName = PD->getNameAsCString();
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001096
1097 // Construct method lists.
1098 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1099 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregor6ab35242009-04-09 21:40:53 +00001100 for (ObjCProtocolDecl::instmeth_iterator
1101 i = PD->instmeth_begin(CGM.getContext()),
1102 e = PD->instmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001103 ObjCMethodDecl *MD = *i;
1104 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1105 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1106 OptInstanceMethods.push_back(C);
1107 } else {
1108 InstanceMethods.push_back(C);
1109 }
1110 }
1111
Douglas Gregor6ab35242009-04-09 21:40:53 +00001112 for (ObjCProtocolDecl::classmeth_iterator
1113 i = PD->classmeth_begin(CGM.getContext()),
1114 e = PD->classmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001115 ObjCMethodDecl *MD = *i;
1116 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1117 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1118 OptClassMethods.push_back(C);
1119 } else {
1120 ClassMethods.push_back(C);
1121 }
1122 }
1123
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001124 std::vector<llvm::Constant*> Values(5);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001125 Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001126 Values[1] = GetClassName(PD->getIdentifier());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001127 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001128 EmitProtocolList("\01L_OBJC_PROTOCOL_REFS_" + PD->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001129 PD->protocol_begin(),
1130 PD->protocol_end());
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001131 Values[3] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001132 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_"
1133 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001134 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1135 InstanceMethods);
1136 Values[4] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001137 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_"
1138 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001139 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1140 ClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001141 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
1142 Values);
1143
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001144 if (Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001145 // Already created, fix the linkage and update the initializer.
1146 Entry->setLinkage(llvm::GlobalValue::InternalLinkage);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001147 Entry->setInitializer(Init);
1148 } else {
1149 Entry =
1150 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
1151 llvm::GlobalValue::InternalLinkage,
1152 Init,
1153 std::string("\01L_OBJC_PROTOCOL_")+ProtocolName,
1154 &CGM.getModule());
1155 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001156 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001157 UsedGlobals.push_back(Entry);
1158 // FIXME: Is this necessary? Why only for protocol?
1159 Entry->setAlignment(4);
1160 }
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001161
1162 return Entry;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001163}
1164
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001165llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001166 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1167
1168 if (!Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001169 // We use the initializer as a marker of whether this is a forward
1170 // reference or not. At module finalization we add the empty
1171 // contents for protocols which were referenced but never defined.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001172 Entry =
1173 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001174 llvm::GlobalValue::ExternalLinkage,
1175 0,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001176 "\01L_OBJC_PROTOCOL_" + PD->getNameAsString(),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001177 &CGM.getModule());
1178 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001179 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001180 UsedGlobals.push_back(Entry);
1181 // FIXME: Is this necessary? Why only for protocol?
1182 Entry->setAlignment(4);
1183 }
1184
1185 return Entry;
1186}
1187
1188/*
1189 struct _objc_protocol_extension {
1190 uint32_t size;
1191 struct objc_method_description_list *optional_instance_methods;
1192 struct objc_method_description_list *optional_class_methods;
1193 struct objc_property_list *instance_properties;
1194 };
1195*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001196llvm::Constant *
1197CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
1198 const ConstantVector &OptInstanceMethods,
1199 const ConstantVector &OptClassMethods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001200 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001201 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolExtensionTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001202 std::vector<llvm::Constant*> Values(4);
1203 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001204 Values[1] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001205 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_"
1206 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001207 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1208 OptInstanceMethods);
1209 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001210 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_"
1211 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001212 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1213 OptClassMethods);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001214 Values[3] = EmitPropertyList("\01L_OBJC_$_PROP_PROTO_LIST_" +
1215 PD->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001216 0, PD, ObjCTypes);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001217
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001218 // Return null if no extension bits are used.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001219 if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
1220 Values[3]->isNullValue())
1221 return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
1222
1223 llvm::Constant *Init =
1224 llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001225
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001226 // No special section, but goes in llvm.used
1227 return CreateMetadataVar("\01L_OBJC_PROTOCOLEXT_" + PD->getNameAsString(),
1228 Init,
1229 0, 0, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001230}
1231
1232/*
1233 struct objc_protocol_list {
1234 struct objc_protocol_list *next;
1235 long count;
1236 Protocol *list[];
1237 };
1238*/
Daniel Dunbardbc933702008-08-21 21:57:41 +00001239llvm::Constant *
1240CGObjCMac::EmitProtocolList(const std::string &Name,
1241 ObjCProtocolDecl::protocol_iterator begin,
1242 ObjCProtocolDecl::protocol_iterator end) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001243 std::vector<llvm::Constant*> ProtocolRefs;
1244
Daniel Dunbardbc933702008-08-21 21:57:41 +00001245 for (; begin != end; ++begin)
1246 ProtocolRefs.push_back(GetProtocolRef(*begin));
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001247
1248 // Just return null for empty protocol lists
1249 if (ProtocolRefs.empty())
1250 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1251
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001252 // This list is null terminated.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001253 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
1254
1255 std::vector<llvm::Constant*> Values(3);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001256 // This field is only used by the runtime.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001257 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1258 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
1259 Values[2] =
1260 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
1261 ProtocolRefs.size()),
1262 ProtocolRefs);
1263
1264 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1265 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001266 CreateMetadataVar(Name, Init, "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001267 4, false);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001268 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
1269}
1270
1271/*
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001272 struct _objc_property {
1273 const char * const name;
1274 const char * const attributes;
1275 };
1276
1277 struct _objc_property_list {
1278 uint32_t entsize; // sizeof (struct _objc_property)
1279 uint32_t prop_count;
1280 struct _objc_property[prop_count];
1281 };
1282*/
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001283llvm::Constant *CGObjCCommonMac::EmitPropertyList(const std::string &Name,
1284 const Decl *Container,
1285 const ObjCContainerDecl *OCD,
1286 const ObjCCommonTypesHelper &ObjCTypes) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001287 std::vector<llvm::Constant*> Properties, Prop(2);
Douglas Gregor6ab35242009-04-09 21:40:53 +00001288 for (ObjCContainerDecl::prop_iterator I = OCD->prop_begin(CGM.getContext()),
1289 E = OCD->prop_end(CGM.getContext()); I != E; ++I) {
Steve Naroff93983f82009-01-11 12:47:58 +00001290 const ObjCPropertyDecl *PD = *I;
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001291 Prop[0] = GetPropertyName(PD->getIdentifier());
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00001292 Prop[1] = GetPropertyTypeString(PD, Container);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001293 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
1294 Prop));
1295 }
1296
1297 // Return null for empty list.
1298 if (Properties.empty())
1299 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1300
1301 unsigned PropertySize =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001302 CGM.getTargetData().getTypePaddedSize(ObjCTypes.PropertyTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001303 std::vector<llvm::Constant*> Values(3);
1304 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
1305 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
1306 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
1307 Properties.size());
1308 Values[2] = llvm::ConstantArray::get(AT, Properties);
1309 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1310
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001311 // No special section on property lists?
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001312 llvm::GlobalVariable *GV =
1313 CreateMetadataVar(Name, Init, (ObjCABI == 2) ? "__DATA, __objc_const" : 0,
1314 0, true);
1315 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.PropertyListPtrTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001316}
1317
1318/*
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001319 struct objc_method_description_list {
1320 int count;
1321 struct objc_method_description list[];
1322 };
1323*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001324llvm::Constant *
1325CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
1326 std::vector<llvm::Constant*> Desc(2);
1327 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1328 ObjCTypes.SelectorPtrTy);
1329 Desc[1] = GetMethodVarType(MD);
1330 return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
1331 Desc);
1332}
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001333
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001334llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name,
1335 const char *Section,
1336 const ConstantVector &Methods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001337 // Return null for empty list.
1338 if (Methods.empty())
1339 return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
1340
1341 std::vector<llvm::Constant*> Values(2);
1342 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1343 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
1344 Methods.size());
1345 Values[1] = llvm::ConstantArray::get(AT, Methods);
1346 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1347
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001348 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 0, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001349 return llvm::ConstantExpr::getBitCast(GV,
1350 ObjCTypes.MethodDescriptionListPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001351}
1352
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001353/*
1354 struct _objc_category {
1355 char *category_name;
1356 char *class_name;
1357 struct _objc_method_list *instance_methods;
1358 struct _objc_method_list *class_methods;
1359 struct _objc_protocol_list *protocols;
1360 uint32_t size; // <rdar://4585769>
1361 struct _objc_property_list *instance_properties;
1362 };
1363 */
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001364void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001365 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.CategoryTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001366
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001367 // FIXME: This is poor design, the OCD should have a pointer to the
1368 // category decl. Additionally, note that Category can be null for
1369 // the @implementation w/o an @interface case. Sema should just
1370 // create one for us as it does for @implementation so everyone else
1371 // can live life under a clear blue sky.
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001372 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001373 const ObjCCategoryDecl *Category =
1374 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001375 std::string ExtName(Interface->getNameAsString() + "_" +
1376 OCD->getNameAsString());
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001377
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001378 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1379 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
1380 e = OCD->instmeth_end(); i != e; ++i) {
1381 // Instance methods should always be defined.
1382 InstanceMethods.push_back(GetMethodConstant(*i));
1383 }
1384 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
1385 e = OCD->classmeth_end(); i != e; ++i) {
1386 // Class methods should always be defined.
1387 ClassMethods.push_back(GetMethodConstant(*i));
1388 }
1389
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001390 std::vector<llvm::Constant*> Values(7);
1391 Values[0] = GetClassName(OCD->getIdentifier());
1392 Values[1] = GetClassName(Interface->getIdentifier());
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001393 Values[2] =
1394 EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") +
1395 ExtName,
1396 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001397 InstanceMethods);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001398 Values[3] =
1399 EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName,
1400 "__OBJC,__cat_class_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001401 ClassMethods);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001402 if (Category) {
1403 Values[4] =
1404 EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName,
1405 Category->protocol_begin(),
1406 Category->protocol_end());
1407 } else {
1408 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1409 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001410 Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001411
1412 // If there is no category @interface then there can be no properties.
1413 if (Category) {
1414 Values[6] = EmitPropertyList(std::string("\01L_OBJC_$_PROP_LIST_") + ExtName,
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001415 OCD, Category, ObjCTypes);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001416 } else {
1417 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1418 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001419
1420 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
1421 Values);
1422
1423 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001424 CreateMetadataVar(std::string("\01L_OBJC_CATEGORY_")+ExtName, Init,
1425 "__OBJC,__category,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001426 4, true);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001427 DefinedCategories.push_back(GV);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001428}
1429
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001430// FIXME: Get from somewhere?
1431enum ClassFlags {
1432 eClassFlags_Factory = 0x00001,
1433 eClassFlags_Meta = 0x00002,
1434 // <rdr://5142207>
1435 eClassFlags_HasCXXStructors = 0x02000,
1436 eClassFlags_Hidden = 0x20000,
1437 eClassFlags_ABI2_Hidden = 0x00010,
1438 eClassFlags_ABI2_HasCXXStructors = 0x00004 // <rdr://4923634>
1439};
1440
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001441/*
1442 struct _objc_class {
1443 Class isa;
1444 Class super_class;
1445 const char *name;
1446 long version;
1447 long info;
1448 long instance_size;
1449 struct _objc_ivar_list *ivars;
1450 struct _objc_method_list *methods;
1451 struct _objc_cache *cache;
1452 struct _objc_protocol_list *protocols;
1453 // Objective-C 1.0 extensions (<rdr://4585769>)
1454 const char *ivar_layout;
1455 struct _objc_class_ext *ext;
1456 };
1457
1458 See EmitClassExtension();
1459 */
1460void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001461 DefinedSymbols.insert(ID->getIdentifier());
1462
Chris Lattner8ec03f52008-11-24 03:54:41 +00001463 std::string ClassName = ID->getNameAsString();
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001464 // FIXME: Gross
1465 ObjCInterfaceDecl *Interface =
1466 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001467 llvm::Constant *Protocols =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001468 EmitProtocolList("\01L_OBJC_CLASS_PROTOCOLS_" + ID->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001469 Interface->protocol_begin(),
1470 Interface->protocol_end());
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001471 const llvm::Type *InterfaceTy =
Chris Lattner03d9f342009-04-01 06:23:52 +00001472 CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(Interface));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001473 unsigned Flags = eClassFlags_Factory;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001474 unsigned Size = CGM.getTargetData().getTypePaddedSize(InterfaceTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001475
1476 // FIXME: Set CXX-structors flag.
Daniel Dunbar04d40782009-04-14 06:00:08 +00001477 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001478 Flags |= eClassFlags_Hidden;
1479
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001480 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1481 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
1482 e = ID->instmeth_end(); i != e; ++i) {
1483 // Instance methods should always be defined.
1484 InstanceMethods.push_back(GetMethodConstant(*i));
1485 }
1486 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
1487 e = ID->classmeth_end(); i != e; ++i) {
1488 // Class methods should always be defined.
1489 ClassMethods.push_back(GetMethodConstant(*i));
1490 }
1491
1492 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
1493 e = ID->propimpl_end(); i != e; ++i) {
1494 ObjCPropertyImplDecl *PID = *i;
1495
1496 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1497 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1498
1499 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
1500 if (llvm::Constant *C = GetMethodConstant(MD))
1501 InstanceMethods.push_back(C);
1502 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
1503 if (llvm::Constant *C = GetMethodConstant(MD))
1504 InstanceMethods.push_back(C);
1505 }
1506 }
1507
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001508 std::vector<llvm::Constant*> Values(12);
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001509 Values[ 0] = EmitMetaClass(ID, Protocols, InterfaceTy, ClassMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001510 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001511 // Record a reference to the super class.
1512 LazySymbols.insert(Super->getIdentifier());
1513
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001514 Values[ 1] =
1515 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1516 ObjCTypes.ClassPtrTy);
1517 } else {
1518 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1519 }
1520 Values[ 2] = GetClassName(ID->getIdentifier());
1521 // Version is always 0.
1522 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1523 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1524 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001525 Values[ 6] = EmitIvarList(ID, false);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001526 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001527 EmitMethodList("\01L_OBJC_INSTANCE_METHODS_" + ID->getNameAsString(),
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001528 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001529 InstanceMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001530 // cache is always NULL.
1531 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1532 Values[ 9] = Protocols;
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001533 // FIXME: Set ivar_layout
Fariborz Jahanian667423a2009-03-25 22:36:49 +00001534 // Values[10] = BuildIvarLayout(ID, true);
1535 Values[10] = GetIvarLayoutName(0, ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001536 Values[11] = EmitClassExtension(ID);
1537 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1538 Values);
1539
1540 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001541 CreateMetadataVar(std::string("\01L_OBJC_CLASS_")+ClassName, Init,
1542 "__OBJC,__class,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001543 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001544 DefinedClasses.push_back(GV);
1545}
1546
1547llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
1548 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001549 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001550 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001551 unsigned Flags = eClassFlags_Meta;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001552 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001553
Daniel Dunbar04d40782009-04-14 06:00:08 +00001554 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001555 Flags |= eClassFlags_Hidden;
1556
1557 std::vector<llvm::Constant*> Values(12);
1558 // The isa for the metaclass is the root of the hierarchy.
1559 const ObjCInterfaceDecl *Root = ID->getClassInterface();
1560 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
1561 Root = Super;
1562 Values[ 0] =
1563 llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
1564 ObjCTypes.ClassPtrTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001565 // The super class for the metaclass is emitted as the name of the
1566 // super class. The runtime fixes this up to point to the
1567 // *metaclass* for the super class.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001568 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
1569 Values[ 1] =
1570 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1571 ObjCTypes.ClassPtrTy);
1572 } else {
1573 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1574 }
1575 Values[ 2] = GetClassName(ID->getIdentifier());
1576 // Version is always 0.
1577 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1578 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1579 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001580 Values[ 6] = EmitIvarList(ID, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001581 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001582 EmitMethodList("\01L_OBJC_CLASS_METHODS_" + ID->getNameAsString(),
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001583 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001584 Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001585 // cache is always NULL.
1586 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1587 Values[ 9] = Protocols;
1588 // ivar_layout for metaclass is always NULL.
1589 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1590 // The class extension is always unused for metaclasses.
1591 Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1592 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1593 Values);
1594
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001595 std::string Name("\01L_OBJC_METACLASS_");
Chris Lattner8ec03f52008-11-24 03:54:41 +00001596 Name += ID->getNameAsCString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001597
1598 // Check for a forward reference.
1599 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
1600 if (GV) {
1601 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1602 "Forward metaclass reference has incorrect type.");
1603 GV->setLinkage(llvm::GlobalValue::InternalLinkage);
1604 GV->setInitializer(Init);
1605 } else {
1606 GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1607 llvm::GlobalValue::InternalLinkage,
1608 Init, Name,
1609 &CGM.getModule());
1610 }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001611 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001612 GV->setAlignment(4);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001613 UsedGlobals.push_back(GV);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001614
1615 return GV;
1616}
1617
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001618llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001619 std::string Name = "\01L_OBJC_METACLASS_" + ID->getNameAsString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001620
1621 // FIXME: Should we look these up somewhere other than the
1622 // module. Its a bit silly since we only generate these while
1623 // processing an implementation, so exactly one pointer would work
1624 // if know when we entered/exitted an implementation block.
1625
1626 // Check for an existing forward reference.
Fariborz Jahanianb0d27942009-01-07 20:11:22 +00001627 // Previously, metaclass with internal linkage may have been defined.
1628 // pass 'true' as 2nd argument so it is returned.
1629 if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true)) {
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001630 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1631 "Forward metaclass reference has incorrect type.");
1632 return GV;
1633 } else {
1634 // Generate as an external reference to keep a consistent
1635 // module. This will be patched up when we emit the metaclass.
1636 return new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1637 llvm::GlobalValue::ExternalLinkage,
1638 0,
1639 Name,
1640 &CGM.getModule());
1641 }
1642}
1643
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001644/*
1645 struct objc_class_ext {
1646 uint32_t size;
1647 const char *weak_ivar_layout;
1648 struct _objc_property_list *properties;
1649 };
1650*/
1651llvm::Constant *
1652CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
1653 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001654 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassExtensionTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001655
1656 std::vector<llvm::Constant*> Values(3);
1657 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001658 // FIXME: Output weak_ivar_layout string.
Fariborz Jahanian667423a2009-03-25 22:36:49 +00001659 // Values[1] = BuildIvarLayout(ID, false);
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00001660 Values[1] = GetIvarLayoutName(0, ObjCTypes);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001661 Values[2] = EmitPropertyList("\01L_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001662 ID, ID->getClassInterface(), ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001663
1664 // Return null if no extension bits are used.
1665 if (Values[1]->isNullValue() && Values[2]->isNullValue())
1666 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1667
1668 llvm::Constant *Init =
1669 llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001670 return CreateMetadataVar("\01L_OBJC_CLASSEXT_" + ID->getNameAsString(),
1671 Init, 0, 0, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001672}
1673
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001674/// countInheritedIvars - count number of ivars in class and its super class(s)
1675///
Douglas Gregor6ab35242009-04-09 21:40:53 +00001676static int countInheritedIvars(const ObjCInterfaceDecl *OI,
1677 ASTContext &Context) {
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001678 int count = 0;
1679 if (!OI)
1680 return 0;
1681 const ObjCInterfaceDecl *SuperClass = OI->getSuperClass();
1682 if (SuperClass)
Douglas Gregor6ab35242009-04-09 21:40:53 +00001683 count += countInheritedIvars(SuperClass, Context);
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001684 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1685 E = OI->ivar_end(); I != E; ++I)
1686 ++count;
Fariborz Jahanian18191882009-03-31 18:11:23 +00001687 // look into properties.
Douglas Gregor6ab35242009-04-09 21:40:53 +00001688 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(Context),
1689 E = OI->prop_end(Context); I != E; ++I) {
Fariborz Jahanian18191882009-03-31 18:11:23 +00001690 if ((*I)->getPropertyIvarDecl())
1691 ++count;
1692 }
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001693 return count;
1694}
1695
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001696/// getInterfaceDeclForIvar - Get the interface declaration node where
1697/// this ivar is declared in.
1698/// FIXME. Ideally, this info should be in the ivar node. But currently
1699/// it is not and prevailing wisdom is that ASTs should not have more
1700/// info than is absolutely needed, even though this info reflects the
1701/// source language.
1702///
1703static const ObjCInterfaceDecl *getInterfaceDeclForIvar(
1704 const ObjCInterfaceDecl *OI,
Douglas Gregor6ab35242009-04-09 21:40:53 +00001705 const ObjCIvarDecl *IVD,
1706 ASTContext &Context) {
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001707 if (!OI)
1708 return 0;
1709 assert(isa<ObjCInterfaceDecl>(OI) && "OI is not an interface");
1710 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1711 E = OI->ivar_end(); I != E; ++I)
1712 if ((*I)->getIdentifier() == IVD->getIdentifier())
1713 return OI;
Fariborz Jahanian5a4b4532009-03-31 17:00:52 +00001714 // look into properties.
Douglas Gregor6ab35242009-04-09 21:40:53 +00001715 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(Context),
1716 E = OI->prop_end(Context); I != E; ++I) {
Fariborz Jahanian5a4b4532009-03-31 17:00:52 +00001717 ObjCPropertyDecl *PDecl = (*I);
1718 if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl())
1719 if (IV->getIdentifier() == IVD->getIdentifier())
1720 return OI;
1721 }
Douglas Gregor6ab35242009-04-09 21:40:53 +00001722 return getInterfaceDeclForIvar(OI->getSuperClass(), IVD, Context);
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001723}
1724
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001725/*
1726 struct objc_ivar {
1727 char *ivar_name;
1728 char *ivar_type;
1729 int ivar_offset;
1730 };
1731
1732 struct objc_ivar_list {
1733 int ivar_count;
1734 struct objc_ivar list[count];
1735 };
1736 */
1737llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001738 bool ForClass) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001739 std::vector<llvm::Constant*> Ivars, Ivar(3);
1740
1741 // When emitting the root class GCC emits ivar entries for the
1742 // actual class structure. It is not clear if we need to follow this
1743 // behavior; for now lets try and get away with not doing it. If so,
1744 // the cleanest solution would be to make up an ObjCInterfaceDecl
1745 // for the class.
1746 if (ForClass)
1747 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001748
1749 ObjCInterfaceDecl *OID =
1750 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00001751 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001752
1753 RecordDecl::field_iterator ifield, pfield;
1754 const RecordDecl *RD = GetFirstIvarInRecord(OID, ifield, pfield);
Douglas Gregor6ab35242009-04-09 21:40:53 +00001755 for (RecordDecl::field_iterator e = RD->field_end(CGM.getContext());
1756 ifield != e; ++ifield) {
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001757 FieldDecl *Field = *ifield;
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00001758 uint64_t Offset = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001759 if (Field->getIdentifier())
1760 Ivar[0] = GetMethodVarName(Field->getIdentifier());
1761 else
1762 Ivar[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Devang Patel7794bb82009-03-04 18:21:39 +00001763 Ivar[1] = GetMethodVarType(Field);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001764 Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy, Offset);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001765 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001766 }
1767
1768 // Return null for empty list.
1769 if (Ivars.empty())
1770 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
1771
1772 std::vector<llvm::Constant*> Values(2);
1773 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
1774 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
1775 Ivars.size());
1776 Values[1] = llvm::ConstantArray::get(AT, Ivars);
1777 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1778
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001779 llvm::GlobalVariable *GV;
1780 if (ForClass)
1781 GV = CreateMetadataVar("\01L_OBJC_CLASS_VARIABLES_" + ID->getNameAsString(),
Daniel Dunbar58a29122009-03-09 22:18:41 +00001782 Init, "__OBJC,__class_vars,regular,no_dead_strip",
1783 4, true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001784 else
1785 GV = CreateMetadataVar("\01L_OBJC_INSTANCE_VARIABLES_"
1786 + ID->getNameAsString(),
1787 Init, "__OBJC,__instance_vars,regular,no_dead_strip",
1788 0, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001789 return llvm::ConstantExpr::getBitCast(GV,
1790 ObjCTypes.IvarListPtrTy);
1791}
1792
1793/*
1794 struct objc_method {
1795 SEL method_name;
1796 char *method_types;
1797 void *method;
1798 };
1799
1800 struct objc_method_list {
1801 struct objc_method_list *obsolete;
1802 int count;
1803 struct objc_method methods_list[count];
1804 };
1805*/
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001806
1807/// GetMethodConstant - Return a struct objc_method constant for the
1808/// given method if it has been defined. The result is null if the
1809/// method has not been defined. The return value has type MethodPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001810llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001811 // FIXME: Use DenseMap::lookup
1812 llvm::Function *Fn = MethodDefinitions[MD];
1813 if (!Fn)
1814 return 0;
1815
1816 std::vector<llvm::Constant*> Method(3);
1817 Method[0] =
1818 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1819 ObjCTypes.SelectorPtrTy);
1820 Method[1] = GetMethodVarType(MD);
1821 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
1822 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
1823}
1824
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001825llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name,
1826 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001827 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001828 // Return null for empty list.
1829 if (Methods.empty())
1830 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
1831
1832 std::vector<llvm::Constant*> Values(3);
1833 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1834 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1835 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
1836 Methods.size());
1837 Values[2] = llvm::ConstantArray::get(AT, Methods);
1838 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1839
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001840 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 0, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001841 return llvm::ConstantExpr::getBitCast(GV,
1842 ObjCTypes.MethodListPtrTy);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001843}
1844
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001845llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD,
Daniel Dunbarbb36d332009-02-02 21:43:58 +00001846 const ObjCContainerDecl *CD) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001847 std::string Name;
Fariborz Jahanian679a5022009-01-10 21:06:09 +00001848 GetNameForMethod(OMD, CD, Name);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001849
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001850 CodeGenTypes &Types = CGM.getTypes();
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001851 const llvm::FunctionType *MethodTy =
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001852 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001853 llvm::Function *Method =
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001854 llvm::Function::Create(MethodTy,
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001855 llvm::GlobalValue::InternalLinkage,
1856 Name,
1857 &CGM.getModule());
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001858 MethodDefinitions.insert(std::make_pair(OMD, Method));
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001859
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001860 return Method;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001861}
1862
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00001863uint64_t CGObjCCommonMac::GetIvarBaseOffset(const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +00001864 const FieldDecl *Field) {
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00001865 if (!Field->isBitField())
1866 return Layout->getElementOffset(
1867 CGM.getTypes().getLLVMFieldNo(Field));
1868 // FIXME. Must be a better way of getting a bitfield base offset.
1869 uint64_t offset = CGM.getTypes().getLLVMFieldNo(Field);
1870 const llvm::Type *Ty = CGM.getTypes().ConvertTypeForMemRecursive(Field->getType());
1871 uint64_t size = CGM.getTypes().getTargetData().getTypePaddedSizeInBits(Ty);
1872 offset = (offset*size)/8;
1873 return offset;
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00001874}
1875
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00001876/// GetFieldBaseOffset - return's field byt offset.
1877uint64_t CGObjCCommonMac::GetFieldBaseOffset(const ObjCInterfaceDecl *OI,
1878 const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +00001879 const FieldDecl *Field) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00001880 const ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
Chris Lattnercd0ee142009-03-31 08:33:16 +00001881 const FieldDecl *FD = OI->lookupFieldDeclForIvar(CGM.getContext(), Ivar);
1882 return GetIvarBaseOffset(Layout, FD);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00001883}
1884
Daniel Dunbarfd65d372009-03-09 20:09:19 +00001885llvm::GlobalVariable *
1886CGObjCCommonMac::CreateMetadataVar(const std::string &Name,
1887 llvm::Constant *Init,
1888 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +00001889 unsigned Align,
1890 bool AddToUsed) {
Daniel Dunbarfd65d372009-03-09 20:09:19 +00001891 const llvm::Type *Ty = Init->getType();
1892 llvm::GlobalVariable *GV =
1893 new llvm::GlobalVariable(Ty, false,
1894 llvm::GlobalValue::InternalLinkage,
1895 Init,
1896 Name,
1897 &CGM.getModule());
1898 if (Section)
1899 GV->setSection(Section);
Daniel Dunbar35bd7632009-03-09 20:50:13 +00001900 if (Align)
1901 GV->setAlignment(Align);
1902 if (AddToUsed)
Daniel Dunbarfd65d372009-03-09 20:09:19 +00001903 UsedGlobals.push_back(GV);
1904 return GV;
1905}
1906
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001907llvm::Function *CGObjCMac::ModuleInitFunction() {
Daniel Dunbarf77ac862008-08-11 21:35:06 +00001908 // Abuse this interface function as a place to finalize.
1909 FinishModule();
1910
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001911 return NULL;
1912}
1913
Chris Lattner74391b42009-03-22 21:03:39 +00001914llvm::Constant *CGObjCMac::GetPropertyGetFunction() {
Daniel Dunbar49f66022008-09-24 03:38:44 +00001915 return ObjCTypes.GetPropertyFn;
1916}
1917
Chris Lattner74391b42009-03-22 21:03:39 +00001918llvm::Constant *CGObjCMac::GetPropertySetFunction() {
Daniel Dunbar49f66022008-09-24 03:38:44 +00001919 return ObjCTypes.SetPropertyFn;
1920}
1921
Chris Lattner74391b42009-03-22 21:03:39 +00001922llvm::Constant *CGObjCMac::EnumerationMutationFunction() {
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001923 return ObjCTypes.EnumerationMutationFn;
1924}
1925
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001926/*
1927
1928Objective-C setjmp-longjmp (sjlj) Exception Handling
1929--
1930
1931The basic framework for a @try-catch-finally is as follows:
1932{
1933 objc_exception_data d;
1934 id _rethrow = null;
Anders Carlsson190d00e2009-02-07 21:26:04 +00001935 bool _call_try_exit = true;
1936
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001937 objc_exception_try_enter(&d);
1938 if (!setjmp(d.jmp_buf)) {
1939 ... try body ...
1940 } else {
1941 // exception path
1942 id _caught = objc_exception_extract(&d);
1943
1944 // enter new try scope for handlers
1945 if (!setjmp(d.jmp_buf)) {
1946 ... match exception and execute catch blocks ...
1947
1948 // fell off end, rethrow.
1949 _rethrow = _caught;
Daniel Dunbar898d5082008-09-30 01:06:03 +00001950 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001951 } else {
1952 // exception in catch block
1953 _rethrow = objc_exception_extract(&d);
Anders Carlsson190d00e2009-02-07 21:26:04 +00001954 _call_try_exit = false;
1955 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001956 }
1957 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00001958 ... jump-through-finally to finally_end ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001959
1960finally:
Anders Carlsson190d00e2009-02-07 21:26:04 +00001961 if (_call_try_exit)
1962 objc_exception_try_exit(&d);
1963
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001964 ... finally block ....
Daniel Dunbar898d5082008-09-30 01:06:03 +00001965 ... dispatch to finally destination ...
1966
1967finally_rethrow:
1968 objc_exception_throw(_rethrow);
1969
1970finally_end:
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001971}
1972
1973This framework differs slightly from the one gcc uses, in that gcc
Daniel Dunbar898d5082008-09-30 01:06:03 +00001974uses _rethrow to determine if objc_exception_try_exit should be called
1975and if the object should be rethrown. This breaks in the face of
1976throwing nil and introduces unnecessary branches.
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001977
1978We specialize this framework for a few particular circumstances:
1979
1980 - If there are no catch blocks, then we avoid emitting the second
1981 exception handling context.
1982
1983 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
1984 e)) we avoid emitting the code to rethrow an uncaught exception.
1985
1986 - FIXME: If there is no @finally block we can do a few more
1987 simplifications.
1988
1989Rethrows and Jumps-Through-Finally
1990--
1991
1992Support for implicit rethrows and jumping through the finally block is
1993handled by storing the current exception-handling context in
1994ObjCEHStack.
1995
Daniel Dunbar898d5082008-09-30 01:06:03 +00001996In order to implement proper @finally semantics, we support one basic
1997mechanism for jumping through the finally block to an arbitrary
1998destination. Constructs which generate exits from a @try or @catch
1999block use this mechanism to implement the proper semantics by chaining
2000jumps, as necessary.
2001
2002This mechanism works like the one used for indirect goto: we
2003arbitrarily assign an ID to each destination and store the ID for the
2004destination in a variable prior to entering the finally block. At the
2005end of the finally block we simply create a switch to the proper
2006destination.
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002007
2008Code gen for @synchronized(expr) stmt;
2009Effectively generating code for:
2010objc_sync_enter(expr);
2011@try stmt @finally { objc_sync_exit(expr); }
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002012*/
2013
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002014void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
2015 const Stmt &S) {
2016 bool isTry = isa<ObjCAtTryStmt>(S);
Daniel Dunbar898d5082008-09-30 01:06:03 +00002017 // Create various blocks we refer to for handling @finally.
Daniel Dunbar55e87422008-11-11 02:29:29 +00002018 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002019 llvm::BasicBlock *FinallyExit = CGF.createBasicBlock("finally.exit");
Daniel Dunbar55e87422008-11-11 02:29:29 +00002020 llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
2021 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
2022 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
Daniel Dunbar1c566672009-02-24 01:43:46 +00002023
2024 // For @synchronized, call objc_sync_enter(sync.expr). The
2025 // evaluation of the expression must occur before we enter the
2026 // @synchronized. We can safely avoid a temp here because jumps into
2027 // @synchronized are illegal & this will dominate uses.
2028 llvm::Value *SyncArg = 0;
2029 if (!isTry) {
2030 SyncArg =
2031 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
2032 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00002033 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar1c566672009-02-24 01:43:46 +00002034 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00002035
2036 // Push an EH context entry, used for handling rethrows and jumps
2037 // through finally.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002038 CGF.PushCleanupBlock(FinallyBlock);
2039
Anders Carlsson273558f2009-02-07 21:37:21 +00002040 CGF.ObjCEHValueStack.push_back(0);
2041
Daniel Dunbar898d5082008-09-30 01:06:03 +00002042 // Allocate memory for the exception data and rethrow pointer.
Anders Carlsson80f25672008-09-09 17:59:25 +00002043 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
2044 "exceptiondata.ptr");
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002045 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
2046 "_rethrow");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002047 llvm::Value *CallTryExitPtr = CGF.CreateTempAlloca(llvm::Type::Int1Ty,
2048 "_call_try_exit");
2049 CGF.Builder.CreateStore(llvm::ConstantInt::getTrue(), CallTryExitPtr);
2050
Anders Carlsson80f25672008-09-09 17:59:25 +00002051 // Enter a new try block and call setjmp.
2052 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
2053 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
2054 "jmpbufarray");
2055 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
2056 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
2057 JmpBufPtr, "result");
Daniel Dunbar898d5082008-09-30 01:06:03 +00002058
Daniel Dunbar55e87422008-11-11 02:29:29 +00002059 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
2060 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002061 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002062 TryHandler, TryBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002063
2064 // Emit the @try block.
2065 CGF.EmitBlock(TryBlock);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002066 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
2067 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002068 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002069
2070 // Emit the "exception in @try" block.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002071 CGF.EmitBlock(TryHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002072
2073 // Retrieve the exception object. We may emit multiple blocks but
2074 // nothing can cross this so the value is already in SSA form.
2075 llvm::Value *Caught = CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
2076 ExceptionData,
2077 "caught");
Anders Carlsson273558f2009-02-07 21:37:21 +00002078 CGF.ObjCEHValueStack.back() = Caught;
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002079 if (!isTry)
2080 {
2081 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002082 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002083 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002084 }
2085 else if (const ObjCAtCatchStmt* CatchStmt =
2086 cast<ObjCAtTryStmt>(S).getCatchStmts())
2087 {
Daniel Dunbar55e40722008-09-27 07:03:52 +00002088 // Enter a new exception try block (in case a @catch block throws
2089 // an exception).
Anders Carlsson80f25672008-09-09 17:59:25 +00002090 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002091
Anders Carlsson80f25672008-09-09 17:59:25 +00002092 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
2093 JmpBufPtr, "result");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002094 llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw");
Anders Carlsson80f25672008-09-09 17:59:25 +00002095
Daniel Dunbar55e87422008-11-11 02:29:29 +00002096 llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch");
2097 llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler");
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002098 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002099
2100 CGF.EmitBlock(CatchBlock);
2101
Daniel Dunbar55e40722008-09-27 07:03:52 +00002102 // Handle catch list. As a special case we check if everything is
2103 // matched and avoid generating code for falling off the end if
2104 // so.
2105 bool AllMatched = false;
Anders Carlsson80f25672008-09-09 17:59:25 +00002106 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbar55e87422008-11-11 02:29:29 +00002107 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch");
Anders Carlsson80f25672008-09-09 17:59:25 +00002108
Steve Naroff7ba138a2009-03-03 19:52:17 +00002109 const ParmVarDecl *CatchParam = CatchStmt->getCatchParamDecl();
Daniel Dunbar129271a2008-09-27 07:36:24 +00002110 const PointerType *PT = 0;
2111
Anders Carlsson80f25672008-09-09 17:59:25 +00002112 // catch(...) always matches.
Daniel Dunbar55e40722008-09-27 07:03:52 +00002113 if (!CatchParam) {
2114 AllMatched = true;
2115 } else {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002116 PT = CatchParam->getType()->getAsPointerType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002117
Daniel Dunbar97f61d12008-09-27 22:21:14 +00002118 // catch(id e) always matches.
2119 // FIXME: For the time being we also match id<X>; this should
2120 // be rejected by Sema instead.
Steve Naroff389bf462009-02-12 17:52:19 +00002121 if ((PT && CGF.getContext().isObjCIdStructType(PT->getPointeeType())) ||
Steve Naroff7ba138a2009-03-03 19:52:17 +00002122 CatchParam->getType()->isObjCQualifiedIdType())
Daniel Dunbar55e40722008-09-27 07:03:52 +00002123 AllMatched = true;
Anders Carlsson80f25672008-09-09 17:59:25 +00002124 }
2125
Daniel Dunbar55e40722008-09-27 07:03:52 +00002126 if (AllMatched) {
Anders Carlssondde0a942008-09-11 09:15:33 +00002127 if (CatchParam) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002128 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002129 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002130 CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002131 }
Anders Carlsson1452f552008-09-11 08:21:54 +00002132
Anders Carlssondde0a942008-09-11 09:15:33 +00002133 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002134 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002135 break;
2136 }
2137
Daniel Dunbar129271a2008-09-27 07:36:24 +00002138 assert(PT && "Unexpected non-pointer type in @catch");
2139 QualType T = PT->getPointeeType();
Anders Carlsson4b7ff6e2008-09-11 06:35:14 +00002140 const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002141 assert(ObjCType && "Catch parameter must have Objective-C type!");
2142
2143 // Check if the @catch block matches the exception object.
2144 llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl());
2145
Anders Carlsson80f25672008-09-09 17:59:25 +00002146 llvm::Value *Match = CGF.Builder.CreateCall2(ObjCTypes.ExceptionMatchFn,
2147 Class, Caught, "match");
Anders Carlsson80f25672008-09-09 17:59:25 +00002148
Daniel Dunbar55e87422008-11-11 02:29:29 +00002149 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched");
Anders Carlsson80f25672008-09-09 17:59:25 +00002150
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002151 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002152 MatchedBlock, NextCatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002153
2154 // Emit the @catch block.
2155 CGF.EmitBlock(MatchedBlock);
Steve Naroff7ba138a2009-03-03 19:52:17 +00002156 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002157 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002158
2159 llvm::Value *Tmp =
Steve Naroff7ba138a2009-03-03 19:52:17 +00002160 CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(CatchParam->getType()),
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002161 "tmp");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002162 CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002163
2164 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002165 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002166
2167 CGF.EmitBlock(NextCatchBlock);
2168 }
2169
Daniel Dunbar55e40722008-09-27 07:03:52 +00002170 if (!AllMatched) {
2171 // None of the handlers caught the exception, so store it to be
2172 // rethrown at the end of the @finally block.
2173 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002174 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002175 }
2176
2177 // Emit the exception handler for the @catch blocks.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002178 CGF.EmitBlock(CatchHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002179 CGF.Builder.CreateStore(CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
2180 ExceptionData),
2181 RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002182 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002183 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002184 } else {
Anders Carlsson80f25672008-09-09 17:59:25 +00002185 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002186 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002187 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Anders Carlsson80f25672008-09-09 17:59:25 +00002188 }
2189
Daniel Dunbar898d5082008-09-30 01:06:03 +00002190 // Pop the exception-handling stack entry. It is important to do
2191 // this now, because the code in the @finally block is not in this
2192 // context.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002193 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
2194
Anders Carlsson273558f2009-02-07 21:37:21 +00002195 CGF.ObjCEHValueStack.pop_back();
2196
Anders Carlsson80f25672008-09-09 17:59:25 +00002197 // Emit the @finally block.
2198 CGF.EmitBlock(FinallyBlock);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002199 llvm::Value* CallTryExit = CGF.Builder.CreateLoad(CallTryExitPtr, "tmp");
2200
2201 CGF.Builder.CreateCondBr(CallTryExit, FinallyExit, FinallyNoExit);
2202
2203 CGF.EmitBlock(FinallyExit);
Anders Carlsson80f25672008-09-09 17:59:25 +00002204 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryExitFn, ExceptionData);
Daniel Dunbar129271a2008-09-27 07:36:24 +00002205
2206 CGF.EmitBlock(FinallyNoExit);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002207 if (isTry) {
2208 if (const ObjCAtFinallyStmt* FinallyStmt =
2209 cast<ObjCAtTryStmt>(S).getFinallyStmt())
2210 CGF.EmitStmt(FinallyStmt->getFinallyBody());
Daniel Dunbar1c566672009-02-24 01:43:46 +00002211 } else {
2212 // Emit objc_sync_exit(expr); as finally's sole statement for
2213 // @synchronized.
2214 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, SyncArg);
Fariborz Jahanianf2878e52008-11-21 19:21:53 +00002215 }
Anders Carlsson80f25672008-09-09 17:59:25 +00002216
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002217 // Emit the switch block
2218 if (Info.SwitchBlock)
2219 CGF.EmitBlock(Info.SwitchBlock);
2220 if (Info.EndBlock)
2221 CGF.EmitBlock(Info.EndBlock);
2222
Daniel Dunbar898d5082008-09-30 01:06:03 +00002223 CGF.EmitBlock(FinallyRethrow);
2224 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn,
2225 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002226 CGF.Builder.CreateUnreachable();
Daniel Dunbar898d5082008-09-30 01:06:03 +00002227
2228 CGF.EmitBlock(FinallyEnd);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002229}
2230
2231void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar898d5082008-09-30 01:06:03 +00002232 const ObjCAtThrowStmt &S) {
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002233 llvm::Value *ExceptionAsObject;
2234
2235 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2236 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
2237 ExceptionAsObject =
2238 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
2239 } else {
Anders Carlsson273558f2009-02-07 21:37:21 +00002240 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002241 "Unexpected rethrow outside @catch block.");
Anders Carlsson273558f2009-02-07 21:37:21 +00002242 ExceptionAsObject = CGF.ObjCEHValueStack.back();
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002243 }
2244
2245 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
Anders Carlsson80f25672008-09-09 17:59:25 +00002246 CGF.Builder.CreateUnreachable();
Daniel Dunbara448fb22008-11-11 23:11:34 +00002247
2248 // Clear the insertion point to indicate we are in unreachable code.
2249 CGF.Builder.ClearInsertionPoint();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002250}
2251
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002252/// EmitObjCWeakRead - Code gen for loading value of a __weak
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002253/// object: objc_read_weak (id *src)
2254///
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002255llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002256 llvm::Value *AddrWeakObj)
2257{
Eli Friedman8339b352009-03-07 03:57:15 +00002258 const llvm::Type* DestTy =
2259 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002260 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002261 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002262 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00002263 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002264 return read_weak;
2265}
2266
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002267/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
2268/// objc_assign_weak (id src, id *dst)
2269///
2270void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
2271 llvm::Value *src, llvm::Value *dst)
2272{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002273 const llvm::Type * SrcTy = src->getType();
2274 if (!isa<llvm::PointerType>(SrcTy)) {
2275 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2276 assert(Size <= 8 && "does not support size > 8");
2277 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2278 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002279 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2280 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002281 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2282 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002283 CGF.Builder.CreateCall2(ObjCTypes.GcAssignWeakFn,
2284 src, dst, "weakassign");
2285 return;
2286}
2287
Fariborz Jahanian58626502008-11-19 00:59:10 +00002288/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
2289/// objc_assign_global (id src, id *dst)
2290///
2291void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
2292 llvm::Value *src, llvm::Value *dst)
2293{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002294 const llvm::Type * SrcTy = src->getType();
2295 if (!isa<llvm::PointerType>(SrcTy)) {
2296 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2297 assert(Size <= 8 && "does not support size > 8");
2298 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2299 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002300 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2301 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002302 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2303 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian58626502008-11-19 00:59:10 +00002304 CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn,
2305 src, dst, "globalassign");
2306 return;
2307}
2308
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002309/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
2310/// objc_assign_ivar (id src, id *dst)
2311///
2312void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
2313 llvm::Value *src, llvm::Value *dst)
2314{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002315 const llvm::Type * SrcTy = src->getType();
2316 if (!isa<llvm::PointerType>(SrcTy)) {
2317 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2318 assert(Size <= 8 && "does not support size > 8");
2319 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2320 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002321 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2322 }
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002323 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2324 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
2325 CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn,
2326 src, dst, "assignivar");
2327 return;
2328}
2329
Fariborz Jahanian58626502008-11-19 00:59:10 +00002330/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
2331/// objc_assign_strongCast (id src, id *dst)
2332///
2333void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
2334 llvm::Value *src, llvm::Value *dst)
2335{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002336 const llvm::Type * SrcTy = src->getType();
2337 if (!isa<llvm::PointerType>(SrcTy)) {
2338 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2339 assert(Size <= 8 && "does not support size > 8");
2340 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2341 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002342 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2343 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002344 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2345 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian58626502008-11-19 00:59:10 +00002346 CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn,
2347 src, dst, "weakassign");
2348 return;
2349}
2350
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002351/// EmitObjCValueForIvar - Code Gen for ivar reference.
2352///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002353LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
2354 QualType ObjectTy,
2355 llvm::Value *BaseValue,
2356 const ObjCIvarDecl *Ivar,
2357 const FieldDecl *Field,
2358 unsigned CVRQualifiers) {
2359 if (Ivar->isBitField())
2360 return CGF.EmitLValueForBitfield(BaseValue, const_cast<FieldDecl *>(Field),
2361 CVRQualifiers);
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002362 // TODO: Add a special case for isa (index 0)
2363 unsigned Index = CGM.getTypes().getLLVMFieldNo(Field);
2364 llvm::Value *V = CGF.Builder.CreateStructGEP(BaseValue, Index, "tmp");
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002365 LValue LV = LValue::MakeAddr(V,
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00002366 Ivar->getType().getCVRQualifiers()|CVRQualifiers,
2367 CGM.getContext().getObjCGCAttrKind(Ivar->getType()));
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002368 LValue::SetObjCIvar(LV, true);
2369 return LV;
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002370}
2371
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002372llvm::Value *CGObjCMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
2373 ObjCInterfaceDecl *Interface,
2374 const ObjCIvarDecl *Ivar) {
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002375 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(Interface);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002376 FieldDecl *Field = Interface->lookupFieldDeclForIvar(CGM.getContext(), Ivar);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00002377 uint64_t Offset = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002378 return llvm::ConstantInt::get(
2379 CGM.getTypes().ConvertType(CGM.getContext().LongTy),
2380 Offset);
2381}
2382
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002383/* *** Private Interface *** */
2384
2385/// EmitImageInfo - Emit the image info marker used to encode some module
2386/// level information.
2387///
2388/// See: <rdr://4810609&4810587&4810587>
2389/// struct IMAGE_INFO {
2390/// unsigned version;
2391/// unsigned flags;
2392/// };
2393enum ImageInfoFlags {
2394 eImageInfo_FixAndContinue = (1 << 0), // FIXME: Not sure what this implies
2395 eImageInfo_GarbageCollected = (1 << 1),
2396 eImageInfo_GCOnly = (1 << 2)
2397};
2398
2399void CGObjCMac::EmitImageInfo() {
2400 unsigned version = 0; // Version is unused?
2401 unsigned flags = 0;
2402
2403 // FIXME: Fix and continue?
2404 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
2405 flags |= eImageInfo_GarbageCollected;
2406 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
2407 flags |= eImageInfo_GCOnly;
2408
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002409 // Emitted as int[2];
2410 llvm::Constant *values[2] = {
2411 llvm::ConstantInt::get(llvm::Type::Int32Ty, version),
2412 llvm::ConstantInt::get(llvm::Type::Int32Ty, flags)
2413 };
2414 llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002415
2416 const char *Section;
2417 if (ObjCABI == 1)
2418 Section = "__OBJC, __image_info,regular";
2419 else
2420 Section = "__DATA, __objc_imageinfo, regular, no_dead_strip";
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002421 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002422 CreateMetadataVar("\01L_OBJC_IMAGE_INFO",
2423 llvm::ConstantArray::get(AT, values, 2),
2424 Section,
2425 0,
2426 true);
2427 GV->setConstant(true);
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002428}
2429
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002430
2431// struct objc_module {
2432// unsigned long version;
2433// unsigned long size;
2434// const char *name;
2435// Symtab symtab;
2436// };
2437
2438// FIXME: Get from somewhere
2439static const int ModuleVersion = 7;
2440
2441void CGObjCMac::EmitModuleInfo() {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00002442 uint64_t Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ModuleTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002443
2444 std::vector<llvm::Constant*> Values(4);
2445 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
2446 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002447 // This used to be the filename, now it is unused. <rdr://4327263>
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002448 Values[2] = GetClassName(&CGM.getContext().Idents.get(""));
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002449 Values[3] = EmitModuleSymbols();
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002450 CreateMetadataVar("\01L_OBJC_MODULES",
2451 llvm::ConstantStruct::get(ObjCTypes.ModuleTy, Values),
2452 "__OBJC,__module_info,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00002453 4, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002454}
2455
2456llvm::Constant *CGObjCMac::EmitModuleSymbols() {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002457 unsigned NumClasses = DefinedClasses.size();
2458 unsigned NumCategories = DefinedCategories.size();
2459
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002460 // Return null if no symbols were defined.
2461 if (!NumClasses && !NumCategories)
2462 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
2463
2464 std::vector<llvm::Constant*> Values(5);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002465 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2466 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
2467 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
2468 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
2469
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002470 // The runtime expects exactly the list of defined classes followed
2471 // by the list of defined categories, in a single array.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002472 std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002473 for (unsigned i=0; i<NumClasses; i++)
2474 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
2475 ObjCTypes.Int8PtrTy);
2476 for (unsigned i=0; i<NumCategories; i++)
2477 Symbols[NumClasses + i] =
2478 llvm::ConstantExpr::getBitCast(DefinedCategories[i],
2479 ObjCTypes.Int8PtrTy);
2480
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002481 Values[4] =
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002482 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002483 NumClasses + NumCategories),
2484 Symbols);
2485
2486 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2487
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002488 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002489 CreateMetadataVar("\01L_OBJC_SYMBOLS", Init,
2490 "__OBJC,__symbols,regular,no_dead_strip",
2491 0, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002492 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
2493}
2494
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002495llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002496 const ObjCInterfaceDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002497 LazySymbols.insert(ID->getIdentifier());
2498
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002499 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
2500
2501 if (!Entry) {
2502 llvm::Constant *Casted =
2503 llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()),
2504 ObjCTypes.ClassPtrTy);
2505 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002506 CreateMetadataVar("\01L_OBJC_CLASS_REFERENCES_", Casted,
2507 "__OBJC,__cls_refs,literal_pointers,no_dead_strip",
2508 0, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002509 }
2510
2511 return Builder.CreateLoad(Entry, false, "tmp");
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002512}
2513
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002514llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002515 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
2516
2517 if (!Entry) {
2518 llvm::Constant *Casted =
2519 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
2520 ObjCTypes.SelectorPtrTy);
2521 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002522 CreateMetadataVar("\01L_OBJC_SELECTOR_REFERENCES_", Casted,
2523 "__OBJC,__message_refs,literal_pointers,no_dead_strip",
2524 0, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002525 }
2526
2527 return Builder.CreateLoad(Entry, false, "tmp");
2528}
2529
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00002530llvm::Constant *CGObjCCommonMac::GetClassName(IdentifierInfo *Ident) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002531 llvm::GlobalVariable *&Entry = ClassNames[Ident];
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002532
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002533 if (!Entry)
2534 Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
2535 llvm::ConstantArray::get(Ident->getName()),
2536 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00002537 1, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002538
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002539 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002540}
2541
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002542/// GetInterfaceDeclStructLayout - Get layout for ivars of given
2543/// interface declaration.
2544const llvm::StructLayout *CGObjCCommonMac::GetInterfaceDeclStructLayout(
2545 const ObjCInterfaceDecl *OID) const {
2546 const llvm::Type *InterfaceTy =
2547 CGM.getTypes().ConvertType(
2548 CGM.getContext().getObjCInterfaceType(
2549 const_cast<ObjCInterfaceDecl*>(OID)));
2550 const llvm::StructLayout *Layout =
2551 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceTy));
2552 return Layout;
2553}
2554
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00002555/// GetIvarLayoutName - Returns a unique constant for the given
2556/// ivar layout bitmap.
2557llvm::Constant *CGObjCCommonMac::GetIvarLayoutName(IdentifierInfo *Ident,
2558 const ObjCCommonTypesHelper &ObjCTypes) {
2559 return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2560}
2561
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002562void CGObjCCommonMac::BuildAggrIvarLayout(const ObjCInterfaceDecl *OI,
2563 const llvm::StructLayout *Layout,
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002564 const RecordDecl *RD,
Chris Lattnerf1690852009-03-31 08:48:01 +00002565 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002566 unsigned int BytePos, bool ForStrongLayout,
2567 int &Index, int &SkIndex, bool &HasUnion) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002568 bool IsUnion = (RD && RD->isUnion());
2569 uint64_t MaxUnionIvarSize = 0;
2570 uint64_t MaxSkippedUnionIvarSize = 0;
2571 FieldDecl *MaxField = 0;
2572 FieldDecl *MaxSkippedField = 0;
Chris Lattnerf1690852009-03-31 08:48:01 +00002573 unsigned base = 0;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002574 if (RecFields.empty())
2575 return;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002576 if (IsUnion)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002577 base = BytePos + GetFieldBaseOffset(OI, Layout, RecFields[0]);
Chris Lattnerf1690852009-03-31 08:48:01 +00002578 unsigned WordSizeInBits = CGM.getContext().Target.getPointerWidth(0);
2579 unsigned ByteSizeInBits = CGM.getContext().Target.getCharWidth();
2580
2581 llvm::SmallVector<FieldDecl*, 16> TmpRecFields;
2582
2583 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002584 FieldDecl *Field = RecFields[i];
2585 // Skip over unnamed or bitfields
2586 if (!Field->getIdentifier() || Field->isBitField())
2587 continue;
2588 QualType FQT = Field->getType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002589 if (FQT->isRecordType() || FQT->isUnionType()) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002590 if (FQT->isUnionType())
2591 HasUnion = true;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002592 else
2593 assert(FQT->isRecordType() &&
2594 "only union/record is supported for ivar layout bitmap");
2595
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002596 const RecordType *RT = FQT->getAsRecordType();
2597 const RecordDecl *RD = RT->getDecl();
2598 // FIXME - Find a more efficiant way of passing records down.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002599 TmpRecFields.append(RD->field_begin(CGM.getContext()),
2600 RD->field_end(CGM.getContext()));
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002601 // FIXME - Is Layout correct?
Chris Lattnerf1690852009-03-31 08:48:01 +00002602 BuildAggrIvarLayout(OI, Layout, RD, TmpRecFields,
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002603 BytePos + GetFieldBaseOffset(OI, Layout, Field),
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002604 ForStrongLayout, Index, SkIndex,
2605 HasUnion);
Chris Lattnerf1690852009-03-31 08:48:01 +00002606 TmpRecFields.clear();
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002607 continue;
2608 }
Chris Lattnerf1690852009-03-31 08:48:01 +00002609
2610 if (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002611 const ConstantArrayType *CArray =
2612 dyn_cast_or_null<ConstantArrayType>(Array);
2613 assert(CArray && "only array with know element size is supported");
2614 FQT = CArray->getElementType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002615 while (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
2616 const ConstantArrayType *CArray =
2617 dyn_cast_or_null<ConstantArrayType>(Array);
2618 FQT = CArray->getElementType();
2619 }
2620
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002621 assert(!FQT->isUnionType() &&
2622 "layout for array of unions not supported");
2623 if (FQT->isRecordType()) {
2624 uint64_t ElCount = CArray->getSize().getZExtValue();
2625 int OldIndex = Index;
2626 int OldSkIndex = SkIndex;
2627
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002628 // FIXME - Use a common routine with the above!
2629 const RecordType *RT = FQT->getAsRecordType();
2630 const RecordDecl *RD = RT->getDecl();
2631 // FIXME - Find a more efficiant way of passing records down.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002632 TmpRecFields.append(RD->field_begin(CGM.getContext()),
2633 RD->field_end(CGM.getContext()));
Chris Lattnerf1690852009-03-31 08:48:01 +00002634
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002635 BuildAggrIvarLayout(OI, Layout, RD,
Chris Lattnerf1690852009-03-31 08:48:01 +00002636 TmpRecFields,
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002637 BytePos + GetFieldBaseOffset(OI, Layout, Field),
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002638 ForStrongLayout, Index, SkIndex,
2639 HasUnion);
Chris Lattnerf1690852009-03-31 08:48:01 +00002640 TmpRecFields.clear();
2641
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002642 // Replicate layout information for each array element. Note that
2643 // one element is already done.
2644 uint64_t ElIx = 1;
2645 for (int FirstIndex = Index, FirstSkIndex = SkIndex;
2646 ElIx < ElCount; ElIx++) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002647 uint64_t Size = CGM.getContext().getTypeSize(RT)/ByteSizeInBits;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002648 for (int i = OldIndex+1; i <= FirstIndex; ++i)
2649 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002650 GC_IVAR gcivar;
2651 gcivar.ivar_bytepos = IvarsInfo[i].ivar_bytepos + Size*ElIx;
2652 gcivar.ivar_size = IvarsInfo[i].ivar_size;
2653 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002654 }
2655
Chris Lattnerf1690852009-03-31 08:48:01 +00002656 for (int i = OldSkIndex+1; i <= FirstSkIndex; ++i) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002657 GC_IVAR skivar;
2658 skivar.ivar_bytepos = SkipIvars[i].ivar_bytepos + Size*ElIx;
2659 skivar.ivar_size = SkipIvars[i].ivar_size;
2660 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002661 }
2662 }
2663 continue;
2664 }
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002665 }
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002666 // At this point, we are done with Record/Union and array there of.
2667 // For other arrays we are down to its element type.
2668 QualType::GCAttrTypes GCAttr = QualType::GCNone;
2669 do {
2670 if (FQT.isObjCGCStrong() || FQT.isObjCGCWeak()) {
2671 GCAttr = FQT.isObjCGCStrong() ? QualType::Strong : QualType::Weak;
2672 break;
2673 }
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002674 else if (CGM.getContext().isObjCObjectPointerType(FQT)) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002675 GCAttr = QualType::Strong;
2676 break;
2677 }
2678 else if (const PointerType *PT = FQT->getAsPointerType()) {
2679 FQT = PT->getPointeeType();
2680 }
2681 else {
2682 break;
2683 }
2684 } while (true);
Chris Lattnerf1690852009-03-31 08:48:01 +00002685
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002686 if ((ForStrongLayout && GCAttr == QualType::Strong)
2687 || (!ForStrongLayout && GCAttr == QualType::Weak)) {
2688 if (IsUnion)
2689 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002690 uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType())
2691 / WordSizeInBits;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002692 if (UnionIvarSize > MaxUnionIvarSize)
2693 {
2694 MaxUnionIvarSize = UnionIvarSize;
2695 MaxField = Field;
2696 }
2697 }
2698 else
2699 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002700 GC_IVAR gcivar;
2701 gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field);
2702 gcivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) /
2703 WordSizeInBits;
2704 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002705 }
2706 }
2707 else if ((ForStrongLayout &&
2708 (GCAttr == QualType::GCNone || GCAttr == QualType::Weak))
2709 || (!ForStrongLayout && GCAttr != QualType::Weak)) {
2710 if (IsUnion)
2711 {
2712 uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType());
2713 if (UnionIvarSize > MaxSkippedUnionIvarSize)
2714 {
2715 MaxSkippedUnionIvarSize = UnionIvarSize;
2716 MaxSkippedField = Field;
2717 }
2718 }
2719 else
2720 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002721 GC_IVAR skivar;
2722 skivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field);
2723 skivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) /
2724 WordSizeInBits;
2725 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002726 }
2727 }
2728 }
Chris Lattnerf1690852009-03-31 08:48:01 +00002729 if (MaxField) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002730 GC_IVAR gcivar;
2731 gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, MaxField);
2732 gcivar.ivar_size = MaxUnionIvarSize;
2733 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002734 }
Chris Lattnerf1690852009-03-31 08:48:01 +00002735
2736 if (MaxSkippedField) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002737 GC_IVAR skivar;
2738 skivar.ivar_bytepos = BytePos +
2739 GetFieldBaseOffset(OI, Layout, MaxSkippedField);
2740 skivar.ivar_size = MaxSkippedUnionIvarSize;
2741 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002742 }
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002743}
2744
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002745static int
Chris Lattnerf1690852009-03-31 08:48:01 +00002746IvarBytePosCompare(const void *a, const void *b)
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002747{
2748 unsigned int sa = ((CGObjCCommonMac::GC_IVAR *)a)->ivar_bytepos;
2749 unsigned int sb = ((CGObjCCommonMac::GC_IVAR *)b)->ivar_bytepos;
2750
2751 if (sa < sb)
2752 return -1;
2753 if (sa > sb)
2754 return 1;
2755 return 0;
2756}
2757
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002758/// BuildIvarLayout - Builds ivar layout bitmap for the class
2759/// implementation for the __strong or __weak case.
2760/// The layout map displays which words in ivar list must be skipped
2761/// and which must be scanned by GC (see below). String is built of bytes.
2762/// Each byte is divided up in two nibbles (4-bit each). Left nibble is count
2763/// of words to skip and right nibble is count of words to scan. So, each
2764/// nibble represents up to 15 workds to skip or scan. Skipping the rest is
2765/// represented by a 0x00 byte which also ends the string.
2766/// 1. when ForStrongLayout is true, following ivars are scanned:
2767/// - id, Class
2768/// - object *
2769/// - __strong anything
2770///
2771/// 2. When ForStrongLayout is false, following ivars are scanned:
2772/// - __weak anything
2773///
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002774llvm::Constant *CGObjCCommonMac::BuildIvarLayout(
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002775 const ObjCImplementationDecl *OMD,
2776 bool ForStrongLayout) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002777 int Index = -1;
2778 int SkIndex = -1;
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002779 bool hasUnion = false;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002780 int SkipScan;
2781 unsigned int WordsToScan, WordsToSkip;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002782 const llvm::Type *PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
2783 if (CGM.getLangOptions().getGCMode() == LangOptions::NonGC)
2784 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002785
Chris Lattnerf1690852009-03-31 08:48:01 +00002786 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002787 const ObjCInterfaceDecl *OI = OMD->getClassInterface();
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002788 CGM.getContext().CollectObjCIvars(OI, RecFields);
2789 if (RecFields.empty())
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002790 return llvm::Constant::getNullValue(PtrTy);
Chris Lattnerf1690852009-03-31 08:48:01 +00002791
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002792 SkipIvars.clear();
2793 IvarsInfo.clear();
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002794
2795 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OI);
Chris Lattnerf1690852009-03-31 08:48:01 +00002796 BuildAggrIvarLayout(OI, Layout, 0, RecFields, 0, ForStrongLayout,
2797 Index, SkIndex, hasUnion);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002798 if (Index == -1)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002799 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002800
2801 // Sort on byte position in case we encounterred a union nested in
2802 // the ivar list.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002803 if (hasUnion && !IvarsInfo.empty())
2804 qsort(&IvarsInfo[0], Index+1, sizeof(GC_IVAR), IvarBytePosCompare);
2805 if (hasUnion && !SkipIvars.empty())
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002806 qsort(&SkipIvars[0], Index+1, sizeof(GC_IVAR), IvarBytePosCompare);
2807
2808 // Build the string of skip/scan nibbles
2809 SkipScan = -1;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002810 SkipScanIvars.clear();
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002811 unsigned int WordSize =
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002812 CGM.getTypes().getTargetData().getTypePaddedSize(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002813 if (IvarsInfo[0].ivar_bytepos == 0) {
2814 WordsToSkip = 0;
2815 WordsToScan = IvarsInfo[0].ivar_size;
2816 }
2817 else {
2818 WordsToSkip = IvarsInfo[0].ivar_bytepos/WordSize;
2819 WordsToScan = IvarsInfo[0].ivar_size;
2820 }
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002821 for (unsigned int i=1, Last=IvarsInfo.size(); i != Last; i++)
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002822 {
2823 unsigned int TailPrevGCObjC =
2824 IvarsInfo[i-1].ivar_bytepos + IvarsInfo[i-1].ivar_size * WordSize;
2825 if (IvarsInfo[i].ivar_bytepos == TailPrevGCObjC)
2826 {
2827 // consecutive 'scanned' object pointers.
2828 WordsToScan += IvarsInfo[i].ivar_size;
2829 }
2830 else
2831 {
2832 // Skip over 'gc'able object pointer which lay over each other.
2833 if (TailPrevGCObjC > IvarsInfo[i].ivar_bytepos)
2834 continue;
2835 // Must skip over 1 or more words. We save current skip/scan values
2836 // and start a new pair.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002837 SKIP_SCAN SkScan;
2838 SkScan.skip = WordsToSkip;
2839 SkScan.scan = WordsToScan;
2840 SkipScanIvars.push_back(SkScan); ++SkipScan;
2841
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002842 // Skip the hole.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002843 SkScan.skip = (IvarsInfo[i].ivar_bytepos - TailPrevGCObjC) / WordSize;
2844 SkScan.scan = 0;
2845 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002846 WordsToSkip = 0;
2847 WordsToScan = IvarsInfo[i].ivar_size;
2848 }
2849 }
2850 if (WordsToScan > 0)
2851 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002852 SKIP_SCAN SkScan;
2853 SkScan.skip = WordsToSkip;
2854 SkScan.scan = WordsToScan;
2855 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002856 }
2857
2858 bool BytesSkipped = false;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002859 if (!SkipIvars.empty())
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002860 {
2861 int LastByteSkipped =
2862 SkipIvars[SkIndex].ivar_bytepos + SkipIvars[SkIndex].ivar_size;
2863 int LastByteScanned =
2864 IvarsInfo[Index].ivar_bytepos + IvarsInfo[Index].ivar_size * WordSize;
2865 BytesSkipped = (LastByteSkipped > LastByteScanned);
2866 // Compute number of bytes to skip at the tail end of the last ivar scanned.
2867 if (BytesSkipped)
2868 {
2869 unsigned int TotalWords = (LastByteSkipped + (WordSize -1)) / WordSize;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002870 SKIP_SCAN SkScan;
2871 SkScan.skip = TotalWords - (LastByteScanned/WordSize);
2872 SkScan.scan = 0;
2873 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002874 }
2875 }
2876 // Mini optimization of nibbles such that an 0xM0 followed by 0x0N is produced
2877 // as 0xMN.
2878 for (int i = 0; i <= SkipScan; i++)
2879 {
2880 if ((i < SkipScan) && SkipScanIvars[i].skip && SkipScanIvars[i].scan == 0
2881 && SkipScanIvars[i+1].skip == 0 && SkipScanIvars[i+1].scan) {
2882 // 0xM0 followed by 0x0N detected.
2883 SkipScanIvars[i].scan = SkipScanIvars[i+1].scan;
2884 for (int j = i+1; j < SkipScan; j++)
2885 SkipScanIvars[j] = SkipScanIvars[j+1];
2886 --SkipScan;
2887 }
2888 }
2889
2890 // Generate the string.
2891 std::string BitMap;
2892 for (int i = 0; i <= SkipScan; i++)
2893 {
2894 unsigned char byte;
2895 unsigned int skip_small = SkipScanIvars[i].skip % 0xf;
2896 unsigned int scan_small = SkipScanIvars[i].scan % 0xf;
2897 unsigned int skip_big = SkipScanIvars[i].skip / 0xf;
2898 unsigned int scan_big = SkipScanIvars[i].scan / 0xf;
2899
2900 if (skip_small > 0 || skip_big > 0)
2901 BytesSkipped = true;
2902 // first skip big.
2903 for (unsigned int ix = 0; ix < skip_big; ix++)
2904 BitMap += (unsigned char)(0xf0);
2905
2906 // next (skip small, scan)
2907 if (skip_small)
2908 {
2909 byte = skip_small << 4;
2910 if (scan_big > 0)
2911 {
2912 byte |= 0xf;
2913 --scan_big;
2914 }
2915 else if (scan_small)
2916 {
2917 byte |= scan_small;
2918 scan_small = 0;
2919 }
2920 BitMap += byte;
2921 }
2922 // next scan big
2923 for (unsigned int ix = 0; ix < scan_big; ix++)
2924 BitMap += (unsigned char)(0x0f);
2925 // last scan small
2926 if (scan_small)
2927 {
2928 byte = scan_small;
2929 BitMap += byte;
2930 }
2931 }
2932 // null terminate string.
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002933 unsigned char zero = 0;
2934 BitMap += zero;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002935 // if ivar_layout bitmap is all 1 bits (nothing skipped) then use NULL as
2936 // final layout.
2937 if (ForStrongLayout && !BytesSkipped)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002938 return llvm::Constant::getNullValue(PtrTy);
2939 llvm::GlobalVariable * Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
2940 llvm::ConstantArray::get(BitMap.c_str()),
2941 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00002942 1, true);
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002943 // FIXME. Need a commomand-line option for this eventually.
2944 if (ForStrongLayout)
2945 printf("\nstrong ivar layout: ");
2946 else
2947 printf("\nweak ivar layout: ");
2948 const unsigned char *s = (unsigned char*)BitMap.c_str();
2949 for (unsigned i = 0; i < BitMap.size(); i++)
Fariborz Jahaniandbf15cb2009-03-26 19:10:36 +00002950 if (!(s[i] & 0xf0))
2951 printf("0x0%x%s", s[i], s[i] != 0 ? ", " : "");
2952 else
2953 printf("0x%x%s", s[i], s[i] != 0 ? ", " : "");
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002954 printf("\n");
2955
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002956 return getConstantGEP(Entry, 0, 0);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002957}
2958
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002959llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002960 llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
2961
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002962 // FIXME: Avoid std::string copying.
2963 if (!Entry)
2964 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_NAME_",
2965 llvm::ConstantArray::get(Sel.getAsString()),
2966 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00002967 1, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002968
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002969 return getConstantGEP(Entry, 0, 0);
2970}
2971
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002972// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002973llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002974 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
2975}
2976
2977// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002978llvm::Constant *CGObjCCommonMac::GetMethodVarName(const std::string &Name) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002979 return GetMethodVarName(&CGM.getContext().Idents.get(Name));
2980}
2981
Devang Patel7794bb82009-03-04 18:21:39 +00002982llvm::Constant *CGObjCCommonMac::GetMethodVarType(FieldDecl *Field) {
2983 std::string TypeStr;
2984 CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
2985
2986 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002987
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002988 if (!Entry)
2989 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
2990 llvm::ConstantArray::get(TypeStr),
2991 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00002992 1, true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002993
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002994 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002995}
2996
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002997llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002998 std::string TypeStr;
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002999 CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D),
3000 TypeStr);
Devang Patel7794bb82009-03-04 18:21:39 +00003001
3002 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
3003
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003004 if (!Entry)
3005 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3006 llvm::ConstantArray::get(TypeStr),
3007 "__TEXT,__cstring,cstring_literals",
3008 1, true);
Devang Patel7794bb82009-03-04 18:21:39 +00003009
3010 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003011}
3012
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003013// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003014llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003015 llvm::GlobalVariable *&Entry = PropertyNames[Ident];
3016
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003017 if (!Entry)
3018 Entry = CreateMetadataVar("\01L_OBJC_PROP_NAME_ATTR_",
3019 llvm::ConstantArray::get(Ident->getName()),
3020 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003021 1, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003022
3023 return getConstantGEP(Entry, 0, 0);
3024}
3025
3026// FIXME: Merge into a single cstring creation function.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003027// FIXME: This Decl should be more precise.
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003028llvm::Constant *
3029 CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
3030 const Decl *Container) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003031 std::string TypeStr;
3032 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003033 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
3034}
3035
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003036void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D,
3037 const ObjCContainerDecl *CD,
3038 std::string &NameOut) {
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00003039 NameOut = '\01';
3040 NameOut += (D->isInstanceMethod() ? '-' : '+');
Chris Lattner077bf5e2008-11-24 03:33:13 +00003041 NameOut += '[';
Fariborz Jahanian679a5022009-01-10 21:06:09 +00003042 assert (CD && "Missing container decl in GetNameForMethod");
3043 NameOut += CD->getNameAsString();
Fariborz Jahanian52847332009-01-26 23:49:05 +00003044 // FIXME. For a method in a category, (CAT_NAME) is inserted here.
3045 // Right now! there is not enough info. to do this.
Chris Lattner077bf5e2008-11-24 03:33:13 +00003046 NameOut += ' ';
3047 NameOut += D->getSelector().getAsString();
3048 NameOut += ']';
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00003049}
3050
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00003051/// GetFirstIvarInRecord - This routine returns the record for the
3052/// implementation of the fiven class OID. It also returns field
3053/// corresponding to the first ivar in the class in FIV. It also
3054/// returns the one before the first ivar.
3055///
3056const RecordDecl *CGObjCCommonMac::GetFirstIvarInRecord(
3057 const ObjCInterfaceDecl *OID,
3058 RecordDecl::field_iterator &FIV,
3059 RecordDecl::field_iterator &PIV) {
Douglas Gregor6ab35242009-04-09 21:40:53 +00003060 int countSuperClassIvars = countInheritedIvars(OID->getSuperClass(),
3061 CGM.getContext());
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00003062 const RecordDecl *RD = CGM.getContext().addRecordToClass(OID);
Douglas Gregor6ab35242009-04-09 21:40:53 +00003063 RecordDecl::field_iterator ifield = RD->field_begin(CGM.getContext());
3064 RecordDecl::field_iterator pfield = RD->field_end(CGM.getContext());
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00003065 while (countSuperClassIvars-- > 0) {
3066 pfield = ifield;
3067 ++ifield;
3068 }
3069 FIV = ifield;
3070 PIV = pfield;
3071 return RD;
3072}
3073
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003074void CGObjCMac::FinishModule() {
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003075 EmitModuleInfo();
3076
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003077 // Emit the dummy bodies for any protocols which were referenced but
3078 // never defined.
3079 for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
3080 i = Protocols.begin(), e = Protocols.end(); i != e; ++i) {
3081 if (i->second->hasInitializer())
3082 continue;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003083
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003084 std::vector<llvm::Constant*> Values(5);
3085 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
3086 Values[1] = GetClassName(i->first);
3087 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
3088 Values[3] = Values[4] =
3089 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
3090 i->second->setLinkage(llvm::GlobalValue::InternalLinkage);
3091 i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
3092 Values));
3093 }
3094
3095 std::vector<llvm::Constant*> Used;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003096 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003097 e = UsedGlobals.end(); i != e; ++i) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003098 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003099 }
3100
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003101 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003102 llvm::GlobalValue *GV =
3103 new llvm::GlobalVariable(AT, false,
3104 llvm::GlobalValue::AppendingLinkage,
3105 llvm::ConstantArray::get(AT, Used),
3106 "llvm.used",
3107 &CGM.getModule());
3108
3109 GV->setSection("llvm.metadata");
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003110
3111 // Add assembler directives to add lazy undefined symbol references
3112 // for classes which are referenced but not defined. This is
3113 // important for correct linker interaction.
3114
3115 // FIXME: Uh, this isn't particularly portable.
3116 std::stringstream s;
Anders Carlsson565c99f2008-12-10 02:21:04 +00003117
3118 if (!CGM.getModule().getModuleInlineAsm().empty())
3119 s << "\n";
3120
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003121 for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(),
3122 e = LazySymbols.end(); i != e; ++i) {
3123 s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n";
3124 }
3125 for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(),
3126 e = DefinedSymbols.end(); i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003127 s << "\t.objc_class_name_" << (*i)->getName() << "=0\n"
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003128 << "\t.globl .objc_class_name_" << (*i)->getName() << "\n";
3129 }
Anders Carlsson565c99f2008-12-10 02:21:04 +00003130
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003131 CGM.getModule().appendModuleInlineAsm(s.str());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003132}
3133
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003134CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003135 : CGObjCCommonMac(cgm),
3136 ObjCTypes(cgm)
3137{
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003138 ObjCEmptyCacheVar = ObjCEmptyVtableVar = NULL;
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003139 ObjCABI = 2;
3140}
3141
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003142/* *** */
3143
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003144ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm)
3145: CGM(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003146{
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003147 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3148 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003149
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003150 ShortTy = Types.ConvertType(Ctx.ShortTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003151 IntTy = Types.ConvertType(Ctx.IntTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003152 LongTy = Types.ConvertType(Ctx.LongTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00003153 LongLongTy = Types.ConvertType(Ctx.LongLongTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003154 Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3155
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003156 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00003157 PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003158 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003159
3160 // FIXME: It would be nice to unify this with the opaque type, so
3161 // that the IR comes out a bit cleaner.
3162 const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
3163 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003164
3165 // I'm not sure I like this. The implicit coordination is a bit
3166 // gross. We should solve this in a reasonable fashion because this
3167 // is a pretty common task (match some runtime data structure with
3168 // an LLVM data structure).
3169
3170 // FIXME: This is leaked.
3171 // FIXME: Merge with rewriter code?
3172
3173 // struct _objc_super {
3174 // id self;
3175 // Class cls;
3176 // }
3177 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3178 SourceLocation(),
3179 &Ctx.Idents.get("_objc_super"));
Douglas Gregor6ab35242009-04-09 21:40:53 +00003180 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3181 Ctx.getObjCIdType(), 0, false));
3182 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3183 Ctx.getObjCClassType(), 0, false));
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003184 RD->completeDefinition(Ctx);
3185
3186 SuperCTy = Ctx.getTagDeclType(RD);
3187 SuperPtrCTy = Ctx.getPointerType(SuperCTy);
3188
3189 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003190 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
3191
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003192 // struct _prop_t {
3193 // char *name;
3194 // char *attributes;
3195 // }
3196 PropertyTy = llvm::StructType::get(Int8PtrTy,
3197 Int8PtrTy,
3198 NULL);
3199 CGM.getModule().addTypeName("struct._prop_t",
3200 PropertyTy);
3201
3202 // struct _prop_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003203 // uint32_t entsize; // sizeof(struct _prop_t)
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003204 // uint32_t count_of_properties;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003205 // struct _prop_t prop_list[count_of_properties];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003206 // }
3207 PropertyListTy = llvm::StructType::get(IntTy,
3208 IntTy,
3209 llvm::ArrayType::get(PropertyTy, 0),
3210 NULL);
3211 CGM.getModule().addTypeName("struct._prop_list_t",
3212 PropertyListTy);
3213 // struct _prop_list_t *
3214 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
3215
3216 // struct _objc_method {
3217 // SEL _cmd;
3218 // char *method_type;
3219 // char *_imp;
3220 // }
3221 MethodTy = llvm::StructType::get(SelectorPtrTy,
3222 Int8PtrTy,
3223 Int8PtrTy,
3224 NULL);
3225 CGM.getModule().addTypeName("struct._objc_method", MethodTy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003226
3227 // struct _objc_cache *
3228 CacheTy = llvm::OpaqueType::get();
3229 CGM.getModule().addTypeName("struct._objc_cache", CacheTy);
3230 CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003231
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003232 // Property manipulation functions.
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003233
3234 QualType IdType = Ctx.getObjCIdType();
3235 QualType SelType = Ctx.getObjCSelType();
3236 llvm::SmallVector<QualType,16> Params;
3237 const llvm::FunctionType *FTy;
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003238
3239 // id objc_getProperty (id, SEL, ptrdiff_t, bool)
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003240 Params.push_back(IdType);
3241 Params.push_back(SelType);
3242 Params.push_back(Ctx.LongTy);
3243 Params.push_back(Ctx.BoolTy);
3244 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params),
3245 false);
3246 GetPropertyFn = CGM.CreateRuntimeFunction(FTy, "objc_getProperty");
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003247
3248 // void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool)
3249 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003250 Params.push_back(IdType);
3251 Params.push_back(SelType);
3252 Params.push_back(Ctx.LongTy);
3253 Params.push_back(IdType);
3254 Params.push_back(Ctx.BoolTy);
3255 Params.push_back(Ctx.BoolTy);
3256 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
3257 SetPropertyFn = CGM.CreateRuntimeFunction(FTy, "objc_setProperty");
3258
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003259 // Enumeration mutation.
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003260
3261 // void objc_enumerationMutation (id)
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003262 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003263 Params.push_back(IdType);
3264 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
3265 EnumerationMutationFn = CGM.CreateRuntimeFunction(FTy,
3266 "objc_enumerationMutation");
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003267
3268 // gc's API
3269 // id objc_read_weak (id *)
3270 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003271 Params.push_back(Ctx.getPointerType(IdType));
3272 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
3273 GcReadWeakFn = CGM.CreateRuntimeFunction(FTy, "objc_read_weak");
3274
3275 // id objc_assign_weak (id, id *)
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003276 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003277 Params.push_back(IdType);
3278 Params.push_back(Ctx.getPointerType(IdType));
3279
3280 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
3281 GcAssignWeakFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_weak");
3282 GcAssignGlobalFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_global");
3283 GcAssignIvarFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_ivar");
3284 GcAssignStrongCastFn =
3285 CGM.CreateRuntimeFunction(FTy, "objc_assign_strongCast");
Anders Carlssonf57c5b22009-02-16 22:59:18 +00003286
3287 // void objc_exception_throw(id)
3288 Params.clear();
3289 Params.push_back(IdType);
3290
3291 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00003292 ExceptionThrowFn =
3293 CGM.CreateRuntimeFunction(FTy, "objc_exception_throw");
Daniel Dunbar1c566672009-02-24 01:43:46 +00003294
3295 // synchronized APIs
Daniel Dunbar1c566672009-02-24 01:43:46 +00003296 // void objc_sync_exit (id)
3297 Params.clear();
3298 Params.push_back(IdType);
3299
3300 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
Daniel Dunbar1c566672009-02-24 01:43:46 +00003301 SyncExitFn = CGM.CreateRuntimeFunction(FTy, "objc_sync_exit");
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003302}
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003303
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003304ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
3305 : ObjCCommonTypesHelper(cgm)
3306{
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003307 // struct _objc_method_description {
3308 // SEL name;
3309 // char *types;
3310 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003311 MethodDescriptionTy =
3312 llvm::StructType::get(SelectorPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003313 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003314 NULL);
3315 CGM.getModule().addTypeName("struct._objc_method_description",
3316 MethodDescriptionTy);
3317
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003318 // struct _objc_method_description_list {
3319 // int count;
3320 // struct _objc_method_description[1];
3321 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003322 MethodDescriptionListTy =
3323 llvm::StructType::get(IntTy,
3324 llvm::ArrayType::get(MethodDescriptionTy, 0),
3325 NULL);
3326 CGM.getModule().addTypeName("struct._objc_method_description_list",
3327 MethodDescriptionListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003328
3329 // struct _objc_method_description_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003330 MethodDescriptionListPtrTy =
3331 llvm::PointerType::getUnqual(MethodDescriptionListTy);
3332
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003333 // Protocol description structures
3334
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003335 // struct _objc_protocol_extension {
3336 // uint32_t size; // sizeof(struct _objc_protocol_extension)
3337 // struct _objc_method_description_list *optional_instance_methods;
3338 // struct _objc_method_description_list *optional_class_methods;
3339 // struct _objc_property_list *instance_properties;
3340 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003341 ProtocolExtensionTy =
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003342 llvm::StructType::get(IntTy,
3343 MethodDescriptionListPtrTy,
3344 MethodDescriptionListPtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003345 PropertyListPtrTy,
3346 NULL);
3347 CGM.getModule().addTypeName("struct._objc_protocol_extension",
3348 ProtocolExtensionTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003349
3350 // struct _objc_protocol_extension *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003351 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
3352
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003353 // Handle recursive construction of Protocol and ProtocolList types
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003354
3355 llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get();
3356 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3357
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003358 const llvm::Type *T =
3359 llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder),
3360 LongTy,
3361 llvm::ArrayType::get(ProtocolTyHolder, 0),
3362 NULL);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003363 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T);
3364
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003365 // struct _objc_protocol {
3366 // struct _objc_protocol_extension *isa;
3367 // char *protocol_name;
3368 // struct _objc_protocol **_objc_protocol_list;
3369 // struct _objc_method_description_list *instance_methods;
3370 // struct _objc_method_description_list *class_methods;
3371 // }
3372 T = llvm::StructType::get(ProtocolExtensionPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003373 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003374 llvm::PointerType::getUnqual(ProtocolListTyHolder),
3375 MethodDescriptionListPtrTy,
3376 MethodDescriptionListPtrTy,
3377 NULL);
3378 cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T);
3379
3380 ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get());
3381 CGM.getModule().addTypeName("struct._objc_protocol_list",
3382 ProtocolListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003383 // struct _objc_protocol_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003384 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
3385
3386 ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get());
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003387 CGM.getModule().addTypeName("struct._objc_protocol", ProtocolTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003388 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003389
3390 // Class description structures
3391
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003392 // struct _objc_ivar {
3393 // char *ivar_name;
3394 // char *ivar_type;
3395 // int ivar_offset;
3396 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003397 IvarTy = llvm::StructType::get(Int8PtrTy,
3398 Int8PtrTy,
3399 IntTy,
3400 NULL);
3401 CGM.getModule().addTypeName("struct._objc_ivar", IvarTy);
3402
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003403 // struct _objc_ivar_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003404 IvarListTy = llvm::OpaqueType::get();
3405 CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy);
3406 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
3407
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003408 // struct _objc_method_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003409 MethodListTy = llvm::OpaqueType::get();
3410 CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy);
3411 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
3412
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003413 // struct _objc_class_extension *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003414 ClassExtensionTy =
3415 llvm::StructType::get(IntTy,
3416 Int8PtrTy,
3417 PropertyListPtrTy,
3418 NULL);
3419 CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy);
3420 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
3421
3422 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3423
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003424 // struct _objc_class {
3425 // Class isa;
3426 // Class super_class;
3427 // char *name;
3428 // long version;
3429 // long info;
3430 // long instance_size;
3431 // struct _objc_ivar_list *ivars;
3432 // struct _objc_method_list *methods;
3433 // struct _objc_cache *cache;
3434 // struct _objc_protocol_list *protocols;
3435 // char *ivar_layout;
3436 // struct _objc_class_ext *ext;
3437 // };
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003438 T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3439 llvm::PointerType::getUnqual(ClassTyHolder),
3440 Int8PtrTy,
3441 LongTy,
3442 LongTy,
3443 LongTy,
3444 IvarListPtrTy,
3445 MethodListPtrTy,
3446 CachePtrTy,
3447 ProtocolListPtrTy,
3448 Int8PtrTy,
3449 ClassExtensionPtrTy,
3450 NULL);
3451 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T);
3452
3453 ClassTy = cast<llvm::StructType>(ClassTyHolder.get());
3454 CGM.getModule().addTypeName("struct._objc_class", ClassTy);
3455 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
3456
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003457 // struct _objc_category {
3458 // char *category_name;
3459 // char *class_name;
3460 // struct _objc_method_list *instance_method;
3461 // struct _objc_method_list *class_method;
3462 // uint32_t size; // sizeof(struct _objc_category)
3463 // struct _objc_property_list *instance_properties;// category's @property
3464 // }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003465 CategoryTy = llvm::StructType::get(Int8PtrTy,
3466 Int8PtrTy,
3467 MethodListPtrTy,
3468 MethodListPtrTy,
3469 ProtocolListPtrTy,
3470 IntTy,
3471 PropertyListPtrTy,
3472 NULL);
3473 CGM.getModule().addTypeName("struct._objc_category", CategoryTy);
3474
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003475 // Global metadata structures
3476
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003477 // struct _objc_symtab {
3478 // long sel_ref_cnt;
3479 // SEL *refs;
3480 // short cls_def_cnt;
3481 // short cat_def_cnt;
3482 // char *defs[cls_def_cnt + cat_def_cnt];
3483 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003484 SymtabTy = llvm::StructType::get(LongTy,
3485 SelectorPtrTy,
3486 ShortTy,
3487 ShortTy,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003488 llvm::ArrayType::get(Int8PtrTy, 0),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003489 NULL);
3490 CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy);
3491 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
3492
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003493 // struct _objc_module {
3494 // long version;
3495 // long size; // sizeof(struct _objc_module)
3496 // char *name;
3497 // struct _objc_symtab* symtab;
3498 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003499 ModuleTy =
3500 llvm::StructType::get(LongTy,
3501 LongTy,
3502 Int8PtrTy,
3503 SymtabPtrTy,
3504 NULL);
3505 CGM.getModule().addTypeName("struct._objc_module", ModuleTy);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003506
Daniel Dunbar49f66022008-09-24 03:38:44 +00003507 // Message send functions.
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003508
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003509 // id objc_msgSend (id, SEL, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003510 std::vector<const llvm::Type*> Params;
3511 Params.push_back(ObjectPtrTy);
3512 Params.push_back(SelectorPtrTy);
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003513 MessageSendFn =
3514 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3515 Params,
3516 true),
3517 "objc_msgSend");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003518
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003519 // id objc_msgSend_stret (id, SEL, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003520 Params.clear();
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003521 Params.push_back(ObjectPtrTy);
3522 Params.push_back(SelectorPtrTy);
3523 MessageSendStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003524 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3525 Params,
3526 true),
3527 "objc_msgSend_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00003528
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003529 //
Daniel Dunbar5669e572008-10-17 03:24:53 +00003530 Params.clear();
3531 Params.push_back(ObjectPtrTy);
3532 Params.push_back(SelectorPtrTy);
3533 // FIXME: This should be long double on x86_64?
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003534 // [double | long double] objc_msgSend_fpret(id self, SEL op, ...)
Daniel Dunbar5669e572008-10-17 03:24:53 +00003535 MessageSendFpretFn =
3536 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::DoubleTy,
3537 Params,
3538 true),
3539 "objc_msgSend_fpret");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003540
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003541 // id objc_msgSendSuper(struct objc_super *super, SEL op, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003542 Params.clear();
3543 Params.push_back(SuperPtrTy);
3544 Params.push_back(SelectorPtrTy);
3545 MessageSendSuperFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003546 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3547 Params,
3548 true),
3549 "objc_msgSendSuper");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003550
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003551 // void objc_msgSendSuper_stret(void * stretAddr, struct objc_super *super,
3552 // SEL op, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003553 Params.clear();
3554 Params.push_back(Int8PtrTy);
3555 Params.push_back(SuperPtrTy);
3556 Params.push_back(SelectorPtrTy);
3557 MessageSendSuperStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003558 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3559 Params,
3560 true),
3561 "objc_msgSendSuper_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00003562
3563 // There is no objc_msgSendSuper_fpret? How can that work?
3564 MessageSendSuperFpretFn = MessageSendSuperFn;
Anders Carlsson2abd89c2008-08-31 04:05:03 +00003565
Anders Carlsson124526b2008-09-09 10:10:21 +00003566 // FIXME: This is the size of the setjmp buffer and should be
3567 // target specific. 18 is what's used on 32-bit X86.
3568 uint64_t SetJmpBufferSize = 18;
3569
3570 // Exceptions
3571 const llvm::Type *StackPtrTy =
Daniel Dunbar10004912008-09-27 06:32:25 +00003572 llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4);
Anders Carlsson124526b2008-09-09 10:10:21 +00003573
3574 ExceptionDataTy =
3575 llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty,
3576 SetJmpBufferSize),
3577 StackPtrTy, NULL);
3578 CGM.getModule().addTypeName("struct._objc_exception_data",
3579 ExceptionDataTy);
3580
3581 Params.clear();
Anders Carlsson124526b2008-09-09 10:10:21 +00003582 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
3583 ExceptionTryEnterFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003584 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3585 Params,
3586 false),
3587 "objc_exception_try_enter");
Anders Carlsson124526b2008-09-09 10:10:21 +00003588 ExceptionTryExitFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003589 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3590 Params,
3591 false),
3592 "objc_exception_try_exit");
Anders Carlsson124526b2008-09-09 10:10:21 +00003593 ExceptionExtractFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003594 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3595 Params,
3596 false),
3597 "objc_exception_extract");
Anders Carlsson124526b2008-09-09 10:10:21 +00003598
3599 Params.clear();
3600 Params.push_back(ClassPtrTy);
3601 Params.push_back(ObjectPtrTy);
3602 ExceptionMatchFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003603 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
3604 Params,
3605 false),
3606 "objc_exception_match");
Chris Lattner10cac6f2008-11-15 21:26:17 +00003607
Anders Carlsson124526b2008-09-09 10:10:21 +00003608 Params.clear();
3609 Params.push_back(llvm::PointerType::getUnqual(llvm::Type::Int32Ty));
3610 SetJmpFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003611 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
3612 Params,
3613 false),
3614 "_setjmp");
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00003615
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003616}
3617
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003618ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003619: ObjCCommonTypesHelper(cgm)
3620{
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003621 // struct _method_list_t {
3622 // uint32_t entsize; // sizeof(struct _objc_method)
3623 // uint32_t method_count;
3624 // struct _objc_method method_list[method_count];
3625 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003626 MethodListnfABITy = llvm::StructType::get(IntTy,
3627 IntTy,
3628 llvm::ArrayType::get(MethodTy, 0),
3629 NULL);
3630 CGM.getModule().addTypeName("struct.__method_list_t",
3631 MethodListnfABITy);
3632 // struct method_list_t *
3633 MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003634
3635 // struct _protocol_t {
3636 // id isa; // NULL
3637 // const char * const protocol_name;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003638 // const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003639 // const struct method_list_t * const instance_methods;
3640 // const struct method_list_t * const class_methods;
3641 // const struct method_list_t *optionalInstanceMethods;
3642 // const struct method_list_t *optionalClassMethods;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003643 // const struct _prop_list_t * properties;
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003644 // const uint32_t size; // sizeof(struct _protocol_t)
3645 // const uint32_t flags; // = 0
3646 // }
3647
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003648 // Holder for struct _protocol_list_t *
3649 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3650
3651 ProtocolnfABITy = llvm::StructType::get(ObjectPtrTy,
3652 Int8PtrTy,
3653 llvm::PointerType::getUnqual(
3654 ProtocolListTyHolder),
3655 MethodListnfABIPtrTy,
3656 MethodListnfABIPtrTy,
3657 MethodListnfABIPtrTy,
3658 MethodListnfABIPtrTy,
3659 PropertyListPtrTy,
3660 IntTy,
3661 IntTy,
3662 NULL);
3663 CGM.getModule().addTypeName("struct._protocol_t",
3664 ProtocolnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003665
3666 // struct _protocol_t*
3667 ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003668
Fariborz Jahanianda320092009-01-29 19:24:30 +00003669 // struct _protocol_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003670 // long protocol_count; // Note, this is 32/64 bit
Daniel Dunbar948e2582009-02-15 07:36:20 +00003671 // struct _protocol_t *[protocol_count];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003672 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003673 ProtocolListnfABITy = llvm::StructType::get(LongTy,
3674 llvm::ArrayType::get(
Daniel Dunbar948e2582009-02-15 07:36:20 +00003675 ProtocolnfABIPtrTy, 0),
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003676 NULL);
3677 CGM.getModule().addTypeName("struct._objc_protocol_list",
3678 ProtocolListnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003679 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(
3680 ProtocolListnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003681
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003682 // struct _objc_protocol_list*
3683 ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003684
3685 // struct _ivar_t {
3686 // unsigned long int *offset; // pointer to ivar offset location
3687 // char *name;
3688 // char *type;
3689 // uint32_t alignment;
3690 // uint32_t size;
3691 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003692 IvarnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(LongTy),
3693 Int8PtrTy,
3694 Int8PtrTy,
3695 IntTy,
3696 IntTy,
3697 NULL);
3698 CGM.getModule().addTypeName("struct._ivar_t", IvarnfABITy);
3699
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003700 // struct _ivar_list_t {
3701 // uint32 entsize; // sizeof(struct _ivar_t)
3702 // uint32 count;
3703 // struct _iver_t list[count];
3704 // }
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003705 IvarListnfABITy = llvm::StructType::get(IntTy,
3706 IntTy,
3707 llvm::ArrayType::get(
3708 IvarnfABITy, 0),
3709 NULL);
3710 CGM.getModule().addTypeName("struct._ivar_list_t", IvarListnfABITy);
3711
3712 IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003713
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003714 // struct _class_ro_t {
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003715 // uint32_t const flags;
3716 // uint32_t const instanceStart;
3717 // uint32_t const instanceSize;
3718 // uint32_t const reserved; // only when building for 64bit targets
3719 // const uint8_t * const ivarLayout;
3720 // const char *const name;
3721 // const struct _method_list_t * const baseMethods;
3722 // const struct _objc_protocol_list *const baseProtocols;
3723 // const struct _ivar_list_t *const ivars;
3724 // const uint8_t * const weakIvarLayout;
3725 // const struct _prop_list_t * const properties;
3726 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003727
3728 // FIXME. Add 'reserved' field in 64bit abi mode!
3729 ClassRonfABITy = llvm::StructType::get(IntTy,
3730 IntTy,
3731 IntTy,
3732 Int8PtrTy,
3733 Int8PtrTy,
3734 MethodListnfABIPtrTy,
3735 ProtocolListnfABIPtrTy,
3736 IvarListnfABIPtrTy,
3737 Int8PtrTy,
3738 PropertyListPtrTy,
3739 NULL);
3740 CGM.getModule().addTypeName("struct._class_ro_t",
3741 ClassRonfABITy);
3742
3743 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
3744 std::vector<const llvm::Type*> Params;
3745 Params.push_back(ObjectPtrTy);
3746 Params.push_back(SelectorPtrTy);
3747 ImpnfABITy = llvm::PointerType::getUnqual(
3748 llvm::FunctionType::get(ObjectPtrTy, Params, false));
3749
3750 // struct _class_t {
3751 // struct _class_t *isa;
3752 // struct _class_t * const superclass;
3753 // void *cache;
3754 // IMP *vtable;
3755 // struct class_ro_t *ro;
3756 // }
3757
3758 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3759 ClassnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3760 llvm::PointerType::getUnqual(ClassTyHolder),
3761 CachePtrTy,
3762 llvm::PointerType::getUnqual(ImpnfABITy),
3763 llvm::PointerType::getUnqual(
3764 ClassRonfABITy),
3765 NULL);
3766 CGM.getModule().addTypeName("struct._class_t", ClassnfABITy);
3767
3768 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(
3769 ClassnfABITy);
3770
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003771 // LLVM for struct _class_t *
3772 ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy);
3773
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003774 // struct _category_t {
3775 // const char * const name;
3776 // struct _class_t *const cls;
3777 // const struct _method_list_t * const instance_methods;
3778 // const struct _method_list_t * const class_methods;
3779 // const struct _protocol_list_t * const protocols;
3780 // const struct _prop_list_t * const properties;
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003781 // }
3782 CategorynfABITy = llvm::StructType::get(Int8PtrTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003783 ClassnfABIPtrTy,
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003784 MethodListnfABIPtrTy,
3785 MethodListnfABIPtrTy,
3786 ProtocolListnfABIPtrTy,
3787 PropertyListPtrTy,
3788 NULL);
3789 CGM.getModule().addTypeName("struct._category_t", CategorynfABITy);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003790
3791 // New types for nonfragile abi messaging.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003792 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3793 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003794
3795 // MessageRefTy - LLVM for:
3796 // struct _message_ref_t {
3797 // IMP messenger;
3798 // SEL name;
3799 // };
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003800
3801 // First the clang type for struct _message_ref_t
3802 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3803 SourceLocation(),
3804 &Ctx.Idents.get("_message_ref_t"));
Douglas Gregor6ab35242009-04-09 21:40:53 +00003805 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3806 Ctx.VoidPtrTy, 0, false));
3807 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3808 Ctx.getObjCSelType(), 0, false));
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003809 RD->completeDefinition(Ctx);
3810
3811 MessageRefCTy = Ctx.getTagDeclType(RD);
3812 MessageRefCPtrTy = Ctx.getPointerType(MessageRefCTy);
3813 MessageRefTy = cast<llvm::StructType>(Types.ConvertType(MessageRefCTy));
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003814
3815 // MessageRefPtrTy - LLVM for struct _message_ref_t*
3816 MessageRefPtrTy = llvm::PointerType::getUnqual(MessageRefTy);
3817
3818 // SuperMessageRefTy - LLVM for:
3819 // struct _super_message_ref_t {
3820 // SUPER_IMP messenger;
3821 // SEL name;
3822 // };
3823 SuperMessageRefTy = llvm::StructType::get(ImpnfABITy,
3824 SelectorPtrTy,
3825 NULL);
3826 CGM.getModule().addTypeName("struct._super_message_ref_t", SuperMessageRefTy);
3827
3828 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
3829 SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy);
3830
3831 // id objc_msgSend_fixup (id, struct message_ref_t*, ...)
3832 Params.clear();
3833 Params.push_back(ObjectPtrTy);
3834 Params.push_back(MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00003835 MessengerTy = llvm::FunctionType::get(ObjectPtrTy,
3836 Params,
3837 true);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003838 MessageSendFixupFn =
Fariborz Jahanianef163782009-02-05 01:13:09 +00003839 CGM.CreateRuntimeFunction(MessengerTy,
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003840 "objc_msgSend_fixup");
3841
3842 // id objc_msgSend_fpret_fixup (id, struct message_ref_t*, ...)
3843 MessageSendFpretFixupFn =
3844 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3845 Params,
3846 true),
3847 "objc_msgSend_fpret_fixup");
3848
3849 // id objc_msgSend_stret_fixup (id, struct message_ref_t*, ...)
3850 MessageSendStretFixupFn =
3851 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3852 Params,
3853 true),
3854 "objc_msgSend_stret_fixup");
3855
3856 // id objc_msgSendId_fixup (id, struct message_ref_t*, ...)
3857 MessageSendIdFixupFn =
3858 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3859 Params,
3860 true),
3861 "objc_msgSendId_fixup");
3862
3863
3864 // id objc_msgSendId_stret_fixup (id, struct message_ref_t*, ...)
3865 MessageSendIdStretFixupFn =
3866 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3867 Params,
3868 true),
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003869 "objc_msgSendId_stret_fixup");
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003870
3871 // id objc_msgSendSuper2_fixup (struct objc_super *,
3872 // struct _super_message_ref_t*, ...)
3873 Params.clear();
3874 Params.push_back(SuperPtrTy);
3875 Params.push_back(SuperMessageRefPtrTy);
3876 MessageSendSuper2FixupFn =
3877 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3878 Params,
3879 true),
3880 "objc_msgSendSuper2_fixup");
3881
3882
3883 // id objc_msgSendSuper2_stret_fixup (struct objc_super *,
3884 // struct _super_message_ref_t*, ...)
3885 MessageSendSuper2StretFixupFn =
3886 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3887 Params,
3888 true),
3889 "objc_msgSendSuper2_stret_fixup");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00003890
3891 Params.clear();
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00003892 Params.push_back(Int8PtrTy);
3893 UnwindResumeOrRethrowFn =
3894 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3895 Params,
3896 false),
3897 "_Unwind_Resume_or_Rethrow");
Daniel Dunbare588b992009-03-01 04:46:24 +00003898 ObjCBeginCatchFn =
3899 CGM.CreateRuntimeFunction(llvm::FunctionType::get(Int8PtrTy,
3900 Params,
3901 false),
3902 "objc_begin_catch");
3903
3904 Params.clear();
3905 ObjCEndCatchFn =
3906 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3907 Params,
3908 false),
3909 "objc_end_catch");
3910
3911 // struct objc_typeinfo {
3912 // const void** vtable; // objc_ehtype_vtable + 2
3913 // const char* name; // c++ typeinfo string
3914 // Class cls;
3915 // };
3916 EHTypeTy = llvm::StructType::get(llvm::PointerType::getUnqual(Int8PtrTy),
3917 Int8PtrTy,
3918 ClassnfABIPtrTy,
3919 NULL);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00003920 CGM.getModule().addTypeName("struct._objc_typeinfo", EHTypeTy);
Daniel Dunbare588b992009-03-01 04:46:24 +00003921 EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy);
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003922}
3923
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003924llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() {
3925 FinishNonFragileABIModule();
3926
3927 return NULL;
3928}
3929
3930void CGObjCNonFragileABIMac::FinishNonFragileABIModule() {
3931 // nonfragile abi has no module definition.
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003932
3933 // Build list of all implemented classe addresses in array
3934 // L_OBJC_LABEL_CLASS_$.
3935 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CLASS_$
3936 // list of 'nonlazy' implementations (defined as those with a +load{}
3937 // method!!).
3938 unsigned NumClasses = DefinedClasses.size();
3939 if (NumClasses) {
3940 std::vector<llvm::Constant*> Symbols(NumClasses);
3941 for (unsigned i=0; i<NumClasses; i++)
3942 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
3943 ObjCTypes.Int8PtrTy);
3944 llvm::Constant* Init =
3945 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
3946 NumClasses),
3947 Symbols);
3948
3949 llvm::GlobalVariable *GV =
3950 new llvm::GlobalVariable(Init->getType(), false,
3951 llvm::GlobalValue::InternalLinkage,
3952 Init,
3953 "\01L_OBJC_LABEL_CLASS_$",
3954 &CGM.getModule());
Daniel Dunbar58a29122009-03-09 22:18:41 +00003955 GV->setAlignment(8);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003956 GV->setSection("__DATA, __objc_classlist, regular, no_dead_strip");
3957 UsedGlobals.push_back(GV);
3958 }
3959
3960 // Build list of all implemented category addresses in array
3961 // L_OBJC_LABEL_CATEGORY_$.
3962 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CATEGORY_$
3963 // list of 'nonlazy' category implementations (defined as those with a +load{}
3964 // method!!).
3965 unsigned NumCategory = DefinedCategories.size();
3966 if (NumCategory) {
3967 std::vector<llvm::Constant*> Symbols(NumCategory);
3968 for (unsigned i=0; i<NumCategory; i++)
3969 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedCategories[i],
3970 ObjCTypes.Int8PtrTy);
3971 llvm::Constant* Init =
3972 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
3973 NumCategory),
3974 Symbols);
3975
3976 llvm::GlobalVariable *GV =
3977 new llvm::GlobalVariable(Init->getType(), false,
3978 llvm::GlobalValue::InternalLinkage,
3979 Init,
3980 "\01L_OBJC_LABEL_CATEGORY_$",
3981 &CGM.getModule());
Daniel Dunbar58a29122009-03-09 22:18:41 +00003982 GV->setAlignment(8);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003983 GV->setSection("__DATA, __objc_catlist, regular, no_dead_strip");
3984 UsedGlobals.push_back(GV);
3985 }
3986
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00003987 // static int L_OBJC_IMAGE_INFO[2] = { 0, flags };
3988 // FIXME. flags can be 0 | 1 | 2 | 6. For now just use 0
3989 std::vector<llvm::Constant*> Values(2);
3990 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, 0);
Fariborz Jahanian067986e2009-02-24 21:08:09 +00003991 unsigned int flags = 0;
Fariborz Jahanian66a5c2c2009-02-24 23:34:44 +00003992 // FIXME: Fix and continue?
3993 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
3994 flags |= eImageInfo_GarbageCollected;
3995 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
3996 flags |= eImageInfo_GCOnly;
Fariborz Jahanian067986e2009-02-24 21:08:09 +00003997 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00003998 llvm::Constant* Init = llvm::ConstantArray::get(
3999 llvm::ArrayType::get(ObjCTypes.IntTy, 2),
4000 Values);
4001 llvm::GlobalVariable *IMGV =
4002 new llvm::GlobalVariable(Init->getType(), false,
4003 llvm::GlobalValue::InternalLinkage,
4004 Init,
4005 "\01L_OBJC_IMAGE_INFO",
4006 &CGM.getModule());
4007 IMGV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
4008 UsedGlobals.push_back(IMGV);
4009
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004010 std::vector<llvm::Constant*> Used;
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004011
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004012 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
4013 e = UsedGlobals.end(); i != e; ++i) {
4014 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
4015 }
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004016
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004017 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
4018 llvm::GlobalValue *GV =
4019 new llvm::GlobalVariable(AT, false,
4020 llvm::GlobalValue::AppendingLinkage,
4021 llvm::ConstantArray::get(AT, Used),
4022 "llvm.used",
4023 &CGM.getModule());
4024
4025 GV->setSection("llvm.metadata");
4026
4027}
4028
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004029// Metadata flags
4030enum MetaDataDlags {
4031 CLS = 0x0,
4032 CLS_META = 0x1,
4033 CLS_ROOT = 0x2,
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004034 OBJC2_CLS_HIDDEN = 0x10,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004035 CLS_EXCEPTION = 0x20
4036};
4037/// BuildClassRoTInitializer - generate meta-data for:
4038/// struct _class_ro_t {
4039/// uint32_t const flags;
4040/// uint32_t const instanceStart;
4041/// uint32_t const instanceSize;
4042/// uint32_t const reserved; // only when building for 64bit targets
4043/// const uint8_t * const ivarLayout;
4044/// const char *const name;
4045/// const struct _method_list_t * const baseMethods;
Fariborz Jahanianda320092009-01-29 19:24:30 +00004046/// const struct _protocol_list_t *const baseProtocols;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004047/// const struct _ivar_list_t *const ivars;
4048/// const uint8_t * const weakIvarLayout;
4049/// const struct _prop_list_t * const properties;
4050/// }
4051///
4052llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer(
4053 unsigned flags,
4054 unsigned InstanceStart,
4055 unsigned InstanceSize,
4056 const ObjCImplementationDecl *ID) {
4057 std::string ClassName = ID->getNameAsString();
4058 std::vector<llvm::Constant*> Values(10); // 11 for 64bit targets!
4059 Values[ 0] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
4060 Values[ 1] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceStart);
4061 Values[ 2] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceSize);
4062 // FIXME. For 64bit targets add 0 here.
Fariborz Jahanianda320092009-01-29 19:24:30 +00004063 // FIXME. ivarLayout is currently null!
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00004064 Values[ 3] = GetIvarLayoutName(0, ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004065 Values[ 4] = GetClassName(ID->getIdentifier());
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004066 // const struct _method_list_t * const baseMethods;
4067 std::vector<llvm::Constant*> Methods;
4068 std::string MethodListName("\01l_OBJC_$_");
4069 if (flags & CLS_META) {
4070 MethodListName += "CLASS_METHODS_" + ID->getNameAsString();
4071 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
4072 e = ID->classmeth_end(); i != e; ++i) {
4073 // Class methods should always be defined.
4074 Methods.push_back(GetMethodConstant(*i));
4075 }
4076 } else {
4077 MethodListName += "INSTANCE_METHODS_" + ID->getNameAsString();
4078 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
4079 e = ID->instmeth_end(); i != e; ++i) {
4080 // Instance methods should always be defined.
4081 Methods.push_back(GetMethodConstant(*i));
4082 }
Fariborz Jahanian939abce2009-01-28 22:46:49 +00004083 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
4084 e = ID->propimpl_end(); i != e; ++i) {
4085 ObjCPropertyImplDecl *PID = *i;
4086
4087 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize){
4088 ObjCPropertyDecl *PD = PID->getPropertyDecl();
4089
4090 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
4091 if (llvm::Constant *C = GetMethodConstant(MD))
4092 Methods.push_back(C);
4093 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
4094 if (llvm::Constant *C = GetMethodConstant(MD))
4095 Methods.push_back(C);
4096 }
4097 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004098 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004099 Values[ 5] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004100 "__DATA, __objc_const", Methods);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004101
4102 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4103 assert(OID && "CGObjCNonFragileABIMac::BuildClassRoTInitializer");
4104 Values[ 6] = EmitProtocolList("\01l_OBJC_CLASS_PROTOCOLS_$_"
4105 + OID->getNameAsString(),
4106 OID->protocol_begin(),
4107 OID->protocol_end());
4108
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004109 if (flags & CLS_META)
4110 Values[ 7] = llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4111 else
4112 Values[ 7] = EmitIvarList(ID);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004113 // FIXME. weakIvarLayout is currently null.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00004114 Values[ 8] = GetIvarLayoutName(0, ObjCTypes);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004115 if (flags & CLS_META)
4116 Values[ 9] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4117 else
4118 Values[ 9] =
4119 EmitPropertyList(
4120 "\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
4121 ID, ID->getClassInterface(), ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004122 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassRonfABITy,
4123 Values);
4124 llvm::GlobalVariable *CLASS_RO_GV =
4125 new llvm::GlobalVariable(ObjCTypes.ClassRonfABITy, false,
4126 llvm::GlobalValue::InternalLinkage,
4127 Init,
4128 (flags & CLS_META) ?
4129 std::string("\01l_OBJC_METACLASS_RO_$_")+ClassName :
4130 std::string("\01l_OBJC_CLASS_RO_$_")+ClassName,
4131 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004132 CLASS_RO_GV->setAlignment(
4133 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassRonfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004134 CLASS_RO_GV->setSection("__DATA, __objc_const");
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004135 return CLASS_RO_GV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004136
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004137}
4138
4139/// BuildClassMetaData - This routine defines that to-level meta-data
4140/// for the given ClassName for:
4141/// struct _class_t {
4142/// struct _class_t *isa;
4143/// struct _class_t * const superclass;
4144/// void *cache;
4145/// IMP *vtable;
4146/// struct class_ro_t *ro;
4147/// }
4148///
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004149llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassMetaData(
4150 std::string &ClassName,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004151 llvm::Constant *IsAGV,
4152 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004153 llvm::Constant *ClassRoGV,
4154 bool HiddenVisibility) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004155 std::vector<llvm::Constant*> Values(5);
4156 Values[0] = IsAGV;
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004157 Values[1] = SuperClassGV
4158 ? SuperClassGV
4159 : llvm::Constant::getNullValue(ObjCTypes.ClassnfABIPtrTy);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004160 Values[2] = ObjCEmptyCacheVar; // &ObjCEmptyCacheVar
4161 Values[3] = ObjCEmptyVtableVar; // &ObjCEmptyVtableVar
4162 Values[4] = ClassRoGV; // &CLASS_RO_GV
4163 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassnfABITy,
4164 Values);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004165 llvm::GlobalVariable *GV = GetClassGlobal(ClassName);
4166 GV->setInitializer(Init);
Fariborz Jahaniandd0db2a2009-01-31 01:07:39 +00004167 GV->setSection("__DATA, __objc_data");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004168 GV->setAlignment(
4169 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassnfABITy));
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004170 if (HiddenVisibility)
4171 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004172 return GV;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004173}
4174
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004175void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) {
4176 std::string ClassName = ID->getNameAsString();
4177 if (!ObjCEmptyCacheVar) {
4178 ObjCEmptyCacheVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004179 ObjCTypes.CacheTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004180 false,
4181 llvm::GlobalValue::ExternalLinkage,
4182 0,
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004183 "_objc_empty_cache",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004184 &CGM.getModule());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004185
4186 ObjCEmptyVtableVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004187 ObjCTypes.ImpnfABITy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004188 false,
4189 llvm::GlobalValue::ExternalLinkage,
4190 0,
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004191 "_objc_empty_vtable",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004192 &CGM.getModule());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004193 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004194 assert(ID->getClassInterface() &&
4195 "CGObjCNonFragileABIMac::GenerateClass - class is 0");
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004196 uint32_t InstanceStart =
4197 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassnfABITy);
4198 uint32_t InstanceSize = InstanceStart;
4199 uint32_t flags = CLS_META;
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004200 std::string ObjCMetaClassName(getMetaclassSymbolPrefix());
4201 std::string ObjCClassName(getClassSymbolPrefix());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004202
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004203 llvm::GlobalVariable *SuperClassGV, *IsAGV;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004204
Daniel Dunbar04d40782009-04-14 06:00:08 +00004205 bool classIsHidden =
4206 CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004207 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004208 flags |= OBJC2_CLS_HIDDEN;
4209 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004210 // class is root
4211 flags |= CLS_ROOT;
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004212 SuperClassGV = GetClassGlobal(ObjCClassName + ClassName);
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004213 IsAGV = GetClassGlobal(ObjCMetaClassName + ClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004214 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004215 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004216 const ObjCInterfaceDecl *Root = ID->getClassInterface();
4217 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
4218 Root = Super;
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004219 IsAGV = GetClassGlobal(ObjCMetaClassName + Root->getNameAsString());
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004220 // work on super class metadata symbol.
4221 std::string SuperClassName =
4222 ObjCMetaClassName + ID->getClassInterface()->getSuperClass()->getNameAsString();
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004223 SuperClassGV = GetClassGlobal(SuperClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004224 }
4225 llvm::GlobalVariable *CLASS_RO_GV = BuildClassRoTInitializer(flags,
4226 InstanceStart,
4227 InstanceSize,ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004228 std::string TClassName = ObjCMetaClassName + ClassName;
4229 llvm::GlobalVariable *MetaTClass =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004230 BuildClassMetaData(TClassName, IsAGV, SuperClassGV, CLASS_RO_GV,
4231 classIsHidden);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004232
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004233 // Metadata for the class
4234 flags = CLS;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004235 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004236 flags |= OBJC2_CLS_HIDDEN;
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004237
4238 if (hasObjCExceptionAttribute(ID->getClassInterface()))
4239 flags |= CLS_EXCEPTION;
4240
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004241 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004242 flags |= CLS_ROOT;
4243 SuperClassGV = 0;
4244 }
4245 else {
4246 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004247 std::string RootClassName =
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004248 ID->getClassInterface()->getSuperClass()->getNameAsString();
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004249 SuperClassGV = GetClassGlobal(ObjCClassName + RootClassName);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004250 }
Fariborz Jahanianebf9ed32009-03-20 20:48:19 +00004251 // FIXME: Gross
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004252 InstanceStart = InstanceSize = 0;
4253 if (ObjCInterfaceDecl *OID =
4254 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface())) {
4255 // FIXME. Share this with the one in EmitIvarList.
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00004256 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID);
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004257
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00004258 RecordDecl::field_iterator firstField, lastField;
4259 const RecordDecl *RD = GetFirstIvarInRecord(OID, firstField, lastField);
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004260
Douglas Gregor6ab35242009-04-09 21:40:53 +00004261 for (RecordDecl::field_iterator e = RD->field_end(CGM.getContext()),
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004262 ifield = firstField; ifield != e; ++ifield)
4263 lastField = ifield;
4264
Douglas Gregor6ab35242009-04-09 21:40:53 +00004265 if (lastField != RD->field_end(CGM.getContext())) {
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004266 FieldDecl *Field = *lastField;
4267 const llvm::Type *FieldTy =
4268 CGM.getTypes().ConvertTypeForMem(Field->getType());
4269 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00004270 InstanceSize = GetIvarBaseOffset(Layout, Field) + Size;
Douglas Gregor6ab35242009-04-09 21:40:53 +00004271 if (firstField == RD->field_end(CGM.getContext()))
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004272 InstanceStart = InstanceSize;
Fariborz Jahanian11894a42009-03-07 19:43:20 +00004273 else {
4274 Field = *firstField;
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00004275 InstanceStart = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanian11894a42009-03-07 19:43:20 +00004276 }
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004277 }
4278 }
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004279 CLASS_RO_GV = BuildClassRoTInitializer(flags,
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004280 InstanceStart,
4281 InstanceSize,
4282 ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004283
4284 TClassName = ObjCClassName + ClassName;
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004285 llvm::GlobalVariable *ClassMD =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004286 BuildClassMetaData(TClassName, MetaTClass, SuperClassGV, CLASS_RO_GV,
4287 classIsHidden);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004288 DefinedClasses.push_back(ClassMD);
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004289
4290 // Force the definition of the EHType if necessary.
4291 if (flags & CLS_EXCEPTION)
4292 GetInterfaceEHType(ID->getClassInterface(), true);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004293}
4294
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004295/// GenerateProtocolRef - This routine is called to generate code for
4296/// a protocol reference expression; as in:
4297/// @code
4298/// @protocol(Proto1);
4299/// @endcode
4300/// It generates a weak reference to l_OBJC_PROTOCOL_REFERENCE_$_Proto1
4301/// which will hold address of the protocol meta-data.
4302///
4303llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CGBuilderTy &Builder,
4304 const ObjCProtocolDecl *PD) {
4305
Fariborz Jahanian960cd062009-04-10 18:47:34 +00004306 // This routine is called for @protocol only. So, we must build definition
4307 // of protocol's meta-data (not a reference to it!)
4308 //
4309 llvm::Constant *Init = llvm::ConstantExpr::getBitCast(GetOrEmitProtocol(PD),
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004310 ObjCTypes.ExternalProtocolPtrTy);
4311
4312 std::string ProtocolName("\01l_OBJC_PROTOCOL_REFERENCE_$_");
4313 ProtocolName += PD->getNameAsCString();
4314
4315 llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName);
4316 if (PTGV)
4317 return Builder.CreateLoad(PTGV, false, "tmp");
4318 PTGV = new llvm::GlobalVariable(
4319 Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00004320 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004321 Init,
4322 ProtocolName,
4323 &CGM.getModule());
4324 PTGV->setSection("__DATA, __objc_protorefs, coalesced, no_dead_strip");
4325 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4326 UsedGlobals.push_back(PTGV);
4327 return Builder.CreateLoad(PTGV, false, "tmp");
4328}
4329
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004330/// GenerateCategory - Build metadata for a category implementation.
4331/// struct _category_t {
4332/// const char * const name;
4333/// struct _class_t *const cls;
4334/// const struct _method_list_t * const instance_methods;
4335/// const struct _method_list_t * const class_methods;
4336/// const struct _protocol_list_t * const protocols;
4337/// const struct _prop_list_t * const properties;
4338/// }
4339///
4340void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD)
4341{
4342 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004343 const char *Prefix = "\01l_OBJC_$_CATEGORY_";
4344 std::string ExtCatName(Prefix + Interface->getNameAsString()+
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004345 "_$_" + OCD->getNameAsString());
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004346 std::string ExtClassName(getClassSymbolPrefix() +
4347 Interface->getNameAsString());
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004348
4349 std::vector<llvm::Constant*> Values(6);
4350 Values[0] = GetClassName(OCD->getIdentifier());
4351 // meta-class entry symbol
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004352 llvm::GlobalVariable *ClassGV = GetClassGlobal(ExtClassName);
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004353 Values[1] = ClassGV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004354 std::vector<llvm::Constant*> Methods;
4355 std::string MethodListName(Prefix);
4356 MethodListName += "INSTANCE_METHODS_" + Interface->getNameAsString() +
4357 "_$_" + OCD->getNameAsString();
4358
4359 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
4360 e = OCD->instmeth_end(); i != e; ++i) {
4361 // Instance methods should always be defined.
4362 Methods.push_back(GetMethodConstant(*i));
4363 }
4364
4365 Values[2] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004366 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004367 Methods);
4368
4369 MethodListName = Prefix;
4370 MethodListName += "CLASS_METHODS_" + Interface->getNameAsString() + "_$_" +
4371 OCD->getNameAsString();
4372 Methods.clear();
4373 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
4374 e = OCD->classmeth_end(); i != e; ++i) {
4375 // Class methods should always be defined.
4376 Methods.push_back(GetMethodConstant(*i));
4377 }
4378
4379 Values[3] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004380 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004381 Methods);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004382 const ObjCCategoryDecl *Category =
4383 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Fariborz Jahanian943ed6f2009-02-13 17:52:22 +00004384 if (Category) {
4385 std::string ExtName(Interface->getNameAsString() + "_$_" +
4386 OCD->getNameAsString());
4387 Values[4] = EmitProtocolList("\01l_OBJC_CATEGORY_PROTOCOLS_$_"
4388 + Interface->getNameAsString() + "_$_"
4389 + Category->getNameAsString(),
4390 Category->protocol_begin(),
4391 Category->protocol_end());
4392 Values[5] =
4393 EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
4394 OCD, Category, ObjCTypes);
4395 }
4396 else {
4397 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4398 Values[5] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4399 }
4400
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004401 llvm::Constant *Init =
4402 llvm::ConstantStruct::get(ObjCTypes.CategorynfABITy,
4403 Values);
4404 llvm::GlobalVariable *GCATV
4405 = new llvm::GlobalVariable(ObjCTypes.CategorynfABITy,
4406 false,
4407 llvm::GlobalValue::InternalLinkage,
4408 Init,
4409 ExtCatName,
4410 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004411 GCATV->setAlignment(
4412 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.CategorynfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004413 GCATV->setSection("__DATA, __objc_const");
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004414 UsedGlobals.push_back(GCATV);
4415 DefinedCategories.push_back(GCATV);
4416}
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004417
4418/// GetMethodConstant - Return a struct objc_method constant for the
4419/// given method if it has been defined. The result is null if the
4420/// method has not been defined. The return value has type MethodPtrTy.
4421llvm::Constant *CGObjCNonFragileABIMac::GetMethodConstant(
4422 const ObjCMethodDecl *MD) {
4423 // FIXME: Use DenseMap::lookup
4424 llvm::Function *Fn = MethodDefinitions[MD];
4425 if (!Fn)
4426 return 0;
4427
4428 std::vector<llvm::Constant*> Method(3);
4429 Method[0] =
4430 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4431 ObjCTypes.SelectorPtrTy);
4432 Method[1] = GetMethodVarType(MD);
4433 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
4434 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
4435}
4436
4437/// EmitMethodList - Build meta-data for method declarations
4438/// struct _method_list_t {
4439/// uint32_t entsize; // sizeof(struct _objc_method)
4440/// uint32_t method_count;
4441/// struct _objc_method method_list[method_count];
4442/// }
4443///
4444llvm::Constant *CGObjCNonFragileABIMac::EmitMethodList(
4445 const std::string &Name,
4446 const char *Section,
4447 const ConstantVector &Methods) {
4448 // Return null for empty list.
4449 if (Methods.empty())
4450 return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy);
4451
4452 std::vector<llvm::Constant*> Values(3);
4453 // sizeof(struct _objc_method)
4454 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.MethodTy);
4455 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4456 // method_count
4457 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
4458 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
4459 Methods.size());
4460 Values[2] = llvm::ConstantArray::get(AT, Methods);
4461 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4462
4463 llvm::GlobalVariable *GV =
4464 new llvm::GlobalVariable(Init->getType(), false,
4465 llvm::GlobalValue::InternalLinkage,
4466 Init,
4467 Name,
4468 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004469 GV->setAlignment(
4470 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004471 GV->setSection(Section);
4472 UsedGlobals.push_back(GV);
4473 return llvm::ConstantExpr::getBitCast(GV,
4474 ObjCTypes.MethodListnfABIPtrTy);
4475}
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004476
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004477/// ObjCIvarOffsetVariable - Returns the ivar offset variable for
4478/// the given ivar.
4479///
4480llvm::GlobalVariable * CGObjCNonFragileABIMac::ObjCIvarOffsetVariable(
4481 std::string &Name,
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004482 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004483 const ObjCIvarDecl *Ivar) {
Daniel Dunbardd131982009-04-14 22:44:26 +00004484 Name += "OBJC_IVAR_$_" +
Douglas Gregor6ab35242009-04-09 21:40:53 +00004485 getInterfaceDeclForIvar(ID, Ivar, CGM.getContext())->getNameAsString() +
4486 '.' + Ivar->getNameAsString();
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004487 llvm::GlobalVariable *IvarOffsetGV =
4488 CGM.getModule().getGlobalVariable(Name);
4489 if (!IvarOffsetGV)
4490 IvarOffsetGV =
4491 new llvm::GlobalVariable(ObjCTypes.LongTy,
4492 false,
4493 llvm::GlobalValue::ExternalLinkage,
4494 0,
4495 Name,
4496 &CGM.getModule());
4497 return IvarOffsetGV;
4498}
4499
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004500llvm::Constant * CGObjCNonFragileABIMac::EmitIvarOffsetVar(
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004501 const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004502 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004503 unsigned long int Offset) {
4504
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004505 assert(ID && "EmitIvarOffsetVar - null interface decl.");
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004506 std::string ExternalName("\01_OBJC_IVAR_$_" + ID->getNameAsString() + '.'
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004507 + Ivar->getNameAsString());
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004508 llvm::Constant *Init = llvm::ConstantInt::get(ObjCTypes.LongTy, Offset);
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004509 llvm::GlobalVariable *IvarOffsetGV =
4510 CGM.getModule().getGlobalVariable(ExternalName);
Fariborz Jahanian77c9fd22009-04-06 18:30:00 +00004511 if (IvarOffsetGV)
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004512 // ivar offset symbol already built due to user code referencing it.
4513 IvarOffsetGV->setInitializer(Init);
Fariborz Jahanian77c9fd22009-04-06 18:30:00 +00004514 else
4515 IvarOffsetGV =
4516 new llvm::GlobalVariable(Init->getType(),
4517 false,
4518 llvm::GlobalValue::ExternalLinkage,
4519 Init,
4520 ExternalName,
4521 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004522 IvarOffsetGV->setAlignment(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004523 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.LongTy));
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004524 // @private and @package have hidden visibility.
4525 bool globalVisibility = (Ivar->getAccessControl() == ObjCIvarDecl::Public ||
Daniel Dunbar04d40782009-04-14 06:00:08 +00004526 Ivar->getAccessControl() == ObjCIvarDecl::Protected);
4527 if (!globalVisibility || CGM.getDeclVisibilityMode(ID) == LangOptions::Hidden)
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004528 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar04d40782009-04-14 06:00:08 +00004529 else
Fariborz Jahanian77c9fd22009-04-06 18:30:00 +00004530 IvarOffsetGV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004531 IvarOffsetGV->setSection("__DATA, __objc_const");
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004532 return IvarOffsetGV;
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004533}
4534
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004535/// EmitIvarList - Emit the ivar list for the given
4536/// implementation. If ForClass is true the list of class ivars
4537/// (i.e. metaclass ivars) is emitted, otherwise the list of
4538/// interface ivars will be emitted. The return value has type
4539/// IvarListnfABIPtrTy.
4540/// struct _ivar_t {
4541/// unsigned long int *offset; // pointer to ivar offset location
4542/// char *name;
4543/// char *type;
4544/// uint32_t alignment;
4545/// uint32_t size;
4546/// }
4547/// struct _ivar_list_t {
4548/// uint32 entsize; // sizeof(struct _ivar_t)
4549/// uint32 count;
4550/// struct _iver_t list[count];
4551/// }
4552///
4553llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList(
4554 const ObjCImplementationDecl *ID) {
4555
4556 std::vector<llvm::Constant*> Ivars, Ivar(5);
4557
4558 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4559 assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface");
4560
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004561 // FIXME. Consolidate this with similar code in GenerateClass.
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00004562 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00004563
4564 RecordDecl::field_iterator i,p;
4565 const RecordDecl *RD = GetFirstIvarInRecord(OID, i,p);
Fariborz Jahanian18191882009-03-31 18:11:23 +00004566 // collect declared and synthesized ivars in a small vector.
4567 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
4568 for (ObjCInterfaceDecl::ivar_iterator I = OID->ivar_begin(),
4569 E = OID->ivar_end(); I != E; ++I)
4570 OIvars.push_back(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +00004571 for (ObjCInterfaceDecl::prop_iterator I = OID->prop_begin(CGM.getContext()),
4572 E = OID->prop_end(CGM.getContext()); I != E; ++I)
Fariborz Jahanian18191882009-03-31 18:11:23 +00004573 if (ObjCIvarDecl *IV = (*I)->getPropertyIvarDecl())
4574 OIvars.push_back(IV);
Fariborz Jahanian99eee362009-04-01 19:37:34 +00004575
Fariborz Jahanian18191882009-03-31 18:11:23 +00004576 unsigned iv = 0;
Douglas Gregor6ab35242009-04-09 21:40:53 +00004577 for (RecordDecl::field_iterator e = RD->field_end(CGM.getContext());
4578 i != e; ++i) {
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004579 FieldDecl *Field = *i;
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00004580 uint64_t offset = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanian18191882009-03-31 18:11:23 +00004581 Ivar[0] = EmitIvarOffsetVar(ID->getClassInterface(), OIvars[iv++], offset);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004582 if (Field->getIdentifier())
4583 Ivar[1] = GetMethodVarName(Field->getIdentifier());
4584 else
4585 Ivar[1] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Devang Patel7794bb82009-03-04 18:21:39 +00004586 Ivar[2] = GetMethodVarType(Field);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004587 const llvm::Type *FieldTy =
4588 CGM.getTypes().ConvertTypeForMem(Field->getType());
4589 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
4590 unsigned Align = CGM.getContext().getPreferredTypeAlign(
4591 Field->getType().getTypePtr()) >> 3;
4592 Align = llvm::Log2_32(Align);
4593 Ivar[3] = llvm::ConstantInt::get(ObjCTypes.IntTy, Align);
Fariborz Jahanian07236ba2009-01-27 22:27:56 +00004594 // NOTE. Size of a bitfield does not match gcc's, because of the way
4595 // bitfields are treated special in each. But I am told that 'size'
4596 // for bitfield ivars is ignored by the runtime so it does not matter.
4597 // (even if it matters, some day, there is enough info. to get the bitfield
4598 // right!
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004599 Ivar[4] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4600 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarnfABITy, Ivar));
4601 }
4602 // Return null for empty list.
4603 if (Ivars.empty())
4604 return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4605 std::vector<llvm::Constant*> Values(3);
4606 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.IvarnfABITy);
4607 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4608 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
4609 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarnfABITy,
4610 Ivars.size());
4611 Values[2] = llvm::ConstantArray::get(AT, Ivars);
4612 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4613 const char *Prefix = "\01l_OBJC_$_INSTANCE_VARIABLES_";
4614 llvm::GlobalVariable *GV =
4615 new llvm::GlobalVariable(Init->getType(), false,
4616 llvm::GlobalValue::InternalLinkage,
4617 Init,
4618 Prefix + OID->getNameAsString(),
4619 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004620 GV->setAlignment(
4621 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004622 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004623
4624 UsedGlobals.push_back(GV);
4625 return llvm::ConstantExpr::getBitCast(GV,
4626 ObjCTypes.IvarListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004627}
4628
4629llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef(
4630 const ObjCProtocolDecl *PD) {
4631 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4632
4633 if (!Entry) {
4634 // We use the initializer as a marker of whether this is a forward
4635 // reference or not. At module finalization we add the empty
4636 // contents for protocols which were referenced but never defined.
4637 Entry =
4638 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
4639 llvm::GlobalValue::ExternalLinkage,
4640 0,
4641 "\01l_OBJC_PROTOCOL_$_" + PD->getNameAsString(),
4642 &CGM.getModule());
4643 Entry->setSection("__DATA,__datacoal_nt,coalesced");
4644 UsedGlobals.push_back(Entry);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004645 }
4646
4647 return Entry;
4648}
4649
4650/// GetOrEmitProtocol - Generate the protocol meta-data:
4651/// @code
4652/// struct _protocol_t {
4653/// id isa; // NULL
4654/// const char * const protocol_name;
4655/// const struct _protocol_list_t * protocol_list; // super protocols
4656/// const struct method_list_t * const instance_methods;
4657/// const struct method_list_t * const class_methods;
4658/// const struct method_list_t *optionalInstanceMethods;
4659/// const struct method_list_t *optionalClassMethods;
4660/// const struct _prop_list_t * properties;
4661/// const uint32_t size; // sizeof(struct _protocol_t)
4662/// const uint32_t flags; // = 0
4663/// }
4664/// @endcode
4665///
4666
4667llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol(
4668 const ObjCProtocolDecl *PD) {
4669 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4670
4671 // Early exit if a defining object has already been generated.
4672 if (Entry && Entry->hasInitializer())
4673 return Entry;
4674
4675 const char *ProtocolName = PD->getNameAsCString();
4676
4677 // Construct method lists.
4678 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
4679 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregor6ab35242009-04-09 21:40:53 +00004680 for (ObjCProtocolDecl::instmeth_iterator
4681 i = PD->instmeth_begin(CGM.getContext()),
4682 e = PD->instmeth_end(CGM.getContext());
4683 i != e; ++i) {
Fariborz Jahanianda320092009-01-29 19:24:30 +00004684 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004685 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004686 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4687 OptInstanceMethods.push_back(C);
4688 } else {
4689 InstanceMethods.push_back(C);
4690 }
4691 }
4692
Douglas Gregor6ab35242009-04-09 21:40:53 +00004693 for (ObjCProtocolDecl::classmeth_iterator
4694 i = PD->classmeth_begin(CGM.getContext()),
4695 e = PD->classmeth_end(CGM.getContext());
4696 i != e; ++i) {
Fariborz Jahanianda320092009-01-29 19:24:30 +00004697 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004698 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004699 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4700 OptClassMethods.push_back(C);
4701 } else {
4702 ClassMethods.push_back(C);
4703 }
4704 }
4705
4706 std::vector<llvm::Constant*> Values(10);
4707 // isa is NULL
4708 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ObjectPtrTy);
4709 Values[1] = GetClassName(PD->getIdentifier());
4710 Values[2] = EmitProtocolList(
4711 "\01l_OBJC_$_PROTOCOL_REFS_" + PD->getNameAsString(),
4712 PD->protocol_begin(),
4713 PD->protocol_end());
4714
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004715 Values[3] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004716 + PD->getNameAsString(),
4717 "__DATA, __objc_const",
4718 InstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004719 Values[4] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004720 + PD->getNameAsString(),
4721 "__DATA, __objc_const",
4722 ClassMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004723 Values[5] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004724 + PD->getNameAsString(),
4725 "__DATA, __objc_const",
4726 OptInstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004727 Values[6] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004728 + PD->getNameAsString(),
4729 "__DATA, __objc_const",
4730 OptClassMethods);
4731 Values[7] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + PD->getNameAsString(),
4732 0, PD, ObjCTypes);
4733 uint32_t Size =
4734 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolnfABITy);
4735 Values[8] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4736 Values[9] = llvm::Constant::getNullValue(ObjCTypes.IntTy);
4737 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolnfABITy,
4738 Values);
4739
4740 if (Entry) {
4741 // Already created, fix the linkage and update the initializer.
Mike Stump286acbd2009-03-07 16:33:28 +00004742 Entry->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004743 Entry->setInitializer(Init);
4744 } else {
4745 Entry =
4746 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004747 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004748 Init,
4749 std::string("\01l_OBJC_PROTOCOL_$_")+ProtocolName,
4750 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004751 Entry->setAlignment(
4752 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABITy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004753 Entry->setSection("__DATA,__datacoal_nt,coalesced");
Fariborz Jahanianda320092009-01-29 19:24:30 +00004754 }
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004755 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
4756
4757 // Use this protocol meta-data to build protocol list table in section
4758 // __DATA, __objc_protolist
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004759 llvm::GlobalVariable *PTGV = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004760 ObjCTypes.ProtocolnfABIPtrTy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004761 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004762 Entry,
4763 std::string("\01l_OBJC_LABEL_PROTOCOL_$_")
4764 +ProtocolName,
4765 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004766 PTGV->setAlignment(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004767 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABIPtrTy));
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004768 PTGV->setSection("__DATA, __objc_protolist");
4769 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4770 UsedGlobals.push_back(PTGV);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004771 return Entry;
4772}
4773
4774/// EmitProtocolList - Generate protocol list meta-data:
4775/// @code
4776/// struct _protocol_list_t {
4777/// long protocol_count; // Note, this is 32/64 bit
4778/// struct _protocol_t[protocol_count];
4779/// }
4780/// @endcode
4781///
4782llvm::Constant *
4783CGObjCNonFragileABIMac::EmitProtocolList(const std::string &Name,
4784 ObjCProtocolDecl::protocol_iterator begin,
4785 ObjCProtocolDecl::protocol_iterator end) {
4786 std::vector<llvm::Constant*> ProtocolRefs;
4787
Fariborz Jahanianda320092009-01-29 19:24:30 +00004788 // Just return null for empty protocol lists
Daniel Dunbar948e2582009-02-15 07:36:20 +00004789 if (begin == end)
Fariborz Jahanianda320092009-01-29 19:24:30 +00004790 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4791
Daniel Dunbar948e2582009-02-15 07:36:20 +00004792 // FIXME: We shouldn't need to do this lookup here, should we?
Fariborz Jahanianda320092009-01-29 19:24:30 +00004793 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
4794 if (GV)
Daniel Dunbar948e2582009-02-15 07:36:20 +00004795 return llvm::ConstantExpr::getBitCast(GV,
4796 ObjCTypes.ProtocolListnfABIPtrTy);
4797
4798 for (; begin != end; ++begin)
4799 ProtocolRefs.push_back(GetProtocolRef(*begin)); // Implemented???
4800
Fariborz Jahanianda320092009-01-29 19:24:30 +00004801 // This list is null terminated.
4802 ProtocolRefs.push_back(llvm::Constant::getNullValue(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004803 ObjCTypes.ProtocolnfABIPtrTy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004804
4805 std::vector<llvm::Constant*> Values(2);
4806 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
4807 Values[1] =
Daniel Dunbar948e2582009-02-15 07:36:20 +00004808 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolnfABIPtrTy,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004809 ProtocolRefs.size()),
4810 ProtocolRefs);
4811
4812 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4813 GV = new llvm::GlobalVariable(Init->getType(), false,
4814 llvm::GlobalValue::InternalLinkage,
4815 Init,
4816 Name,
4817 &CGM.getModule());
4818 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004819 GV->setAlignment(
4820 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004821 UsedGlobals.push_back(GV);
Daniel Dunbar948e2582009-02-15 07:36:20 +00004822 return llvm::ConstantExpr::getBitCast(GV,
4823 ObjCTypes.ProtocolListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004824}
4825
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004826/// GetMethodDescriptionConstant - This routine build following meta-data:
4827/// struct _objc_method {
4828/// SEL _cmd;
4829/// char *method_type;
4830/// char *_imp;
4831/// }
4832
4833llvm::Constant *
4834CGObjCNonFragileABIMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
4835 std::vector<llvm::Constant*> Desc(3);
4836 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4837 ObjCTypes.SelectorPtrTy);
4838 Desc[1] = GetMethodVarType(MD);
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004839 // Protocol methods have no implementation. So, this entry is always NULL.
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004840 Desc[2] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
4841 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Desc);
4842}
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004843
4844/// EmitObjCValueForIvar - Code Gen for nonfragile ivar reference.
4845/// This code gen. amounts to generating code for:
4846/// @code
4847/// (type *)((char *)base + _OBJC_IVAR_$_.ivar;
4848/// @encode
4849///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004850LValue CGObjCNonFragileABIMac::EmitObjCValueForIvar(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004851 CodeGen::CodeGenFunction &CGF,
4852 QualType ObjectTy,
4853 llvm::Value *BaseValue,
4854 const ObjCIvarDecl *Ivar,
4855 const FieldDecl *Field,
4856 unsigned CVRQualifiers) {
4857 assert(ObjectTy->isObjCInterfaceType() &&
4858 "CGObjCNonFragileABIMac::EmitObjCValueForIvar");
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004859 ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004860 std::string ExternalName;
4861 llvm::GlobalVariable *IvarOffsetGV =
4862 ObjCIvarOffsetVariable(ExternalName, ID, Ivar);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004863
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004864 // (char *) BaseValue
4865 llvm::Value *V = CGF.Builder.CreateBitCast(BaseValue,
4866 ObjCTypes.Int8PtrTy);
4867 llvm::Value *Offset = CGF.Builder.CreateLoad(IvarOffsetGV);
4868 // (char*)BaseValue + Offset_symbol
4869 V = CGF.Builder.CreateGEP(V, Offset, "add.ptr");
4870 // (type *)((char*)BaseValue + Offset_symbol)
4871 const llvm::Type *IvarTy =
4872 CGM.getTypes().ConvertType(Ivar->getType());
4873 llvm::Type *ptrIvarTy = llvm::PointerType::getUnqual(IvarTy);
4874 V = CGF.Builder.CreateBitCast(V, ptrIvarTy);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004875
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00004876 if (Ivar->isBitField()) {
4877 CodeGenTypes::BitFieldInfo bitFieldInfo =
4878 CGM.getTypes().getBitFieldInfo(Field);
4879 return LValue::MakeBitfield(V, bitFieldInfo.Begin, bitFieldInfo.Size,
4880 Field->getType()->isSignedIntegerType(),
4881 Field->getType().getCVRQualifiers()|CVRQualifiers);
4882 }
4883
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004884 LValue LV = LValue::MakeAddr(V,
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004885 Ivar->getType().getCVRQualifiers()|CVRQualifiers,
4886 CGM.getContext().getObjCGCAttrKind(Ivar->getType()));
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004887 LValue::SetObjCIvar(LV, true);
4888 return LV;
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004889}
4890
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004891llvm::Value *CGObjCNonFragileABIMac::EmitIvarOffset(
4892 CodeGen::CodeGenFunction &CGF,
4893 ObjCInterfaceDecl *Interface,
4894 const ObjCIvarDecl *Ivar) {
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004895 std::string ExternalName;
4896 llvm::GlobalVariable *IvarOffsetGV =
4897 ObjCIvarOffsetVariable(ExternalName, Interface, Ivar);
4898
4899 return CGF.Builder.CreateLoad(IvarOffsetGV, false, "ivar");
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004900}
4901
Fariborz Jahanian46551122009-02-04 00:22:57 +00004902CodeGen::RValue CGObjCNonFragileABIMac::EmitMessageSend(
4903 CodeGen::CodeGenFunction &CGF,
4904 QualType ResultType,
4905 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004906 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +00004907 QualType Arg0Ty,
4908 bool IsSuper,
4909 const CallArgList &CallArgs) {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004910 // FIXME. Even though IsSuper is passes. This function doese not
4911 // handle calls to 'super' receivers.
4912 CodeGenTypes &Types = CGM.getTypes();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004913 llvm::Value *Arg0 = Receiver;
4914 if (!IsSuper)
4915 Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy, "tmp");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004916
4917 // Find the message function name.
Fariborz Jahanianef163782009-02-05 01:13:09 +00004918 // FIXME. This is too much work to get the ABI-specific result type
4919 // needed to find the message name.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004920 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType,
4921 llvm::SmallVector<QualType, 16>());
4922 llvm::Constant *Fn;
4923 std::string Name("\01l_");
4924 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004925#if 0
4926 // unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004927 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
4928 Fn = ObjCTypes.MessageSendIdStretFixupFn;
4929 // FIXME. Is there a better way of getting these names.
4930 // They are available in RuntimeFunctions vector pair.
4931 Name += "objc_msgSendId_stret_fixup";
4932 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004933 else
4934#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004935 if (IsSuper) {
4936 Fn = ObjCTypes.MessageSendSuper2StretFixupFn;
4937 Name += "objc_msgSendSuper2_stret_fixup";
4938 }
4939 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004940 {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004941 Fn = ObjCTypes.MessageSendStretFixupFn;
4942 Name += "objc_msgSend_stret_fixup";
4943 }
4944 }
Fariborz Jahanian1a6b3682009-02-05 19:35:43 +00004945 else if (ResultType->isFloatingType() &&
4946 // Selection of frret API only happens in 32bit nonfragile ABI.
4947 CGM.getTargetData().getTypePaddedSize(ObjCTypes.LongTy) == 4) {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004948 Fn = ObjCTypes.MessageSendFpretFixupFn;
4949 Name += "objc_msgSend_fpret_fixup";
4950 }
4951 else {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004952#if 0
4953// unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004954 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
4955 Fn = ObjCTypes.MessageSendIdFixupFn;
4956 Name += "objc_msgSendId_fixup";
4957 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004958 else
4959#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004960 if (IsSuper) {
4961 Fn = ObjCTypes.MessageSendSuper2FixupFn;
4962 Name += "objc_msgSendSuper2_fixup";
4963 }
4964 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004965 {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004966 Fn = ObjCTypes.MessageSendFixupFn;
4967 Name += "objc_msgSend_fixup";
4968 }
4969 }
4970 Name += '_';
4971 std::string SelName(Sel.getAsString());
4972 // Replace all ':' in selector name with '_' ouch!
4973 for(unsigned i = 0; i < SelName.size(); i++)
4974 if (SelName[i] == ':')
4975 SelName[i] = '_';
4976 Name += SelName;
4977 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
4978 if (!GV) {
4979 // Build messafe ref table entry.
4980 std::vector<llvm::Constant*> Values(2);
4981 Values[0] = Fn;
4982 Values[1] = GetMethodVarName(Sel);
4983 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4984 GV = new llvm::GlobalVariable(Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00004985 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004986 Init,
4987 Name,
4988 &CGM.getModule());
4989 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4990 GV->setAlignment(
4991 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.MessageRefTy));
4992 GV->setSection("__DATA, __objc_msgrefs, coalesced");
4993 UsedGlobals.push_back(GV);
4994 }
4995 llvm::Value *Arg1 = CGF.Builder.CreateBitCast(GV, ObjCTypes.MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00004996
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004997 CallArgList ActualArgs;
4998 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
4999 ActualArgs.push_back(std::make_pair(RValue::get(Arg1),
5000 ObjCTypes.MessageRefCPtrTy));
5001 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Fariborz Jahanianef163782009-02-05 01:13:09 +00005002 const CGFunctionInfo &FnInfo1 = Types.getFunctionInfo(ResultType, ActualArgs);
5003 llvm::Value *Callee = CGF.Builder.CreateStructGEP(Arg1, 0);
5004 Callee = CGF.Builder.CreateLoad(Callee);
Fariborz Jahanian3ab75bd2009-02-14 21:25:36 +00005005 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo1, true);
Fariborz Jahanianef163782009-02-05 01:13:09 +00005006 Callee = CGF.Builder.CreateBitCast(Callee,
5007 llvm::PointerType::getUnqual(FTy));
5008 return CGF.EmitCall(FnInfo1, Callee, ActualArgs);
Fariborz Jahanian46551122009-02-04 00:22:57 +00005009}
5010
5011/// Generate code for a message send expression in the nonfragile abi.
5012CodeGen::RValue CGObjCNonFragileABIMac::GenerateMessageSend(
5013 CodeGen::CodeGenFunction &CGF,
5014 QualType ResultType,
5015 Selector Sel,
5016 llvm::Value *Receiver,
5017 bool IsClassMessage,
5018 const CallArgList &CallArgs) {
Fariborz Jahanian46551122009-02-04 00:22:57 +00005019 return EmitMessageSend(CGF, ResultType, Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005020 Receiver, CGF.getContext().getObjCIdType(),
Fariborz Jahanian46551122009-02-04 00:22:57 +00005021 false, CallArgs);
5022}
5023
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005024llvm::GlobalVariable *
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005025CGObjCNonFragileABIMac::GetClassGlobal(const std::string &Name) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005026 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5027
Daniel Dunbardfff2302009-03-02 05:18:14 +00005028 if (!GV) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005029 GV = new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
5030 llvm::GlobalValue::ExternalLinkage,
5031 0, Name, &CGM.getModule());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005032 }
5033
5034 return GV;
5035}
5036
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005037llvm::Value *CGObjCNonFragileABIMac::EmitClassRef(CGBuilderTy &Builder,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005038 const ObjCInterfaceDecl *ID,
5039 bool IsSuper) {
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005040
5041 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
5042
5043 if (!Entry) {
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005044 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005045 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005046 Entry =
5047 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5048 llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005049 ClassGV,
5050 IsSuper ? "\01L_OBJC_CLASSLIST_SUP_REFS_$_"
5051 : "\01L_OBJC_CLASSLIST_REFERENCES_$_",
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005052 &CGM.getModule());
5053 Entry->setAlignment(
5054 CGM.getTargetData().getPrefTypeAlignment(
5055 ObjCTypes.ClassnfABIPtrTy));
5056
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005057 if (IsSuper)
Fariborz Jahanian21228b72009-02-26 22:30:39 +00005058 Entry->setSection("__DATA,__objc_superrefs,regular,no_dead_strip");
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005059 else
Fariborz Jahanian21228b72009-02-26 22:30:39 +00005060 Entry->setSection("__DATA,__objc_classrefs,regular,no_dead_strip");
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005061 UsedGlobals.push_back(Entry);
5062 }
5063
5064 return Builder.CreateLoad(Entry, false, "tmp");
5065}
5066
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005067/// EmitMetaClassRef - Return a Value * of the address of _class_t
5068/// meta-data
5069///
5070llvm::Value *CGObjCNonFragileABIMac::EmitMetaClassRef(CGBuilderTy &Builder,
5071 const ObjCInterfaceDecl *ID) {
5072 llvm::GlobalVariable * &Entry = MetaClassReferences[ID->getIdentifier()];
5073 if (Entry)
5074 return Builder.CreateLoad(Entry, false, "tmp");
5075
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005076 std::string MetaClassName(getMetaclassSymbolPrefix() + ID->getNameAsString());
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005077 llvm::GlobalVariable *MetaClassGV = GetClassGlobal(MetaClassName);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005078 Entry =
5079 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5080 llvm::GlobalValue::InternalLinkage,
5081 MetaClassGV,
5082 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5083 &CGM.getModule());
5084 Entry->setAlignment(
5085 CGM.getTargetData().getPrefTypeAlignment(
5086 ObjCTypes.ClassnfABIPtrTy));
5087
5088 Entry->setSection("__OBJC,__objc_superrefs,regular,no_dead_strip");
5089 UsedGlobals.push_back(Entry);
5090
5091 return Builder.CreateLoad(Entry, false, "tmp");
5092}
5093
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005094/// GetClass - Return a reference to the class for the given interface
5095/// decl.
5096llvm::Value *CGObjCNonFragileABIMac::GetClass(CGBuilderTy &Builder,
5097 const ObjCInterfaceDecl *ID) {
5098 return EmitClassRef(Builder, ID);
5099}
5100
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005101/// Generates a message send where the super is the receiver. This is
5102/// a message send to self with special delivery semantics indicating
5103/// which class's method should be called.
5104CodeGen::RValue
5105CGObjCNonFragileABIMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
5106 QualType ResultType,
5107 Selector Sel,
5108 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005109 bool isCategoryImpl,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005110 llvm::Value *Receiver,
5111 bool IsClassMessage,
5112 const CodeGen::CallArgList &CallArgs) {
5113 // ...
5114 // Create and init a super structure; this is a (receiver, class)
5115 // pair we will pass to objc_msgSendSuper.
5116 llvm::Value *ObjCSuper =
5117 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
5118
5119 llvm::Value *ReceiverAsObject =
5120 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
5121 CGF.Builder.CreateStore(ReceiverAsObject,
5122 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
5123
5124 // If this is a class message the metaclass is passed as the target.
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005125 llvm::Value *Target;
5126 if (IsClassMessage) {
5127 if (isCategoryImpl) {
5128 // Message sent to "super' in a class method defined in
5129 // a category implementation.
5130 Target = EmitClassRef(CGF.Builder, Class, false);
5131 Target = CGF.Builder.CreateStructGEP(Target, 0);
5132 Target = CGF.Builder.CreateLoad(Target);
5133 }
5134 else
5135 Target = EmitMetaClassRef(CGF.Builder, Class);
5136 }
5137 else
5138 Target = EmitClassRef(CGF.Builder, Class, true);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005139
5140 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
5141 // and ObjCTypes types.
5142 const llvm::Type *ClassTy =
5143 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
5144 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
5145 CGF.Builder.CreateStore(Target,
5146 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
5147
5148 return EmitMessageSend(CGF, ResultType, Sel,
5149 ObjCSuper, ObjCTypes.SuperPtrCTy,
5150 true, CallArgs);
5151}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005152
5153llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CGBuilderTy &Builder,
5154 Selector Sel) {
5155 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
5156
5157 if (!Entry) {
5158 llvm::Constant *Casted =
5159 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
5160 ObjCTypes.SelectorPtrTy);
5161 Entry =
5162 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
5163 llvm::GlobalValue::InternalLinkage,
5164 Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
5165 &CGM.getModule());
5166 Entry->setSection("__DATA,__objc_selrefs,literal_pointers,no_dead_strip");
5167 UsedGlobals.push_back(Entry);
5168 }
5169
5170 return Builder.CreateLoad(Entry, false, "tmp");
5171}
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005172/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
5173/// objc_assign_ivar (id src, id *dst)
5174///
5175void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
5176 llvm::Value *src, llvm::Value *dst)
5177{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005178 const llvm::Type * SrcTy = src->getType();
5179 if (!isa<llvm::PointerType>(SrcTy)) {
5180 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5181 assert(Size <= 8 && "does not support size > 8");
5182 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5183 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005184 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5185 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005186 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5187 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5188 CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn,
5189 src, dst, "assignivar");
5190 return;
5191}
5192
5193/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
5194/// objc_assign_strongCast (id src, id *dst)
5195///
5196void CGObjCNonFragileABIMac::EmitObjCStrongCastAssign(
5197 CodeGen::CodeGenFunction &CGF,
5198 llvm::Value *src, llvm::Value *dst)
5199{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005200 const llvm::Type * SrcTy = src->getType();
5201 if (!isa<llvm::PointerType>(SrcTy)) {
5202 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5203 assert(Size <= 8 && "does not support size > 8");
5204 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5205 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005206 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5207 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005208 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5209 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5210 CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn,
5211 src, dst, "weakassign");
5212 return;
5213}
5214
5215/// EmitObjCWeakRead - Code gen for loading value of a __weak
5216/// object: objc_read_weak (id *src)
5217///
5218llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead(
5219 CodeGen::CodeGenFunction &CGF,
5220 llvm::Value *AddrWeakObj)
5221{
Eli Friedman8339b352009-03-07 03:57:15 +00005222 const llvm::Type* DestTy =
5223 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005224 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
5225 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
5226 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00005227 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005228 return read_weak;
5229}
5230
5231/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
5232/// objc_assign_weak (id src, id *dst)
5233///
5234void CGObjCNonFragileABIMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
5235 llvm::Value *src, llvm::Value *dst)
5236{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005237 const llvm::Type * SrcTy = src->getType();
5238 if (!isa<llvm::PointerType>(SrcTy)) {
5239 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5240 assert(Size <= 8 && "does not support size > 8");
5241 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5242 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005243 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5244 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005245 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5246 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5247 CGF.Builder.CreateCall2(ObjCTypes.GcAssignWeakFn,
5248 src, dst, "weakassign");
5249 return;
5250}
5251
5252/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
5253/// objc_assign_global (id src, id *dst)
5254///
5255void CGObjCNonFragileABIMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
5256 llvm::Value *src, llvm::Value *dst)
5257{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005258 const llvm::Type * SrcTy = src->getType();
5259 if (!isa<llvm::PointerType>(SrcTy)) {
5260 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5261 assert(Size <= 8 && "does not support size > 8");
5262 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5263 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005264 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5265 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005266 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5267 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5268 CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn,
5269 src, dst, "globalassign");
5270 return;
5271}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005272
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005273void
5274CGObjCNonFragileABIMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
5275 const Stmt &S) {
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005276 bool isTry = isa<ObjCAtTryStmt>(S);
5277 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
5278 llvm::BasicBlock *PrevLandingPad = CGF.getInvokeDest();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005279 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005280 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005281 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005282 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
5283
5284 // For @synchronized, call objc_sync_enter(sync.expr). The
5285 // evaluation of the expression must occur before we enter the
5286 // @synchronized. We can safely avoid a temp here because jumps into
5287 // @synchronized are illegal & this will dominate uses.
5288 llvm::Value *SyncArg = 0;
5289 if (!isTry) {
5290 SyncArg =
5291 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
5292 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005293 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005294 }
5295
5296 // Push an EH context entry, used for handling rethrows and jumps
5297 // through finally.
5298 CGF.PushCleanupBlock(FinallyBlock);
5299
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005300 CGF.setInvokeDest(TryHandler);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005301
5302 CGF.EmitBlock(TryBlock);
5303 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
5304 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
5305 CGF.EmitBranchThroughCleanup(FinallyEnd);
5306
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005307 // Emit the exception handler.
5308
5309 CGF.EmitBlock(TryHandler);
5310
5311 llvm::Value *llvm_eh_exception =
5312 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_exception);
5313 llvm::Value *llvm_eh_selector_i64 =
5314 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector_i64);
5315 llvm::Value *llvm_eh_typeid_for_i64 =
5316 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for_i64);
5317 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5318 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(Exc->getType(), "_rethrow");
5319
5320 llvm::SmallVector<llvm::Value*, 8> SelectorArgs;
5321 SelectorArgs.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005322 SelectorArgs.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005323
5324 // Construct the lists of (type, catch body) to handle.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005325 llvm::SmallVector<std::pair<const ParmVarDecl*, const Stmt*>, 8> Handlers;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005326 bool HasCatchAll = false;
5327 if (isTry) {
5328 if (const ObjCAtCatchStmt* CatchStmt =
5329 cast<ObjCAtTryStmt>(S).getCatchStmts()) {
5330 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005331 const ParmVarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
Steve Naroff7ba138a2009-03-03 19:52:17 +00005332 Handlers.push_back(std::make_pair(CatchDecl, CatchStmt->getCatchBody()));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005333
5334 // catch(...) always matches.
Steve Naroff7ba138a2009-03-03 19:52:17 +00005335 if (!CatchDecl) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005336 // Use i8* null here to signal this is a catch all, not a cleanup.
5337 llvm::Value *Null = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
5338 SelectorArgs.push_back(Null);
5339 HasCatchAll = true;
5340 break;
5341 }
5342
Daniel Dunbarede8de92009-03-06 00:01:21 +00005343 if (CGF.getContext().isObjCIdType(CatchDecl->getType()) ||
5344 CatchDecl->getType()->isObjCQualifiedIdType()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005345 llvm::Value *IDEHType =
5346 CGM.getModule().getGlobalVariable("OBJC_EHTYPE_id");
5347 if (!IDEHType)
5348 IDEHType =
5349 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5350 llvm::GlobalValue::ExternalLinkage,
5351 0, "OBJC_EHTYPE_id", &CGM.getModule());
5352 SelectorArgs.push_back(IDEHType);
5353 HasCatchAll = true;
5354 break;
5355 }
5356
5357 // All other types should be Objective-C interface pointer types.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005358 const PointerType *PT = CatchDecl->getType()->getAsPointerType();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005359 assert(PT && "Invalid @catch type.");
5360 const ObjCInterfaceType *IT =
5361 PT->getPointeeType()->getAsObjCInterfaceType();
5362 assert(IT && "Invalid @catch type.");
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005363 llvm::Value *EHType = GetInterfaceEHType(IT->getDecl(), false);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005364 SelectorArgs.push_back(EHType);
5365 }
5366 }
5367 }
5368
5369 // We use a cleanup unless there was already a catch all.
5370 if (!HasCatchAll) {
5371 SelectorArgs.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
Daniel Dunbarede8de92009-03-06 00:01:21 +00005372 Handlers.push_back(std::make_pair((const ParmVarDecl*) 0, (const Stmt*) 0));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005373 }
5374
5375 llvm::Value *Selector =
5376 CGF.Builder.CreateCall(llvm_eh_selector_i64,
5377 SelectorArgs.begin(), SelectorArgs.end(),
5378 "selector");
5379 for (unsigned i = 0, e = Handlers.size(); i != e; ++i) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005380 const ParmVarDecl *CatchParam = Handlers[i].first;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005381 const Stmt *CatchBody = Handlers[i].second;
5382
5383 llvm::BasicBlock *Next = 0;
5384
5385 // The last handler always matches.
5386 if (i + 1 != e) {
5387 assert(CatchParam && "Only last handler can be a catch all.");
5388
5389 llvm::BasicBlock *Match = CGF.createBasicBlock("match");
5390 Next = CGF.createBasicBlock("catch.next");
5391 llvm::Value *Id =
5392 CGF.Builder.CreateCall(llvm_eh_typeid_for_i64,
5393 CGF.Builder.CreateBitCast(SelectorArgs[i+2],
5394 ObjCTypes.Int8PtrTy));
5395 CGF.Builder.CreateCondBr(CGF.Builder.CreateICmpEQ(Selector, Id),
5396 Match, Next);
5397
5398 CGF.EmitBlock(Match);
5399 }
5400
5401 if (CatchBody) {
5402 llvm::BasicBlock *MatchEnd = CGF.createBasicBlock("match.end");
5403 llvm::BasicBlock *MatchHandler = CGF.createBasicBlock("match.handler");
5404
5405 // Cleanups must call objc_end_catch.
5406 //
5407 // FIXME: It seems incorrect for objc_begin_catch to be inside
5408 // this context, but this matches gcc.
5409 CGF.PushCleanupBlock(MatchEnd);
5410 CGF.setInvokeDest(MatchHandler);
5411
5412 llvm::Value *ExcObject =
5413 CGF.Builder.CreateCall(ObjCTypes.ObjCBeginCatchFn, Exc);
5414
5415 // Bind the catch parameter if it exists.
5416 if (CatchParam) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005417 ExcObject =
5418 CGF.Builder.CreateBitCast(ExcObject,
5419 CGF.ConvertType(CatchParam->getType()));
5420 // CatchParam is a ParmVarDecl because of the grammar
5421 // construction used to handle this, but for codegen purposes
5422 // we treat this as a local decl.
5423 CGF.EmitLocalBlockVarDecl(*CatchParam);
5424 CGF.Builder.CreateStore(ExcObject, CGF.GetAddrOfLocalVar(CatchParam));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005425 }
5426
5427 CGF.ObjCEHValueStack.push_back(ExcObject);
5428 CGF.EmitStmt(CatchBody);
5429 CGF.ObjCEHValueStack.pop_back();
5430
5431 CGF.EmitBranchThroughCleanup(FinallyEnd);
5432
5433 CGF.EmitBlock(MatchHandler);
5434
5435 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5436 // We are required to emit this call to satisfy LLVM, even
5437 // though we don't use the result.
5438 llvm::SmallVector<llvm::Value*, 8> Args;
5439 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005440 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005441 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5442 0));
5443 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5444 CGF.Builder.CreateStore(Exc, RethrowPtr);
5445 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5446
5447 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5448
5449 CGF.EmitBlock(MatchEnd);
5450
5451 // Unfortunately, we also have to generate another EH frame here
5452 // in case this throws.
5453 llvm::BasicBlock *MatchEndHandler =
5454 CGF.createBasicBlock("match.end.handler");
5455 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
5456 CGF.Builder.CreateInvoke(ObjCTypes.ObjCEndCatchFn,
5457 Cont, MatchEndHandler,
5458 Args.begin(), Args.begin());
5459
5460 CGF.EmitBlock(Cont);
5461 if (Info.SwitchBlock)
5462 CGF.EmitBlock(Info.SwitchBlock);
5463 if (Info.EndBlock)
5464 CGF.EmitBlock(Info.EndBlock);
5465
5466 CGF.EmitBlock(MatchEndHandler);
5467 Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5468 // We are required to emit this call to satisfy LLVM, even
5469 // though we don't use the result.
5470 Args.clear();
5471 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005472 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005473 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5474 0));
5475 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5476 CGF.Builder.CreateStore(Exc, RethrowPtr);
5477 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5478
5479 if (Next)
5480 CGF.EmitBlock(Next);
5481 } else {
5482 assert(!Next && "catchup should be last handler.");
5483
5484 CGF.Builder.CreateStore(Exc, RethrowPtr);
5485 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5486 }
5487 }
5488
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005489 // Pop the cleanup entry, the @finally is outside this cleanup
5490 // scope.
5491 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5492 CGF.setInvokeDest(PrevLandingPad);
5493
5494 CGF.EmitBlock(FinallyBlock);
5495
5496 if (isTry) {
5497 if (const ObjCAtFinallyStmt* FinallyStmt =
5498 cast<ObjCAtTryStmt>(S).getFinallyStmt())
5499 CGF.EmitStmt(FinallyStmt->getFinallyBody());
5500 } else {
5501 // Emit 'objc_sync_exit(expr)' as finally's sole statement for
5502 // @synchronized.
5503 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, SyncArg);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005504 }
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005505
5506 if (Info.SwitchBlock)
5507 CGF.EmitBlock(Info.SwitchBlock);
5508 if (Info.EndBlock)
5509 CGF.EmitBlock(Info.EndBlock);
5510
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005511 // Branch around the rethrow code.
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005512 CGF.EmitBranch(FinallyEnd);
5513
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005514 CGF.EmitBlock(FinallyRethrow);
5515 CGF.Builder.CreateCall(ObjCTypes.UnwindResumeOrRethrowFn,
5516 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005517 CGF.Builder.CreateUnreachable();
5518
5519 CGF.EmitBlock(FinallyEnd);
5520}
5521
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005522/// EmitThrowStmt - Generate code for a throw statement.
5523void CGObjCNonFragileABIMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
5524 const ObjCAtThrowStmt &S) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005525 llvm::Value *Exception;
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005526 if (const Expr *ThrowExpr = S.getThrowExpr()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005527 Exception = CGF.EmitScalarExpr(ThrowExpr);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005528 } else {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005529 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
5530 "Unexpected rethrow outside @catch block.");
5531 Exception = CGF.ObjCEHValueStack.back();
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005532 }
5533
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005534 llvm::Value *ExceptionAsObject =
5535 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
5536 llvm::BasicBlock *InvokeDest = CGF.getInvokeDest();
5537 if (InvokeDest) {
5538 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
5539 CGF.Builder.CreateInvoke(ObjCTypes.ExceptionThrowFn,
5540 Cont, InvokeDest,
5541 &ExceptionAsObject, &ExceptionAsObject + 1);
5542 CGF.EmitBlock(Cont);
5543 } else
5544 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
5545 CGF.Builder.CreateUnreachable();
5546
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005547 // Clear the insertion point to indicate we are in unreachable code.
5548 CGF.Builder.ClearInsertionPoint();
5549}
Daniel Dunbare588b992009-03-01 04:46:24 +00005550
5551llvm::Value *
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005552CGObjCNonFragileABIMac::GetInterfaceEHType(const ObjCInterfaceDecl *ID,
5553 bool ForDefinition) {
Daniel Dunbare588b992009-03-01 04:46:24 +00005554 llvm::GlobalVariable * &Entry = EHTypeReferences[ID->getIdentifier()];
Daniel Dunbare588b992009-03-01 04:46:24 +00005555
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005556 // If we don't need a definition, return the entry if found or check
5557 // if we use an external reference.
5558 if (!ForDefinition) {
5559 if (Entry)
5560 return Entry;
Daniel Dunbar7e075cb2009-04-07 06:43:45 +00005561
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005562 // If this type (or a super class) has the __objc_exception__
5563 // attribute, emit an external reference.
5564 if (hasObjCExceptionAttribute(ID))
5565 return Entry =
5566 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5567 llvm::GlobalValue::ExternalLinkage,
5568 0,
5569 (std::string("OBJC_EHTYPE_$_") +
5570 ID->getIdentifier()->getName()),
5571 &CGM.getModule());
5572 }
5573
5574 // Otherwise we need to either make a new entry or fill in the
5575 // initializer.
5576 assert((!Entry || !Entry->hasInitializer()) && "Duplicate EHType definition");
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005577 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbare588b992009-03-01 04:46:24 +00005578 std::string VTableName = "objc_ehtype_vtable";
5579 llvm::GlobalVariable *VTableGV =
5580 CGM.getModule().getGlobalVariable(VTableName);
5581 if (!VTableGV)
5582 VTableGV = new llvm::GlobalVariable(ObjCTypes.Int8PtrTy, false,
5583 llvm::GlobalValue::ExternalLinkage,
5584 0, VTableName, &CGM.getModule());
5585
5586 llvm::Value *VTableIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, 2);
5587
5588 std::vector<llvm::Constant*> Values(3);
5589 Values[0] = llvm::ConstantExpr::getGetElementPtr(VTableGV, &VTableIdx, 1);
5590 Values[1] = GetClassName(ID->getIdentifier());
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005591 Values[2] = GetClassGlobal(ClassName);
Daniel Dunbare588b992009-03-01 04:46:24 +00005592 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.EHTypeTy, Values);
5593
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005594 if (Entry) {
5595 Entry->setInitializer(Init);
5596 } else {
5597 Entry = new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5598 llvm::GlobalValue::WeakAnyLinkage,
5599 Init,
5600 (std::string("OBJC_EHTYPE_$_") +
5601 ID->getIdentifier()->getName()),
5602 &CGM.getModule());
5603 }
5604
Daniel Dunbar04d40782009-04-14 06:00:08 +00005605 if (CGM.getLangOptions().getVisibilityMode() == LangOptions::Hidden)
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005606 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005607 Entry->setAlignment(8);
5608
5609 if (ForDefinition) {
5610 Entry->setSection("__DATA,__objc_const");
5611 Entry->setLinkage(llvm::GlobalValue::ExternalLinkage);
5612 } else {
5613 Entry->setSection("__DATA,__datacoal_nt,coalesced");
5614 }
Daniel Dunbare588b992009-03-01 04:46:24 +00005615
5616 return Entry;
5617}
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005618
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00005619/* *** */
5620
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00005621CodeGen::CGObjCRuntime *
5622CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00005623 return new CGObjCMac(CGM);
5624}
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005625
5626CodeGen::CGObjCRuntime *
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00005627CodeGen::CreateMacNonFragileABIObjCRuntime(CodeGen::CodeGenModule &CGM) {
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00005628 return new CGObjCNonFragileABIMac(CGM);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005629}