blob: 116d8b010fe20baa52d5082fa828f1a35b520d3b [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 Jahaniancf71dd42009-04-07 20:26:30 +0000443 bool IsClassHidden(const ObjCInterfaceDecl *ID);
444
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000445 void BuildAggrIvarLayout(const ObjCInterfaceDecl *OI,
446 const llvm::StructLayout *Layout,
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000447 const RecordDecl *RD,
Chris Lattnerf1690852009-03-31 08:48:01 +0000448 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000449 unsigned int BytePos, bool ForStrongLayout,
450 int &Index, int &SkIndex, bool &HasUnion);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000451
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +0000452 /// GetIvarLayoutName - Returns a unique constant for the given
453 /// ivar layout bitmap.
454 llvm::Constant *GetIvarLayoutName(IdentifierInfo *Ident,
455 const ObjCCommonTypesHelper &ObjCTypes);
456
Fariborz Jahanian46b86c62009-01-28 19:12:34 +0000457 const RecordDecl *GetFirstIvarInRecord(const ObjCInterfaceDecl *OID,
458 RecordDecl::field_iterator &FIV,
459 RecordDecl::field_iterator &PIV);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +0000460 /// EmitPropertyList - Emit the given property list. The return
461 /// value has type PropertyListPtrTy.
462 llvm::Constant *EmitPropertyList(const std::string &Name,
463 const Decl *Container,
464 const ObjCContainerDecl *OCD,
465 const ObjCCommonTypesHelper &ObjCTypes);
466
Fariborz Jahanianda320092009-01-29 19:24:30 +0000467 /// GetProtocolRef - Return a reference to the internal protocol
468 /// description, creating an empty one if it has not been
469 /// defined. The return value has type ProtocolPtrTy.
470 llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +0000471
472 /// GetIvarBaseOffset - returns ivars byte offset.
473 uint64_t GetIvarBaseOffset(const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +0000474 const FieldDecl *Field);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000475
Chris Lattnercd0ee142009-03-31 08:33:16 +0000476 /// GetFieldBaseOffset - return's field byte offset.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000477 uint64_t GetFieldBaseOffset(const ObjCInterfaceDecl *OI,
478 const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +0000479 const FieldDecl *Field);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000480
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000481 /// CreateMetadataVar - Create a global variable with internal
482 /// linkage for use by the Objective-C runtime.
483 ///
484 /// This is a convenience wrapper which not only creates the
485 /// variable, but also sets the section and alignment and adds the
486 /// global to the UsedGlobals list.
Daniel Dunbar35bd7632009-03-09 20:50:13 +0000487 ///
488 /// \param Name - The variable name.
489 /// \param Init - The variable initializer; this is also used to
490 /// define the type of the variable.
491 /// \param Section - The section the variable should go into, or 0.
492 /// \param Align - The alignment for the variable, or 0.
493 /// \param AddToUsed - Whether the variable should be added to
494 /// llvm.
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000495 llvm::GlobalVariable *CreateMetadataVar(const std::string &Name,
496 llvm::Constant *Init,
497 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +0000498 unsigned Align,
499 bool AddToUsed);
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000500
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000501public:
502 CGObjCCommonMac(CodeGen::CodeGenModule &cgm) : CGM(cgm)
503 { }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000504
Steve Naroff33fdb732009-03-31 16:53:37 +0000505 virtual llvm::Constant *GenerateConstantString(const ObjCStringLiteral *SL);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000506
507 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
508 const ObjCContainerDecl *CD=0);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000509
510 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
511
512 /// GetOrEmitProtocol - Get the protocol object for the given
513 /// declaration, emitting it if necessary. The return value has type
514 /// ProtocolPtrTy.
515 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD)=0;
516
517 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
518 /// object for the given declaration, emitting it if needed. These
519 /// forward references will be filled in with empty bodies if no
520 /// definition is seen. The return value has type ProtocolPtrTy.
521 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD)=0;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000522};
523
524class CGObjCMac : public CGObjCCommonMac {
525private:
526 ObjCTypesHelper ObjCTypes;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000527 /// EmitImageInfo - Emit the image info marker used to encode some module
528 /// level information.
529 void EmitImageInfo();
530
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000531 /// EmitModuleInfo - Another marker encoding module level
532 /// information.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000533 void EmitModuleInfo();
534
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000535 /// EmitModuleSymols - Emit module symbols, the list of defined
536 /// classes and categories. The result has type SymtabPtrTy.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000537 llvm::Constant *EmitModuleSymbols();
538
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000539 /// FinishModule - Write out global data structures at the end of
540 /// processing a translation unit.
541 void FinishModule();
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000542
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000543 /// EmitClassExtension - Generate the class extension structure used
544 /// to store the weak ivar layout and properties. The return value
545 /// has type ClassExtensionPtrTy.
546 llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID);
547
548 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
549 /// for the given class.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000550 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000551 const ObjCInterfaceDecl *ID);
552
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000553 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000554 QualType ResultType,
555 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000556 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000557 QualType Arg0Ty,
558 bool IsSuper,
559 const CallArgList &CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000560
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000561 /// EmitIvarList - Emit the ivar list for the given
562 /// implementation. If ForClass is true the list of class ivars
563 /// (i.e. metaclass ivars) is emitted, otherwise the list of
564 /// interface ivars will be emitted. The return value has type
565 /// IvarListPtrTy.
566 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +0000567 bool ForClass);
568
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000569 /// EmitMetaClass - Emit a forward reference to the class structure
570 /// for the metaclass of the given interface. The return value has
571 /// type ClassPtrTy.
572 llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
573
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000574 /// EmitMetaClass - Emit a class structure for the metaclass of the
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000575 /// given implementation. The return value has type ClassPtrTy.
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000576 llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
577 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000578 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000579 const ConstantVector &Methods);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000580
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000581 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000582
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000583 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000584
585 /// EmitMethodList - Emit the method list for the given
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000586 /// implementation. The return value has type MethodListPtrTy.
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000587 llvm::Constant *EmitMethodList(const std::string &Name,
588 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000589 const ConstantVector &Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000590
591 /// EmitMethodDescList - Emit a method description list for a list of
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000592 /// method declarations.
593 /// - TypeName: The name for the type containing the methods.
594 /// - IsProtocol: True iff these methods are for a protocol.
595 /// - ClassMethds: True iff these are class methods.
596 /// - Required: When true, only "required" methods are
597 /// listed. Similarly, when false only "optional" methods are
598 /// listed. For classes this should always be true.
599 /// - begin, end: The method list to output.
600 ///
601 /// The return value has type MethodDescriptionListPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000602 llvm::Constant *EmitMethodDescList(const std::string &Name,
603 const char *Section,
604 const ConstantVector &Methods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000605
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000606 /// GetOrEmitProtocol - Get the protocol object for the given
607 /// declaration, emitting it if necessary. The return value has type
608 /// ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +0000609 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000610
611 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
612 /// object for the given declaration, emitting it if needed. These
613 /// forward references will be filled in with empty bodies if no
614 /// definition is seen. The return value has type ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +0000615 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000616
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000617 /// EmitProtocolExtension - Generate the protocol extension
618 /// structure used to store optional instance and class methods, and
619 /// protocol properties. The return value has type
620 /// ProtocolExtensionPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000621 llvm::Constant *
622 EmitProtocolExtension(const ObjCProtocolDecl *PD,
623 const ConstantVector &OptInstanceMethods,
624 const ConstantVector &OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000625
626 /// EmitProtocolList - Generate the list of referenced
627 /// protocols. The return value has type ProtocolListPtrTy.
Daniel Dunbardbc93372008-08-21 21:57:41 +0000628 llvm::Constant *EmitProtocolList(const std::string &Name,
629 ObjCProtocolDecl::protocol_iterator begin,
630 ObjCProtocolDecl::protocol_iterator end);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000631
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000632 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
633 /// for the given selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000634 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000635
Fariborz Jahanianda320092009-01-29 19:24:30 +0000636 public:
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000637 CGObjCMac(CodeGen::CodeGenModule &cgm);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000638
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000639 virtual llvm::Function *ModuleInitFunction();
640
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000641 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000642 QualType ResultType,
643 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000644 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000645 bool IsClassMessage,
646 const CallArgList &CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000647
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000648 virtual CodeGen::RValue
649 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000650 QualType ResultType,
651 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000652 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000653 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000654 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000655 bool IsClassMessage,
656 const CallArgList &CallArgs);
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000657
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000658 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000659 const ObjCInterfaceDecl *ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000660
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000661 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000662
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000663 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000664
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000665 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000666
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000667 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000668 const ObjCProtocolDecl *PD);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000669
Chris Lattner74391b42009-03-22 21:03:39 +0000670 virtual llvm::Constant *GetPropertyGetFunction();
671 virtual llvm::Constant *GetPropertySetFunction();
672 virtual llvm::Constant *EnumerationMutationFunction();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000673
Fariborz Jahanianbd71be42008-11-21 00:49:24 +0000674 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
675 const Stmt &S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000676 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
677 const ObjCAtThrowStmt &S);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000678 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +0000679 llvm::Value *AddrWeakObj);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000680 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
681 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000682 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
683 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian7eda8362008-11-20 19:23:36 +0000684 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
685 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000686 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
687 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian0bb20362009-02-02 20:02:29 +0000688
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000689 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
690 QualType ObjectTy,
691 llvm::Value *BaseValue,
692 const ObjCIvarDecl *Ivar,
693 const FieldDecl *Field,
694 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000695 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
696 ObjCInterfaceDecl *Interface,
697 const ObjCIvarDecl *Ivar);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000698};
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000699
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000700class CGObjCNonFragileABIMac : public CGObjCCommonMac {
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000701private:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000702 ObjCNonFragileABITypesHelper ObjCTypes;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000703 llvm::GlobalVariable* ObjCEmptyCacheVar;
704 llvm::GlobalVariable* ObjCEmptyVtableVar;
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000705
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000706 /// MetaClassReferences - uniqued meta class references.
707 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> MetaClassReferences;
Daniel Dunbare588b992009-03-01 04:46:24 +0000708
709 /// EHTypeReferences - uniqued class ehtype references.
710 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> EHTypeReferences;
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000711
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000712 /// FinishNonFragileABIModule - Write out global data structures at the end of
713 /// processing a translation unit.
714 void FinishNonFragileABIModule();
Daniel Dunbar8158a2f2009-04-08 04:21:03 +0000715
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000716 llvm::GlobalVariable * BuildClassRoTInitializer(unsigned flags,
717 unsigned InstanceStart,
718 unsigned InstanceSize,
719 const ObjCImplementationDecl *ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +0000720 llvm::GlobalVariable * BuildClassMetaData(std::string &ClassName,
721 llvm::Constant *IsAGV,
722 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +0000723 llvm::Constant *ClassRoGV,
724 bool HiddenVisibility);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000725
726 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
727
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +0000728 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
729
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000730 /// EmitMethodList - Emit the method list for the given
731 /// implementation. The return value has type MethodListnfABITy.
732 llvm::Constant *EmitMethodList(const std::string &Name,
733 const char *Section,
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +0000734 const ConstantVector &Methods);
735 /// EmitIvarList - Emit the ivar list for the given
736 /// implementation. If ForClass is true the list of class ivars
737 /// (i.e. metaclass ivars) is emitted, otherwise the list of
738 /// interface ivars will be emitted. The return value has type
739 /// IvarListnfABIPtrTy.
740 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000741
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000742 llvm::Constant *EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +0000743 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +0000744 unsigned long int offset);
745
Fariborz Jahanianda320092009-01-29 19:24:30 +0000746 /// GetOrEmitProtocol - Get the protocol object for the given
747 /// declaration, emitting it if necessary. The return value has type
748 /// ProtocolPtrTy.
749 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
750
751 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
752 /// object for the given declaration, emitting it if needed. These
753 /// forward references will be filled in with empty bodies if no
754 /// definition is seen. The return value has type ProtocolPtrTy.
755 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
756
757 /// EmitProtocolList - Generate the list of referenced
758 /// protocols. The return value has type ProtocolListPtrTy.
759 llvm::Constant *EmitProtocolList(const std::string &Name,
760 ObjCProtocolDecl::protocol_iterator begin,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000761 ObjCProtocolDecl::protocol_iterator end);
762
763 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
764 QualType ResultType,
765 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000766 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000767 QualType Arg0Ty,
768 bool IsSuper,
769 const CallArgList &CallArgs);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +0000770
771 /// GetClassGlobal - Return the global variable for the Objective-C
772 /// class of the given name.
Daniel Dunbar6ab187a2009-04-07 05:48:37 +0000773 llvm::GlobalVariable *GetClassGlobal(const std::string &Name,
774 bool AddToUsed = true);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000775
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000776 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
777 /// for the given class.
778 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000779 const ObjCInterfaceDecl *ID,
780 bool IsSuper = false);
781
782 /// EmitMetaClassRef - Return a Value * of the address of _class_t
783 /// meta-data
784 llvm::Value *EmitMetaClassRef(CGBuilderTy &Builder,
785 const ObjCInterfaceDecl *ID);
786
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000787 /// ObjCIvarOffsetVariable - Returns the ivar offset variable for
788 /// the given ivar.
789 ///
790 llvm::GlobalVariable * ObjCIvarOffsetVariable(std::string &Name,
Fariborz Jahanian01a0c362009-02-12 18:51:23 +0000791 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000792 const ObjCIvarDecl *Ivar);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000793
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +0000794 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
795 /// for the given selector.
796 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbare588b992009-03-01 04:46:24 +0000797
Daniel Dunbar8158a2f2009-04-08 04:21:03 +0000798 /// GetInterfaceEHType - Get the cached ehtype for the given Objective-C
Daniel Dunbare588b992009-03-01 04:46:24 +0000799 /// interface. The return value has type EHTypePtrTy.
Daniel Dunbar8158a2f2009-04-08 04:21:03 +0000800 llvm::Value *GetInterfaceEHType(const ObjCInterfaceDecl *ID,
801 bool ForDefinition);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +0000802
803 const char *getMetaclassSymbolPrefix() const {
804 return "OBJC_METACLASS_$_";
805 }
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000806
Daniel Dunbar6ab187a2009-04-07 05:48:37 +0000807 const char *getClassSymbolPrefix() const {
808 return "OBJC_CLASS_$_";
809 }
810
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000811public:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000812 CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000813 // FIXME. All stubs for now!
814 virtual llvm::Function *ModuleInitFunction();
815
816 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
817 QualType ResultType,
818 Selector Sel,
819 llvm::Value *Receiver,
820 bool IsClassMessage,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000821 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000822
823 virtual CodeGen::RValue
824 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
825 QualType ResultType,
826 Selector Sel,
827 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000828 bool isCategoryImpl,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000829 llvm::Value *Receiver,
830 bool IsClassMessage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000831 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000832
833 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000834 const ObjCInterfaceDecl *ID);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000835
836 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel)
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +0000837 { return EmitSelector(Builder, Sel); }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000838
Fariborz Jahanianeb062d92009-01-26 18:32:24 +0000839 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000840
841 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000842 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +0000843 const ObjCProtocolDecl *PD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000844
Chris Lattner74391b42009-03-22 21:03:39 +0000845 virtual llvm::Constant *GetPropertyGetFunction() {
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000846 return ObjCTypes.GetPropertyFn;
847 }
Chris Lattner74391b42009-03-22 21:03:39 +0000848 virtual llvm::Constant *GetPropertySetFunction() {
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000849 return ObjCTypes.SetPropertyFn;
850 }
Chris Lattner74391b42009-03-22 21:03:39 +0000851 virtual llvm::Constant *EnumerationMutationFunction() {
Daniel Dunbar28ed0842009-02-16 18:48:45 +0000852 return ObjCTypes.EnumerationMutationFn;
853 }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000854
855 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000856 const Stmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000857 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000858 const ObjCAtThrowStmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000859 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000860 llvm::Value *AddrWeakObj);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000861 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000862 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000863 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000864 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000865 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000866 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000867 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000868 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000869 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
870 QualType ObjectTy,
871 llvm::Value *BaseValue,
872 const ObjCIvarDecl *Ivar,
873 const FieldDecl *Field,
874 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000875 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
876 ObjCInterfaceDecl *Interface,
877 const ObjCIvarDecl *Ivar);
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000878};
879
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000880} // end anonymous namespace
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000881
882/* *** Helper Functions *** */
883
884/// getConstantGEP() - Help routine to construct simple GEPs.
885static llvm::Constant *getConstantGEP(llvm::Constant *C,
886 unsigned idx0,
887 unsigned idx1) {
888 llvm::Value *Idxs[] = {
889 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx0),
890 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx1)
891 };
892 return llvm::ConstantExpr::getGetElementPtr(C, Idxs, 2);
893}
894
Daniel Dunbar8158a2f2009-04-08 04:21:03 +0000895/// hasObjCExceptionAttribute - Return true if this class or any super
896/// class has the __objc_exception__ attribute.
897static bool hasObjCExceptionAttribute(const ObjCInterfaceDecl *OID) {
898 if (OID->getAttr<ObjCExceptionAttr>())
899 return true;
900 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
901 return hasObjCExceptionAttribute(Super);
902 return false;
903}
904
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000905/* *** CGObjCMac Public Interface *** */
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000906
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000907CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm),
908 ObjCTypes(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000909{
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000910 ObjCABI = 1;
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000911 EmitImageInfo();
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000912}
913
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000914/// GetClass - Return a reference to the class for the given interface
915/// decl.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000916llvm::Value *CGObjCMac::GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000917 const ObjCInterfaceDecl *ID) {
918 return EmitClassRef(Builder, ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000919}
920
921/// GetSelector - Return the pointer to the unique'd string for this selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000922llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000923 return EmitSelector(Builder, Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000924}
925
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000926/// Generate a constant CFString object.
927/*
928 struct __builtin_CFString {
929 const int *isa; // point to __CFConstantStringClassReference
930 int flags;
931 const char *str;
932 long length;
933 };
934*/
935
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000936llvm::Constant *CGObjCCommonMac::GenerateConstantString(
Steve Naroff33fdb732009-03-31 16:53:37 +0000937 const ObjCStringLiteral *SL) {
Steve Naroff8d4141f2009-04-01 13:55:36 +0000938 return CGM.GetAddrOfConstantCFString(SL->getString());
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000939}
940
941/// Generates a message send where the super is the receiver. This is
942/// a message send to self with special delivery semantics indicating
943/// which class's method should be called.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000944CodeGen::RValue
945CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000946 QualType ResultType,
947 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000948 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000949 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000950 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000951 bool IsClassMessage,
Daniel Dunbar46f45b92008-09-09 01:06:48 +0000952 const CodeGen::CallArgList &CallArgs) {
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000953 // Create and init a super structure; this is a (receiver, class)
954 // pair we will pass to objc_msgSendSuper.
955 llvm::Value *ObjCSuper =
956 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
957 llvm::Value *ReceiverAsObject =
958 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
959 CGF.Builder.CreateStore(ReceiverAsObject,
960 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000961
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000962 // If this is a class message the metaclass is passed as the target.
963 llvm::Value *Target;
964 if (IsClassMessage) {
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000965 if (isCategoryImpl) {
966 // Message sent to 'super' in a class method defined in a category
967 // implementation requires an odd treatment.
968 // If we are in a class method, we must retrieve the
969 // _metaclass_ for the current class, pointed at by
970 // the class's "isa" pointer. The following assumes that
971 // isa" is the first ivar in a class (which it must be).
972 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
973 Target = CGF.Builder.CreateStructGEP(Target, 0);
974 Target = CGF.Builder.CreateLoad(Target);
975 }
976 else {
977 llvm::Value *MetaClassPtr = EmitMetaClassRef(Class);
978 llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1);
979 llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr);
980 Target = Super;
981 }
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000982 } else {
983 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
984 }
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000985 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
986 // and ObjCTypes types.
987 const llvm::Type *ClassTy =
988 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000989 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000990 CGF.Builder.CreateStore(Target,
991 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
992
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000993 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000994 ObjCSuper, ObjCTypes.SuperPtrCTy,
995 true, CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000996}
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000997
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000998/// Generate code for a message send expression.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000999CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001000 QualType ResultType,
1001 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001002 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001003 bool IsClassMessage,
1004 const CallArgList &CallArgs) {
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001005 llvm::Value *Arg0 =
1006 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy, "tmp");
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001007 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001008 Arg0, CGF.getContext().getObjCIdType(),
1009 false, CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001010}
1011
1012CodeGen::RValue CGObjCMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001013 QualType ResultType,
1014 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001015 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001016 QualType Arg0Ty,
1017 bool IsSuper,
1018 const CallArgList &CallArgs) {
1019 CallArgList ActualArgs;
Daniel Dunbar46f45b92008-09-09 01:06:48 +00001020 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
1021 ActualArgs.push_back(std::make_pair(RValue::get(EmitSelector(CGF.Builder,
1022 Sel)),
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001023 CGF.getContext().getObjCSelType()));
1024 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001025
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001026 CodeGenTypes &Types = CGM.getTypes();
1027 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs);
1028 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo, false);
Daniel Dunbar5669e572008-10-17 03:24:53 +00001029
1030 llvm::Constant *Fn;
Daniel Dunbar88b53962009-02-02 22:03:45 +00001031 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Daniel Dunbar5669e572008-10-17 03:24:53 +00001032 Fn = ObjCTypes.getSendStretFn(IsSuper);
1033 } else if (ResultType->isFloatingType()) {
1034 // FIXME: Sadly, this is wrong. This actually depends on the
1035 // architecture. This happens to be right for x86-32 though.
1036 Fn = ObjCTypes.getSendFpretFn(IsSuper);
1037 } else {
1038 Fn = ObjCTypes.getSendFn(IsSuper);
1039 }
Daniel Dunbar62d5c1b2008-09-10 07:00:50 +00001040 Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy));
Daniel Dunbar88b53962009-02-02 22:03:45 +00001041 return CGF.EmitCall(FnInfo, Fn, ActualArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001042}
1043
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001044llvm::Value *CGObjCMac::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001045 const ObjCProtocolDecl *PD) {
Daniel Dunbarc67876d2008-09-04 04:33:15 +00001046 // FIXME: I don't understand why gcc generates this, or where it is
1047 // resolved. Investigate. Its also wasteful to look this up over and
1048 // over.
1049 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1050
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001051 return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
1052 ObjCTypes.ExternalProtocolPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001053}
1054
Fariborz Jahanianda320092009-01-29 19:24:30 +00001055void CGObjCCommonMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001056 // FIXME: We shouldn't need this, the protocol decl should contain
1057 // enough information to tell us whether this was a declaration or a
1058 // definition.
1059 DefinedProtocols.insert(PD->getIdentifier());
1060
1061 // If we have generated a forward reference to this protocol, emit
1062 // it now. Otherwise do nothing, the protocol objects are lazily
1063 // emitted.
1064 if (Protocols.count(PD->getIdentifier()))
1065 GetOrEmitProtocol(PD);
1066}
1067
Fariborz Jahanianda320092009-01-29 19:24:30 +00001068llvm::Constant *CGObjCCommonMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001069 if (DefinedProtocols.count(PD->getIdentifier()))
1070 return GetOrEmitProtocol(PD);
1071 return GetOrEmitProtocolRef(PD);
1072}
1073
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001074/*
1075 // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions
1076 struct _objc_protocol {
1077 struct _objc_protocol_extension *isa;
1078 char *protocol_name;
1079 struct _objc_protocol_list *protocol_list;
1080 struct _objc__method_prototype_list *instance_methods;
1081 struct _objc__method_prototype_list *class_methods
1082 };
1083
1084 See EmitProtocolExtension().
1085*/
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001086llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
1087 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1088
1089 // Early exit if a defining object has already been generated.
1090 if (Entry && Entry->hasInitializer())
1091 return Entry;
1092
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001093 // FIXME: I don't understand why gcc generates this, or where it is
1094 // resolved. Investigate. Its also wasteful to look this up over and
1095 // over.
1096 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1097
Chris Lattner8ec03f52008-11-24 03:54:41 +00001098 const char *ProtocolName = PD->getNameAsCString();
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001099
1100 // Construct method lists.
1101 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1102 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
1103 for (ObjCProtocolDecl::instmeth_iterator i = PD->instmeth_begin(),
1104 e = PD->instmeth_end(); i != e; ++i) {
1105 ObjCMethodDecl *MD = *i;
1106 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1107 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1108 OptInstanceMethods.push_back(C);
1109 } else {
1110 InstanceMethods.push_back(C);
1111 }
1112 }
1113
1114 for (ObjCProtocolDecl::classmeth_iterator i = PD->classmeth_begin(),
1115 e = PD->classmeth_end(); i != e; ++i) {
1116 ObjCMethodDecl *MD = *i;
1117 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1118 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1119 OptClassMethods.push_back(C);
1120 } else {
1121 ClassMethods.push_back(C);
1122 }
1123 }
1124
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001125 std::vector<llvm::Constant*> Values(5);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001126 Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001127 Values[1] = GetClassName(PD->getIdentifier());
Daniel Dunbardbc93372008-08-21 21:57:41 +00001128 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001129 EmitProtocolList("\01L_OBJC_PROTOCOL_REFS_" + PD->getNameAsString(),
Daniel Dunbardbc93372008-08-21 21:57:41 +00001130 PD->protocol_begin(),
1131 PD->protocol_end());
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001132 Values[3] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001133 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_"
1134 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001135 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1136 InstanceMethods);
1137 Values[4] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001138 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_"
1139 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001140 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1141 ClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001142 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
1143 Values);
1144
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001145 if (Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001146 // Already created, fix the linkage and update the initializer.
1147 Entry->setLinkage(llvm::GlobalValue::InternalLinkage);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001148 Entry->setInitializer(Init);
1149 } else {
1150 Entry =
1151 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
1152 llvm::GlobalValue::InternalLinkage,
1153 Init,
1154 std::string("\01L_OBJC_PROTOCOL_")+ProtocolName,
1155 &CGM.getModule());
1156 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001157 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001158 UsedGlobals.push_back(Entry);
1159 // FIXME: Is this necessary? Why only for protocol?
1160 Entry->setAlignment(4);
1161 }
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001162
1163 return Entry;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001164}
1165
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001166llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001167 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1168
1169 if (!Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001170 // We use the initializer as a marker of whether this is a forward
1171 // reference or not. At module finalization we add the empty
1172 // contents for protocols which were referenced but never defined.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001173 Entry =
1174 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001175 llvm::GlobalValue::ExternalLinkage,
1176 0,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001177 "\01L_OBJC_PROTOCOL_" + PD->getNameAsString(),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001178 &CGM.getModule());
1179 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001180 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001181 UsedGlobals.push_back(Entry);
1182 // FIXME: Is this necessary? Why only for protocol?
1183 Entry->setAlignment(4);
1184 }
1185
1186 return Entry;
1187}
1188
1189/*
1190 struct _objc_protocol_extension {
1191 uint32_t size;
1192 struct objc_method_description_list *optional_instance_methods;
1193 struct objc_method_description_list *optional_class_methods;
1194 struct objc_property_list *instance_properties;
1195 };
1196*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001197llvm::Constant *
1198CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
1199 const ConstantVector &OptInstanceMethods,
1200 const ConstantVector &OptClassMethods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001201 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001202 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolExtensionTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001203 std::vector<llvm::Constant*> Values(4);
1204 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001205 Values[1] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001206 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_"
1207 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001208 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1209 OptInstanceMethods);
1210 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001211 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_"
1212 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001213 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1214 OptClassMethods);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001215 Values[3] = EmitPropertyList("\01L_OBJC_$_PROP_PROTO_LIST_" +
1216 PD->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001217 0, PD, ObjCTypes);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001218
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001219 // Return null if no extension bits are used.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001220 if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
1221 Values[3]->isNullValue())
1222 return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
1223
1224 llvm::Constant *Init =
1225 llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001226
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001227 // No special section, but goes in llvm.used
1228 return CreateMetadataVar("\01L_OBJC_PROTOCOLEXT_" + PD->getNameAsString(),
1229 Init,
1230 0, 0, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001231}
1232
1233/*
1234 struct objc_protocol_list {
1235 struct objc_protocol_list *next;
1236 long count;
1237 Protocol *list[];
1238 };
1239*/
Daniel Dunbardbc93372008-08-21 21:57:41 +00001240llvm::Constant *
1241CGObjCMac::EmitProtocolList(const std::string &Name,
1242 ObjCProtocolDecl::protocol_iterator begin,
1243 ObjCProtocolDecl::protocol_iterator end) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001244 std::vector<llvm::Constant*> ProtocolRefs;
1245
Daniel Dunbardbc93372008-08-21 21:57:41 +00001246 for (; begin != end; ++begin)
1247 ProtocolRefs.push_back(GetProtocolRef(*begin));
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001248
1249 // Just return null for empty protocol lists
1250 if (ProtocolRefs.empty())
1251 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1252
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001253 // This list is null terminated.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001254 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
1255
1256 std::vector<llvm::Constant*> Values(3);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001257 // This field is only used by the runtime.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001258 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1259 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
1260 Values[2] =
1261 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
1262 ProtocolRefs.size()),
1263 ProtocolRefs);
1264
1265 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1266 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001267 CreateMetadataVar(Name, Init, "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001268 4, false);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001269 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
1270}
1271
1272/*
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001273 struct _objc_property {
1274 const char * const name;
1275 const char * const attributes;
1276 };
1277
1278 struct _objc_property_list {
1279 uint32_t entsize; // sizeof (struct _objc_property)
1280 uint32_t prop_count;
1281 struct _objc_property[prop_count];
1282 };
1283*/
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001284llvm::Constant *CGObjCCommonMac::EmitPropertyList(const std::string &Name,
1285 const Decl *Container,
1286 const ObjCContainerDecl *OCD,
1287 const ObjCCommonTypesHelper &ObjCTypes) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001288 std::vector<llvm::Constant*> Properties, Prop(2);
Steve Naroff93983f82009-01-11 12:47:58 +00001289 for (ObjCContainerDecl::prop_iterator I = OCD->prop_begin(),
1290 E = OCD->prop_end(); I != E; ++I) {
1291 const ObjCPropertyDecl *PD = *I;
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001292 Prop[0] = GetPropertyName(PD->getIdentifier());
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00001293 Prop[1] = GetPropertyTypeString(PD, Container);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001294 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
1295 Prop));
1296 }
1297
1298 // Return null for empty list.
1299 if (Properties.empty())
1300 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1301
1302 unsigned PropertySize =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001303 CGM.getTargetData().getTypePaddedSize(ObjCTypes.PropertyTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001304 std::vector<llvm::Constant*> Values(3);
1305 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
1306 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
1307 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
1308 Properties.size());
1309 Values[2] = llvm::ConstantArray::get(AT, Properties);
1310 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1311
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001312 // No special section on property lists?
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001313 llvm::GlobalVariable *GV =
1314 CreateMetadataVar(Name, Init, (ObjCABI == 2) ? "__DATA, __objc_const" : 0,
1315 0, true);
1316 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.PropertyListPtrTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001317}
1318
1319/*
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001320 struct objc_method_description_list {
1321 int count;
1322 struct objc_method_description list[];
1323 };
1324*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001325llvm::Constant *
1326CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
1327 std::vector<llvm::Constant*> Desc(2);
1328 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1329 ObjCTypes.SelectorPtrTy);
1330 Desc[1] = GetMethodVarType(MD);
1331 return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
1332 Desc);
1333}
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001334
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001335llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name,
1336 const char *Section,
1337 const ConstantVector &Methods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001338 // Return null for empty list.
1339 if (Methods.empty())
1340 return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
1341
1342 std::vector<llvm::Constant*> Values(2);
1343 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1344 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
1345 Methods.size());
1346 Values[1] = llvm::ConstantArray::get(AT, Methods);
1347 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1348
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001349 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 0, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001350 return llvm::ConstantExpr::getBitCast(GV,
1351 ObjCTypes.MethodDescriptionListPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001352}
1353
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001354/*
1355 struct _objc_category {
1356 char *category_name;
1357 char *class_name;
1358 struct _objc_method_list *instance_methods;
1359 struct _objc_method_list *class_methods;
1360 struct _objc_protocol_list *protocols;
1361 uint32_t size; // <rdar://4585769>
1362 struct _objc_property_list *instance_properties;
1363 };
1364 */
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001365void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001366 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.CategoryTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001367
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001368 // FIXME: This is poor design, the OCD should have a pointer to the
1369 // category decl. Additionally, note that Category can be null for
1370 // the @implementation w/o an @interface case. Sema should just
1371 // create one for us as it does for @implementation so everyone else
1372 // can live life under a clear blue sky.
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001373 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001374 const ObjCCategoryDecl *Category =
1375 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001376 std::string ExtName(Interface->getNameAsString() + "_" +
1377 OCD->getNameAsString());
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001378
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001379 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1380 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
1381 e = OCD->instmeth_end(); i != e; ++i) {
1382 // Instance methods should always be defined.
1383 InstanceMethods.push_back(GetMethodConstant(*i));
1384 }
1385 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
1386 e = OCD->classmeth_end(); i != e; ++i) {
1387 // Class methods should always be defined.
1388 ClassMethods.push_back(GetMethodConstant(*i));
1389 }
1390
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001391 std::vector<llvm::Constant*> Values(7);
1392 Values[0] = GetClassName(OCD->getIdentifier());
1393 Values[1] = GetClassName(Interface->getIdentifier());
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001394 Values[2] =
1395 EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") +
1396 ExtName,
1397 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001398 InstanceMethods);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001399 Values[3] =
1400 EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName,
1401 "__OBJC,__cat_class_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001402 ClassMethods);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001403 if (Category) {
1404 Values[4] =
1405 EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName,
1406 Category->protocol_begin(),
1407 Category->protocol_end());
1408 } else {
1409 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1410 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001411 Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001412
1413 // If there is no category @interface then there can be no properties.
1414 if (Category) {
1415 Values[6] = EmitPropertyList(std::string("\01L_OBJC_$_PROP_LIST_") + ExtName,
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001416 OCD, Category, ObjCTypes);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001417 } else {
1418 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1419 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001420
1421 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
1422 Values);
1423
1424 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001425 CreateMetadataVar(std::string("\01L_OBJC_CATEGORY_")+ExtName, Init,
1426 "__OBJC,__category,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001427 4, true);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001428 DefinedCategories.push_back(GV);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001429}
1430
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001431// FIXME: Get from somewhere?
1432enum ClassFlags {
1433 eClassFlags_Factory = 0x00001,
1434 eClassFlags_Meta = 0x00002,
1435 // <rdr://5142207>
1436 eClassFlags_HasCXXStructors = 0x02000,
1437 eClassFlags_Hidden = 0x20000,
1438 eClassFlags_ABI2_Hidden = 0x00010,
1439 eClassFlags_ABI2_HasCXXStructors = 0x00004 // <rdr://4923634>
1440};
1441
Fariborz Jahaniancf71dd42009-04-07 20:26:30 +00001442bool CGObjCCommonMac::IsClassHidden(const ObjCInterfaceDecl *ID) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001443 if (const VisibilityAttr *attr = ID->getAttr<VisibilityAttr>()) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001444 switch (attr->getVisibility()) {
1445 default:
1446 assert(0 && "Unknown visibility");
1447 return false;
1448 case VisibilityAttr::DefaultVisibility:
1449 case VisibilityAttr::ProtectedVisibility: // FIXME: What do we do here?
1450 return false;
1451 case VisibilityAttr::HiddenVisibility:
1452 return true;
1453 }
Fariborz Jahaniancf71dd42009-04-07 20:26:30 +00001454 } else
1455 return (CGM.getLangOptions().getVisibilityMode() ==
1456 LangOptions::HiddenVisibility);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001457}
1458
1459/*
1460 struct _objc_class {
1461 Class isa;
1462 Class super_class;
1463 const char *name;
1464 long version;
1465 long info;
1466 long instance_size;
1467 struct _objc_ivar_list *ivars;
1468 struct _objc_method_list *methods;
1469 struct _objc_cache *cache;
1470 struct _objc_protocol_list *protocols;
1471 // Objective-C 1.0 extensions (<rdr://4585769>)
1472 const char *ivar_layout;
1473 struct _objc_class_ext *ext;
1474 };
1475
1476 See EmitClassExtension();
1477 */
1478void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001479 DefinedSymbols.insert(ID->getIdentifier());
1480
Chris Lattner8ec03f52008-11-24 03:54:41 +00001481 std::string ClassName = ID->getNameAsString();
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001482 // FIXME: Gross
1483 ObjCInterfaceDecl *Interface =
1484 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Daniel Dunbardbc93372008-08-21 21:57:41 +00001485 llvm::Constant *Protocols =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001486 EmitProtocolList("\01L_OBJC_CLASS_PROTOCOLS_" + ID->getNameAsString(),
Daniel Dunbardbc93372008-08-21 21:57:41 +00001487 Interface->protocol_begin(),
1488 Interface->protocol_end());
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001489 const llvm::Type *InterfaceTy =
Chris Lattner03d9f342009-04-01 06:23:52 +00001490 CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(Interface));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001491 unsigned Flags = eClassFlags_Factory;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001492 unsigned Size = CGM.getTargetData().getTypePaddedSize(InterfaceTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001493
1494 // FIXME: Set CXX-structors flag.
1495 if (IsClassHidden(ID->getClassInterface()))
1496 Flags |= eClassFlags_Hidden;
1497
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001498 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1499 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
1500 e = ID->instmeth_end(); i != e; ++i) {
1501 // Instance methods should always be defined.
1502 InstanceMethods.push_back(GetMethodConstant(*i));
1503 }
1504 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
1505 e = ID->classmeth_end(); i != e; ++i) {
1506 // Class methods should always be defined.
1507 ClassMethods.push_back(GetMethodConstant(*i));
1508 }
1509
1510 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
1511 e = ID->propimpl_end(); i != e; ++i) {
1512 ObjCPropertyImplDecl *PID = *i;
1513
1514 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1515 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1516
1517 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
1518 if (llvm::Constant *C = GetMethodConstant(MD))
1519 InstanceMethods.push_back(C);
1520 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
1521 if (llvm::Constant *C = GetMethodConstant(MD))
1522 InstanceMethods.push_back(C);
1523 }
1524 }
1525
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001526 std::vector<llvm::Constant*> Values(12);
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001527 Values[ 0] = EmitMetaClass(ID, Protocols, InterfaceTy, ClassMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001528 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001529 // Record a reference to the super class.
1530 LazySymbols.insert(Super->getIdentifier());
1531
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001532 Values[ 1] =
1533 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1534 ObjCTypes.ClassPtrTy);
1535 } else {
1536 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1537 }
1538 Values[ 2] = GetClassName(ID->getIdentifier());
1539 // Version is always 0.
1540 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1541 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1542 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001543 Values[ 6] = EmitIvarList(ID, false);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001544 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001545 EmitMethodList("\01L_OBJC_INSTANCE_METHODS_" + ID->getNameAsString(),
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001546 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001547 InstanceMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001548 // cache is always NULL.
1549 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1550 Values[ 9] = Protocols;
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001551 // FIXME: Set ivar_layout
Fariborz Jahanian667423a2009-03-25 22:36:49 +00001552 // Values[10] = BuildIvarLayout(ID, true);
1553 Values[10] = GetIvarLayoutName(0, ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001554 Values[11] = EmitClassExtension(ID);
1555 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1556 Values);
1557
1558 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001559 CreateMetadataVar(std::string("\01L_OBJC_CLASS_")+ClassName, Init,
1560 "__OBJC,__class,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001561 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001562 DefinedClasses.push_back(GV);
1563}
1564
1565llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
1566 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001567 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001568 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001569 unsigned Flags = eClassFlags_Meta;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001570 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001571
1572 if (IsClassHidden(ID->getClassInterface()))
1573 Flags |= eClassFlags_Hidden;
1574
1575 std::vector<llvm::Constant*> Values(12);
1576 // The isa for the metaclass is the root of the hierarchy.
1577 const ObjCInterfaceDecl *Root = ID->getClassInterface();
1578 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
1579 Root = Super;
1580 Values[ 0] =
1581 llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
1582 ObjCTypes.ClassPtrTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001583 // The super class for the metaclass is emitted as the name of the
1584 // super class. The runtime fixes this up to point to the
1585 // *metaclass* for the super class.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001586 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
1587 Values[ 1] =
1588 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1589 ObjCTypes.ClassPtrTy);
1590 } else {
1591 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1592 }
1593 Values[ 2] = GetClassName(ID->getIdentifier());
1594 // Version is always 0.
1595 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1596 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1597 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001598 Values[ 6] = EmitIvarList(ID, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001599 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001600 EmitMethodList("\01L_OBJC_CLASS_METHODS_" + ID->getNameAsString(),
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001601 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001602 Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001603 // cache is always NULL.
1604 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1605 Values[ 9] = Protocols;
1606 // ivar_layout for metaclass is always NULL.
1607 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1608 // The class extension is always unused for metaclasses.
1609 Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1610 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1611 Values);
1612
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001613 std::string Name("\01L_OBJC_METACLASS_");
Chris Lattner8ec03f52008-11-24 03:54:41 +00001614 Name += ID->getNameAsCString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001615
1616 // Check for a forward reference.
1617 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
1618 if (GV) {
1619 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1620 "Forward metaclass reference has incorrect type.");
1621 GV->setLinkage(llvm::GlobalValue::InternalLinkage);
1622 GV->setInitializer(Init);
1623 } else {
1624 GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1625 llvm::GlobalValue::InternalLinkage,
1626 Init, Name,
1627 &CGM.getModule());
1628 }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001629 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001630 GV->setAlignment(4);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001631 UsedGlobals.push_back(GV);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001632
1633 return GV;
1634}
1635
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001636llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001637 std::string Name = "\01L_OBJC_METACLASS_" + ID->getNameAsString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001638
1639 // FIXME: Should we look these up somewhere other than the
1640 // module. Its a bit silly since we only generate these while
1641 // processing an implementation, so exactly one pointer would work
1642 // if know when we entered/exitted an implementation block.
1643
1644 // Check for an existing forward reference.
Fariborz Jahanianb0d27942009-01-07 20:11:22 +00001645 // Previously, metaclass with internal linkage may have been defined.
1646 // pass 'true' as 2nd argument so it is returned.
1647 if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true)) {
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001648 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1649 "Forward metaclass reference has incorrect type.");
1650 return GV;
1651 } else {
1652 // Generate as an external reference to keep a consistent
1653 // module. This will be patched up when we emit the metaclass.
1654 return new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1655 llvm::GlobalValue::ExternalLinkage,
1656 0,
1657 Name,
1658 &CGM.getModule());
1659 }
1660}
1661
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001662/*
1663 struct objc_class_ext {
1664 uint32_t size;
1665 const char *weak_ivar_layout;
1666 struct _objc_property_list *properties;
1667 };
1668*/
1669llvm::Constant *
1670CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
1671 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001672 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassExtensionTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001673
1674 std::vector<llvm::Constant*> Values(3);
1675 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001676 // FIXME: Output weak_ivar_layout string.
Fariborz Jahanian667423a2009-03-25 22:36:49 +00001677 // Values[1] = BuildIvarLayout(ID, false);
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00001678 Values[1] = GetIvarLayoutName(0, ObjCTypes);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001679 Values[2] = EmitPropertyList("\01L_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001680 ID, ID->getClassInterface(), ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001681
1682 // Return null if no extension bits are used.
1683 if (Values[1]->isNullValue() && Values[2]->isNullValue())
1684 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1685
1686 llvm::Constant *Init =
1687 llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001688 return CreateMetadataVar("\01L_OBJC_CLASSEXT_" + ID->getNameAsString(),
1689 Init, 0, 0, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001690}
1691
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001692/// countInheritedIvars - count number of ivars in class and its super class(s)
1693///
1694static int countInheritedIvars(const ObjCInterfaceDecl *OI) {
1695 int count = 0;
1696 if (!OI)
1697 return 0;
1698 const ObjCInterfaceDecl *SuperClass = OI->getSuperClass();
1699 if (SuperClass)
1700 count += countInheritedIvars(SuperClass);
1701 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1702 E = OI->ivar_end(); I != E; ++I)
1703 ++count;
Fariborz Jahanian18191882009-03-31 18:11:23 +00001704 // look into properties.
1705 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
1706 E = OI->prop_end(); I != E; ++I) {
1707 if ((*I)->getPropertyIvarDecl())
1708 ++count;
1709 }
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001710 return count;
1711}
1712
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001713/// getInterfaceDeclForIvar - Get the interface declaration node where
1714/// this ivar is declared in.
1715/// FIXME. Ideally, this info should be in the ivar node. But currently
1716/// it is not and prevailing wisdom is that ASTs should not have more
1717/// info than is absolutely needed, even though this info reflects the
1718/// source language.
1719///
1720static const ObjCInterfaceDecl *getInterfaceDeclForIvar(
1721 const ObjCInterfaceDecl *OI,
1722 const ObjCIvarDecl *IVD) {
1723 if (!OI)
1724 return 0;
1725 assert(isa<ObjCInterfaceDecl>(OI) && "OI is not an interface");
1726 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1727 E = OI->ivar_end(); I != E; ++I)
1728 if ((*I)->getIdentifier() == IVD->getIdentifier())
1729 return OI;
Fariborz Jahanian5a4b4532009-03-31 17:00:52 +00001730 // look into properties.
1731 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
1732 E = OI->prop_end(); I != E; ++I) {
1733 ObjCPropertyDecl *PDecl = (*I);
1734 if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl())
1735 if (IV->getIdentifier() == IVD->getIdentifier())
1736 return OI;
1737 }
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001738 return getInterfaceDeclForIvar(OI->getSuperClass(), IVD);
1739}
1740
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001741/*
1742 struct objc_ivar {
1743 char *ivar_name;
1744 char *ivar_type;
1745 int ivar_offset;
1746 };
1747
1748 struct objc_ivar_list {
1749 int ivar_count;
1750 struct objc_ivar list[count];
1751 };
1752 */
1753llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001754 bool ForClass) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001755 std::vector<llvm::Constant*> Ivars, Ivar(3);
1756
1757 // When emitting the root class GCC emits ivar entries for the
1758 // actual class structure. It is not clear if we need to follow this
1759 // behavior; for now lets try and get away with not doing it. If so,
1760 // the cleanest solution would be to make up an ObjCInterfaceDecl
1761 // for the class.
1762 if (ForClass)
1763 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001764
1765 ObjCInterfaceDecl *OID =
1766 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00001767 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001768
1769 RecordDecl::field_iterator ifield, pfield;
1770 const RecordDecl *RD = GetFirstIvarInRecord(OID, ifield, pfield);
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001771 for (RecordDecl::field_iterator e = RD->field_end(); ifield != e; ++ifield) {
1772 FieldDecl *Field = *ifield;
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00001773 uint64_t Offset = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001774 if (Field->getIdentifier())
1775 Ivar[0] = GetMethodVarName(Field->getIdentifier());
1776 else
1777 Ivar[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Devang Patel7794bb82009-03-04 18:21:39 +00001778 Ivar[1] = GetMethodVarType(Field);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001779 Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy, Offset);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001780 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001781 }
1782
1783 // Return null for empty list.
1784 if (Ivars.empty())
1785 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
1786
1787 std::vector<llvm::Constant*> Values(2);
1788 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
1789 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
1790 Ivars.size());
1791 Values[1] = llvm::ConstantArray::get(AT, Ivars);
1792 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1793
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001794 llvm::GlobalVariable *GV;
1795 if (ForClass)
1796 GV = CreateMetadataVar("\01L_OBJC_CLASS_VARIABLES_" + ID->getNameAsString(),
Daniel Dunbar58a29122009-03-09 22:18:41 +00001797 Init, "__OBJC,__class_vars,regular,no_dead_strip",
1798 4, true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001799 else
1800 GV = CreateMetadataVar("\01L_OBJC_INSTANCE_VARIABLES_"
1801 + ID->getNameAsString(),
1802 Init, "__OBJC,__instance_vars,regular,no_dead_strip",
1803 0, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001804 return llvm::ConstantExpr::getBitCast(GV,
1805 ObjCTypes.IvarListPtrTy);
1806}
1807
1808/*
1809 struct objc_method {
1810 SEL method_name;
1811 char *method_types;
1812 void *method;
1813 };
1814
1815 struct objc_method_list {
1816 struct objc_method_list *obsolete;
1817 int count;
1818 struct objc_method methods_list[count];
1819 };
1820*/
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001821
1822/// GetMethodConstant - Return a struct objc_method constant for the
1823/// given method if it has been defined. The result is null if the
1824/// method has not been defined. The return value has type MethodPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001825llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001826 // FIXME: Use DenseMap::lookup
1827 llvm::Function *Fn = MethodDefinitions[MD];
1828 if (!Fn)
1829 return 0;
1830
1831 std::vector<llvm::Constant*> Method(3);
1832 Method[0] =
1833 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1834 ObjCTypes.SelectorPtrTy);
1835 Method[1] = GetMethodVarType(MD);
1836 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
1837 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
1838}
1839
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001840llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name,
1841 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001842 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001843 // Return null for empty list.
1844 if (Methods.empty())
1845 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
1846
1847 std::vector<llvm::Constant*> Values(3);
1848 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1849 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1850 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
1851 Methods.size());
1852 Values[2] = llvm::ConstantArray::get(AT, Methods);
1853 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1854
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001855 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 0, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001856 return llvm::ConstantExpr::getBitCast(GV,
1857 ObjCTypes.MethodListPtrTy);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001858}
1859
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001860llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD,
Daniel Dunbarbb36d332009-02-02 21:43:58 +00001861 const ObjCContainerDecl *CD) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001862 std::string Name;
Fariborz Jahanian679a5022009-01-10 21:06:09 +00001863 GetNameForMethod(OMD, CD, Name);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001864
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001865 CodeGenTypes &Types = CGM.getTypes();
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001866 const llvm::FunctionType *MethodTy =
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001867 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001868 llvm::Function *Method =
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001869 llvm::Function::Create(MethodTy,
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001870 llvm::GlobalValue::InternalLinkage,
1871 Name,
1872 &CGM.getModule());
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001873 MethodDefinitions.insert(std::make_pair(OMD, Method));
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001874
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001875 return Method;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001876}
1877
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00001878uint64_t CGObjCCommonMac::GetIvarBaseOffset(const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +00001879 const FieldDecl *Field) {
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00001880 if (!Field->isBitField())
1881 return Layout->getElementOffset(
1882 CGM.getTypes().getLLVMFieldNo(Field));
1883 // FIXME. Must be a better way of getting a bitfield base offset.
1884 uint64_t offset = CGM.getTypes().getLLVMFieldNo(Field);
1885 const llvm::Type *Ty = CGM.getTypes().ConvertTypeForMemRecursive(Field->getType());
1886 uint64_t size = CGM.getTypes().getTargetData().getTypePaddedSizeInBits(Ty);
1887 offset = (offset*size)/8;
1888 return offset;
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00001889}
1890
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00001891/// GetFieldBaseOffset - return's field byt offset.
1892uint64_t CGObjCCommonMac::GetFieldBaseOffset(const ObjCInterfaceDecl *OI,
1893 const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +00001894 const FieldDecl *Field) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00001895 const ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
Chris Lattnercd0ee142009-03-31 08:33:16 +00001896 const FieldDecl *FD = OI->lookupFieldDeclForIvar(CGM.getContext(), Ivar);
1897 return GetIvarBaseOffset(Layout, FD);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00001898}
1899
Daniel Dunbarfd65d372009-03-09 20:09:19 +00001900llvm::GlobalVariable *
1901CGObjCCommonMac::CreateMetadataVar(const std::string &Name,
1902 llvm::Constant *Init,
1903 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +00001904 unsigned Align,
1905 bool AddToUsed) {
Daniel Dunbarfd65d372009-03-09 20:09:19 +00001906 const llvm::Type *Ty = Init->getType();
1907 llvm::GlobalVariable *GV =
1908 new llvm::GlobalVariable(Ty, false,
1909 llvm::GlobalValue::InternalLinkage,
1910 Init,
1911 Name,
1912 &CGM.getModule());
1913 if (Section)
1914 GV->setSection(Section);
Daniel Dunbar35bd7632009-03-09 20:50:13 +00001915 if (Align)
1916 GV->setAlignment(Align);
1917 if (AddToUsed)
Daniel Dunbarfd65d372009-03-09 20:09:19 +00001918 UsedGlobals.push_back(GV);
1919 return GV;
1920}
1921
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001922llvm::Function *CGObjCMac::ModuleInitFunction() {
Daniel Dunbarf77ac862008-08-11 21:35:06 +00001923 // Abuse this interface function as a place to finalize.
1924 FinishModule();
1925
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001926 return NULL;
1927}
1928
Chris Lattner74391b42009-03-22 21:03:39 +00001929llvm::Constant *CGObjCMac::GetPropertyGetFunction() {
Daniel Dunbar49f66022008-09-24 03:38:44 +00001930 return ObjCTypes.GetPropertyFn;
1931}
1932
Chris Lattner74391b42009-03-22 21:03:39 +00001933llvm::Constant *CGObjCMac::GetPropertySetFunction() {
Daniel Dunbar49f66022008-09-24 03:38:44 +00001934 return ObjCTypes.SetPropertyFn;
1935}
1936
Chris Lattner74391b42009-03-22 21:03:39 +00001937llvm::Constant *CGObjCMac::EnumerationMutationFunction() {
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001938 return ObjCTypes.EnumerationMutationFn;
1939}
1940
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001941/*
1942
1943Objective-C setjmp-longjmp (sjlj) Exception Handling
1944--
1945
1946The basic framework for a @try-catch-finally is as follows:
1947{
1948 objc_exception_data d;
1949 id _rethrow = null;
Anders Carlsson190d00e2009-02-07 21:26:04 +00001950 bool _call_try_exit = true;
1951
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001952 objc_exception_try_enter(&d);
1953 if (!setjmp(d.jmp_buf)) {
1954 ... try body ...
1955 } else {
1956 // exception path
1957 id _caught = objc_exception_extract(&d);
1958
1959 // enter new try scope for handlers
1960 if (!setjmp(d.jmp_buf)) {
1961 ... match exception and execute catch blocks ...
1962
1963 // fell off end, rethrow.
1964 _rethrow = _caught;
Daniel Dunbar898d5082008-09-30 01:06:03 +00001965 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001966 } else {
1967 // exception in catch block
1968 _rethrow = objc_exception_extract(&d);
Anders Carlsson190d00e2009-02-07 21:26:04 +00001969 _call_try_exit = false;
1970 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001971 }
1972 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00001973 ... jump-through-finally to finally_end ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001974
1975finally:
Anders Carlsson190d00e2009-02-07 21:26:04 +00001976 if (_call_try_exit)
1977 objc_exception_try_exit(&d);
1978
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001979 ... finally block ....
Daniel Dunbar898d5082008-09-30 01:06:03 +00001980 ... dispatch to finally destination ...
1981
1982finally_rethrow:
1983 objc_exception_throw(_rethrow);
1984
1985finally_end:
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001986}
1987
1988This framework differs slightly from the one gcc uses, in that gcc
Daniel Dunbar898d5082008-09-30 01:06:03 +00001989uses _rethrow to determine if objc_exception_try_exit should be called
1990and if the object should be rethrown. This breaks in the face of
1991throwing nil and introduces unnecessary branches.
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001992
1993We specialize this framework for a few particular circumstances:
1994
1995 - If there are no catch blocks, then we avoid emitting the second
1996 exception handling context.
1997
1998 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
1999 e)) we avoid emitting the code to rethrow an uncaught exception.
2000
2001 - FIXME: If there is no @finally block we can do a few more
2002 simplifications.
2003
2004Rethrows and Jumps-Through-Finally
2005--
2006
2007Support for implicit rethrows and jumping through the finally block is
2008handled by storing the current exception-handling context in
2009ObjCEHStack.
2010
Daniel Dunbar898d5082008-09-30 01:06:03 +00002011In order to implement proper @finally semantics, we support one basic
2012mechanism for jumping through the finally block to an arbitrary
2013destination. Constructs which generate exits from a @try or @catch
2014block use this mechanism to implement the proper semantics by chaining
2015jumps, as necessary.
2016
2017This mechanism works like the one used for indirect goto: we
2018arbitrarily assign an ID to each destination and store the ID for the
2019destination in a variable prior to entering the finally block. At the
2020end of the finally block we simply create a switch to the proper
2021destination.
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002022
2023Code gen for @synchronized(expr) stmt;
2024Effectively generating code for:
2025objc_sync_enter(expr);
2026@try stmt @finally { objc_sync_exit(expr); }
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002027*/
2028
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002029void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
2030 const Stmt &S) {
2031 bool isTry = isa<ObjCAtTryStmt>(S);
Daniel Dunbar898d5082008-09-30 01:06:03 +00002032 // Create various blocks we refer to for handling @finally.
Daniel Dunbar55e87422008-11-11 02:29:29 +00002033 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002034 llvm::BasicBlock *FinallyExit = CGF.createBasicBlock("finally.exit");
Daniel Dunbar55e87422008-11-11 02:29:29 +00002035 llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
2036 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
2037 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
Daniel Dunbar1c566672009-02-24 01:43:46 +00002038
2039 // For @synchronized, call objc_sync_enter(sync.expr). The
2040 // evaluation of the expression must occur before we enter the
2041 // @synchronized. We can safely avoid a temp here because jumps into
2042 // @synchronized are illegal & this will dominate uses.
2043 llvm::Value *SyncArg = 0;
2044 if (!isTry) {
2045 SyncArg =
2046 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
2047 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00002048 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar1c566672009-02-24 01:43:46 +00002049 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00002050
2051 // Push an EH context entry, used for handling rethrows and jumps
2052 // through finally.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002053 CGF.PushCleanupBlock(FinallyBlock);
2054
Anders Carlsson273558f2009-02-07 21:37:21 +00002055 CGF.ObjCEHValueStack.push_back(0);
2056
Daniel Dunbar898d5082008-09-30 01:06:03 +00002057 // Allocate memory for the exception data and rethrow pointer.
Anders Carlsson80f25672008-09-09 17:59:25 +00002058 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
2059 "exceptiondata.ptr");
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002060 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
2061 "_rethrow");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002062 llvm::Value *CallTryExitPtr = CGF.CreateTempAlloca(llvm::Type::Int1Ty,
2063 "_call_try_exit");
2064 CGF.Builder.CreateStore(llvm::ConstantInt::getTrue(), CallTryExitPtr);
2065
Anders Carlsson80f25672008-09-09 17:59:25 +00002066 // Enter a new try block and call setjmp.
2067 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
2068 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
2069 "jmpbufarray");
2070 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
2071 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
2072 JmpBufPtr, "result");
Daniel Dunbar898d5082008-09-30 01:06:03 +00002073
Daniel Dunbar55e87422008-11-11 02:29:29 +00002074 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
2075 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002076 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002077 TryHandler, TryBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002078
2079 // Emit the @try block.
2080 CGF.EmitBlock(TryBlock);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002081 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
2082 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002083 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002084
2085 // Emit the "exception in @try" block.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002086 CGF.EmitBlock(TryHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002087
2088 // Retrieve the exception object. We may emit multiple blocks but
2089 // nothing can cross this so the value is already in SSA form.
2090 llvm::Value *Caught = CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
2091 ExceptionData,
2092 "caught");
Anders Carlsson273558f2009-02-07 21:37:21 +00002093 CGF.ObjCEHValueStack.back() = Caught;
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002094 if (!isTry)
2095 {
2096 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002097 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002098 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002099 }
2100 else if (const ObjCAtCatchStmt* CatchStmt =
2101 cast<ObjCAtTryStmt>(S).getCatchStmts())
2102 {
Daniel Dunbar55e40722008-09-27 07:03:52 +00002103 // Enter a new exception try block (in case a @catch block throws
2104 // an exception).
Anders Carlsson80f25672008-09-09 17:59:25 +00002105 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002106
Anders Carlsson80f25672008-09-09 17:59:25 +00002107 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
2108 JmpBufPtr, "result");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002109 llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw");
Anders Carlsson80f25672008-09-09 17:59:25 +00002110
Daniel Dunbar55e87422008-11-11 02:29:29 +00002111 llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch");
2112 llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler");
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002113 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002114
2115 CGF.EmitBlock(CatchBlock);
2116
Daniel Dunbar55e40722008-09-27 07:03:52 +00002117 // Handle catch list. As a special case we check if everything is
2118 // matched and avoid generating code for falling off the end if
2119 // so.
2120 bool AllMatched = false;
Anders Carlsson80f25672008-09-09 17:59:25 +00002121 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbar55e87422008-11-11 02:29:29 +00002122 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch");
Anders Carlsson80f25672008-09-09 17:59:25 +00002123
Steve Naroff7ba138a2009-03-03 19:52:17 +00002124 const ParmVarDecl *CatchParam = CatchStmt->getCatchParamDecl();
Daniel Dunbar129271a2008-09-27 07:36:24 +00002125 const PointerType *PT = 0;
2126
Anders Carlsson80f25672008-09-09 17:59:25 +00002127 // catch(...) always matches.
Daniel Dunbar55e40722008-09-27 07:03:52 +00002128 if (!CatchParam) {
2129 AllMatched = true;
2130 } else {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002131 PT = CatchParam->getType()->getAsPointerType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002132
Daniel Dunbar97f61d12008-09-27 22:21:14 +00002133 // catch(id e) always matches.
2134 // FIXME: For the time being we also match id<X>; this should
2135 // be rejected by Sema instead.
Steve Naroff389bf462009-02-12 17:52:19 +00002136 if ((PT && CGF.getContext().isObjCIdStructType(PT->getPointeeType())) ||
Steve Naroff7ba138a2009-03-03 19:52:17 +00002137 CatchParam->getType()->isObjCQualifiedIdType())
Daniel Dunbar55e40722008-09-27 07:03:52 +00002138 AllMatched = true;
Anders Carlsson80f25672008-09-09 17:59:25 +00002139 }
2140
Daniel Dunbar55e40722008-09-27 07:03:52 +00002141 if (AllMatched) {
Anders Carlssondde0a942008-09-11 09:15:33 +00002142 if (CatchParam) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002143 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002144 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002145 CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002146 }
Anders Carlsson1452f552008-09-11 08:21:54 +00002147
Anders Carlssondde0a942008-09-11 09:15:33 +00002148 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002149 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002150 break;
2151 }
2152
Daniel Dunbar129271a2008-09-27 07:36:24 +00002153 assert(PT && "Unexpected non-pointer type in @catch");
2154 QualType T = PT->getPointeeType();
Anders Carlsson4b7ff6e2008-09-11 06:35:14 +00002155 const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002156 assert(ObjCType && "Catch parameter must have Objective-C type!");
2157
2158 // Check if the @catch block matches the exception object.
2159 llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl());
2160
Anders Carlsson80f25672008-09-09 17:59:25 +00002161 llvm::Value *Match = CGF.Builder.CreateCall2(ObjCTypes.ExceptionMatchFn,
2162 Class, Caught, "match");
Anders Carlsson80f25672008-09-09 17:59:25 +00002163
Daniel Dunbar55e87422008-11-11 02:29:29 +00002164 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched");
Anders Carlsson80f25672008-09-09 17:59:25 +00002165
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002166 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002167 MatchedBlock, NextCatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002168
2169 // Emit the @catch block.
2170 CGF.EmitBlock(MatchedBlock);
Steve Naroff7ba138a2009-03-03 19:52:17 +00002171 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002172 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002173
2174 llvm::Value *Tmp =
Steve Naroff7ba138a2009-03-03 19:52:17 +00002175 CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(CatchParam->getType()),
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002176 "tmp");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002177 CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002178
2179 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002180 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002181
2182 CGF.EmitBlock(NextCatchBlock);
2183 }
2184
Daniel Dunbar55e40722008-09-27 07:03:52 +00002185 if (!AllMatched) {
2186 // None of the handlers caught the exception, so store it to be
2187 // rethrown at the end of the @finally block.
2188 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002189 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002190 }
2191
2192 // Emit the exception handler for the @catch blocks.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002193 CGF.EmitBlock(CatchHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002194 CGF.Builder.CreateStore(CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
2195 ExceptionData),
2196 RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002197 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002198 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002199 } else {
Anders Carlsson80f25672008-09-09 17:59:25 +00002200 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002201 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002202 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Anders Carlsson80f25672008-09-09 17:59:25 +00002203 }
2204
Daniel Dunbar898d5082008-09-30 01:06:03 +00002205 // Pop the exception-handling stack entry. It is important to do
2206 // this now, because the code in the @finally block is not in this
2207 // context.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002208 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
2209
Anders Carlsson273558f2009-02-07 21:37:21 +00002210 CGF.ObjCEHValueStack.pop_back();
2211
Anders Carlsson80f25672008-09-09 17:59:25 +00002212 // Emit the @finally block.
2213 CGF.EmitBlock(FinallyBlock);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002214 llvm::Value* CallTryExit = CGF.Builder.CreateLoad(CallTryExitPtr, "tmp");
2215
2216 CGF.Builder.CreateCondBr(CallTryExit, FinallyExit, FinallyNoExit);
2217
2218 CGF.EmitBlock(FinallyExit);
Anders Carlsson80f25672008-09-09 17:59:25 +00002219 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryExitFn, ExceptionData);
Daniel Dunbar129271a2008-09-27 07:36:24 +00002220
2221 CGF.EmitBlock(FinallyNoExit);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002222 if (isTry) {
2223 if (const ObjCAtFinallyStmt* FinallyStmt =
2224 cast<ObjCAtTryStmt>(S).getFinallyStmt())
2225 CGF.EmitStmt(FinallyStmt->getFinallyBody());
Daniel Dunbar1c566672009-02-24 01:43:46 +00002226 } else {
2227 // Emit objc_sync_exit(expr); as finally's sole statement for
2228 // @synchronized.
2229 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, SyncArg);
Fariborz Jahanianf2878e52008-11-21 19:21:53 +00002230 }
Anders Carlsson80f25672008-09-09 17:59:25 +00002231
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002232 // Emit the switch block
2233 if (Info.SwitchBlock)
2234 CGF.EmitBlock(Info.SwitchBlock);
2235 if (Info.EndBlock)
2236 CGF.EmitBlock(Info.EndBlock);
2237
Daniel Dunbar898d5082008-09-30 01:06:03 +00002238 CGF.EmitBlock(FinallyRethrow);
2239 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn,
2240 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002241 CGF.Builder.CreateUnreachable();
Daniel Dunbar898d5082008-09-30 01:06:03 +00002242
2243 CGF.EmitBlock(FinallyEnd);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002244}
2245
2246void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar898d5082008-09-30 01:06:03 +00002247 const ObjCAtThrowStmt &S) {
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002248 llvm::Value *ExceptionAsObject;
2249
2250 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2251 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
2252 ExceptionAsObject =
2253 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
2254 } else {
Anders Carlsson273558f2009-02-07 21:37:21 +00002255 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002256 "Unexpected rethrow outside @catch block.");
Anders Carlsson273558f2009-02-07 21:37:21 +00002257 ExceptionAsObject = CGF.ObjCEHValueStack.back();
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002258 }
2259
2260 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
Anders Carlsson80f25672008-09-09 17:59:25 +00002261 CGF.Builder.CreateUnreachable();
Daniel Dunbara448fb22008-11-11 23:11:34 +00002262
2263 // Clear the insertion point to indicate we are in unreachable code.
2264 CGF.Builder.ClearInsertionPoint();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002265}
2266
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002267/// EmitObjCWeakRead - Code gen for loading value of a __weak
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002268/// object: objc_read_weak (id *src)
2269///
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002270llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002271 llvm::Value *AddrWeakObj)
2272{
Eli Friedman8339b352009-03-07 03:57:15 +00002273 const llvm::Type* DestTy =
2274 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002275 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002276 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002277 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00002278 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002279 return read_weak;
2280}
2281
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002282/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
2283/// objc_assign_weak (id src, id *dst)
2284///
2285void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
2286 llvm::Value *src, llvm::Value *dst)
2287{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002288 const llvm::Type * SrcTy = src->getType();
2289 if (!isa<llvm::PointerType>(SrcTy)) {
2290 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2291 assert(Size <= 8 && "does not support size > 8");
2292 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2293 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002294 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2295 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002296 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2297 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002298 CGF.Builder.CreateCall2(ObjCTypes.GcAssignWeakFn,
2299 src, dst, "weakassign");
2300 return;
2301}
2302
Fariborz Jahanian58626502008-11-19 00:59:10 +00002303/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
2304/// objc_assign_global (id src, id *dst)
2305///
2306void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
2307 llvm::Value *src, llvm::Value *dst)
2308{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002309 const llvm::Type * SrcTy = src->getType();
2310 if (!isa<llvm::PointerType>(SrcTy)) {
2311 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2312 assert(Size <= 8 && "does not support size > 8");
2313 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2314 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002315 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2316 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002317 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2318 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian58626502008-11-19 00:59:10 +00002319 CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn,
2320 src, dst, "globalassign");
2321 return;
2322}
2323
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002324/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
2325/// objc_assign_ivar (id src, id *dst)
2326///
2327void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
2328 llvm::Value *src, llvm::Value *dst)
2329{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002330 const llvm::Type * SrcTy = src->getType();
2331 if (!isa<llvm::PointerType>(SrcTy)) {
2332 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2333 assert(Size <= 8 && "does not support size > 8");
2334 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2335 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002336 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2337 }
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002338 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2339 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
2340 CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn,
2341 src, dst, "assignivar");
2342 return;
2343}
2344
Fariborz Jahanian58626502008-11-19 00:59:10 +00002345/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
2346/// objc_assign_strongCast (id src, id *dst)
2347///
2348void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
2349 llvm::Value *src, llvm::Value *dst)
2350{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002351 const llvm::Type * SrcTy = src->getType();
2352 if (!isa<llvm::PointerType>(SrcTy)) {
2353 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2354 assert(Size <= 8 && "does not support size > 8");
2355 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2356 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002357 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2358 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002359 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2360 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian58626502008-11-19 00:59:10 +00002361 CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn,
2362 src, dst, "weakassign");
2363 return;
2364}
2365
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002366/// EmitObjCValueForIvar - Code Gen for ivar reference.
2367///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002368LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
2369 QualType ObjectTy,
2370 llvm::Value *BaseValue,
2371 const ObjCIvarDecl *Ivar,
2372 const FieldDecl *Field,
2373 unsigned CVRQualifiers) {
2374 if (Ivar->isBitField())
2375 return CGF.EmitLValueForBitfield(BaseValue, const_cast<FieldDecl *>(Field),
2376 CVRQualifiers);
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002377 // TODO: Add a special case for isa (index 0)
2378 unsigned Index = CGM.getTypes().getLLVMFieldNo(Field);
2379 llvm::Value *V = CGF.Builder.CreateStructGEP(BaseValue, Index, "tmp");
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002380 LValue LV = LValue::MakeAddr(V,
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00002381 Ivar->getType().getCVRQualifiers()|CVRQualifiers,
2382 CGM.getContext().getObjCGCAttrKind(Ivar->getType()));
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002383 LValue::SetObjCIvar(LV, true);
2384 return LV;
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002385}
2386
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002387llvm::Value *CGObjCMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
2388 ObjCInterfaceDecl *Interface,
2389 const ObjCIvarDecl *Ivar) {
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002390 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(Interface);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002391 FieldDecl *Field = Interface->lookupFieldDeclForIvar(CGM.getContext(), Ivar);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00002392 uint64_t Offset = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002393 return llvm::ConstantInt::get(
2394 CGM.getTypes().ConvertType(CGM.getContext().LongTy),
2395 Offset);
2396}
2397
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002398/* *** Private Interface *** */
2399
2400/// EmitImageInfo - Emit the image info marker used to encode some module
2401/// level information.
2402///
2403/// See: <rdr://4810609&4810587&4810587>
2404/// struct IMAGE_INFO {
2405/// unsigned version;
2406/// unsigned flags;
2407/// };
2408enum ImageInfoFlags {
2409 eImageInfo_FixAndContinue = (1 << 0), // FIXME: Not sure what this implies
2410 eImageInfo_GarbageCollected = (1 << 1),
2411 eImageInfo_GCOnly = (1 << 2)
2412};
2413
2414void CGObjCMac::EmitImageInfo() {
2415 unsigned version = 0; // Version is unused?
2416 unsigned flags = 0;
2417
2418 // FIXME: Fix and continue?
2419 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
2420 flags |= eImageInfo_GarbageCollected;
2421 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
2422 flags |= eImageInfo_GCOnly;
2423
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002424 // Emitted as int[2];
2425 llvm::Constant *values[2] = {
2426 llvm::ConstantInt::get(llvm::Type::Int32Ty, version),
2427 llvm::ConstantInt::get(llvm::Type::Int32Ty, flags)
2428 };
2429 llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002430
2431 const char *Section;
2432 if (ObjCABI == 1)
2433 Section = "__OBJC, __image_info,regular";
2434 else
2435 Section = "__DATA, __objc_imageinfo, regular, no_dead_strip";
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002436 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002437 CreateMetadataVar("\01L_OBJC_IMAGE_INFO",
2438 llvm::ConstantArray::get(AT, values, 2),
2439 Section,
2440 0,
2441 true);
2442 GV->setConstant(true);
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002443}
2444
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002445
2446// struct objc_module {
2447// unsigned long version;
2448// unsigned long size;
2449// const char *name;
2450// Symtab symtab;
2451// };
2452
2453// FIXME: Get from somewhere
2454static const int ModuleVersion = 7;
2455
2456void CGObjCMac::EmitModuleInfo() {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00002457 uint64_t Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ModuleTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002458
2459 std::vector<llvm::Constant*> Values(4);
2460 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
2461 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002462 // This used to be the filename, now it is unused. <rdr://4327263>
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002463 Values[2] = GetClassName(&CGM.getContext().Idents.get(""));
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002464 Values[3] = EmitModuleSymbols();
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002465 CreateMetadataVar("\01L_OBJC_MODULES",
2466 llvm::ConstantStruct::get(ObjCTypes.ModuleTy, Values),
2467 "__OBJC,__module_info,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00002468 4, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002469}
2470
2471llvm::Constant *CGObjCMac::EmitModuleSymbols() {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002472 unsigned NumClasses = DefinedClasses.size();
2473 unsigned NumCategories = DefinedCategories.size();
2474
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002475 // Return null if no symbols were defined.
2476 if (!NumClasses && !NumCategories)
2477 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
2478
2479 std::vector<llvm::Constant*> Values(5);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002480 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2481 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
2482 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
2483 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
2484
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002485 // The runtime expects exactly the list of defined classes followed
2486 // by the list of defined categories, in a single array.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002487 std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002488 for (unsigned i=0; i<NumClasses; i++)
2489 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
2490 ObjCTypes.Int8PtrTy);
2491 for (unsigned i=0; i<NumCategories; i++)
2492 Symbols[NumClasses + i] =
2493 llvm::ConstantExpr::getBitCast(DefinedCategories[i],
2494 ObjCTypes.Int8PtrTy);
2495
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002496 Values[4] =
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002497 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002498 NumClasses + NumCategories),
2499 Symbols);
2500
2501 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2502
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002503 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002504 CreateMetadataVar("\01L_OBJC_SYMBOLS", Init,
2505 "__OBJC,__symbols,regular,no_dead_strip",
2506 0, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002507 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
2508}
2509
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002510llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002511 const ObjCInterfaceDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002512 LazySymbols.insert(ID->getIdentifier());
2513
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002514 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
2515
2516 if (!Entry) {
2517 llvm::Constant *Casted =
2518 llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()),
2519 ObjCTypes.ClassPtrTy);
2520 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002521 CreateMetadataVar("\01L_OBJC_CLASS_REFERENCES_", Casted,
2522 "__OBJC,__cls_refs,literal_pointers,no_dead_strip",
2523 0, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002524 }
2525
2526 return Builder.CreateLoad(Entry, false, "tmp");
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002527}
2528
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002529llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002530 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
2531
2532 if (!Entry) {
2533 llvm::Constant *Casted =
2534 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
2535 ObjCTypes.SelectorPtrTy);
2536 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002537 CreateMetadataVar("\01L_OBJC_SELECTOR_REFERENCES_", Casted,
2538 "__OBJC,__message_refs,literal_pointers,no_dead_strip",
2539 0, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002540 }
2541
2542 return Builder.CreateLoad(Entry, false, "tmp");
2543}
2544
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00002545llvm::Constant *CGObjCCommonMac::GetClassName(IdentifierInfo *Ident) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002546 llvm::GlobalVariable *&Entry = ClassNames[Ident];
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002547
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002548 if (!Entry)
2549 Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
2550 llvm::ConstantArray::get(Ident->getName()),
2551 "__TEXT,__cstring,cstring_literals",
2552 0, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002553
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002554 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002555}
2556
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002557/// GetInterfaceDeclStructLayout - Get layout for ivars of given
2558/// interface declaration.
2559const llvm::StructLayout *CGObjCCommonMac::GetInterfaceDeclStructLayout(
2560 const ObjCInterfaceDecl *OID) const {
2561 const llvm::Type *InterfaceTy =
2562 CGM.getTypes().ConvertType(
2563 CGM.getContext().getObjCInterfaceType(
2564 const_cast<ObjCInterfaceDecl*>(OID)));
2565 const llvm::StructLayout *Layout =
2566 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceTy));
2567 return Layout;
2568}
2569
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00002570/// GetIvarLayoutName - Returns a unique constant for the given
2571/// ivar layout bitmap.
2572llvm::Constant *CGObjCCommonMac::GetIvarLayoutName(IdentifierInfo *Ident,
2573 const ObjCCommonTypesHelper &ObjCTypes) {
2574 return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2575}
2576
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002577void CGObjCCommonMac::BuildAggrIvarLayout(const ObjCInterfaceDecl *OI,
2578 const llvm::StructLayout *Layout,
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002579 const RecordDecl *RD,
Chris Lattnerf1690852009-03-31 08:48:01 +00002580 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002581 unsigned int BytePos, bool ForStrongLayout,
2582 int &Index, int &SkIndex, bool &HasUnion) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002583 bool IsUnion = (RD && RD->isUnion());
2584 uint64_t MaxUnionIvarSize = 0;
2585 uint64_t MaxSkippedUnionIvarSize = 0;
2586 FieldDecl *MaxField = 0;
2587 FieldDecl *MaxSkippedField = 0;
Chris Lattnerf1690852009-03-31 08:48:01 +00002588 unsigned base = 0;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002589 if (RecFields.empty())
2590 return;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002591 if (IsUnion)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002592 base = BytePos + GetFieldBaseOffset(OI, Layout, RecFields[0]);
Chris Lattnerf1690852009-03-31 08:48:01 +00002593 unsigned WordSizeInBits = CGM.getContext().Target.getPointerWidth(0);
2594 unsigned ByteSizeInBits = CGM.getContext().Target.getCharWidth();
2595
2596 llvm::SmallVector<FieldDecl*, 16> TmpRecFields;
2597
2598 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002599 FieldDecl *Field = RecFields[i];
2600 // Skip over unnamed or bitfields
2601 if (!Field->getIdentifier() || Field->isBitField())
2602 continue;
2603 QualType FQT = Field->getType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002604 if (FQT->isRecordType() || FQT->isUnionType()) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002605 if (FQT->isUnionType())
2606 HasUnion = true;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002607 else
2608 assert(FQT->isRecordType() &&
2609 "only union/record is supported for ivar layout bitmap");
2610
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002611 const RecordType *RT = FQT->getAsRecordType();
2612 const RecordDecl *RD = RT->getDecl();
2613 // FIXME - Find a more efficiant way of passing records down.
Chris Lattnerf1690852009-03-31 08:48:01 +00002614 TmpRecFields.append(RD->field_begin(), RD->field_end());
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002615 // FIXME - Is Layout correct?
Chris Lattnerf1690852009-03-31 08:48:01 +00002616 BuildAggrIvarLayout(OI, Layout, RD, TmpRecFields,
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002617 BytePos + GetFieldBaseOffset(OI, Layout, Field),
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002618 ForStrongLayout, Index, SkIndex,
2619 HasUnion);
Chris Lattnerf1690852009-03-31 08:48:01 +00002620 TmpRecFields.clear();
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002621 continue;
2622 }
Chris Lattnerf1690852009-03-31 08:48:01 +00002623
2624 if (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002625 const ConstantArrayType *CArray =
2626 dyn_cast_or_null<ConstantArrayType>(Array);
2627 assert(CArray && "only array with know element size is supported");
2628 FQT = CArray->getElementType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002629 while (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
2630 const ConstantArrayType *CArray =
2631 dyn_cast_or_null<ConstantArrayType>(Array);
2632 FQT = CArray->getElementType();
2633 }
2634
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002635 assert(!FQT->isUnionType() &&
2636 "layout for array of unions not supported");
2637 if (FQT->isRecordType()) {
2638 uint64_t ElCount = CArray->getSize().getZExtValue();
2639 int OldIndex = Index;
2640 int OldSkIndex = SkIndex;
2641
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002642 // FIXME - Use a common routine with the above!
2643 const RecordType *RT = FQT->getAsRecordType();
2644 const RecordDecl *RD = RT->getDecl();
2645 // FIXME - Find a more efficiant way of passing records down.
Chris Lattnerf1690852009-03-31 08:48:01 +00002646 TmpRecFields.append(RD->field_begin(), RD->field_end());
2647
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002648 BuildAggrIvarLayout(OI, Layout, RD,
Chris Lattnerf1690852009-03-31 08:48:01 +00002649 TmpRecFields,
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002650 BytePos + GetFieldBaseOffset(OI, Layout, Field),
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002651 ForStrongLayout, Index, SkIndex,
2652 HasUnion);
Chris Lattnerf1690852009-03-31 08:48:01 +00002653 TmpRecFields.clear();
2654
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002655 // Replicate layout information for each array element. Note that
2656 // one element is already done.
2657 uint64_t ElIx = 1;
2658 for (int FirstIndex = Index, FirstSkIndex = SkIndex;
2659 ElIx < ElCount; ElIx++) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002660 uint64_t Size = CGM.getContext().getTypeSize(RT)/ByteSizeInBits;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002661 for (int i = OldIndex+1; i <= FirstIndex; ++i)
2662 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002663 GC_IVAR gcivar;
2664 gcivar.ivar_bytepos = IvarsInfo[i].ivar_bytepos + Size*ElIx;
2665 gcivar.ivar_size = IvarsInfo[i].ivar_size;
2666 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002667 }
2668
Chris Lattnerf1690852009-03-31 08:48:01 +00002669 for (int i = OldSkIndex+1; i <= FirstSkIndex; ++i) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002670 GC_IVAR skivar;
2671 skivar.ivar_bytepos = SkipIvars[i].ivar_bytepos + Size*ElIx;
2672 skivar.ivar_size = SkipIvars[i].ivar_size;
2673 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002674 }
2675 }
2676 continue;
2677 }
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002678 }
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002679 // At this point, we are done with Record/Union and array there of.
2680 // For other arrays we are down to its element type.
2681 QualType::GCAttrTypes GCAttr = QualType::GCNone;
2682 do {
2683 if (FQT.isObjCGCStrong() || FQT.isObjCGCWeak()) {
2684 GCAttr = FQT.isObjCGCStrong() ? QualType::Strong : QualType::Weak;
2685 break;
2686 }
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002687 else if (CGM.getContext().isObjCObjectPointerType(FQT)) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002688 GCAttr = QualType::Strong;
2689 break;
2690 }
2691 else if (const PointerType *PT = FQT->getAsPointerType()) {
2692 FQT = PT->getPointeeType();
2693 }
2694 else {
2695 break;
2696 }
2697 } while (true);
Chris Lattnerf1690852009-03-31 08:48:01 +00002698
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002699 if ((ForStrongLayout && GCAttr == QualType::Strong)
2700 || (!ForStrongLayout && GCAttr == QualType::Weak)) {
2701 if (IsUnion)
2702 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002703 uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType())
2704 / WordSizeInBits;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002705 if (UnionIvarSize > MaxUnionIvarSize)
2706 {
2707 MaxUnionIvarSize = UnionIvarSize;
2708 MaxField = Field;
2709 }
2710 }
2711 else
2712 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002713 GC_IVAR gcivar;
2714 gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field);
2715 gcivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) /
2716 WordSizeInBits;
2717 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002718 }
2719 }
2720 else if ((ForStrongLayout &&
2721 (GCAttr == QualType::GCNone || GCAttr == QualType::Weak))
2722 || (!ForStrongLayout && GCAttr != QualType::Weak)) {
2723 if (IsUnion)
2724 {
2725 uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType());
2726 if (UnionIvarSize > MaxSkippedUnionIvarSize)
2727 {
2728 MaxSkippedUnionIvarSize = UnionIvarSize;
2729 MaxSkippedField = Field;
2730 }
2731 }
2732 else
2733 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002734 GC_IVAR skivar;
2735 skivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field);
2736 skivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) /
2737 WordSizeInBits;
2738 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002739 }
2740 }
2741 }
Chris Lattnerf1690852009-03-31 08:48:01 +00002742 if (MaxField) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002743 GC_IVAR gcivar;
2744 gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, MaxField);
2745 gcivar.ivar_size = MaxUnionIvarSize;
2746 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002747 }
Chris Lattnerf1690852009-03-31 08:48:01 +00002748
2749 if (MaxSkippedField) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002750 GC_IVAR skivar;
2751 skivar.ivar_bytepos = BytePos +
2752 GetFieldBaseOffset(OI, Layout, MaxSkippedField);
2753 skivar.ivar_size = MaxSkippedUnionIvarSize;
2754 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002755 }
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002756}
2757
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002758static int
Chris Lattnerf1690852009-03-31 08:48:01 +00002759IvarBytePosCompare(const void *a, const void *b)
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002760{
2761 unsigned int sa = ((CGObjCCommonMac::GC_IVAR *)a)->ivar_bytepos;
2762 unsigned int sb = ((CGObjCCommonMac::GC_IVAR *)b)->ivar_bytepos;
2763
2764 if (sa < sb)
2765 return -1;
2766 if (sa > sb)
2767 return 1;
2768 return 0;
2769}
2770
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002771/// BuildIvarLayout - Builds ivar layout bitmap for the class
2772/// implementation for the __strong or __weak case.
2773/// The layout map displays which words in ivar list must be skipped
2774/// and which must be scanned by GC (see below). String is built of bytes.
2775/// Each byte is divided up in two nibbles (4-bit each). Left nibble is count
2776/// of words to skip and right nibble is count of words to scan. So, each
2777/// nibble represents up to 15 workds to skip or scan. Skipping the rest is
2778/// represented by a 0x00 byte which also ends the string.
2779/// 1. when ForStrongLayout is true, following ivars are scanned:
2780/// - id, Class
2781/// - object *
2782/// - __strong anything
2783///
2784/// 2. When ForStrongLayout is false, following ivars are scanned:
2785/// - __weak anything
2786///
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002787llvm::Constant *CGObjCCommonMac::BuildIvarLayout(
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002788 const ObjCImplementationDecl *OMD,
2789 bool ForStrongLayout) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002790 int Index = -1;
2791 int SkIndex = -1;
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002792 bool hasUnion = false;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002793 int SkipScan;
2794 unsigned int WordsToScan, WordsToSkip;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002795 const llvm::Type *PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
2796 if (CGM.getLangOptions().getGCMode() == LangOptions::NonGC)
2797 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002798
Chris Lattnerf1690852009-03-31 08:48:01 +00002799 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002800 const ObjCInterfaceDecl *OI = OMD->getClassInterface();
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002801 CGM.getContext().CollectObjCIvars(OI, RecFields);
2802 if (RecFields.empty())
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002803 return llvm::Constant::getNullValue(PtrTy);
Chris Lattnerf1690852009-03-31 08:48:01 +00002804
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002805 SkipIvars.clear();
2806 IvarsInfo.clear();
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002807
2808 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OI);
Chris Lattnerf1690852009-03-31 08:48:01 +00002809 BuildAggrIvarLayout(OI, Layout, 0, RecFields, 0, ForStrongLayout,
2810 Index, SkIndex, hasUnion);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002811 if (Index == -1)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002812 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002813
2814 // Sort on byte position in case we encounterred a union nested in
2815 // the ivar list.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002816 if (hasUnion && !IvarsInfo.empty())
2817 qsort(&IvarsInfo[0], Index+1, sizeof(GC_IVAR), IvarBytePosCompare);
2818 if (hasUnion && !SkipIvars.empty())
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002819 qsort(&SkipIvars[0], Index+1, sizeof(GC_IVAR), IvarBytePosCompare);
2820
2821 // Build the string of skip/scan nibbles
2822 SkipScan = -1;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002823 SkipScanIvars.clear();
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002824 unsigned int WordSize =
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002825 CGM.getTypes().getTargetData().getTypePaddedSize(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002826 if (IvarsInfo[0].ivar_bytepos == 0) {
2827 WordsToSkip = 0;
2828 WordsToScan = IvarsInfo[0].ivar_size;
2829 }
2830 else {
2831 WordsToSkip = IvarsInfo[0].ivar_bytepos/WordSize;
2832 WordsToScan = IvarsInfo[0].ivar_size;
2833 }
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002834 for (unsigned int i=1, Last=IvarsInfo.size(); i != Last; i++)
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002835 {
2836 unsigned int TailPrevGCObjC =
2837 IvarsInfo[i-1].ivar_bytepos + IvarsInfo[i-1].ivar_size * WordSize;
2838 if (IvarsInfo[i].ivar_bytepos == TailPrevGCObjC)
2839 {
2840 // consecutive 'scanned' object pointers.
2841 WordsToScan += IvarsInfo[i].ivar_size;
2842 }
2843 else
2844 {
2845 // Skip over 'gc'able object pointer which lay over each other.
2846 if (TailPrevGCObjC > IvarsInfo[i].ivar_bytepos)
2847 continue;
2848 // Must skip over 1 or more words. We save current skip/scan values
2849 // and start a new pair.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002850 SKIP_SCAN SkScan;
2851 SkScan.skip = WordsToSkip;
2852 SkScan.scan = WordsToScan;
2853 SkipScanIvars.push_back(SkScan); ++SkipScan;
2854
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002855 // Skip the hole.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002856 SkScan.skip = (IvarsInfo[i].ivar_bytepos - TailPrevGCObjC) / WordSize;
2857 SkScan.scan = 0;
2858 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002859 WordsToSkip = 0;
2860 WordsToScan = IvarsInfo[i].ivar_size;
2861 }
2862 }
2863 if (WordsToScan > 0)
2864 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002865 SKIP_SCAN SkScan;
2866 SkScan.skip = WordsToSkip;
2867 SkScan.scan = WordsToScan;
2868 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002869 }
2870
2871 bool BytesSkipped = false;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002872 if (!SkipIvars.empty())
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002873 {
2874 int LastByteSkipped =
2875 SkipIvars[SkIndex].ivar_bytepos + SkipIvars[SkIndex].ivar_size;
2876 int LastByteScanned =
2877 IvarsInfo[Index].ivar_bytepos + IvarsInfo[Index].ivar_size * WordSize;
2878 BytesSkipped = (LastByteSkipped > LastByteScanned);
2879 // Compute number of bytes to skip at the tail end of the last ivar scanned.
2880 if (BytesSkipped)
2881 {
2882 unsigned int TotalWords = (LastByteSkipped + (WordSize -1)) / WordSize;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002883 SKIP_SCAN SkScan;
2884 SkScan.skip = TotalWords - (LastByteScanned/WordSize);
2885 SkScan.scan = 0;
2886 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002887 }
2888 }
2889 // Mini optimization of nibbles such that an 0xM0 followed by 0x0N is produced
2890 // as 0xMN.
2891 for (int i = 0; i <= SkipScan; i++)
2892 {
2893 if ((i < SkipScan) && SkipScanIvars[i].skip && SkipScanIvars[i].scan == 0
2894 && SkipScanIvars[i+1].skip == 0 && SkipScanIvars[i+1].scan) {
2895 // 0xM0 followed by 0x0N detected.
2896 SkipScanIvars[i].scan = SkipScanIvars[i+1].scan;
2897 for (int j = i+1; j < SkipScan; j++)
2898 SkipScanIvars[j] = SkipScanIvars[j+1];
2899 --SkipScan;
2900 }
2901 }
2902
2903 // Generate the string.
2904 std::string BitMap;
2905 for (int i = 0; i <= SkipScan; i++)
2906 {
2907 unsigned char byte;
2908 unsigned int skip_small = SkipScanIvars[i].skip % 0xf;
2909 unsigned int scan_small = SkipScanIvars[i].scan % 0xf;
2910 unsigned int skip_big = SkipScanIvars[i].skip / 0xf;
2911 unsigned int scan_big = SkipScanIvars[i].scan / 0xf;
2912
2913 if (skip_small > 0 || skip_big > 0)
2914 BytesSkipped = true;
2915 // first skip big.
2916 for (unsigned int ix = 0; ix < skip_big; ix++)
2917 BitMap += (unsigned char)(0xf0);
2918
2919 // next (skip small, scan)
2920 if (skip_small)
2921 {
2922 byte = skip_small << 4;
2923 if (scan_big > 0)
2924 {
2925 byte |= 0xf;
2926 --scan_big;
2927 }
2928 else if (scan_small)
2929 {
2930 byte |= scan_small;
2931 scan_small = 0;
2932 }
2933 BitMap += byte;
2934 }
2935 // next scan big
2936 for (unsigned int ix = 0; ix < scan_big; ix++)
2937 BitMap += (unsigned char)(0x0f);
2938 // last scan small
2939 if (scan_small)
2940 {
2941 byte = scan_small;
2942 BitMap += byte;
2943 }
2944 }
2945 // null terminate string.
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002946 unsigned char zero = 0;
2947 BitMap += zero;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002948 // if ivar_layout bitmap is all 1 bits (nothing skipped) then use NULL as
2949 // final layout.
2950 if (ForStrongLayout && !BytesSkipped)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002951 return llvm::Constant::getNullValue(PtrTy);
2952 llvm::GlobalVariable * Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
2953 llvm::ConstantArray::get(BitMap.c_str()),
2954 "__TEXT,__cstring,cstring_literals",
2955 0, true);
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002956 // FIXME. Need a commomand-line option for this eventually.
2957 if (ForStrongLayout)
2958 printf("\nstrong ivar layout: ");
2959 else
2960 printf("\nweak ivar layout: ");
2961 const unsigned char *s = (unsigned char*)BitMap.c_str();
2962 for (unsigned i = 0; i < BitMap.size(); i++)
Fariborz Jahaniandbf15cb2009-03-26 19:10:36 +00002963 if (!(s[i] & 0xf0))
2964 printf("0x0%x%s", s[i], s[i] != 0 ? ", " : "");
2965 else
2966 printf("0x%x%s", s[i], s[i] != 0 ? ", " : "");
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002967 printf("\n");
2968
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002969 return getConstantGEP(Entry, 0, 0);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002970}
2971
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002972llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002973 llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
2974
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002975 // FIXME: Avoid std::string copying.
2976 if (!Entry)
2977 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_NAME_",
2978 llvm::ConstantArray::get(Sel.getAsString()),
2979 "__TEXT,__cstring,cstring_literals",
2980 0, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002981
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002982 return getConstantGEP(Entry, 0, 0);
2983}
2984
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002985// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002986llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002987 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
2988}
2989
2990// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002991llvm::Constant *CGObjCCommonMac::GetMethodVarName(const std::string &Name) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002992 return GetMethodVarName(&CGM.getContext().Idents.get(Name));
2993}
2994
Devang Patel7794bb82009-03-04 18:21:39 +00002995llvm::Constant *CGObjCCommonMac::GetMethodVarType(FieldDecl *Field) {
2996 std::string TypeStr;
2997 CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
2998
2999 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003000
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003001 if (!Entry)
3002 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3003 llvm::ConstantArray::get(TypeStr),
3004 "__TEXT,__cstring,cstring_literals",
3005 0, true);
3006
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003007 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003008}
3009
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003010llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003011 std::string TypeStr;
Daniel Dunbarc45ef602008-08-26 21:51:14 +00003012 CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D),
3013 TypeStr);
Devang Patel7794bb82009-03-04 18:21:39 +00003014
3015 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
3016
3017 if (!Entry) {
3018 llvm::Constant *C = llvm::ConstantArray::get(TypeStr);
3019 Entry =
3020 new llvm::GlobalVariable(C->getType(), false,
3021 llvm::GlobalValue::InternalLinkage,
3022 C, "\01L_OBJC_METH_VAR_TYPE_",
3023 &CGM.getModule());
3024 Entry->setSection("__TEXT,__cstring,cstring_literals");
3025 UsedGlobals.push_back(Entry);
3026 }
3027
3028 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003029}
3030
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003031// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003032llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003033 llvm::GlobalVariable *&Entry = PropertyNames[Ident];
3034
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003035 if (!Entry)
3036 Entry = CreateMetadataVar("\01L_OBJC_PROP_NAME_ATTR_",
3037 llvm::ConstantArray::get(Ident->getName()),
3038 "__TEXT,__cstring,cstring_literals",
3039 0, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003040
3041 return getConstantGEP(Entry, 0, 0);
3042}
3043
3044// FIXME: Merge into a single cstring creation function.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003045// FIXME: This Decl should be more precise.
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003046llvm::Constant *
3047 CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
3048 const Decl *Container) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003049 std::string TypeStr;
3050 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003051 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
3052}
3053
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003054void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D,
3055 const ObjCContainerDecl *CD,
3056 std::string &NameOut) {
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00003057 NameOut = '\01';
3058 NameOut += (D->isInstanceMethod() ? '-' : '+');
Chris Lattner077bf5e2008-11-24 03:33:13 +00003059 NameOut += '[';
Fariborz Jahanian679a5022009-01-10 21:06:09 +00003060 assert (CD && "Missing container decl in GetNameForMethod");
3061 NameOut += CD->getNameAsString();
Fariborz Jahanian52847332009-01-26 23:49:05 +00003062 // FIXME. For a method in a category, (CAT_NAME) is inserted here.
3063 // Right now! there is not enough info. to do this.
Chris Lattner077bf5e2008-11-24 03:33:13 +00003064 NameOut += ' ';
3065 NameOut += D->getSelector().getAsString();
3066 NameOut += ']';
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00003067}
3068
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00003069/// GetFirstIvarInRecord - This routine returns the record for the
3070/// implementation of the fiven class OID. It also returns field
3071/// corresponding to the first ivar in the class in FIV. It also
3072/// returns the one before the first ivar.
3073///
3074const RecordDecl *CGObjCCommonMac::GetFirstIvarInRecord(
3075 const ObjCInterfaceDecl *OID,
3076 RecordDecl::field_iterator &FIV,
3077 RecordDecl::field_iterator &PIV) {
3078 int countSuperClassIvars = countInheritedIvars(OID->getSuperClass());
3079 const RecordDecl *RD = CGM.getContext().addRecordToClass(OID);
3080 RecordDecl::field_iterator ifield = RD->field_begin();
3081 RecordDecl::field_iterator pfield = RD->field_end();
3082 while (countSuperClassIvars-- > 0) {
3083 pfield = ifield;
3084 ++ifield;
3085 }
3086 FIV = ifield;
3087 PIV = pfield;
3088 return RD;
3089}
3090
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003091void CGObjCMac::FinishModule() {
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003092 EmitModuleInfo();
3093
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003094 // Emit the dummy bodies for any protocols which were referenced but
3095 // never defined.
3096 for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
3097 i = Protocols.begin(), e = Protocols.end(); i != e; ++i) {
3098 if (i->second->hasInitializer())
3099 continue;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003100
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003101 std::vector<llvm::Constant*> Values(5);
3102 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
3103 Values[1] = GetClassName(i->first);
3104 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
3105 Values[3] = Values[4] =
3106 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
3107 i->second->setLinkage(llvm::GlobalValue::InternalLinkage);
3108 i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
3109 Values));
3110 }
3111
3112 std::vector<llvm::Constant*> Used;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003113 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003114 e = UsedGlobals.end(); i != e; ++i) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003115 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003116 }
3117
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003118 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003119 llvm::GlobalValue *GV =
3120 new llvm::GlobalVariable(AT, false,
3121 llvm::GlobalValue::AppendingLinkage,
3122 llvm::ConstantArray::get(AT, Used),
3123 "llvm.used",
3124 &CGM.getModule());
3125
3126 GV->setSection("llvm.metadata");
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003127
3128 // Add assembler directives to add lazy undefined symbol references
3129 // for classes which are referenced but not defined. This is
3130 // important for correct linker interaction.
3131
3132 // FIXME: Uh, this isn't particularly portable.
3133 std::stringstream s;
Anders Carlsson565c99f2008-12-10 02:21:04 +00003134
3135 if (!CGM.getModule().getModuleInlineAsm().empty())
3136 s << "\n";
3137
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003138 for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(),
3139 e = LazySymbols.end(); i != e; ++i) {
3140 s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n";
3141 }
3142 for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(),
3143 e = DefinedSymbols.end(); i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003144 s << "\t.objc_class_name_" << (*i)->getName() << "=0\n"
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003145 << "\t.globl .objc_class_name_" << (*i)->getName() << "\n";
3146 }
Anders Carlsson565c99f2008-12-10 02:21:04 +00003147
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003148 CGM.getModule().appendModuleInlineAsm(s.str());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003149}
3150
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003151CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003152 : CGObjCCommonMac(cgm),
3153 ObjCTypes(cgm)
3154{
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003155 ObjCEmptyCacheVar = ObjCEmptyVtableVar = NULL;
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003156 ObjCABI = 2;
3157}
3158
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003159/* *** */
3160
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003161ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm)
3162: CGM(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003163{
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003164 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3165 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003166
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003167 ShortTy = Types.ConvertType(Ctx.ShortTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003168 IntTy = Types.ConvertType(Ctx.IntTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003169 LongTy = Types.ConvertType(Ctx.LongTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00003170 LongLongTy = Types.ConvertType(Ctx.LongLongTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003171 Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3172
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003173 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00003174 PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003175 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003176
3177 // FIXME: It would be nice to unify this with the opaque type, so
3178 // that the IR comes out a bit cleaner.
3179 const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
3180 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003181
3182 // I'm not sure I like this. The implicit coordination is a bit
3183 // gross. We should solve this in a reasonable fashion because this
3184 // is a pretty common task (match some runtime data structure with
3185 // an LLVM data structure).
3186
3187 // FIXME: This is leaked.
3188 // FIXME: Merge with rewriter code?
3189
3190 // struct _objc_super {
3191 // id self;
3192 // Class cls;
3193 // }
3194 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3195 SourceLocation(),
3196 &Ctx.Idents.get("_objc_super"));
3197 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3198 Ctx.getObjCIdType(), 0, false));
3199 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3200 Ctx.getObjCClassType(), 0, false));
3201 RD->completeDefinition(Ctx);
3202
3203 SuperCTy = Ctx.getTagDeclType(RD);
3204 SuperPtrCTy = Ctx.getPointerType(SuperCTy);
3205
3206 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003207 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
3208
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003209 // struct _prop_t {
3210 // char *name;
3211 // char *attributes;
3212 // }
3213 PropertyTy = llvm::StructType::get(Int8PtrTy,
3214 Int8PtrTy,
3215 NULL);
3216 CGM.getModule().addTypeName("struct._prop_t",
3217 PropertyTy);
3218
3219 // struct _prop_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003220 // uint32_t entsize; // sizeof(struct _prop_t)
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003221 // uint32_t count_of_properties;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003222 // struct _prop_t prop_list[count_of_properties];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003223 // }
3224 PropertyListTy = llvm::StructType::get(IntTy,
3225 IntTy,
3226 llvm::ArrayType::get(PropertyTy, 0),
3227 NULL);
3228 CGM.getModule().addTypeName("struct._prop_list_t",
3229 PropertyListTy);
3230 // struct _prop_list_t *
3231 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
3232
3233 // struct _objc_method {
3234 // SEL _cmd;
3235 // char *method_type;
3236 // char *_imp;
3237 // }
3238 MethodTy = llvm::StructType::get(SelectorPtrTy,
3239 Int8PtrTy,
3240 Int8PtrTy,
3241 NULL);
3242 CGM.getModule().addTypeName("struct._objc_method", MethodTy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003243
3244 // struct _objc_cache *
3245 CacheTy = llvm::OpaqueType::get();
3246 CGM.getModule().addTypeName("struct._objc_cache", CacheTy);
3247 CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003248
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003249 // Property manipulation functions.
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003250
3251 QualType IdType = Ctx.getObjCIdType();
3252 QualType SelType = Ctx.getObjCSelType();
3253 llvm::SmallVector<QualType,16> Params;
3254 const llvm::FunctionType *FTy;
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003255
3256 // id objc_getProperty (id, SEL, ptrdiff_t, bool)
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003257 Params.push_back(IdType);
3258 Params.push_back(SelType);
3259 Params.push_back(Ctx.LongTy);
3260 Params.push_back(Ctx.BoolTy);
3261 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params),
3262 false);
3263 GetPropertyFn = CGM.CreateRuntimeFunction(FTy, "objc_getProperty");
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003264
3265 // void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool)
3266 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003267 Params.push_back(IdType);
3268 Params.push_back(SelType);
3269 Params.push_back(Ctx.LongTy);
3270 Params.push_back(IdType);
3271 Params.push_back(Ctx.BoolTy);
3272 Params.push_back(Ctx.BoolTy);
3273 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
3274 SetPropertyFn = CGM.CreateRuntimeFunction(FTy, "objc_setProperty");
3275
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003276 // Enumeration mutation.
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003277
3278 // void objc_enumerationMutation (id)
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003279 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003280 Params.push_back(IdType);
3281 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
3282 EnumerationMutationFn = CGM.CreateRuntimeFunction(FTy,
3283 "objc_enumerationMutation");
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003284
3285 // gc's API
3286 // id objc_read_weak (id *)
3287 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003288 Params.push_back(Ctx.getPointerType(IdType));
3289 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
3290 GcReadWeakFn = CGM.CreateRuntimeFunction(FTy, "objc_read_weak");
3291
3292 // id objc_assign_weak (id, id *)
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003293 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003294 Params.push_back(IdType);
3295 Params.push_back(Ctx.getPointerType(IdType));
3296
3297 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
3298 GcAssignWeakFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_weak");
3299 GcAssignGlobalFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_global");
3300 GcAssignIvarFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_ivar");
3301 GcAssignStrongCastFn =
3302 CGM.CreateRuntimeFunction(FTy, "objc_assign_strongCast");
Anders Carlssonf57c5b22009-02-16 22:59:18 +00003303
3304 // void objc_exception_throw(id)
3305 Params.clear();
3306 Params.push_back(IdType);
3307
3308 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00003309 ExceptionThrowFn =
3310 CGM.CreateRuntimeFunction(FTy, "objc_exception_throw");
Daniel Dunbar1c566672009-02-24 01:43:46 +00003311
3312 // synchronized APIs
Daniel Dunbar1c566672009-02-24 01:43:46 +00003313 // void objc_sync_exit (id)
3314 Params.clear();
3315 Params.push_back(IdType);
3316
3317 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
Daniel Dunbar1c566672009-02-24 01:43:46 +00003318 SyncExitFn = CGM.CreateRuntimeFunction(FTy, "objc_sync_exit");
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003319}
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003320
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003321ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
3322 : ObjCCommonTypesHelper(cgm)
3323{
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003324 // struct _objc_method_description {
3325 // SEL name;
3326 // char *types;
3327 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003328 MethodDescriptionTy =
3329 llvm::StructType::get(SelectorPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003330 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003331 NULL);
3332 CGM.getModule().addTypeName("struct._objc_method_description",
3333 MethodDescriptionTy);
3334
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003335 // struct _objc_method_description_list {
3336 // int count;
3337 // struct _objc_method_description[1];
3338 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003339 MethodDescriptionListTy =
3340 llvm::StructType::get(IntTy,
3341 llvm::ArrayType::get(MethodDescriptionTy, 0),
3342 NULL);
3343 CGM.getModule().addTypeName("struct._objc_method_description_list",
3344 MethodDescriptionListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003345
3346 // struct _objc_method_description_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003347 MethodDescriptionListPtrTy =
3348 llvm::PointerType::getUnqual(MethodDescriptionListTy);
3349
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003350 // Protocol description structures
3351
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003352 // struct _objc_protocol_extension {
3353 // uint32_t size; // sizeof(struct _objc_protocol_extension)
3354 // struct _objc_method_description_list *optional_instance_methods;
3355 // struct _objc_method_description_list *optional_class_methods;
3356 // struct _objc_property_list *instance_properties;
3357 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003358 ProtocolExtensionTy =
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003359 llvm::StructType::get(IntTy,
3360 MethodDescriptionListPtrTy,
3361 MethodDescriptionListPtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003362 PropertyListPtrTy,
3363 NULL);
3364 CGM.getModule().addTypeName("struct._objc_protocol_extension",
3365 ProtocolExtensionTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003366
3367 // struct _objc_protocol_extension *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003368 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
3369
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003370 // Handle recursive construction of Protocol and ProtocolList types
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003371
3372 llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get();
3373 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3374
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003375 const llvm::Type *T =
3376 llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder),
3377 LongTy,
3378 llvm::ArrayType::get(ProtocolTyHolder, 0),
3379 NULL);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003380 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T);
3381
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003382 // struct _objc_protocol {
3383 // struct _objc_protocol_extension *isa;
3384 // char *protocol_name;
3385 // struct _objc_protocol **_objc_protocol_list;
3386 // struct _objc_method_description_list *instance_methods;
3387 // struct _objc_method_description_list *class_methods;
3388 // }
3389 T = llvm::StructType::get(ProtocolExtensionPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003390 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003391 llvm::PointerType::getUnqual(ProtocolListTyHolder),
3392 MethodDescriptionListPtrTy,
3393 MethodDescriptionListPtrTy,
3394 NULL);
3395 cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T);
3396
3397 ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get());
3398 CGM.getModule().addTypeName("struct._objc_protocol_list",
3399 ProtocolListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003400 // struct _objc_protocol_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003401 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
3402
3403 ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get());
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003404 CGM.getModule().addTypeName("struct._objc_protocol", ProtocolTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003405 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003406
3407 // Class description structures
3408
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003409 // struct _objc_ivar {
3410 // char *ivar_name;
3411 // char *ivar_type;
3412 // int ivar_offset;
3413 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003414 IvarTy = llvm::StructType::get(Int8PtrTy,
3415 Int8PtrTy,
3416 IntTy,
3417 NULL);
3418 CGM.getModule().addTypeName("struct._objc_ivar", IvarTy);
3419
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003420 // struct _objc_ivar_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003421 IvarListTy = llvm::OpaqueType::get();
3422 CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy);
3423 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
3424
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003425 // struct _objc_method_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003426 MethodListTy = llvm::OpaqueType::get();
3427 CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy);
3428 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
3429
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003430 // struct _objc_class_extension *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003431 ClassExtensionTy =
3432 llvm::StructType::get(IntTy,
3433 Int8PtrTy,
3434 PropertyListPtrTy,
3435 NULL);
3436 CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy);
3437 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
3438
3439 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3440
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003441 // struct _objc_class {
3442 // Class isa;
3443 // Class super_class;
3444 // char *name;
3445 // long version;
3446 // long info;
3447 // long instance_size;
3448 // struct _objc_ivar_list *ivars;
3449 // struct _objc_method_list *methods;
3450 // struct _objc_cache *cache;
3451 // struct _objc_protocol_list *protocols;
3452 // char *ivar_layout;
3453 // struct _objc_class_ext *ext;
3454 // };
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003455 T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3456 llvm::PointerType::getUnqual(ClassTyHolder),
3457 Int8PtrTy,
3458 LongTy,
3459 LongTy,
3460 LongTy,
3461 IvarListPtrTy,
3462 MethodListPtrTy,
3463 CachePtrTy,
3464 ProtocolListPtrTy,
3465 Int8PtrTy,
3466 ClassExtensionPtrTy,
3467 NULL);
3468 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T);
3469
3470 ClassTy = cast<llvm::StructType>(ClassTyHolder.get());
3471 CGM.getModule().addTypeName("struct._objc_class", ClassTy);
3472 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
3473
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003474 // struct _objc_category {
3475 // char *category_name;
3476 // char *class_name;
3477 // struct _objc_method_list *instance_method;
3478 // struct _objc_method_list *class_method;
3479 // uint32_t size; // sizeof(struct _objc_category)
3480 // struct _objc_property_list *instance_properties;// category's @property
3481 // }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003482 CategoryTy = llvm::StructType::get(Int8PtrTy,
3483 Int8PtrTy,
3484 MethodListPtrTy,
3485 MethodListPtrTy,
3486 ProtocolListPtrTy,
3487 IntTy,
3488 PropertyListPtrTy,
3489 NULL);
3490 CGM.getModule().addTypeName("struct._objc_category", CategoryTy);
3491
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003492 // Global metadata structures
3493
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003494 // struct _objc_symtab {
3495 // long sel_ref_cnt;
3496 // SEL *refs;
3497 // short cls_def_cnt;
3498 // short cat_def_cnt;
3499 // char *defs[cls_def_cnt + cat_def_cnt];
3500 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003501 SymtabTy = llvm::StructType::get(LongTy,
3502 SelectorPtrTy,
3503 ShortTy,
3504 ShortTy,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003505 llvm::ArrayType::get(Int8PtrTy, 0),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003506 NULL);
3507 CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy);
3508 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
3509
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003510 // struct _objc_module {
3511 // long version;
3512 // long size; // sizeof(struct _objc_module)
3513 // char *name;
3514 // struct _objc_symtab* symtab;
3515 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003516 ModuleTy =
3517 llvm::StructType::get(LongTy,
3518 LongTy,
3519 Int8PtrTy,
3520 SymtabPtrTy,
3521 NULL);
3522 CGM.getModule().addTypeName("struct._objc_module", ModuleTy);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003523
Daniel Dunbar49f66022008-09-24 03:38:44 +00003524 // Message send functions.
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003525
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003526 // id objc_msgSend (id, SEL, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003527 std::vector<const llvm::Type*> Params;
3528 Params.push_back(ObjectPtrTy);
3529 Params.push_back(SelectorPtrTy);
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003530 MessageSendFn =
3531 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3532 Params,
3533 true),
3534 "objc_msgSend");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003535
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003536 // id objc_msgSend_stret (id, SEL, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003537 Params.clear();
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003538 Params.push_back(ObjectPtrTy);
3539 Params.push_back(SelectorPtrTy);
3540 MessageSendStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003541 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3542 Params,
3543 true),
3544 "objc_msgSend_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00003545
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003546 //
Daniel Dunbar5669e572008-10-17 03:24:53 +00003547 Params.clear();
3548 Params.push_back(ObjectPtrTy);
3549 Params.push_back(SelectorPtrTy);
3550 // FIXME: This should be long double on x86_64?
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003551 // [double | long double] objc_msgSend_fpret(id self, SEL op, ...)
Daniel Dunbar5669e572008-10-17 03:24:53 +00003552 MessageSendFpretFn =
3553 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::DoubleTy,
3554 Params,
3555 true),
3556 "objc_msgSend_fpret");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003557
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003558 // id objc_msgSendSuper(struct objc_super *super, SEL op, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003559 Params.clear();
3560 Params.push_back(SuperPtrTy);
3561 Params.push_back(SelectorPtrTy);
3562 MessageSendSuperFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003563 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3564 Params,
3565 true),
3566 "objc_msgSendSuper");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003567
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003568 // void objc_msgSendSuper_stret(void * stretAddr, struct objc_super *super,
3569 // SEL op, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003570 Params.clear();
3571 Params.push_back(Int8PtrTy);
3572 Params.push_back(SuperPtrTy);
3573 Params.push_back(SelectorPtrTy);
3574 MessageSendSuperStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003575 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3576 Params,
3577 true),
3578 "objc_msgSendSuper_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00003579
3580 // There is no objc_msgSendSuper_fpret? How can that work?
3581 MessageSendSuperFpretFn = MessageSendSuperFn;
Anders Carlsson2abd89c2008-08-31 04:05:03 +00003582
Anders Carlsson124526b2008-09-09 10:10:21 +00003583 // FIXME: This is the size of the setjmp buffer and should be
3584 // target specific. 18 is what's used on 32-bit X86.
3585 uint64_t SetJmpBufferSize = 18;
3586
3587 // Exceptions
3588 const llvm::Type *StackPtrTy =
Daniel Dunbar10004912008-09-27 06:32:25 +00003589 llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4);
Anders Carlsson124526b2008-09-09 10:10:21 +00003590
3591 ExceptionDataTy =
3592 llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty,
3593 SetJmpBufferSize),
3594 StackPtrTy, NULL);
3595 CGM.getModule().addTypeName("struct._objc_exception_data",
3596 ExceptionDataTy);
3597
3598 Params.clear();
Anders Carlsson124526b2008-09-09 10:10:21 +00003599 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
3600 ExceptionTryEnterFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003601 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3602 Params,
3603 false),
3604 "objc_exception_try_enter");
Anders Carlsson124526b2008-09-09 10:10:21 +00003605 ExceptionTryExitFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003606 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3607 Params,
3608 false),
3609 "objc_exception_try_exit");
Anders Carlsson124526b2008-09-09 10:10:21 +00003610 ExceptionExtractFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003611 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3612 Params,
3613 false),
3614 "objc_exception_extract");
Anders Carlsson124526b2008-09-09 10:10:21 +00003615
3616 Params.clear();
3617 Params.push_back(ClassPtrTy);
3618 Params.push_back(ObjectPtrTy);
3619 ExceptionMatchFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003620 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
3621 Params,
3622 false),
3623 "objc_exception_match");
Chris Lattner10cac6f2008-11-15 21:26:17 +00003624
Anders Carlsson124526b2008-09-09 10:10:21 +00003625 Params.clear();
3626 Params.push_back(llvm::PointerType::getUnqual(llvm::Type::Int32Ty));
3627 SetJmpFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003628 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
3629 Params,
3630 false),
3631 "_setjmp");
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00003632
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003633}
3634
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003635ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003636: ObjCCommonTypesHelper(cgm)
3637{
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003638 // struct _method_list_t {
3639 // uint32_t entsize; // sizeof(struct _objc_method)
3640 // uint32_t method_count;
3641 // struct _objc_method method_list[method_count];
3642 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003643 MethodListnfABITy = llvm::StructType::get(IntTy,
3644 IntTy,
3645 llvm::ArrayType::get(MethodTy, 0),
3646 NULL);
3647 CGM.getModule().addTypeName("struct.__method_list_t",
3648 MethodListnfABITy);
3649 // struct method_list_t *
3650 MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003651
3652 // struct _protocol_t {
3653 // id isa; // NULL
3654 // const char * const protocol_name;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003655 // const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003656 // const struct method_list_t * const instance_methods;
3657 // const struct method_list_t * const class_methods;
3658 // const struct method_list_t *optionalInstanceMethods;
3659 // const struct method_list_t *optionalClassMethods;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003660 // const struct _prop_list_t * properties;
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003661 // const uint32_t size; // sizeof(struct _protocol_t)
3662 // const uint32_t flags; // = 0
3663 // }
3664
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003665 // Holder for struct _protocol_list_t *
3666 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3667
3668 ProtocolnfABITy = llvm::StructType::get(ObjectPtrTy,
3669 Int8PtrTy,
3670 llvm::PointerType::getUnqual(
3671 ProtocolListTyHolder),
3672 MethodListnfABIPtrTy,
3673 MethodListnfABIPtrTy,
3674 MethodListnfABIPtrTy,
3675 MethodListnfABIPtrTy,
3676 PropertyListPtrTy,
3677 IntTy,
3678 IntTy,
3679 NULL);
3680 CGM.getModule().addTypeName("struct._protocol_t",
3681 ProtocolnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003682
3683 // struct _protocol_t*
3684 ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003685
Fariborz Jahanianda320092009-01-29 19:24:30 +00003686 // struct _protocol_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003687 // long protocol_count; // Note, this is 32/64 bit
Daniel Dunbar948e2582009-02-15 07:36:20 +00003688 // struct _protocol_t *[protocol_count];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003689 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003690 ProtocolListnfABITy = llvm::StructType::get(LongTy,
3691 llvm::ArrayType::get(
Daniel Dunbar948e2582009-02-15 07:36:20 +00003692 ProtocolnfABIPtrTy, 0),
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003693 NULL);
3694 CGM.getModule().addTypeName("struct._objc_protocol_list",
3695 ProtocolListnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003696 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(
3697 ProtocolListnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003698
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003699 // struct _objc_protocol_list*
3700 ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003701
3702 // struct _ivar_t {
3703 // unsigned long int *offset; // pointer to ivar offset location
3704 // char *name;
3705 // char *type;
3706 // uint32_t alignment;
3707 // uint32_t size;
3708 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003709 IvarnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(LongTy),
3710 Int8PtrTy,
3711 Int8PtrTy,
3712 IntTy,
3713 IntTy,
3714 NULL);
3715 CGM.getModule().addTypeName("struct._ivar_t", IvarnfABITy);
3716
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003717 // struct _ivar_list_t {
3718 // uint32 entsize; // sizeof(struct _ivar_t)
3719 // uint32 count;
3720 // struct _iver_t list[count];
3721 // }
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003722 IvarListnfABITy = llvm::StructType::get(IntTy,
3723 IntTy,
3724 llvm::ArrayType::get(
3725 IvarnfABITy, 0),
3726 NULL);
3727 CGM.getModule().addTypeName("struct._ivar_list_t", IvarListnfABITy);
3728
3729 IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003730
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003731 // struct _class_ro_t {
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003732 // uint32_t const flags;
3733 // uint32_t const instanceStart;
3734 // uint32_t const instanceSize;
3735 // uint32_t const reserved; // only when building for 64bit targets
3736 // const uint8_t * const ivarLayout;
3737 // const char *const name;
3738 // const struct _method_list_t * const baseMethods;
3739 // const struct _objc_protocol_list *const baseProtocols;
3740 // const struct _ivar_list_t *const ivars;
3741 // const uint8_t * const weakIvarLayout;
3742 // const struct _prop_list_t * const properties;
3743 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003744
3745 // FIXME. Add 'reserved' field in 64bit abi mode!
3746 ClassRonfABITy = llvm::StructType::get(IntTy,
3747 IntTy,
3748 IntTy,
3749 Int8PtrTy,
3750 Int8PtrTy,
3751 MethodListnfABIPtrTy,
3752 ProtocolListnfABIPtrTy,
3753 IvarListnfABIPtrTy,
3754 Int8PtrTy,
3755 PropertyListPtrTy,
3756 NULL);
3757 CGM.getModule().addTypeName("struct._class_ro_t",
3758 ClassRonfABITy);
3759
3760 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
3761 std::vector<const llvm::Type*> Params;
3762 Params.push_back(ObjectPtrTy);
3763 Params.push_back(SelectorPtrTy);
3764 ImpnfABITy = llvm::PointerType::getUnqual(
3765 llvm::FunctionType::get(ObjectPtrTy, Params, false));
3766
3767 // struct _class_t {
3768 // struct _class_t *isa;
3769 // struct _class_t * const superclass;
3770 // void *cache;
3771 // IMP *vtable;
3772 // struct class_ro_t *ro;
3773 // }
3774
3775 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3776 ClassnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3777 llvm::PointerType::getUnqual(ClassTyHolder),
3778 CachePtrTy,
3779 llvm::PointerType::getUnqual(ImpnfABITy),
3780 llvm::PointerType::getUnqual(
3781 ClassRonfABITy),
3782 NULL);
3783 CGM.getModule().addTypeName("struct._class_t", ClassnfABITy);
3784
3785 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(
3786 ClassnfABITy);
3787
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003788 // LLVM for struct _class_t *
3789 ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy);
3790
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003791 // struct _category_t {
3792 // const char * const name;
3793 // struct _class_t *const cls;
3794 // const struct _method_list_t * const instance_methods;
3795 // const struct _method_list_t * const class_methods;
3796 // const struct _protocol_list_t * const protocols;
3797 // const struct _prop_list_t * const properties;
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003798 // }
3799 CategorynfABITy = llvm::StructType::get(Int8PtrTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003800 ClassnfABIPtrTy,
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003801 MethodListnfABIPtrTy,
3802 MethodListnfABIPtrTy,
3803 ProtocolListnfABIPtrTy,
3804 PropertyListPtrTy,
3805 NULL);
3806 CGM.getModule().addTypeName("struct._category_t", CategorynfABITy);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003807
3808 // New types for nonfragile abi messaging.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003809 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3810 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003811
3812 // MessageRefTy - LLVM for:
3813 // struct _message_ref_t {
3814 // IMP messenger;
3815 // SEL name;
3816 // };
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003817
3818 // First the clang type for struct _message_ref_t
3819 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3820 SourceLocation(),
3821 &Ctx.Idents.get("_message_ref_t"));
3822 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3823 Ctx.VoidPtrTy, 0, false));
3824 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3825 Ctx.getObjCSelType(), 0, false));
3826 RD->completeDefinition(Ctx);
3827
3828 MessageRefCTy = Ctx.getTagDeclType(RD);
3829 MessageRefCPtrTy = Ctx.getPointerType(MessageRefCTy);
3830 MessageRefTy = cast<llvm::StructType>(Types.ConvertType(MessageRefCTy));
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003831
3832 // MessageRefPtrTy - LLVM for struct _message_ref_t*
3833 MessageRefPtrTy = llvm::PointerType::getUnqual(MessageRefTy);
3834
3835 // SuperMessageRefTy - LLVM for:
3836 // struct _super_message_ref_t {
3837 // SUPER_IMP messenger;
3838 // SEL name;
3839 // };
3840 SuperMessageRefTy = llvm::StructType::get(ImpnfABITy,
3841 SelectorPtrTy,
3842 NULL);
3843 CGM.getModule().addTypeName("struct._super_message_ref_t", SuperMessageRefTy);
3844
3845 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
3846 SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy);
3847
3848 // id objc_msgSend_fixup (id, struct message_ref_t*, ...)
3849 Params.clear();
3850 Params.push_back(ObjectPtrTy);
3851 Params.push_back(MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00003852 MessengerTy = llvm::FunctionType::get(ObjectPtrTy,
3853 Params,
3854 true);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003855 MessageSendFixupFn =
Fariborz Jahanianef163782009-02-05 01:13:09 +00003856 CGM.CreateRuntimeFunction(MessengerTy,
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003857 "objc_msgSend_fixup");
3858
3859 // id objc_msgSend_fpret_fixup (id, struct message_ref_t*, ...)
3860 MessageSendFpretFixupFn =
3861 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3862 Params,
3863 true),
3864 "objc_msgSend_fpret_fixup");
3865
3866 // id objc_msgSend_stret_fixup (id, struct message_ref_t*, ...)
3867 MessageSendStretFixupFn =
3868 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3869 Params,
3870 true),
3871 "objc_msgSend_stret_fixup");
3872
3873 // id objc_msgSendId_fixup (id, struct message_ref_t*, ...)
3874 MessageSendIdFixupFn =
3875 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3876 Params,
3877 true),
3878 "objc_msgSendId_fixup");
3879
3880
3881 // id objc_msgSendId_stret_fixup (id, struct message_ref_t*, ...)
3882 MessageSendIdStretFixupFn =
3883 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3884 Params,
3885 true),
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003886 "objc_msgSendId_stret_fixup");
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003887
3888 // id objc_msgSendSuper2_fixup (struct objc_super *,
3889 // struct _super_message_ref_t*, ...)
3890 Params.clear();
3891 Params.push_back(SuperPtrTy);
3892 Params.push_back(SuperMessageRefPtrTy);
3893 MessageSendSuper2FixupFn =
3894 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3895 Params,
3896 true),
3897 "objc_msgSendSuper2_fixup");
3898
3899
3900 // id objc_msgSendSuper2_stret_fixup (struct objc_super *,
3901 // struct _super_message_ref_t*, ...)
3902 MessageSendSuper2StretFixupFn =
3903 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3904 Params,
3905 true),
3906 "objc_msgSendSuper2_stret_fixup");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00003907
3908 Params.clear();
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00003909 Params.push_back(Int8PtrTy);
3910 UnwindResumeOrRethrowFn =
3911 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3912 Params,
3913 false),
3914 "_Unwind_Resume_or_Rethrow");
Daniel Dunbare588b992009-03-01 04:46:24 +00003915 ObjCBeginCatchFn =
3916 CGM.CreateRuntimeFunction(llvm::FunctionType::get(Int8PtrTy,
3917 Params,
3918 false),
3919 "objc_begin_catch");
3920
3921 Params.clear();
3922 ObjCEndCatchFn =
3923 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3924 Params,
3925 false),
3926 "objc_end_catch");
3927
3928 // struct objc_typeinfo {
3929 // const void** vtable; // objc_ehtype_vtable + 2
3930 // const char* name; // c++ typeinfo string
3931 // Class cls;
3932 // };
3933 EHTypeTy = llvm::StructType::get(llvm::PointerType::getUnqual(Int8PtrTy),
3934 Int8PtrTy,
3935 ClassnfABIPtrTy,
3936 NULL);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00003937 CGM.getModule().addTypeName("struct._objc_typeinfo", EHTypeTy);
Daniel Dunbare588b992009-03-01 04:46:24 +00003938 EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy);
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003939}
3940
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003941llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() {
3942 FinishNonFragileABIModule();
3943
3944 return NULL;
3945}
3946
3947void CGObjCNonFragileABIMac::FinishNonFragileABIModule() {
3948 // nonfragile abi has no module definition.
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003949
3950 // Build list of all implemented classe addresses in array
3951 // L_OBJC_LABEL_CLASS_$.
3952 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CLASS_$
3953 // list of 'nonlazy' implementations (defined as those with a +load{}
3954 // method!!).
3955 unsigned NumClasses = DefinedClasses.size();
3956 if (NumClasses) {
3957 std::vector<llvm::Constant*> Symbols(NumClasses);
3958 for (unsigned i=0; i<NumClasses; i++)
3959 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
3960 ObjCTypes.Int8PtrTy);
3961 llvm::Constant* Init =
3962 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
3963 NumClasses),
3964 Symbols);
3965
3966 llvm::GlobalVariable *GV =
3967 new llvm::GlobalVariable(Init->getType(), false,
3968 llvm::GlobalValue::InternalLinkage,
3969 Init,
3970 "\01L_OBJC_LABEL_CLASS_$",
3971 &CGM.getModule());
Daniel Dunbar58a29122009-03-09 22:18:41 +00003972 GV->setAlignment(8);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003973 GV->setSection("__DATA, __objc_classlist, regular, no_dead_strip");
3974 UsedGlobals.push_back(GV);
3975 }
3976
3977 // Build list of all implemented category addresses in array
3978 // L_OBJC_LABEL_CATEGORY_$.
3979 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CATEGORY_$
3980 // list of 'nonlazy' category implementations (defined as those with a +load{}
3981 // method!!).
3982 unsigned NumCategory = DefinedCategories.size();
3983 if (NumCategory) {
3984 std::vector<llvm::Constant*> Symbols(NumCategory);
3985 for (unsigned i=0; i<NumCategory; i++)
3986 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedCategories[i],
3987 ObjCTypes.Int8PtrTy);
3988 llvm::Constant* Init =
3989 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
3990 NumCategory),
3991 Symbols);
3992
3993 llvm::GlobalVariable *GV =
3994 new llvm::GlobalVariable(Init->getType(), false,
3995 llvm::GlobalValue::InternalLinkage,
3996 Init,
3997 "\01L_OBJC_LABEL_CATEGORY_$",
3998 &CGM.getModule());
Daniel Dunbar58a29122009-03-09 22:18:41 +00003999 GV->setAlignment(8);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004000 GV->setSection("__DATA, __objc_catlist, regular, no_dead_strip");
4001 UsedGlobals.push_back(GV);
4002 }
4003
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004004 // static int L_OBJC_IMAGE_INFO[2] = { 0, flags };
4005 // FIXME. flags can be 0 | 1 | 2 | 6. For now just use 0
4006 std::vector<llvm::Constant*> Values(2);
4007 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, 0);
Fariborz Jahanian067986e2009-02-24 21:08:09 +00004008 unsigned int flags = 0;
Fariborz Jahanian66a5c2c2009-02-24 23:34:44 +00004009 // FIXME: Fix and continue?
4010 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
4011 flags |= eImageInfo_GarbageCollected;
4012 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
4013 flags |= eImageInfo_GCOnly;
Fariborz Jahanian067986e2009-02-24 21:08:09 +00004014 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004015 llvm::Constant* Init = llvm::ConstantArray::get(
4016 llvm::ArrayType::get(ObjCTypes.IntTy, 2),
4017 Values);
4018 llvm::GlobalVariable *IMGV =
4019 new llvm::GlobalVariable(Init->getType(), false,
4020 llvm::GlobalValue::InternalLinkage,
4021 Init,
4022 "\01L_OBJC_IMAGE_INFO",
4023 &CGM.getModule());
4024 IMGV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
4025 UsedGlobals.push_back(IMGV);
4026
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004027 std::vector<llvm::Constant*> Used;
4028 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
4029 e = UsedGlobals.end(); i != e; ++i) {
4030 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
4031 }
4032
4033 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
4034 llvm::GlobalValue *GV =
4035 new llvm::GlobalVariable(AT, false,
4036 llvm::GlobalValue::AppendingLinkage,
4037 llvm::ConstantArray::get(AT, Used),
4038 "llvm.used",
4039 &CGM.getModule());
4040
4041 GV->setSection("llvm.metadata");
4042
4043}
4044
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004045// Metadata flags
4046enum MetaDataDlags {
4047 CLS = 0x0,
4048 CLS_META = 0x1,
4049 CLS_ROOT = 0x2,
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004050 OBJC2_CLS_HIDDEN = 0x10,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004051 CLS_EXCEPTION = 0x20
4052};
4053/// BuildClassRoTInitializer - generate meta-data for:
4054/// struct _class_ro_t {
4055/// uint32_t const flags;
4056/// uint32_t const instanceStart;
4057/// uint32_t const instanceSize;
4058/// uint32_t const reserved; // only when building for 64bit targets
4059/// const uint8_t * const ivarLayout;
4060/// const char *const name;
4061/// const struct _method_list_t * const baseMethods;
Fariborz Jahanianda320092009-01-29 19:24:30 +00004062/// const struct _protocol_list_t *const baseProtocols;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004063/// const struct _ivar_list_t *const ivars;
4064/// const uint8_t * const weakIvarLayout;
4065/// const struct _prop_list_t * const properties;
4066/// }
4067///
4068llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer(
4069 unsigned flags,
4070 unsigned InstanceStart,
4071 unsigned InstanceSize,
4072 const ObjCImplementationDecl *ID) {
4073 std::string ClassName = ID->getNameAsString();
4074 std::vector<llvm::Constant*> Values(10); // 11 for 64bit targets!
4075 Values[ 0] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
4076 Values[ 1] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceStart);
4077 Values[ 2] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceSize);
4078 // FIXME. For 64bit targets add 0 here.
Fariborz Jahanianda320092009-01-29 19:24:30 +00004079 // FIXME. ivarLayout is currently null!
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00004080 Values[ 3] = GetIvarLayoutName(0, ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004081 Values[ 4] = GetClassName(ID->getIdentifier());
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004082 // const struct _method_list_t * const baseMethods;
4083 std::vector<llvm::Constant*> Methods;
4084 std::string MethodListName("\01l_OBJC_$_");
4085 if (flags & CLS_META) {
4086 MethodListName += "CLASS_METHODS_" + ID->getNameAsString();
4087 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
4088 e = ID->classmeth_end(); i != e; ++i) {
4089 // Class methods should always be defined.
4090 Methods.push_back(GetMethodConstant(*i));
4091 }
4092 } else {
4093 MethodListName += "INSTANCE_METHODS_" + ID->getNameAsString();
4094 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
4095 e = ID->instmeth_end(); i != e; ++i) {
4096 // Instance methods should always be defined.
4097 Methods.push_back(GetMethodConstant(*i));
4098 }
Fariborz Jahanian939abce2009-01-28 22:46:49 +00004099 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
4100 e = ID->propimpl_end(); i != e; ++i) {
4101 ObjCPropertyImplDecl *PID = *i;
4102
4103 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize){
4104 ObjCPropertyDecl *PD = PID->getPropertyDecl();
4105
4106 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
4107 if (llvm::Constant *C = GetMethodConstant(MD))
4108 Methods.push_back(C);
4109 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
4110 if (llvm::Constant *C = GetMethodConstant(MD))
4111 Methods.push_back(C);
4112 }
4113 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004114 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004115 Values[ 5] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004116 "__DATA, __objc_const", Methods);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004117
4118 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4119 assert(OID && "CGObjCNonFragileABIMac::BuildClassRoTInitializer");
4120 Values[ 6] = EmitProtocolList("\01l_OBJC_CLASS_PROTOCOLS_$_"
4121 + OID->getNameAsString(),
4122 OID->protocol_begin(),
4123 OID->protocol_end());
4124
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004125 if (flags & CLS_META)
4126 Values[ 7] = llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4127 else
4128 Values[ 7] = EmitIvarList(ID);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004129 // FIXME. weakIvarLayout is currently null.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00004130 Values[ 8] = GetIvarLayoutName(0, ObjCTypes);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004131 if (flags & CLS_META)
4132 Values[ 9] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4133 else
4134 Values[ 9] =
4135 EmitPropertyList(
4136 "\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
4137 ID, ID->getClassInterface(), ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004138 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassRonfABITy,
4139 Values);
4140 llvm::GlobalVariable *CLASS_RO_GV =
4141 new llvm::GlobalVariable(ObjCTypes.ClassRonfABITy, false,
4142 llvm::GlobalValue::InternalLinkage,
4143 Init,
4144 (flags & CLS_META) ?
4145 std::string("\01l_OBJC_METACLASS_RO_$_")+ClassName :
4146 std::string("\01l_OBJC_CLASS_RO_$_")+ClassName,
4147 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004148 CLASS_RO_GV->setAlignment(
4149 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassRonfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004150 CLASS_RO_GV->setSection("__DATA, __objc_const");
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004151 return CLASS_RO_GV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004152
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004153}
4154
4155/// BuildClassMetaData - This routine defines that to-level meta-data
4156/// for the given ClassName for:
4157/// struct _class_t {
4158/// struct _class_t *isa;
4159/// struct _class_t * const superclass;
4160/// void *cache;
4161/// IMP *vtable;
4162/// struct class_ro_t *ro;
4163/// }
4164///
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004165llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassMetaData(
4166 std::string &ClassName,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004167 llvm::Constant *IsAGV,
4168 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004169 llvm::Constant *ClassRoGV,
4170 bool HiddenVisibility) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004171 std::vector<llvm::Constant*> Values(5);
4172 Values[0] = IsAGV;
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004173 Values[1] = SuperClassGV
4174 ? SuperClassGV
4175 : llvm::Constant::getNullValue(ObjCTypes.ClassnfABIPtrTy);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004176 Values[2] = ObjCEmptyCacheVar; // &ObjCEmptyCacheVar
4177 Values[3] = ObjCEmptyVtableVar; // &ObjCEmptyVtableVar
4178 Values[4] = ClassRoGV; // &CLASS_RO_GV
4179 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassnfABITy,
4180 Values);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004181 llvm::GlobalVariable *GV = GetClassGlobal(ClassName);
4182 GV->setInitializer(Init);
Fariborz Jahaniandd0db2a2009-01-31 01:07:39 +00004183 GV->setSection("__DATA, __objc_data");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004184 GV->setAlignment(
4185 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassnfABITy));
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004186 if (HiddenVisibility)
4187 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004188 return GV;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004189}
4190
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004191void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) {
4192 std::string ClassName = ID->getNameAsString();
4193 if (!ObjCEmptyCacheVar) {
4194 ObjCEmptyCacheVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004195 ObjCTypes.CacheTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004196 false,
4197 llvm::GlobalValue::ExternalLinkage,
4198 0,
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004199 "_objc_empty_cache",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004200 &CGM.getModule());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004201
4202 ObjCEmptyVtableVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004203 ObjCTypes.ImpnfABITy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004204 false,
4205 llvm::GlobalValue::ExternalLinkage,
4206 0,
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004207 "_objc_empty_vtable",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004208 &CGM.getModule());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004209 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004210 assert(ID->getClassInterface() &&
4211 "CGObjCNonFragileABIMac::GenerateClass - class is 0");
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004212 uint32_t InstanceStart =
4213 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassnfABITy);
4214 uint32_t InstanceSize = InstanceStart;
4215 uint32_t flags = CLS_META;
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004216 std::string ObjCMetaClassName(getMetaclassSymbolPrefix());
4217 std::string ObjCClassName(getClassSymbolPrefix());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004218
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004219 llvm::GlobalVariable *SuperClassGV, *IsAGV;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004220
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004221 bool classIsHidden = IsClassHidden(ID->getClassInterface());
4222 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004223 flags |= OBJC2_CLS_HIDDEN;
4224 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004225 // class is root
4226 flags |= CLS_ROOT;
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004227 SuperClassGV = GetClassGlobal(ObjCClassName + ClassName);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004228 IsAGV = GetClassGlobal(ObjCMetaClassName + ClassName, false);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004229 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004230 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004231 const ObjCInterfaceDecl *Root = ID->getClassInterface();
4232 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
4233 Root = Super;
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004234 IsAGV = GetClassGlobal(ObjCMetaClassName + Root->getNameAsString(), false);
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004235 // work on super class metadata symbol.
4236 std::string SuperClassName =
4237 ObjCMetaClassName + ID->getClassInterface()->getSuperClass()->getNameAsString();
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004238 SuperClassGV = GetClassGlobal(SuperClassName, false);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004239 }
4240 llvm::GlobalVariable *CLASS_RO_GV = BuildClassRoTInitializer(flags,
4241 InstanceStart,
4242 InstanceSize,ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004243 std::string TClassName = ObjCMetaClassName + ClassName;
4244 llvm::GlobalVariable *MetaTClass =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004245 BuildClassMetaData(TClassName, IsAGV, SuperClassGV, CLASS_RO_GV,
4246 classIsHidden);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004247
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004248 // Metadata for the class
4249 flags = CLS;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004250 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004251 flags |= OBJC2_CLS_HIDDEN;
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004252
4253 if (hasObjCExceptionAttribute(ID->getClassInterface()))
4254 flags |= CLS_EXCEPTION;
4255
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004256 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004257 flags |= CLS_ROOT;
4258 SuperClassGV = 0;
4259 }
4260 else {
4261 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004262 std::string RootClassName =
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004263 ID->getClassInterface()->getSuperClass()->getNameAsString();
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004264 SuperClassGV = GetClassGlobal(ObjCClassName + RootClassName);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004265 }
Fariborz Jahanianebf9ed32009-03-20 20:48:19 +00004266 // FIXME: Gross
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004267 InstanceStart = InstanceSize = 0;
4268 if (ObjCInterfaceDecl *OID =
4269 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface())) {
4270 // FIXME. Share this with the one in EmitIvarList.
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00004271 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID);
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004272
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00004273 RecordDecl::field_iterator firstField, lastField;
4274 const RecordDecl *RD = GetFirstIvarInRecord(OID, firstField, lastField);
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004275
4276 for (RecordDecl::field_iterator e = RD->field_end(),
4277 ifield = firstField; ifield != e; ++ifield)
4278 lastField = ifield;
4279
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004280 if (lastField != RD->field_end()) {
4281 FieldDecl *Field = *lastField;
4282 const llvm::Type *FieldTy =
4283 CGM.getTypes().ConvertTypeForMem(Field->getType());
4284 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00004285 InstanceSize = GetIvarBaseOffset(Layout, Field) + Size;
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004286 if (firstField == RD->field_end())
4287 InstanceStart = InstanceSize;
Fariborz Jahanian11894a42009-03-07 19:43:20 +00004288 else {
4289 Field = *firstField;
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00004290 InstanceStart = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanian11894a42009-03-07 19:43:20 +00004291 }
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004292 }
4293 }
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004294 CLASS_RO_GV = BuildClassRoTInitializer(flags,
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004295 InstanceStart,
4296 InstanceSize,
4297 ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004298
4299 TClassName = ObjCClassName + ClassName;
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004300 llvm::GlobalVariable *ClassMD =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004301 BuildClassMetaData(TClassName, MetaTClass, SuperClassGV, CLASS_RO_GV,
4302 classIsHidden);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004303 UsedGlobals.push_back(ClassMD);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004304 DefinedClasses.push_back(ClassMD);
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004305
4306 // Force the definition of the EHType if necessary.
4307 if (flags & CLS_EXCEPTION)
4308 GetInterfaceEHType(ID->getClassInterface(), true);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004309}
4310
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004311/// GenerateProtocolRef - This routine is called to generate code for
4312/// a protocol reference expression; as in:
4313/// @code
4314/// @protocol(Proto1);
4315/// @endcode
4316/// It generates a weak reference to l_OBJC_PROTOCOL_REFERENCE_$_Proto1
4317/// which will hold address of the protocol meta-data.
4318///
4319llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CGBuilderTy &Builder,
4320 const ObjCProtocolDecl *PD) {
4321
4322 llvm::Constant *Init = llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
4323 ObjCTypes.ExternalProtocolPtrTy);
4324
4325 std::string ProtocolName("\01l_OBJC_PROTOCOL_REFERENCE_$_");
4326 ProtocolName += PD->getNameAsCString();
4327
4328 llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName);
4329 if (PTGV)
4330 return Builder.CreateLoad(PTGV, false, "tmp");
4331 PTGV = new llvm::GlobalVariable(
4332 Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00004333 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004334 Init,
4335 ProtocolName,
4336 &CGM.getModule());
4337 PTGV->setSection("__DATA, __objc_protorefs, coalesced, no_dead_strip");
4338 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4339 UsedGlobals.push_back(PTGV);
4340 return Builder.CreateLoad(PTGV, false, "tmp");
4341}
4342
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004343/// GenerateCategory - Build metadata for a category implementation.
4344/// struct _category_t {
4345/// const char * const name;
4346/// struct _class_t *const cls;
4347/// const struct _method_list_t * const instance_methods;
4348/// const struct _method_list_t * const class_methods;
4349/// const struct _protocol_list_t * const protocols;
4350/// const struct _prop_list_t * const properties;
4351/// }
4352///
4353void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD)
4354{
4355 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004356 const char *Prefix = "\01l_OBJC_$_CATEGORY_";
4357 std::string ExtCatName(Prefix + Interface->getNameAsString()+
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004358 "_$_" + OCD->getNameAsString());
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004359 std::string ExtClassName(getClassSymbolPrefix() +
4360 Interface->getNameAsString());
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004361
4362 std::vector<llvm::Constant*> Values(6);
4363 Values[0] = GetClassName(OCD->getIdentifier());
4364 // meta-class entry symbol
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004365 llvm::GlobalVariable *ClassGV = GetClassGlobal(ExtClassName);
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004366 Values[1] = ClassGV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004367 std::vector<llvm::Constant*> Methods;
4368 std::string MethodListName(Prefix);
4369 MethodListName += "INSTANCE_METHODS_" + Interface->getNameAsString() +
4370 "_$_" + OCD->getNameAsString();
4371
4372 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
4373 e = OCD->instmeth_end(); i != e; ++i) {
4374 // Instance methods should always be defined.
4375 Methods.push_back(GetMethodConstant(*i));
4376 }
4377
4378 Values[2] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004379 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004380 Methods);
4381
4382 MethodListName = Prefix;
4383 MethodListName += "CLASS_METHODS_" + Interface->getNameAsString() + "_$_" +
4384 OCD->getNameAsString();
4385 Methods.clear();
4386 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
4387 e = OCD->classmeth_end(); i != e; ++i) {
4388 // Class methods should always be defined.
4389 Methods.push_back(GetMethodConstant(*i));
4390 }
4391
4392 Values[3] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004393 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004394 Methods);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004395 const ObjCCategoryDecl *Category =
4396 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Fariborz Jahanian943ed6f2009-02-13 17:52:22 +00004397 if (Category) {
4398 std::string ExtName(Interface->getNameAsString() + "_$_" +
4399 OCD->getNameAsString());
4400 Values[4] = EmitProtocolList("\01l_OBJC_CATEGORY_PROTOCOLS_$_"
4401 + Interface->getNameAsString() + "_$_"
4402 + Category->getNameAsString(),
4403 Category->protocol_begin(),
4404 Category->protocol_end());
4405 Values[5] =
4406 EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
4407 OCD, Category, ObjCTypes);
4408 }
4409 else {
4410 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4411 Values[5] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4412 }
4413
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004414 llvm::Constant *Init =
4415 llvm::ConstantStruct::get(ObjCTypes.CategorynfABITy,
4416 Values);
4417 llvm::GlobalVariable *GCATV
4418 = new llvm::GlobalVariable(ObjCTypes.CategorynfABITy,
4419 false,
4420 llvm::GlobalValue::InternalLinkage,
4421 Init,
4422 ExtCatName,
4423 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004424 GCATV->setAlignment(
4425 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.CategorynfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004426 GCATV->setSection("__DATA, __objc_const");
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004427 UsedGlobals.push_back(GCATV);
4428 DefinedCategories.push_back(GCATV);
4429}
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004430
4431/// GetMethodConstant - Return a struct objc_method constant for the
4432/// given method if it has been defined. The result is null if the
4433/// method has not been defined. The return value has type MethodPtrTy.
4434llvm::Constant *CGObjCNonFragileABIMac::GetMethodConstant(
4435 const ObjCMethodDecl *MD) {
4436 // FIXME: Use DenseMap::lookup
4437 llvm::Function *Fn = MethodDefinitions[MD];
4438 if (!Fn)
4439 return 0;
4440
4441 std::vector<llvm::Constant*> Method(3);
4442 Method[0] =
4443 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4444 ObjCTypes.SelectorPtrTy);
4445 Method[1] = GetMethodVarType(MD);
4446 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
4447 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
4448}
4449
4450/// EmitMethodList - Build meta-data for method declarations
4451/// struct _method_list_t {
4452/// uint32_t entsize; // sizeof(struct _objc_method)
4453/// uint32_t method_count;
4454/// struct _objc_method method_list[method_count];
4455/// }
4456///
4457llvm::Constant *CGObjCNonFragileABIMac::EmitMethodList(
4458 const std::string &Name,
4459 const char *Section,
4460 const ConstantVector &Methods) {
4461 // Return null for empty list.
4462 if (Methods.empty())
4463 return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy);
4464
4465 std::vector<llvm::Constant*> Values(3);
4466 // sizeof(struct _objc_method)
4467 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.MethodTy);
4468 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4469 // method_count
4470 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
4471 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
4472 Methods.size());
4473 Values[2] = llvm::ConstantArray::get(AT, Methods);
4474 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4475
4476 llvm::GlobalVariable *GV =
4477 new llvm::GlobalVariable(Init->getType(), false,
4478 llvm::GlobalValue::InternalLinkage,
4479 Init,
4480 Name,
4481 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004482 GV->setAlignment(
4483 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004484 GV->setSection(Section);
4485 UsedGlobals.push_back(GV);
4486 return llvm::ConstantExpr::getBitCast(GV,
4487 ObjCTypes.MethodListnfABIPtrTy);
4488}
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004489
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004490/// ObjCIvarOffsetVariable - Returns the ivar offset variable for
4491/// the given ivar.
4492///
4493llvm::GlobalVariable * CGObjCNonFragileABIMac::ObjCIvarOffsetVariable(
4494 std::string &Name,
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004495 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004496 const ObjCIvarDecl *Ivar) {
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004497 Name += "\01_OBJC_IVAR_$_" +
4498 getInterfaceDeclForIvar(ID, Ivar)->getNameAsString() + '.'
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004499 + Ivar->getNameAsString();
4500 llvm::GlobalVariable *IvarOffsetGV =
4501 CGM.getModule().getGlobalVariable(Name);
4502 if (!IvarOffsetGV)
4503 IvarOffsetGV =
4504 new llvm::GlobalVariable(ObjCTypes.LongTy,
4505 false,
4506 llvm::GlobalValue::ExternalLinkage,
4507 0,
4508 Name,
4509 &CGM.getModule());
4510 return IvarOffsetGV;
4511}
4512
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004513llvm::Constant * CGObjCNonFragileABIMac::EmitIvarOffsetVar(
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004514 const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004515 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004516 unsigned long int Offset) {
4517
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004518 assert(ID && "EmitIvarOffsetVar - null interface decl.");
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004519 std::string ExternalName("\01_OBJC_IVAR_$_" + ID->getNameAsString() + '.'
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004520 + Ivar->getNameAsString());
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004521 llvm::Constant *Init = llvm::ConstantInt::get(ObjCTypes.LongTy, Offset);
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004522 llvm::GlobalVariable *IvarOffsetGV =
4523 CGM.getModule().getGlobalVariable(ExternalName);
Fariborz Jahanian77c9fd22009-04-06 18:30:00 +00004524 if (IvarOffsetGV)
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004525 // ivar offset symbol already built due to user code referencing it.
4526 IvarOffsetGV->setInitializer(Init);
Fariborz Jahanian77c9fd22009-04-06 18:30:00 +00004527 else
4528 IvarOffsetGV =
4529 new llvm::GlobalVariable(Init->getType(),
4530 false,
4531 llvm::GlobalValue::ExternalLinkage,
4532 Init,
4533 ExternalName,
4534 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004535 IvarOffsetGV->setAlignment(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004536 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.LongTy));
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004537 // @private and @package have hidden visibility.
4538 bool globalVisibility = (Ivar->getAccessControl() == ObjCIvarDecl::Public ||
Fariborz Jahanian77c9fd22009-04-06 18:30:00 +00004539 Ivar->getAccessControl() == ObjCIvarDecl::Protected);
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004540 if (!globalVisibility)
4541 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahanian77c9fd22009-04-06 18:30:00 +00004542 else if (IsClassHidden(ID))
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004543 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahanian77c9fd22009-04-06 18:30:00 +00004544 else if (CGM.getLangOptions().getVisibilityMode() ==
Fariborz Jahanian77c9fd22009-04-06 18:30:00 +00004545 LangOptions::DefaultVisibility)
4546 IvarOffsetGV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004547 IvarOffsetGV->setSection("__DATA, __objc_const");
4548 UsedGlobals.push_back(IvarOffsetGV);
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004549 return IvarOffsetGV;
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004550}
4551
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004552/// EmitIvarList - Emit the ivar list for the given
4553/// implementation. If ForClass is true the list of class ivars
4554/// (i.e. metaclass ivars) is emitted, otherwise the list of
4555/// interface ivars will be emitted. The return value has type
4556/// IvarListnfABIPtrTy.
4557/// struct _ivar_t {
4558/// unsigned long int *offset; // pointer to ivar offset location
4559/// char *name;
4560/// char *type;
4561/// uint32_t alignment;
4562/// uint32_t size;
4563/// }
4564/// struct _ivar_list_t {
4565/// uint32 entsize; // sizeof(struct _ivar_t)
4566/// uint32 count;
4567/// struct _iver_t list[count];
4568/// }
4569///
4570llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList(
4571 const ObjCImplementationDecl *ID) {
4572
4573 std::vector<llvm::Constant*> Ivars, Ivar(5);
4574
4575 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4576 assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface");
4577
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004578 // FIXME. Consolidate this with similar code in GenerateClass.
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00004579 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00004580
4581 RecordDecl::field_iterator i,p;
4582 const RecordDecl *RD = GetFirstIvarInRecord(OID, i,p);
Fariborz Jahanian18191882009-03-31 18:11:23 +00004583 // collect declared and synthesized ivars in a small vector.
4584 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
4585 for (ObjCInterfaceDecl::ivar_iterator I = OID->ivar_begin(),
4586 E = OID->ivar_end(); I != E; ++I)
4587 OIvars.push_back(*I);
4588 for (ObjCInterfaceDecl::prop_iterator I = OID->prop_begin(),
4589 E = OID->prop_end(); I != E; ++I)
4590 if (ObjCIvarDecl *IV = (*I)->getPropertyIvarDecl())
4591 OIvars.push_back(IV);
Fariborz Jahanian99eee362009-04-01 19:37:34 +00004592
Fariborz Jahanian18191882009-03-31 18:11:23 +00004593 unsigned iv = 0;
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004594 for (RecordDecl::field_iterator e = RD->field_end(); i != e; ++i) {
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004595 FieldDecl *Field = *i;
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00004596 uint64_t offset = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanian18191882009-03-31 18:11:23 +00004597 Ivar[0] = EmitIvarOffsetVar(ID->getClassInterface(), OIvars[iv++], offset);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004598 if (Field->getIdentifier())
4599 Ivar[1] = GetMethodVarName(Field->getIdentifier());
4600 else
4601 Ivar[1] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Devang Patel7794bb82009-03-04 18:21:39 +00004602 Ivar[2] = GetMethodVarType(Field);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004603 const llvm::Type *FieldTy =
4604 CGM.getTypes().ConvertTypeForMem(Field->getType());
4605 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
4606 unsigned Align = CGM.getContext().getPreferredTypeAlign(
4607 Field->getType().getTypePtr()) >> 3;
4608 Align = llvm::Log2_32(Align);
4609 Ivar[3] = llvm::ConstantInt::get(ObjCTypes.IntTy, Align);
Fariborz Jahanian07236ba2009-01-27 22:27:56 +00004610 // NOTE. Size of a bitfield does not match gcc's, because of the way
4611 // bitfields are treated special in each. But I am told that 'size'
4612 // for bitfield ivars is ignored by the runtime so it does not matter.
4613 // (even if it matters, some day, there is enough info. to get the bitfield
4614 // right!
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004615 Ivar[4] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4616 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarnfABITy, Ivar));
4617 }
4618 // Return null for empty list.
4619 if (Ivars.empty())
4620 return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4621 std::vector<llvm::Constant*> Values(3);
4622 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.IvarnfABITy);
4623 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4624 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
4625 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarnfABITy,
4626 Ivars.size());
4627 Values[2] = llvm::ConstantArray::get(AT, Ivars);
4628 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4629 const char *Prefix = "\01l_OBJC_$_INSTANCE_VARIABLES_";
4630 llvm::GlobalVariable *GV =
4631 new llvm::GlobalVariable(Init->getType(), false,
4632 llvm::GlobalValue::InternalLinkage,
4633 Init,
4634 Prefix + OID->getNameAsString(),
4635 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004636 GV->setAlignment(
4637 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004638 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004639
4640 UsedGlobals.push_back(GV);
4641 return llvm::ConstantExpr::getBitCast(GV,
4642 ObjCTypes.IvarListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004643}
4644
4645llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef(
4646 const ObjCProtocolDecl *PD) {
4647 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4648
4649 if (!Entry) {
4650 // We use the initializer as a marker of whether this is a forward
4651 // reference or not. At module finalization we add the empty
4652 // contents for protocols which were referenced but never defined.
4653 Entry =
4654 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
4655 llvm::GlobalValue::ExternalLinkage,
4656 0,
4657 "\01l_OBJC_PROTOCOL_$_" + PD->getNameAsString(),
4658 &CGM.getModule());
4659 Entry->setSection("__DATA,__datacoal_nt,coalesced");
4660 UsedGlobals.push_back(Entry);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004661 }
4662
4663 return Entry;
4664}
4665
4666/// GetOrEmitProtocol - Generate the protocol meta-data:
4667/// @code
4668/// struct _protocol_t {
4669/// id isa; // NULL
4670/// const char * const protocol_name;
4671/// const struct _protocol_list_t * protocol_list; // super protocols
4672/// const struct method_list_t * const instance_methods;
4673/// const struct method_list_t * const class_methods;
4674/// const struct method_list_t *optionalInstanceMethods;
4675/// const struct method_list_t *optionalClassMethods;
4676/// const struct _prop_list_t * properties;
4677/// const uint32_t size; // sizeof(struct _protocol_t)
4678/// const uint32_t flags; // = 0
4679/// }
4680/// @endcode
4681///
4682
4683llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol(
4684 const ObjCProtocolDecl *PD) {
4685 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4686
4687 // Early exit if a defining object has already been generated.
4688 if (Entry && Entry->hasInitializer())
4689 return Entry;
4690
4691 const char *ProtocolName = PD->getNameAsCString();
4692
4693 // Construct method lists.
4694 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
4695 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
4696 for (ObjCProtocolDecl::instmeth_iterator i = PD->instmeth_begin(),
4697 e = PD->instmeth_end(); i != e; ++i) {
4698 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004699 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004700 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4701 OptInstanceMethods.push_back(C);
4702 } else {
4703 InstanceMethods.push_back(C);
4704 }
4705 }
4706
4707 for (ObjCProtocolDecl::classmeth_iterator i = PD->classmeth_begin(),
4708 e = PD->classmeth_end(); i != e; ++i) {
4709 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004710 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004711 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4712 OptClassMethods.push_back(C);
4713 } else {
4714 ClassMethods.push_back(C);
4715 }
4716 }
4717
4718 std::vector<llvm::Constant*> Values(10);
4719 // isa is NULL
4720 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ObjectPtrTy);
4721 Values[1] = GetClassName(PD->getIdentifier());
4722 Values[2] = EmitProtocolList(
4723 "\01l_OBJC_$_PROTOCOL_REFS_" + PD->getNameAsString(),
4724 PD->protocol_begin(),
4725 PD->protocol_end());
4726
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004727 Values[3] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004728 + PD->getNameAsString(),
4729 "__DATA, __objc_const",
4730 InstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004731 Values[4] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004732 + PD->getNameAsString(),
4733 "__DATA, __objc_const",
4734 ClassMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004735 Values[5] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004736 + PD->getNameAsString(),
4737 "__DATA, __objc_const",
4738 OptInstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004739 Values[6] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004740 + PD->getNameAsString(),
4741 "__DATA, __objc_const",
4742 OptClassMethods);
4743 Values[7] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + PD->getNameAsString(),
4744 0, PD, ObjCTypes);
4745 uint32_t Size =
4746 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolnfABITy);
4747 Values[8] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4748 Values[9] = llvm::Constant::getNullValue(ObjCTypes.IntTy);
4749 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolnfABITy,
4750 Values);
4751
4752 if (Entry) {
4753 // Already created, fix the linkage and update the initializer.
Mike Stump286acbd2009-03-07 16:33:28 +00004754 Entry->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004755 Entry->setInitializer(Init);
4756 } else {
4757 Entry =
4758 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004759 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004760 Init,
4761 std::string("\01l_OBJC_PROTOCOL_$_")+ProtocolName,
4762 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004763 Entry->setAlignment(
4764 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABITy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004765 Entry->setSection("__DATA,__datacoal_nt,coalesced");
Fariborz Jahanianda320092009-01-29 19:24:30 +00004766 }
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004767 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
4768
4769 // Use this protocol meta-data to build protocol list table in section
4770 // __DATA, __objc_protolist
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004771 llvm::GlobalVariable *PTGV = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004772 ObjCTypes.ProtocolnfABIPtrTy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004773 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004774 Entry,
4775 std::string("\01l_OBJC_LABEL_PROTOCOL_$_")
4776 +ProtocolName,
4777 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004778 PTGV->setAlignment(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004779 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABIPtrTy));
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004780 PTGV->setSection("__DATA, __objc_protolist");
4781 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4782 UsedGlobals.push_back(PTGV);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004783 return Entry;
4784}
4785
4786/// EmitProtocolList - Generate protocol list meta-data:
4787/// @code
4788/// struct _protocol_list_t {
4789/// long protocol_count; // Note, this is 32/64 bit
4790/// struct _protocol_t[protocol_count];
4791/// }
4792/// @endcode
4793///
4794llvm::Constant *
4795CGObjCNonFragileABIMac::EmitProtocolList(const std::string &Name,
4796 ObjCProtocolDecl::protocol_iterator begin,
4797 ObjCProtocolDecl::protocol_iterator end) {
4798 std::vector<llvm::Constant*> ProtocolRefs;
4799
Fariborz Jahanianda320092009-01-29 19:24:30 +00004800 // Just return null for empty protocol lists
Daniel Dunbar948e2582009-02-15 07:36:20 +00004801 if (begin == end)
Fariborz Jahanianda320092009-01-29 19:24:30 +00004802 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4803
Daniel Dunbar948e2582009-02-15 07:36:20 +00004804 // FIXME: We shouldn't need to do this lookup here, should we?
Fariborz Jahanianda320092009-01-29 19:24:30 +00004805 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
4806 if (GV)
Daniel Dunbar948e2582009-02-15 07:36:20 +00004807 return llvm::ConstantExpr::getBitCast(GV,
4808 ObjCTypes.ProtocolListnfABIPtrTy);
4809
4810 for (; begin != end; ++begin)
4811 ProtocolRefs.push_back(GetProtocolRef(*begin)); // Implemented???
4812
Fariborz Jahanianda320092009-01-29 19:24:30 +00004813 // This list is null terminated.
4814 ProtocolRefs.push_back(llvm::Constant::getNullValue(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004815 ObjCTypes.ProtocolnfABIPtrTy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004816
4817 std::vector<llvm::Constant*> Values(2);
4818 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
4819 Values[1] =
Daniel Dunbar948e2582009-02-15 07:36:20 +00004820 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolnfABIPtrTy,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004821 ProtocolRefs.size()),
4822 ProtocolRefs);
4823
4824 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4825 GV = new llvm::GlobalVariable(Init->getType(), false,
4826 llvm::GlobalValue::InternalLinkage,
4827 Init,
4828 Name,
4829 &CGM.getModule());
4830 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004831 GV->setAlignment(
4832 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004833 UsedGlobals.push_back(GV);
Daniel Dunbar948e2582009-02-15 07:36:20 +00004834 return llvm::ConstantExpr::getBitCast(GV,
4835 ObjCTypes.ProtocolListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004836}
4837
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004838/// GetMethodDescriptionConstant - This routine build following meta-data:
4839/// struct _objc_method {
4840/// SEL _cmd;
4841/// char *method_type;
4842/// char *_imp;
4843/// }
4844
4845llvm::Constant *
4846CGObjCNonFragileABIMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
4847 std::vector<llvm::Constant*> Desc(3);
4848 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4849 ObjCTypes.SelectorPtrTy);
4850 Desc[1] = GetMethodVarType(MD);
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004851 // Protocol methods have no implementation. So, this entry is always NULL.
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004852 Desc[2] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
4853 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Desc);
4854}
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004855
4856/// EmitObjCValueForIvar - Code Gen for nonfragile ivar reference.
4857/// This code gen. amounts to generating code for:
4858/// @code
4859/// (type *)((char *)base + _OBJC_IVAR_$_.ivar;
4860/// @encode
4861///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004862LValue CGObjCNonFragileABIMac::EmitObjCValueForIvar(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004863 CodeGen::CodeGenFunction &CGF,
4864 QualType ObjectTy,
4865 llvm::Value *BaseValue,
4866 const ObjCIvarDecl *Ivar,
4867 const FieldDecl *Field,
4868 unsigned CVRQualifiers) {
4869 assert(ObjectTy->isObjCInterfaceType() &&
4870 "CGObjCNonFragileABIMac::EmitObjCValueForIvar");
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004871 ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004872 std::string ExternalName;
4873 llvm::GlobalVariable *IvarOffsetGV =
4874 ObjCIvarOffsetVariable(ExternalName, ID, Ivar);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004875
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004876 // (char *) BaseValue
4877 llvm::Value *V = CGF.Builder.CreateBitCast(BaseValue,
4878 ObjCTypes.Int8PtrTy);
4879 llvm::Value *Offset = CGF.Builder.CreateLoad(IvarOffsetGV);
4880 // (char*)BaseValue + Offset_symbol
4881 V = CGF.Builder.CreateGEP(V, Offset, "add.ptr");
4882 // (type *)((char*)BaseValue + Offset_symbol)
4883 const llvm::Type *IvarTy =
4884 CGM.getTypes().ConvertType(Ivar->getType());
4885 llvm::Type *ptrIvarTy = llvm::PointerType::getUnqual(IvarTy);
4886 V = CGF.Builder.CreateBitCast(V, ptrIvarTy);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004887
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00004888 if (Ivar->isBitField()) {
4889 CodeGenTypes::BitFieldInfo bitFieldInfo =
4890 CGM.getTypes().getBitFieldInfo(Field);
4891 return LValue::MakeBitfield(V, bitFieldInfo.Begin, bitFieldInfo.Size,
4892 Field->getType()->isSignedIntegerType(),
4893 Field->getType().getCVRQualifiers()|CVRQualifiers);
4894 }
4895
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004896 LValue LV = LValue::MakeAddr(V,
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004897 Ivar->getType().getCVRQualifiers()|CVRQualifiers,
4898 CGM.getContext().getObjCGCAttrKind(Ivar->getType()));
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004899 LValue::SetObjCIvar(LV, true);
4900 return LV;
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004901}
4902
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004903llvm::Value *CGObjCNonFragileABIMac::EmitIvarOffset(
4904 CodeGen::CodeGenFunction &CGF,
4905 ObjCInterfaceDecl *Interface,
4906 const ObjCIvarDecl *Ivar) {
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004907 std::string ExternalName;
4908 llvm::GlobalVariable *IvarOffsetGV =
4909 ObjCIvarOffsetVariable(ExternalName, Interface, Ivar);
4910
4911 return CGF.Builder.CreateLoad(IvarOffsetGV, false, "ivar");
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004912}
4913
Fariborz Jahanian46551122009-02-04 00:22:57 +00004914CodeGen::RValue CGObjCNonFragileABIMac::EmitMessageSend(
4915 CodeGen::CodeGenFunction &CGF,
4916 QualType ResultType,
4917 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004918 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +00004919 QualType Arg0Ty,
4920 bool IsSuper,
4921 const CallArgList &CallArgs) {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004922 // FIXME. Even though IsSuper is passes. This function doese not
4923 // handle calls to 'super' receivers.
4924 CodeGenTypes &Types = CGM.getTypes();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004925 llvm::Value *Arg0 = Receiver;
4926 if (!IsSuper)
4927 Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy, "tmp");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004928
4929 // Find the message function name.
Fariborz Jahanianef163782009-02-05 01:13:09 +00004930 // FIXME. This is too much work to get the ABI-specific result type
4931 // needed to find the message name.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004932 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType,
4933 llvm::SmallVector<QualType, 16>());
4934 llvm::Constant *Fn;
4935 std::string Name("\01l_");
4936 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004937#if 0
4938 // unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004939 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
4940 Fn = ObjCTypes.MessageSendIdStretFixupFn;
4941 // FIXME. Is there a better way of getting these names.
4942 // They are available in RuntimeFunctions vector pair.
4943 Name += "objc_msgSendId_stret_fixup";
4944 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004945 else
4946#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004947 if (IsSuper) {
4948 Fn = ObjCTypes.MessageSendSuper2StretFixupFn;
4949 Name += "objc_msgSendSuper2_stret_fixup";
4950 }
4951 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004952 {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004953 Fn = ObjCTypes.MessageSendStretFixupFn;
4954 Name += "objc_msgSend_stret_fixup";
4955 }
4956 }
Fariborz Jahanian1a6b3682009-02-05 19:35:43 +00004957 else if (ResultType->isFloatingType() &&
4958 // Selection of frret API only happens in 32bit nonfragile ABI.
4959 CGM.getTargetData().getTypePaddedSize(ObjCTypes.LongTy) == 4) {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004960 Fn = ObjCTypes.MessageSendFpretFixupFn;
4961 Name += "objc_msgSend_fpret_fixup";
4962 }
4963 else {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004964#if 0
4965// unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004966 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
4967 Fn = ObjCTypes.MessageSendIdFixupFn;
4968 Name += "objc_msgSendId_fixup";
4969 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004970 else
4971#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004972 if (IsSuper) {
4973 Fn = ObjCTypes.MessageSendSuper2FixupFn;
4974 Name += "objc_msgSendSuper2_fixup";
4975 }
4976 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004977 {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004978 Fn = ObjCTypes.MessageSendFixupFn;
4979 Name += "objc_msgSend_fixup";
4980 }
4981 }
4982 Name += '_';
4983 std::string SelName(Sel.getAsString());
4984 // Replace all ':' in selector name with '_' ouch!
4985 for(unsigned i = 0; i < SelName.size(); i++)
4986 if (SelName[i] == ':')
4987 SelName[i] = '_';
4988 Name += SelName;
4989 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
4990 if (!GV) {
4991 // Build messafe ref table entry.
4992 std::vector<llvm::Constant*> Values(2);
4993 Values[0] = Fn;
4994 Values[1] = GetMethodVarName(Sel);
4995 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4996 GV = new llvm::GlobalVariable(Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00004997 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004998 Init,
4999 Name,
5000 &CGM.getModule());
5001 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
5002 GV->setAlignment(
5003 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.MessageRefTy));
5004 GV->setSection("__DATA, __objc_msgrefs, coalesced");
5005 UsedGlobals.push_back(GV);
5006 }
5007 llvm::Value *Arg1 = CGF.Builder.CreateBitCast(GV, ObjCTypes.MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00005008
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005009 CallArgList ActualArgs;
5010 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
5011 ActualArgs.push_back(std::make_pair(RValue::get(Arg1),
5012 ObjCTypes.MessageRefCPtrTy));
5013 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Fariborz Jahanianef163782009-02-05 01:13:09 +00005014 const CGFunctionInfo &FnInfo1 = Types.getFunctionInfo(ResultType, ActualArgs);
5015 llvm::Value *Callee = CGF.Builder.CreateStructGEP(Arg1, 0);
5016 Callee = CGF.Builder.CreateLoad(Callee);
Fariborz Jahanian3ab75bd2009-02-14 21:25:36 +00005017 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo1, true);
Fariborz Jahanianef163782009-02-05 01:13:09 +00005018 Callee = CGF.Builder.CreateBitCast(Callee,
5019 llvm::PointerType::getUnqual(FTy));
5020 return CGF.EmitCall(FnInfo1, Callee, ActualArgs);
Fariborz Jahanian46551122009-02-04 00:22:57 +00005021}
5022
5023/// Generate code for a message send expression in the nonfragile abi.
5024CodeGen::RValue CGObjCNonFragileABIMac::GenerateMessageSend(
5025 CodeGen::CodeGenFunction &CGF,
5026 QualType ResultType,
5027 Selector Sel,
5028 llvm::Value *Receiver,
5029 bool IsClassMessage,
5030 const CallArgList &CallArgs) {
Fariborz Jahanian46551122009-02-04 00:22:57 +00005031 return EmitMessageSend(CGF, ResultType, Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005032 Receiver, CGF.getContext().getObjCIdType(),
Fariborz Jahanian46551122009-02-04 00:22:57 +00005033 false, CallArgs);
5034}
5035
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005036llvm::GlobalVariable *
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005037CGObjCNonFragileABIMac::GetClassGlobal(const std::string &Name,
5038 bool AddToUsed) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005039 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5040
Daniel Dunbardfff2302009-03-02 05:18:14 +00005041 if (!GV) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005042 GV = new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
5043 llvm::GlobalValue::ExternalLinkage,
5044 0, Name, &CGM.getModule());
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005045 if (AddToUsed)
5046 UsedGlobals.push_back(GV);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005047 }
5048
5049 return GV;
5050}
5051
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005052llvm::Value *CGObjCNonFragileABIMac::EmitClassRef(CGBuilderTy &Builder,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005053 const ObjCInterfaceDecl *ID,
5054 bool IsSuper) {
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005055
5056 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
5057
5058 if (!Entry) {
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005059 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005060 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005061 Entry =
5062 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5063 llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005064 ClassGV,
5065 IsSuper ? "\01L_OBJC_CLASSLIST_SUP_REFS_$_"
5066 : "\01L_OBJC_CLASSLIST_REFERENCES_$_",
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005067 &CGM.getModule());
5068 Entry->setAlignment(
5069 CGM.getTargetData().getPrefTypeAlignment(
5070 ObjCTypes.ClassnfABIPtrTy));
5071
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005072 if (IsSuper)
Fariborz Jahanian21228b72009-02-26 22:30:39 +00005073 Entry->setSection("__DATA,__objc_superrefs,regular,no_dead_strip");
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005074 else
Fariborz Jahanian21228b72009-02-26 22:30:39 +00005075 Entry->setSection("__DATA,__objc_classrefs,regular,no_dead_strip");
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005076 UsedGlobals.push_back(Entry);
5077 }
5078
5079 return Builder.CreateLoad(Entry, false, "tmp");
5080}
5081
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005082/// EmitMetaClassRef - Return a Value * of the address of _class_t
5083/// meta-data
5084///
5085llvm::Value *CGObjCNonFragileABIMac::EmitMetaClassRef(CGBuilderTy &Builder,
5086 const ObjCInterfaceDecl *ID) {
5087 llvm::GlobalVariable * &Entry = MetaClassReferences[ID->getIdentifier()];
5088 if (Entry)
5089 return Builder.CreateLoad(Entry, false, "tmp");
5090
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005091 std::string MetaClassName(getMetaclassSymbolPrefix() + ID->getNameAsString());
5092 llvm::GlobalVariable *MetaClassGV = GetClassGlobal(MetaClassName, false);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005093 Entry =
5094 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5095 llvm::GlobalValue::InternalLinkage,
5096 MetaClassGV,
5097 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5098 &CGM.getModule());
5099 Entry->setAlignment(
5100 CGM.getTargetData().getPrefTypeAlignment(
5101 ObjCTypes.ClassnfABIPtrTy));
5102
5103 Entry->setSection("__OBJC,__objc_superrefs,regular,no_dead_strip");
5104 UsedGlobals.push_back(Entry);
5105
5106 return Builder.CreateLoad(Entry, false, "tmp");
5107}
5108
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005109/// GetClass - Return a reference to the class for the given interface
5110/// decl.
5111llvm::Value *CGObjCNonFragileABIMac::GetClass(CGBuilderTy &Builder,
5112 const ObjCInterfaceDecl *ID) {
5113 return EmitClassRef(Builder, ID);
5114}
5115
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005116/// Generates a message send where the super is the receiver. This is
5117/// a message send to self with special delivery semantics indicating
5118/// which class's method should be called.
5119CodeGen::RValue
5120CGObjCNonFragileABIMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
5121 QualType ResultType,
5122 Selector Sel,
5123 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005124 bool isCategoryImpl,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005125 llvm::Value *Receiver,
5126 bool IsClassMessage,
5127 const CodeGen::CallArgList &CallArgs) {
5128 // ...
5129 // Create and init a super structure; this is a (receiver, class)
5130 // pair we will pass to objc_msgSendSuper.
5131 llvm::Value *ObjCSuper =
5132 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
5133
5134 llvm::Value *ReceiverAsObject =
5135 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
5136 CGF.Builder.CreateStore(ReceiverAsObject,
5137 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
5138
5139 // If this is a class message the metaclass is passed as the target.
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005140 llvm::Value *Target;
5141 if (IsClassMessage) {
5142 if (isCategoryImpl) {
5143 // Message sent to "super' in a class method defined in
5144 // a category implementation.
5145 Target = EmitClassRef(CGF.Builder, Class, false);
5146 Target = CGF.Builder.CreateStructGEP(Target, 0);
5147 Target = CGF.Builder.CreateLoad(Target);
5148 }
5149 else
5150 Target = EmitMetaClassRef(CGF.Builder, Class);
5151 }
5152 else
5153 Target = EmitClassRef(CGF.Builder, Class, true);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005154
5155 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
5156 // and ObjCTypes types.
5157 const llvm::Type *ClassTy =
5158 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
5159 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
5160 CGF.Builder.CreateStore(Target,
5161 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
5162
5163 return EmitMessageSend(CGF, ResultType, Sel,
5164 ObjCSuper, ObjCTypes.SuperPtrCTy,
5165 true, CallArgs);
5166}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005167
5168llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CGBuilderTy &Builder,
5169 Selector Sel) {
5170 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
5171
5172 if (!Entry) {
5173 llvm::Constant *Casted =
5174 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
5175 ObjCTypes.SelectorPtrTy);
5176 Entry =
5177 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
5178 llvm::GlobalValue::InternalLinkage,
5179 Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
5180 &CGM.getModule());
5181 Entry->setSection("__DATA,__objc_selrefs,literal_pointers,no_dead_strip");
5182 UsedGlobals.push_back(Entry);
5183 }
5184
5185 return Builder.CreateLoad(Entry, false, "tmp");
5186}
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005187/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
5188/// objc_assign_ivar (id src, id *dst)
5189///
5190void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
5191 llvm::Value *src, llvm::Value *dst)
5192{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005193 const llvm::Type * SrcTy = src->getType();
5194 if (!isa<llvm::PointerType>(SrcTy)) {
5195 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5196 assert(Size <= 8 && "does not support size > 8");
5197 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5198 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005199 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5200 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005201 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5202 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5203 CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn,
5204 src, dst, "assignivar");
5205 return;
5206}
5207
5208/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
5209/// objc_assign_strongCast (id src, id *dst)
5210///
5211void CGObjCNonFragileABIMac::EmitObjCStrongCastAssign(
5212 CodeGen::CodeGenFunction &CGF,
5213 llvm::Value *src, llvm::Value *dst)
5214{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005215 const llvm::Type * SrcTy = src->getType();
5216 if (!isa<llvm::PointerType>(SrcTy)) {
5217 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5218 assert(Size <= 8 && "does not support size > 8");
5219 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5220 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005221 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5222 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005223 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5224 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5225 CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn,
5226 src, dst, "weakassign");
5227 return;
5228}
5229
5230/// EmitObjCWeakRead - Code gen for loading value of a __weak
5231/// object: objc_read_weak (id *src)
5232///
5233llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead(
5234 CodeGen::CodeGenFunction &CGF,
5235 llvm::Value *AddrWeakObj)
5236{
Eli Friedman8339b352009-03-07 03:57:15 +00005237 const llvm::Type* DestTy =
5238 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005239 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
5240 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
5241 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00005242 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005243 return read_weak;
5244}
5245
5246/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
5247/// objc_assign_weak (id src, id *dst)
5248///
5249void CGObjCNonFragileABIMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
5250 llvm::Value *src, llvm::Value *dst)
5251{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005252 const llvm::Type * SrcTy = src->getType();
5253 if (!isa<llvm::PointerType>(SrcTy)) {
5254 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5255 assert(Size <= 8 && "does not support size > 8");
5256 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5257 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005258 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5259 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005260 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5261 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5262 CGF.Builder.CreateCall2(ObjCTypes.GcAssignWeakFn,
5263 src, dst, "weakassign");
5264 return;
5265}
5266
5267/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
5268/// objc_assign_global (id src, id *dst)
5269///
5270void CGObjCNonFragileABIMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
5271 llvm::Value *src, llvm::Value *dst)
5272{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005273 const llvm::Type * SrcTy = src->getType();
5274 if (!isa<llvm::PointerType>(SrcTy)) {
5275 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5276 assert(Size <= 8 && "does not support size > 8");
5277 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5278 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005279 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5280 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005281 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5282 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5283 CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn,
5284 src, dst, "globalassign");
5285 return;
5286}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005287
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005288void
5289CGObjCNonFragileABIMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
5290 const Stmt &S) {
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005291 bool isTry = isa<ObjCAtTryStmt>(S);
5292 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
5293 llvm::BasicBlock *PrevLandingPad = CGF.getInvokeDest();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005294 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005295 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005296 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005297 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
5298
5299 // For @synchronized, call objc_sync_enter(sync.expr). The
5300 // evaluation of the expression must occur before we enter the
5301 // @synchronized. We can safely avoid a temp here because jumps into
5302 // @synchronized are illegal & this will dominate uses.
5303 llvm::Value *SyncArg = 0;
5304 if (!isTry) {
5305 SyncArg =
5306 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
5307 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005308 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005309 }
5310
5311 // Push an EH context entry, used for handling rethrows and jumps
5312 // through finally.
5313 CGF.PushCleanupBlock(FinallyBlock);
5314
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005315 CGF.setInvokeDest(TryHandler);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005316
5317 CGF.EmitBlock(TryBlock);
5318 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
5319 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
5320 CGF.EmitBranchThroughCleanup(FinallyEnd);
5321
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005322 // Emit the exception handler.
5323
5324 CGF.EmitBlock(TryHandler);
5325
5326 llvm::Value *llvm_eh_exception =
5327 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_exception);
5328 llvm::Value *llvm_eh_selector_i64 =
5329 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector_i64);
5330 llvm::Value *llvm_eh_typeid_for_i64 =
5331 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for_i64);
5332 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5333 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(Exc->getType(), "_rethrow");
5334
5335 llvm::SmallVector<llvm::Value*, 8> SelectorArgs;
5336 SelectorArgs.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005337 SelectorArgs.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005338
5339 // Construct the lists of (type, catch body) to handle.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005340 llvm::SmallVector<std::pair<const ParmVarDecl*, const Stmt*>, 8> Handlers;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005341 bool HasCatchAll = false;
5342 if (isTry) {
5343 if (const ObjCAtCatchStmt* CatchStmt =
5344 cast<ObjCAtTryStmt>(S).getCatchStmts()) {
5345 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005346 const ParmVarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
Steve Naroff7ba138a2009-03-03 19:52:17 +00005347 Handlers.push_back(std::make_pair(CatchDecl, CatchStmt->getCatchBody()));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005348
5349 // catch(...) always matches.
Steve Naroff7ba138a2009-03-03 19:52:17 +00005350 if (!CatchDecl) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005351 // Use i8* null here to signal this is a catch all, not a cleanup.
5352 llvm::Value *Null = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
5353 SelectorArgs.push_back(Null);
5354 HasCatchAll = true;
5355 break;
5356 }
5357
Daniel Dunbarede8de92009-03-06 00:01:21 +00005358 if (CGF.getContext().isObjCIdType(CatchDecl->getType()) ||
5359 CatchDecl->getType()->isObjCQualifiedIdType()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005360 llvm::Value *IDEHType =
5361 CGM.getModule().getGlobalVariable("OBJC_EHTYPE_id");
5362 if (!IDEHType)
5363 IDEHType =
5364 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5365 llvm::GlobalValue::ExternalLinkage,
5366 0, "OBJC_EHTYPE_id", &CGM.getModule());
5367 SelectorArgs.push_back(IDEHType);
5368 HasCatchAll = true;
5369 break;
5370 }
5371
5372 // All other types should be Objective-C interface pointer types.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005373 const PointerType *PT = CatchDecl->getType()->getAsPointerType();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005374 assert(PT && "Invalid @catch type.");
5375 const ObjCInterfaceType *IT =
5376 PT->getPointeeType()->getAsObjCInterfaceType();
5377 assert(IT && "Invalid @catch type.");
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005378 llvm::Value *EHType = GetInterfaceEHType(IT->getDecl(), false);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005379 SelectorArgs.push_back(EHType);
5380 }
5381 }
5382 }
5383
5384 // We use a cleanup unless there was already a catch all.
5385 if (!HasCatchAll) {
5386 SelectorArgs.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
Daniel Dunbarede8de92009-03-06 00:01:21 +00005387 Handlers.push_back(std::make_pair((const ParmVarDecl*) 0, (const Stmt*) 0));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005388 }
5389
5390 llvm::Value *Selector =
5391 CGF.Builder.CreateCall(llvm_eh_selector_i64,
5392 SelectorArgs.begin(), SelectorArgs.end(),
5393 "selector");
5394 for (unsigned i = 0, e = Handlers.size(); i != e; ++i) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005395 const ParmVarDecl *CatchParam = Handlers[i].first;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005396 const Stmt *CatchBody = Handlers[i].second;
5397
5398 llvm::BasicBlock *Next = 0;
5399
5400 // The last handler always matches.
5401 if (i + 1 != e) {
5402 assert(CatchParam && "Only last handler can be a catch all.");
5403
5404 llvm::BasicBlock *Match = CGF.createBasicBlock("match");
5405 Next = CGF.createBasicBlock("catch.next");
5406 llvm::Value *Id =
5407 CGF.Builder.CreateCall(llvm_eh_typeid_for_i64,
5408 CGF.Builder.CreateBitCast(SelectorArgs[i+2],
5409 ObjCTypes.Int8PtrTy));
5410 CGF.Builder.CreateCondBr(CGF.Builder.CreateICmpEQ(Selector, Id),
5411 Match, Next);
5412
5413 CGF.EmitBlock(Match);
5414 }
5415
5416 if (CatchBody) {
5417 llvm::BasicBlock *MatchEnd = CGF.createBasicBlock("match.end");
5418 llvm::BasicBlock *MatchHandler = CGF.createBasicBlock("match.handler");
5419
5420 // Cleanups must call objc_end_catch.
5421 //
5422 // FIXME: It seems incorrect for objc_begin_catch to be inside
5423 // this context, but this matches gcc.
5424 CGF.PushCleanupBlock(MatchEnd);
5425 CGF.setInvokeDest(MatchHandler);
5426
5427 llvm::Value *ExcObject =
5428 CGF.Builder.CreateCall(ObjCTypes.ObjCBeginCatchFn, Exc);
5429
5430 // Bind the catch parameter if it exists.
5431 if (CatchParam) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005432 ExcObject =
5433 CGF.Builder.CreateBitCast(ExcObject,
5434 CGF.ConvertType(CatchParam->getType()));
5435 // CatchParam is a ParmVarDecl because of the grammar
5436 // construction used to handle this, but for codegen purposes
5437 // we treat this as a local decl.
5438 CGF.EmitLocalBlockVarDecl(*CatchParam);
5439 CGF.Builder.CreateStore(ExcObject, CGF.GetAddrOfLocalVar(CatchParam));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005440 }
5441
5442 CGF.ObjCEHValueStack.push_back(ExcObject);
5443 CGF.EmitStmt(CatchBody);
5444 CGF.ObjCEHValueStack.pop_back();
5445
5446 CGF.EmitBranchThroughCleanup(FinallyEnd);
5447
5448 CGF.EmitBlock(MatchHandler);
5449
5450 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5451 // We are required to emit this call to satisfy LLVM, even
5452 // though we don't use the result.
5453 llvm::SmallVector<llvm::Value*, 8> Args;
5454 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005455 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005456 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5457 0));
5458 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5459 CGF.Builder.CreateStore(Exc, RethrowPtr);
5460 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5461
5462 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5463
5464 CGF.EmitBlock(MatchEnd);
5465
5466 // Unfortunately, we also have to generate another EH frame here
5467 // in case this throws.
5468 llvm::BasicBlock *MatchEndHandler =
5469 CGF.createBasicBlock("match.end.handler");
5470 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
5471 CGF.Builder.CreateInvoke(ObjCTypes.ObjCEndCatchFn,
5472 Cont, MatchEndHandler,
5473 Args.begin(), Args.begin());
5474
5475 CGF.EmitBlock(Cont);
5476 if (Info.SwitchBlock)
5477 CGF.EmitBlock(Info.SwitchBlock);
5478 if (Info.EndBlock)
5479 CGF.EmitBlock(Info.EndBlock);
5480
5481 CGF.EmitBlock(MatchEndHandler);
5482 Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5483 // We are required to emit this call to satisfy LLVM, even
5484 // though we don't use the result.
5485 Args.clear();
5486 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005487 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005488 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5489 0));
5490 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5491 CGF.Builder.CreateStore(Exc, RethrowPtr);
5492 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5493
5494 if (Next)
5495 CGF.EmitBlock(Next);
5496 } else {
5497 assert(!Next && "catchup should be last handler.");
5498
5499 CGF.Builder.CreateStore(Exc, RethrowPtr);
5500 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5501 }
5502 }
5503
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005504 // Pop the cleanup entry, the @finally is outside this cleanup
5505 // scope.
5506 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5507 CGF.setInvokeDest(PrevLandingPad);
5508
5509 CGF.EmitBlock(FinallyBlock);
5510
5511 if (isTry) {
5512 if (const ObjCAtFinallyStmt* FinallyStmt =
5513 cast<ObjCAtTryStmt>(S).getFinallyStmt())
5514 CGF.EmitStmt(FinallyStmt->getFinallyBody());
5515 } else {
5516 // Emit 'objc_sync_exit(expr)' as finally's sole statement for
5517 // @synchronized.
5518 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, SyncArg);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005519 }
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005520
5521 if (Info.SwitchBlock)
5522 CGF.EmitBlock(Info.SwitchBlock);
5523 if (Info.EndBlock)
5524 CGF.EmitBlock(Info.EndBlock);
5525
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005526 // Branch around the rethrow code.
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005527 CGF.EmitBranch(FinallyEnd);
5528
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005529 CGF.EmitBlock(FinallyRethrow);
5530 CGF.Builder.CreateCall(ObjCTypes.UnwindResumeOrRethrowFn,
5531 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005532 CGF.Builder.CreateUnreachable();
5533
5534 CGF.EmitBlock(FinallyEnd);
5535}
5536
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005537/// EmitThrowStmt - Generate code for a throw statement.
5538void CGObjCNonFragileABIMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
5539 const ObjCAtThrowStmt &S) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005540 llvm::Value *Exception;
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005541 if (const Expr *ThrowExpr = S.getThrowExpr()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005542 Exception = CGF.EmitScalarExpr(ThrowExpr);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005543 } else {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005544 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
5545 "Unexpected rethrow outside @catch block.");
5546 Exception = CGF.ObjCEHValueStack.back();
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005547 }
5548
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005549 llvm::Value *ExceptionAsObject =
5550 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
5551 llvm::BasicBlock *InvokeDest = CGF.getInvokeDest();
5552 if (InvokeDest) {
5553 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
5554 CGF.Builder.CreateInvoke(ObjCTypes.ExceptionThrowFn,
5555 Cont, InvokeDest,
5556 &ExceptionAsObject, &ExceptionAsObject + 1);
5557 CGF.EmitBlock(Cont);
5558 } else
5559 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
5560 CGF.Builder.CreateUnreachable();
5561
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005562 // Clear the insertion point to indicate we are in unreachable code.
5563 CGF.Builder.ClearInsertionPoint();
5564}
Daniel Dunbare588b992009-03-01 04:46:24 +00005565
5566llvm::Value *
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005567CGObjCNonFragileABIMac::GetInterfaceEHType(const ObjCInterfaceDecl *ID,
5568 bool ForDefinition) {
Daniel Dunbare588b992009-03-01 04:46:24 +00005569 llvm::GlobalVariable * &Entry = EHTypeReferences[ID->getIdentifier()];
Daniel Dunbare588b992009-03-01 04:46:24 +00005570
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005571 // If we don't need a definition, return the entry if found or check
5572 // if we use an external reference.
5573 if (!ForDefinition) {
5574 if (Entry)
5575 return Entry;
Daniel Dunbar7e075cb2009-04-07 06:43:45 +00005576
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005577 // If this type (or a super class) has the __objc_exception__
5578 // attribute, emit an external reference.
5579 if (hasObjCExceptionAttribute(ID))
5580 return Entry =
5581 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5582 llvm::GlobalValue::ExternalLinkage,
5583 0,
5584 (std::string("OBJC_EHTYPE_$_") +
5585 ID->getIdentifier()->getName()),
5586 &CGM.getModule());
5587 }
5588
5589 // Otherwise we need to either make a new entry or fill in the
5590 // initializer.
5591 assert((!Entry || !Entry->hasInitializer()) && "Duplicate EHType definition");
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005592 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbare588b992009-03-01 04:46:24 +00005593 std::string VTableName = "objc_ehtype_vtable";
5594 llvm::GlobalVariable *VTableGV =
5595 CGM.getModule().getGlobalVariable(VTableName);
5596 if (!VTableGV)
5597 VTableGV = new llvm::GlobalVariable(ObjCTypes.Int8PtrTy, false,
5598 llvm::GlobalValue::ExternalLinkage,
5599 0, VTableName, &CGM.getModule());
5600
5601 llvm::Value *VTableIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, 2);
5602
5603 std::vector<llvm::Constant*> Values(3);
5604 Values[0] = llvm::ConstantExpr::getGetElementPtr(VTableGV, &VTableIdx, 1);
5605 Values[1] = GetClassName(ID->getIdentifier());
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005606 Values[2] = GetClassGlobal(ClassName, false);
Daniel Dunbare588b992009-03-01 04:46:24 +00005607 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.EHTypeTy, Values);
5608
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005609 if (Entry) {
5610 Entry->setInitializer(Init);
5611 } else {
5612 Entry = new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5613 llvm::GlobalValue::WeakAnyLinkage,
5614 Init,
5615 (std::string("OBJC_EHTYPE_$_") +
5616 ID->getIdentifier()->getName()),
5617 &CGM.getModule());
5618 }
5619
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005620 if (CGM.getLangOptions().getVisibilityMode() ==
5621 LangOptions::HiddenVisibility)
5622 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005623 Entry->setAlignment(8);
5624
5625 if (ForDefinition) {
5626 Entry->setSection("__DATA,__objc_const");
5627 Entry->setLinkage(llvm::GlobalValue::ExternalLinkage);
5628 } else {
5629 Entry->setSection("__DATA,__datacoal_nt,coalesced");
5630 }
Daniel Dunbare588b992009-03-01 04:46:24 +00005631
5632 return Entry;
5633}
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005634
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00005635/* *** */
5636
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00005637CodeGen::CGObjCRuntime *
5638CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00005639 return new CGObjCMac(CGM);
5640}
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005641
5642CodeGen::CGObjCRuntime *
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00005643CodeGen::CreateMacNonFragileABIObjCRuntime(CodeGen::CodeGenModule &CGM) {
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00005644 return new CGObjCNonFragileABIMac(CGM);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005645}