blob: 426ad8c0f5f0a229484b2b236ee4bf616519109d [file] [log] [blame]
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001//===------- CGObjCMac.cpp - Interface to Apple Objective-C Runtime -------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This provides Objective-C code generation targetting the Apple runtime.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CGObjCRuntime.h"
Daniel Dunbarf77ac862008-08-11 21:35:06 +000015
16#include "CodeGenModule.h"
Daniel Dunbarb7ec2462008-08-16 03:19:19 +000017#include "CodeGenFunction.h"
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000018#include "clang/AST/ASTContext.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000019#include "clang/AST/Decl.h"
Daniel Dunbar6efc0c52008-08-13 03:21:16 +000020#include "clang/AST/DeclObjC.h"
Daniel Dunbarf77ac862008-08-11 21:35:06 +000021#include "clang/Basic/LangOptions.h"
22
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +000023#include "llvm/Intrinsics.h"
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000024#include "llvm/Module.h"
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +000025#include "llvm/ADT/DenseSet.h"
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +000026#include "llvm/Target/TargetData.h"
Daniel Dunbarb7ec2462008-08-16 03:19:19 +000027#include <sstream>
Daniel Dunbarc17a4d32008-08-11 02:45:11 +000028
29using namespace clang;
Daniel Dunbar46f45b92008-09-09 01:06:48 +000030using namespace CodeGen;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +000031
32namespace {
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000033
Daniel Dunbarae226fa2008-08-27 02:31:56 +000034 typedef std::vector<llvm::Constant*> ConstantVector;
35
Daniel Dunbar6efc0c52008-08-13 03:21:16 +000036 // FIXME: We should find a nicer way to make the labels for
37 // metadata, string concatenation is lame.
38
Fariborz Jahanianee0af742009-01-21 22:04:16 +000039class ObjCCommonTypesHelper {
40protected:
41 CodeGen::CodeGenModule &CGM;
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000042
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000043public:
Fariborz Jahanian0a855d02009-03-23 19:10:40 +000044 const llvm::Type *ShortTy, *IntTy, *LongTy, *LongLongTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +000045 const llvm::Type *Int8PtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +000046
Daniel Dunbar2bedbf82008-08-12 05:28:47 +000047 /// ObjectPtrTy - LLVM type for object handles (typeof(id))
48 const llvm::Type *ObjectPtrTy;
Fariborz Jahanian6d657c42008-11-18 20:18:11 +000049
50 /// PtrObjectPtrTy - LLVM type for id *
51 const llvm::Type *PtrObjectPtrTy;
52
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +000053 /// SelectorPtrTy - LLVM type for selector handles (typeof(SEL))
Daniel Dunbar2bedbf82008-08-12 05:28:47 +000054 const llvm::Type *SelectorPtrTy;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +000055 /// ProtocolPtrTy - LLVM type for external protocol handles
56 /// (typeof(Protocol))
57 const llvm::Type *ExternalProtocolPtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +000058
Daniel Dunbar19cd87e2008-08-30 03:02:31 +000059 // SuperCTy - clang type for struct objc_super.
60 QualType SuperCTy;
61 // SuperPtrCTy - clang type for struct objc_super *.
62 QualType SuperPtrCTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +000063
Daniel Dunbare8b470d2008-08-23 04:28:29 +000064 /// SuperTy - LLVM type for struct objc_super.
65 const llvm::StructType *SuperTy;
Daniel Dunbar14c80b72008-08-23 09:25:55 +000066 /// SuperPtrTy - LLVM type for struct objc_super *.
67 const llvm::Type *SuperPtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +000068
Fariborz Jahanian30bc5712009-01-22 23:02:58 +000069 /// PropertyTy - LLVM type for struct objc_property (struct _prop_t
70 /// in GCC parlance).
71 const llvm::StructType *PropertyTy;
72
73 /// PropertyListTy - LLVM type for struct objc_property_list
74 /// (_prop_list_t in GCC parlance).
75 const llvm::StructType *PropertyListTy;
76 /// PropertyListPtrTy - LLVM type for struct objc_property_list*.
77 const llvm::Type *PropertyListPtrTy;
78
79 // MethodTy - LLVM type for struct objc_method.
80 const llvm::StructType *MethodTy;
81
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +000082 /// CacheTy - LLVM type for struct objc_cache.
83 const llvm::Type *CacheTy;
84 /// CachePtrTy - LLVM type for struct objc_cache *.
85 const llvm::Type *CachePtrTy;
86
Chris Lattner74391b42009-03-22 21:03:39 +000087 llvm::Constant *GetPropertyFn, *SetPropertyFn;
Fariborz Jahaniandb286862009-01-22 00:37:21 +000088
Chris Lattner74391b42009-03-22 21:03:39 +000089 llvm::Constant *EnumerationMutationFn;
Fariborz Jahaniandb286862009-01-22 00:37:21 +000090
91 /// GcReadWeakFn -- LLVM objc_read_weak (id *src) function.
Chris Lattner74391b42009-03-22 21:03:39 +000092 llvm::Constant *GcReadWeakFn;
Fariborz Jahaniandb286862009-01-22 00:37:21 +000093
94 /// GcAssignWeakFn -- LLVM objc_assign_weak function.
Chris Lattner74391b42009-03-22 21:03:39 +000095 llvm::Constant *GcAssignWeakFn;
Fariborz Jahaniandb286862009-01-22 00:37:21 +000096
97 /// GcAssignGlobalFn -- LLVM objc_assign_global function.
Chris Lattner74391b42009-03-22 21:03:39 +000098 llvm::Constant *GcAssignGlobalFn;
Fariborz Jahaniandb286862009-01-22 00:37:21 +000099
100 /// GcAssignIvarFn -- LLVM objc_assign_ivar function.
Chris Lattner74391b42009-03-22 21:03:39 +0000101 llvm::Constant *GcAssignIvarFn;
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000102
103 /// GcAssignStrongCastFn -- LLVM objc_assign_strongCast function.
Chris Lattner74391b42009-03-22 21:03:39 +0000104 llvm::Constant *GcAssignStrongCastFn;
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000105
106 /// ExceptionThrowFn - LLVM objc_exception_throw function.
Chris Lattner74391b42009-03-22 21:03:39 +0000107 llvm::Constant *ExceptionThrowFn;
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000108
Daniel Dunbar1c566672009-02-24 01:43:46 +0000109 /// SyncEnterFn - LLVM object_sync_enter function.
Chris Lattnerb02e53b2009-04-06 16:53:45 +0000110 llvm::Constant *getSyncEnterFn() {
111 // void objc_sync_enter (id)
112 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
113 llvm::FunctionType *FTy =
114 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
115 return CGM.CreateRuntimeFunction(FTy, "objc_sync_enter");
116 }
Daniel Dunbar1c566672009-02-24 01:43:46 +0000117
118 /// SyncExitFn - LLVM object_sync_exit function.
Chris Lattner74391b42009-03-22 21:03:39 +0000119 llvm::Constant *SyncExitFn;
Daniel Dunbar1c566672009-02-24 01:43:46 +0000120
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000121 ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm);
122 ~ObjCCommonTypesHelper(){}
123};
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000124
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000125/// ObjCTypesHelper - Helper class that encapsulates lazy
126/// construction of varies types used during ObjC generation.
127class ObjCTypesHelper : public ObjCCommonTypesHelper {
128private:
129
Chris Lattner74391b42009-03-22 21:03:39 +0000130 llvm::Constant *MessageSendFn, *MessageSendStretFn, *MessageSendFpretFn;
131 llvm::Constant *MessageSendSuperFn, *MessageSendSuperStretFn,
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000132 *MessageSendSuperFpretFn;
133
134public:
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000135 /// SymtabTy - LLVM type for struct objc_symtab.
136 const llvm::StructType *SymtabTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000137 /// SymtabPtrTy - LLVM type for struct objc_symtab *.
138 const llvm::Type *SymtabPtrTy;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000139 /// ModuleTy - LLVM type for struct objc_module.
140 const llvm::StructType *ModuleTy;
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000141
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000142 /// ProtocolTy - LLVM type for struct objc_protocol.
143 const llvm::StructType *ProtocolTy;
144 /// ProtocolPtrTy - LLVM type for struct objc_protocol *.
145 const llvm::Type *ProtocolPtrTy;
146 /// ProtocolExtensionTy - LLVM type for struct
147 /// objc_protocol_extension.
148 const llvm::StructType *ProtocolExtensionTy;
149 /// ProtocolExtensionTy - LLVM type for struct
150 /// objc_protocol_extension *.
151 const llvm::Type *ProtocolExtensionPtrTy;
152 /// MethodDescriptionTy - LLVM type for struct
153 /// objc_method_description.
154 const llvm::StructType *MethodDescriptionTy;
155 /// MethodDescriptionListTy - LLVM type for struct
156 /// objc_method_description_list.
157 const llvm::StructType *MethodDescriptionListTy;
158 /// MethodDescriptionListPtrTy - LLVM type for struct
159 /// objc_method_description_list *.
160 const llvm::Type *MethodDescriptionListPtrTy;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000161 /// ProtocolListTy - LLVM type for struct objc_property_list.
162 const llvm::Type *ProtocolListTy;
163 /// ProtocolListPtrTy - LLVM type for struct objc_property_list*.
164 const llvm::Type *ProtocolListPtrTy;
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000165 /// CategoryTy - LLVM type for struct objc_category.
166 const llvm::StructType *CategoryTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000167 /// ClassTy - LLVM type for struct objc_class.
168 const llvm::StructType *ClassTy;
169 /// ClassPtrTy - LLVM type for struct objc_class *.
170 const llvm::Type *ClassPtrTy;
171 /// ClassExtensionTy - LLVM type for struct objc_class_ext.
172 const llvm::StructType *ClassExtensionTy;
173 /// ClassExtensionPtrTy - LLVM type for struct objc_class_ext *.
174 const llvm::Type *ClassExtensionPtrTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000175 // IvarTy - LLVM type for struct objc_ivar.
176 const llvm::StructType *IvarTy;
177 /// IvarListTy - LLVM type for struct objc_ivar_list.
178 const llvm::Type *IvarListTy;
179 /// IvarListPtrTy - LLVM type for struct objc_ivar_list *.
180 const llvm::Type *IvarListPtrTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000181 /// MethodListTy - LLVM type for struct objc_method_list.
182 const llvm::Type *MethodListTy;
183 /// MethodListPtrTy - LLVM type for struct objc_method_list *.
184 const llvm::Type *MethodListPtrTy;
Anders Carlsson124526b2008-09-09 10:10:21 +0000185
186 /// ExceptionDataTy - LLVM type for struct _objc_exception_data.
187 const llvm::Type *ExceptionDataTy;
188
Anders Carlsson124526b2008-09-09 10:10:21 +0000189 /// ExceptionTryEnterFn - LLVM objc_exception_try_enter function.
Chris Lattner74391b42009-03-22 21:03:39 +0000190 llvm::Constant *ExceptionTryEnterFn;
Anders Carlsson124526b2008-09-09 10:10:21 +0000191
192 /// ExceptionTryExitFn - LLVM objc_exception_try_exit function.
Chris Lattner74391b42009-03-22 21:03:39 +0000193 llvm::Constant *ExceptionTryExitFn;
Anders Carlsson124526b2008-09-09 10:10:21 +0000194
195 /// ExceptionExtractFn - LLVM objc_exception_extract function.
Chris Lattner74391b42009-03-22 21:03:39 +0000196 llvm::Constant *ExceptionExtractFn;
Anders Carlsson124526b2008-09-09 10:10:21 +0000197
198 /// ExceptionMatchFn - LLVM objc_exception_match function.
Chris Lattner74391b42009-03-22 21:03:39 +0000199 llvm::Constant *ExceptionMatchFn;
Anders Carlsson124526b2008-09-09 10:10:21 +0000200
201 /// SetJmpFn - LLVM _setjmp function.
Chris Lattner74391b42009-03-22 21:03:39 +0000202 llvm::Constant *SetJmpFn;
Chris Lattner10cac6f2008-11-15 21:26:17 +0000203
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000204public:
205 ObjCTypesHelper(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000206 ~ObjCTypesHelper() {}
Daniel Dunbar5669e572008-10-17 03:24:53 +0000207
208
Chris Lattner74391b42009-03-22 21:03:39 +0000209 llvm::Constant *getSendFn(bool IsSuper) {
Daniel Dunbar5669e572008-10-17 03:24:53 +0000210 return IsSuper ? MessageSendSuperFn : MessageSendFn;
211 }
212
Chris Lattner74391b42009-03-22 21:03:39 +0000213 llvm::Constant *getSendStretFn(bool IsSuper) {
Daniel Dunbar5669e572008-10-17 03:24:53 +0000214 return IsSuper ? MessageSendSuperStretFn : MessageSendStretFn;
215 }
216
Chris Lattner74391b42009-03-22 21:03:39 +0000217 llvm::Constant *getSendFpretFn(bool IsSuper) {
Daniel Dunbar5669e572008-10-17 03:24:53 +0000218 return IsSuper ? MessageSendSuperFpretFn : MessageSendFpretFn;
219 }
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000220};
221
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000222/// ObjCNonFragileABITypesHelper - will have all types needed by objective-c's
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000223/// modern abi
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000224class ObjCNonFragileABITypesHelper : public ObjCCommonTypesHelper {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000225public:
Chris Lattner74391b42009-03-22 21:03:39 +0000226 llvm::Constant *MessageSendFixupFn, *MessageSendFpretFixupFn,
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000227 *MessageSendStretFixupFn, *MessageSendIdFixupFn,
228 *MessageSendIdStretFixupFn, *MessageSendSuper2FixupFn,
229 *MessageSendSuper2StretFixupFn;
230
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000231 // MethodListnfABITy - LLVM for struct _method_list_t
232 const llvm::StructType *MethodListnfABITy;
233
234 // MethodListnfABIPtrTy - LLVM for struct _method_list_t*
235 const llvm::Type *MethodListnfABIPtrTy;
236
237 // ProtocolnfABITy = LLVM for struct _protocol_t
238 const llvm::StructType *ProtocolnfABITy;
239
Daniel Dunbar948e2582009-02-15 07:36:20 +0000240 // ProtocolnfABIPtrTy = LLVM for struct _protocol_t*
241 const llvm::Type *ProtocolnfABIPtrTy;
242
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000243 // ProtocolListnfABITy - LLVM for struct _objc_protocol_list
244 const llvm::StructType *ProtocolListnfABITy;
245
246 // ProtocolListnfABIPtrTy - LLVM for struct _objc_protocol_list*
247 const llvm::Type *ProtocolListnfABIPtrTy;
248
249 // ClassnfABITy - LLVM for struct _class_t
250 const llvm::StructType *ClassnfABITy;
251
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000252 // ClassnfABIPtrTy - LLVM for struct _class_t*
253 const llvm::Type *ClassnfABIPtrTy;
254
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000255 // IvarnfABITy - LLVM for struct _ivar_t
256 const llvm::StructType *IvarnfABITy;
257
258 // IvarListnfABITy - LLVM for struct _ivar_list_t
259 const llvm::StructType *IvarListnfABITy;
260
261 // IvarListnfABIPtrTy = LLVM for struct _ivar_list_t*
262 const llvm::Type *IvarListnfABIPtrTy;
263
264 // ClassRonfABITy - LLVM for struct _class_ro_t
265 const llvm::StructType *ClassRonfABITy;
266
267 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
268 const llvm::Type *ImpnfABITy;
269
270 // CategorynfABITy - LLVM for struct _category_t
271 const llvm::StructType *CategorynfABITy;
272
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000273 // New types for nonfragile abi messaging.
274
275 // MessageRefTy - LLVM for:
276 // struct _message_ref_t {
277 // IMP messenger;
278 // SEL name;
279 // };
280 const llvm::StructType *MessageRefTy;
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000281 // MessageRefCTy - clang type for struct _message_ref_t
282 QualType MessageRefCTy;
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000283
284 // MessageRefPtrTy - LLVM for struct _message_ref_t*
285 const llvm::Type *MessageRefPtrTy;
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000286 // MessageRefCPtrTy - clang type for struct _message_ref_t*
287 QualType MessageRefCPtrTy;
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000288
Fariborz Jahanianef163782009-02-05 01:13:09 +0000289 // MessengerTy - Type of the messenger (shown as IMP above)
290 const llvm::FunctionType *MessengerTy;
291
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000292 // SuperMessageRefTy - LLVM for:
293 // struct _super_message_ref_t {
294 // SUPER_IMP messenger;
295 // SEL name;
296 // };
297 const llvm::StructType *SuperMessageRefTy;
298
299 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
300 const llvm::Type *SuperMessageRefPtrTy;
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000301
302 /// EHPersonalityPtr - LLVM value for an i8* to the Objective-C
303 /// exception personality function.
Chris Lattnerb02e53b2009-04-06 16:53:45 +0000304 llvm::Value *getEHPersonalityPtr() {
305 llvm::Constant *Personality =
306 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
307 std::vector<const llvm::Type*>(),
308 true),
309 "__objc_personality_v0");
310 return llvm::ConstantExpr::getBitCast(Personality, Int8PtrTy);
311 }
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000312
Chris Lattner74391b42009-03-22 21:03:39 +0000313 llvm::Constant *UnwindResumeOrRethrowFn, *ObjCBeginCatchFn, *ObjCEndCatchFn;
Daniel Dunbare588b992009-03-01 04:46:24 +0000314
315 const llvm::StructType *EHTypeTy;
316 const llvm::Type *EHTypePtrTy;
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000317
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000318 ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm);
319 ~ObjCNonFragileABITypesHelper(){}
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000320};
321
322class CGObjCCommonMac : public CodeGen::CGObjCRuntime {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000323public:
324 // FIXME - accessibility
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000325 class GC_IVAR {
Fariborz Jahanian820e0202009-03-11 00:07:04 +0000326 public:
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000327 unsigned int ivar_bytepos;
328 unsigned int ivar_size;
329 GC_IVAR() : ivar_bytepos(0), ivar_size(0) {}
330 };
331
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000332 class SKIP_SCAN {
333 public:
334 unsigned int skip;
335 unsigned int scan;
336 SKIP_SCAN() : skip(0), scan(0) {}
337 };
338
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000339protected:
340 CodeGen::CodeGenModule &CGM;
341 // FIXME! May not be needing this after all.
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000342 unsigned ObjCABI;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000343
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000344 // gc ivar layout bitmap calculation helper caches.
345 llvm::SmallVector<GC_IVAR, 16> SkipIvars;
346 llvm::SmallVector<GC_IVAR, 16> IvarsInfo;
347 llvm::SmallVector<SKIP_SCAN, 32> SkipScanIvars;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000348
Daniel Dunbar242d4dc2008-08-25 06:02:07 +0000349 /// LazySymbols - Symbols to generate a lazy reference for. See
350 /// DefinedSymbols and FinishModule().
351 std::set<IdentifierInfo*> LazySymbols;
352
353 /// DefinedSymbols - External symbols which are defined by this
354 /// module. The symbols in this list and LazySymbols are used to add
355 /// special linker symbols which ensure that Objective-C modules are
356 /// linked properly.
357 std::set<IdentifierInfo*> DefinedSymbols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000358
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000359 /// ClassNames - uniqued class names.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000360 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000361
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000362 /// MethodVarNames - uniqued method variable names.
363 llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000364
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000365 /// MethodVarTypes - uniqued method type signatures. We have to use
366 /// a StringMap here because have no other unique reference.
367 llvm::StringMap<llvm::GlobalVariable*> MethodVarTypes;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000368
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000369 /// MethodDefinitions - map of methods which have been defined in
370 /// this translation unit.
371 llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> MethodDefinitions;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000372
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000373 /// PropertyNames - uniqued method variable names.
374 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000375
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000376 /// ClassReferences - uniqued class references.
377 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000378
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000379 /// SelectorReferences - uniqued selector references.
380 llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000381
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000382 /// Protocols - Protocols for which an objc_protocol structure has
383 /// been emitted. Forward declarations are handled by creating an
384 /// empty structure whose initializer is filled in when/if defined.
385 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> Protocols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000386
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000387 /// DefinedProtocols - Protocols which have actually been
388 /// defined. We should not need this, see FIXME in GenerateProtocol.
389 llvm::DenseSet<IdentifierInfo*> DefinedProtocols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000390
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000391 /// DefinedClasses - List of defined classes.
392 std::vector<llvm::GlobalValue*> DefinedClasses;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000393
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000394 /// DefinedCategories - List of defined categories.
395 std::vector<llvm::GlobalValue*> DefinedCategories;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000396
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000397 /// UsedGlobals - List of globals to pack into the llvm.used metadata
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000398 /// to prevent them from being clobbered.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000399 std::vector<llvm::GlobalVariable*> UsedGlobals;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000400
Fariborz Jahanian56210f72009-01-21 23:34:32 +0000401 /// GetNameForMethod - Return a name for the given method.
402 /// \param[out] NameOut - The return value.
403 void GetNameForMethod(const ObjCMethodDecl *OMD,
404 const ObjCContainerDecl *CD,
405 std::string &NameOut);
406
407 /// GetMethodVarName - Return a unique constant for the given
408 /// selector's name. The return value has type char *.
409 llvm::Constant *GetMethodVarName(Selector Sel);
410 llvm::Constant *GetMethodVarName(IdentifierInfo *Ident);
411 llvm::Constant *GetMethodVarName(const std::string &Name);
412
413 /// GetMethodVarType - Return a unique constant for the given
414 /// selector's name. The return value has type char *.
415
416 // FIXME: This is a horrible name.
417 llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D);
Devang Patel7794bb82009-03-04 18:21:39 +0000418 llvm::Constant *GetMethodVarType(FieldDecl *D);
Fariborz Jahanian56210f72009-01-21 23:34:32 +0000419
420 /// GetPropertyName - Return a unique constant for the given
421 /// name. The return value has type char *.
422 llvm::Constant *GetPropertyName(IdentifierInfo *Ident);
423
424 // FIXME: This can be dropped once string functions are unified.
425 llvm::Constant *GetPropertyTypeString(const ObjCPropertyDecl *PD,
426 const Decl *Container);
427
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000428 /// GetClassName - Return a unique constant for the given selector's
429 /// name. The return value has type char *.
430 llvm::Constant *GetClassName(IdentifierInfo *Ident);
431
Fariborz Jahanian21e6f172009-03-11 21:42:00 +0000432 /// GetInterfaceDeclStructLayout - Get layout for ivars of given
433 /// interface declaration.
434 const llvm::StructLayout *GetInterfaceDeclStructLayout(
435 const ObjCInterfaceDecl *ID) const;
436
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000437 /// BuildIvarLayout - Builds ivar layout bitmap for the class
438 /// implementation for the __strong or __weak case.
439 ///
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000440 llvm::Constant *BuildIvarLayout(const ObjCImplementationDecl *OI,
441 bool ForStrongLayout);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000442
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000443 void BuildAggrIvarLayout(const ObjCInterfaceDecl *OI,
444 const llvm::StructLayout *Layout,
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000445 const RecordDecl *RD,
Chris Lattnerf1690852009-03-31 08:48:01 +0000446 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000447 unsigned int BytePos, bool ForStrongLayout,
448 int &Index, int &SkIndex, bool &HasUnion);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000449
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +0000450 /// GetIvarLayoutName - Returns a unique constant for the given
451 /// ivar layout bitmap.
452 llvm::Constant *GetIvarLayoutName(IdentifierInfo *Ident,
453 const ObjCCommonTypesHelper &ObjCTypes);
454
Fariborz Jahanian46b86c62009-01-28 19:12:34 +0000455 const RecordDecl *GetFirstIvarInRecord(const ObjCInterfaceDecl *OID,
456 RecordDecl::field_iterator &FIV,
457 RecordDecl::field_iterator &PIV);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +0000458 /// EmitPropertyList - Emit the given property list. The return
459 /// value has type PropertyListPtrTy.
460 llvm::Constant *EmitPropertyList(const std::string &Name,
461 const Decl *Container,
462 const ObjCContainerDecl *OCD,
463 const ObjCCommonTypesHelper &ObjCTypes);
464
Fariborz Jahanianda320092009-01-29 19:24:30 +0000465 /// GetProtocolRef - Return a reference to the internal protocol
466 /// description, creating an empty one if it has not been
467 /// defined. The return value has type ProtocolPtrTy.
468 llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +0000469
470 /// GetIvarBaseOffset - returns ivars byte offset.
471 uint64_t GetIvarBaseOffset(const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +0000472 const FieldDecl *Field);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000473
Chris Lattnercd0ee142009-03-31 08:33:16 +0000474 /// GetFieldBaseOffset - return's field byte offset.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000475 uint64_t GetFieldBaseOffset(const ObjCInterfaceDecl *OI,
476 const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +0000477 const FieldDecl *Field);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000478
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000479 /// CreateMetadataVar - Create a global variable with internal
480 /// linkage for use by the Objective-C runtime.
481 ///
482 /// This is a convenience wrapper which not only creates the
483 /// variable, but also sets the section and alignment and adds the
484 /// global to the UsedGlobals list.
Daniel Dunbar35bd7632009-03-09 20:50:13 +0000485 ///
486 /// \param Name - The variable name.
487 /// \param Init - The variable initializer; this is also used to
488 /// define the type of the variable.
489 /// \param Section - The section the variable should go into, or 0.
490 /// \param Align - The alignment for the variable, or 0.
491 /// \param AddToUsed - Whether the variable should be added to
492 /// llvm.
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000493 llvm::GlobalVariable *CreateMetadataVar(const std::string &Name,
494 llvm::Constant *Init,
495 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +0000496 unsigned Align,
497 bool AddToUsed);
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000498
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000499public:
500 CGObjCCommonMac(CodeGen::CodeGenModule &cgm) : CGM(cgm)
501 { }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000502
Steve Naroff33fdb732009-03-31 16:53:37 +0000503 virtual llvm::Constant *GenerateConstantString(const ObjCStringLiteral *SL);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000504
505 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
506 const ObjCContainerDecl *CD=0);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000507
508 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
509
510 /// GetOrEmitProtocol - Get the protocol object for the given
511 /// declaration, emitting it if necessary. The return value has type
512 /// ProtocolPtrTy.
513 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD)=0;
514
515 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
516 /// object for the given declaration, emitting it if needed. These
517 /// forward references will be filled in with empty bodies if no
518 /// definition is seen. The return value has type ProtocolPtrTy.
519 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD)=0;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000520};
521
522class CGObjCMac : public CGObjCCommonMac {
523private:
524 ObjCTypesHelper ObjCTypes;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000525 /// EmitImageInfo - Emit the image info marker used to encode some module
526 /// level information.
527 void EmitImageInfo();
528
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000529 /// EmitModuleInfo - Another marker encoding module level
530 /// information.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000531 void EmitModuleInfo();
532
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000533 /// EmitModuleSymols - Emit module symbols, the list of defined
534 /// classes and categories. The result has type SymtabPtrTy.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000535 llvm::Constant *EmitModuleSymbols();
536
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000537 /// FinishModule - Write out global data structures at the end of
538 /// processing a translation unit.
539 void FinishModule();
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000540
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000541 /// EmitClassExtension - Generate the class extension structure used
542 /// to store the weak ivar layout and properties. The return value
543 /// has type ClassExtensionPtrTy.
544 llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID);
545
546 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
547 /// for the given class.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000548 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000549 const ObjCInterfaceDecl *ID);
550
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000551 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000552 QualType ResultType,
553 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000554 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000555 QualType Arg0Ty,
556 bool IsSuper,
557 const CallArgList &CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000558
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000559 /// EmitIvarList - Emit the ivar list for the given
560 /// implementation. If ForClass is true the list of class ivars
561 /// (i.e. metaclass ivars) is emitted, otherwise the list of
562 /// interface ivars will be emitted. The return value has type
563 /// IvarListPtrTy.
564 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +0000565 bool ForClass);
566
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000567 /// EmitMetaClass - Emit a forward reference to the class structure
568 /// for the metaclass of the given interface. The return value has
569 /// type ClassPtrTy.
570 llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
571
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000572 /// EmitMetaClass - Emit a class structure for the metaclass of the
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000573 /// given implementation. The return value has type ClassPtrTy.
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000574 llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
575 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000576 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000577 const ConstantVector &Methods);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000578
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000579 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000580
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000581 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000582
583 /// EmitMethodList - Emit the method list for the given
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000584 /// implementation. The return value has type MethodListPtrTy.
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000585 llvm::Constant *EmitMethodList(const std::string &Name,
586 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000587 const ConstantVector &Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000588
589 /// EmitMethodDescList - Emit a method description list for a list of
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000590 /// method declarations.
591 /// - TypeName: The name for the type containing the methods.
592 /// - IsProtocol: True iff these methods are for a protocol.
593 /// - ClassMethds: True iff these are class methods.
594 /// - Required: When true, only "required" methods are
595 /// listed. Similarly, when false only "optional" methods are
596 /// listed. For classes this should always be true.
597 /// - begin, end: The method list to output.
598 ///
599 /// The return value has type MethodDescriptionListPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000600 llvm::Constant *EmitMethodDescList(const std::string &Name,
601 const char *Section,
602 const ConstantVector &Methods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000603
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000604 /// GetOrEmitProtocol - Get the protocol object for the given
605 /// declaration, emitting it if necessary. The return value has type
606 /// ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +0000607 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000608
609 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
610 /// object for the given declaration, emitting it if needed. These
611 /// forward references will be filled in with empty bodies if no
612 /// definition is seen. The return value has type ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +0000613 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000614
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000615 /// EmitProtocolExtension - Generate the protocol extension
616 /// structure used to store optional instance and class methods, and
617 /// protocol properties. The return value has type
618 /// ProtocolExtensionPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000619 llvm::Constant *
620 EmitProtocolExtension(const ObjCProtocolDecl *PD,
621 const ConstantVector &OptInstanceMethods,
622 const ConstantVector &OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000623
624 /// EmitProtocolList - Generate the list of referenced
625 /// protocols. The return value has type ProtocolListPtrTy.
Daniel Dunbardbc933702008-08-21 21:57:41 +0000626 llvm::Constant *EmitProtocolList(const std::string &Name,
627 ObjCProtocolDecl::protocol_iterator begin,
628 ObjCProtocolDecl::protocol_iterator end);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000629
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000630 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
631 /// for the given selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000632 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000633
Fariborz Jahanianda320092009-01-29 19:24:30 +0000634 public:
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000635 CGObjCMac(CodeGen::CodeGenModule &cgm);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000636
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000637 virtual llvm::Function *ModuleInitFunction();
638
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000639 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000640 QualType ResultType,
641 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000642 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000643 bool IsClassMessage,
644 const CallArgList &CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000645
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000646 virtual CodeGen::RValue
647 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000648 QualType ResultType,
649 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000650 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000651 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000652 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000653 bool IsClassMessage,
654 const CallArgList &CallArgs);
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000655
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000656 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000657 const ObjCInterfaceDecl *ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000658
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000659 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000660
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000661 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000662
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000663 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000664
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000665 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000666 const ObjCProtocolDecl *PD);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000667
Chris Lattner74391b42009-03-22 21:03:39 +0000668 virtual llvm::Constant *GetPropertyGetFunction();
669 virtual llvm::Constant *GetPropertySetFunction();
670 virtual llvm::Constant *EnumerationMutationFunction();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000671
Fariborz Jahanianbd71be42008-11-21 00:49:24 +0000672 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
673 const Stmt &S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000674 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
675 const ObjCAtThrowStmt &S);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000676 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +0000677 llvm::Value *AddrWeakObj);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000678 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
679 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000680 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
681 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian7eda8362008-11-20 19:23:36 +0000682 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
683 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000684 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
685 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian0bb20362009-02-02 20:02:29 +0000686
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000687 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
688 QualType ObjectTy,
689 llvm::Value *BaseValue,
690 const ObjCIvarDecl *Ivar,
691 const FieldDecl *Field,
692 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000693 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
694 ObjCInterfaceDecl *Interface,
695 const ObjCIvarDecl *Ivar);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000696};
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000697
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000698class CGObjCNonFragileABIMac : public CGObjCCommonMac {
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000699private:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000700 ObjCNonFragileABITypesHelper ObjCTypes;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000701 llvm::GlobalVariable* ObjCEmptyCacheVar;
702 llvm::GlobalVariable* ObjCEmptyVtableVar;
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000703
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000704 /// MetaClassReferences - uniqued meta class references.
705 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> MetaClassReferences;
Daniel Dunbare588b992009-03-01 04:46:24 +0000706
707 /// EHTypeReferences - uniqued class ehtype references.
708 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> EHTypeReferences;
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000709
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000710 /// FinishNonFragileABIModule - Write out global data structures at the end of
711 /// processing a translation unit.
712 void FinishNonFragileABIModule();
713
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000714 llvm::GlobalVariable * BuildClassRoTInitializer(unsigned flags,
715 unsigned InstanceStart,
716 unsigned InstanceSize,
717 const ObjCImplementationDecl *ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +0000718 llvm::GlobalVariable * BuildClassMetaData(std::string &ClassName,
719 llvm::Constant *IsAGV,
720 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +0000721 llvm::Constant *ClassRoGV,
722 bool HiddenVisibility);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000723
724 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
725
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +0000726 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
727
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000728 /// EmitMethodList - Emit the method list for the given
729 /// implementation. The return value has type MethodListnfABITy.
730 llvm::Constant *EmitMethodList(const std::string &Name,
731 const char *Section,
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +0000732 const ConstantVector &Methods);
733 /// EmitIvarList - Emit the ivar list for the given
734 /// implementation. If ForClass is true the list of class ivars
735 /// (i.e. metaclass ivars) is emitted, otherwise the list of
736 /// interface ivars will be emitted. The return value has type
737 /// IvarListnfABIPtrTy.
738 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000739
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000740 llvm::Constant *EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +0000741 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +0000742 unsigned long int offset);
743
Fariborz Jahanianda320092009-01-29 19:24:30 +0000744 /// GetOrEmitProtocol - Get the protocol object for the given
745 /// declaration, emitting it if necessary. The return value has type
746 /// ProtocolPtrTy.
747 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
748
749 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
750 /// object for the given declaration, emitting it if needed. These
751 /// forward references will be filled in with empty bodies if no
752 /// definition is seen. The return value has type ProtocolPtrTy.
753 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
754
755 /// EmitProtocolList - Generate the list of referenced
756 /// protocols. The return value has type ProtocolListPtrTy.
757 llvm::Constant *EmitProtocolList(const std::string &Name,
758 ObjCProtocolDecl::protocol_iterator begin,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000759 ObjCProtocolDecl::protocol_iterator end);
760
761 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
762 QualType ResultType,
763 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000764 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000765 QualType Arg0Ty,
766 bool IsSuper,
767 const CallArgList &CallArgs);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +0000768
769 /// GetClassGlobal - Return the global variable for the Objective-C
770 /// class of the given name.
771 llvm::GlobalVariable *GetClassGlobal(const std::string &Name);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000772
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000773 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
774 /// for the given class.
775 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000776 const ObjCInterfaceDecl *ID,
777 bool IsSuper = false);
778
779 /// EmitMetaClassRef - Return a Value * of the address of _class_t
780 /// meta-data
781 llvm::Value *EmitMetaClassRef(CGBuilderTy &Builder,
782 const ObjCInterfaceDecl *ID);
783
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000784 /// ObjCIvarOffsetVariable - Returns the ivar offset variable for
785 /// the given ivar.
786 ///
787 llvm::GlobalVariable * ObjCIvarOffsetVariable(std::string &Name,
Fariborz Jahanian01a0c362009-02-12 18:51:23 +0000788 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000789 const ObjCIvarDecl *Ivar);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000790
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +0000791 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
792 /// for the given selector.
793 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbare588b992009-03-01 04:46:24 +0000794
795 /// GetInterfaceEHType - Get the ehtype for the given Objective-C
796 /// interface. The return value has type EHTypePtrTy.
797 llvm::Value *GetInterfaceEHType(const ObjCInterfaceType *IT);
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000798
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000799public:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000800 CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000801 // FIXME. All stubs for now!
802 virtual llvm::Function *ModuleInitFunction();
803
804 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
805 QualType ResultType,
806 Selector Sel,
807 llvm::Value *Receiver,
808 bool IsClassMessage,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000809 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000810
811 virtual CodeGen::RValue
812 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
813 QualType ResultType,
814 Selector Sel,
815 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000816 bool isCategoryImpl,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000817 llvm::Value *Receiver,
818 bool IsClassMessage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000819 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000820
821 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000822 const ObjCInterfaceDecl *ID);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000823
824 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel)
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +0000825 { return EmitSelector(Builder, Sel); }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000826
Fariborz Jahanianeb062d92009-01-26 18:32:24 +0000827 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000828
829 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000830 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +0000831 const ObjCProtocolDecl *PD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000832
Chris Lattner74391b42009-03-22 21:03:39 +0000833 virtual llvm::Constant *GetPropertyGetFunction() {
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000834 return ObjCTypes.GetPropertyFn;
835 }
Chris Lattner74391b42009-03-22 21:03:39 +0000836 virtual llvm::Constant *GetPropertySetFunction() {
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000837 return ObjCTypes.SetPropertyFn;
838 }
Chris Lattner74391b42009-03-22 21:03:39 +0000839 virtual llvm::Constant *EnumerationMutationFunction() {
Daniel Dunbar28ed0842009-02-16 18:48:45 +0000840 return ObjCTypes.EnumerationMutationFn;
841 }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000842
843 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000844 const Stmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000845 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000846 const ObjCAtThrowStmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000847 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000848 llvm::Value *AddrWeakObj);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000849 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000850 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000851 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000852 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000853 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000854 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000855 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000856 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000857 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
858 QualType ObjectTy,
859 llvm::Value *BaseValue,
860 const ObjCIvarDecl *Ivar,
861 const FieldDecl *Field,
862 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000863 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
864 ObjCInterfaceDecl *Interface,
865 const ObjCIvarDecl *Ivar);
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000866};
867
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000868} // end anonymous namespace
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000869
870/* *** Helper Functions *** */
871
872/// getConstantGEP() - Help routine to construct simple GEPs.
873static llvm::Constant *getConstantGEP(llvm::Constant *C,
874 unsigned idx0,
875 unsigned idx1) {
876 llvm::Value *Idxs[] = {
877 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx0),
878 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx1)
879 };
880 return llvm::ConstantExpr::getGetElementPtr(C, Idxs, 2);
881}
882
883/* *** CGObjCMac Public Interface *** */
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000884
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000885CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm),
886 ObjCTypes(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000887{
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000888 ObjCABI = 1;
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000889 EmitImageInfo();
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000890}
891
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000892/// GetClass - Return a reference to the class for the given interface
893/// decl.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000894llvm::Value *CGObjCMac::GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000895 const ObjCInterfaceDecl *ID) {
896 return EmitClassRef(Builder, ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000897}
898
899/// GetSelector - Return the pointer to the unique'd string for this selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000900llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000901 return EmitSelector(Builder, Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000902}
903
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000904/// Generate a constant CFString object.
905/*
906 struct __builtin_CFString {
907 const int *isa; // point to __CFConstantStringClassReference
908 int flags;
909 const char *str;
910 long length;
911 };
912*/
913
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000914llvm::Constant *CGObjCCommonMac::GenerateConstantString(
Steve Naroff33fdb732009-03-31 16:53:37 +0000915 const ObjCStringLiteral *SL) {
Steve Naroff8d4141f2009-04-01 13:55:36 +0000916 return CGM.GetAddrOfConstantCFString(SL->getString());
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000917}
918
919/// Generates a message send where the super is the receiver. This is
920/// a message send to self with special delivery semantics indicating
921/// which class's method should be called.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000922CodeGen::RValue
923CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000924 QualType ResultType,
925 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000926 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000927 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000928 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000929 bool IsClassMessage,
Daniel Dunbar46f45b92008-09-09 01:06:48 +0000930 const CodeGen::CallArgList &CallArgs) {
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000931 // Create and init a super structure; this is a (receiver, class)
932 // pair we will pass to objc_msgSendSuper.
933 llvm::Value *ObjCSuper =
934 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
935 llvm::Value *ReceiverAsObject =
936 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
937 CGF.Builder.CreateStore(ReceiverAsObject,
938 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000939
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000940 // If this is a class message the metaclass is passed as the target.
941 llvm::Value *Target;
942 if (IsClassMessage) {
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000943 if (isCategoryImpl) {
944 // Message sent to 'super' in a class method defined in a category
945 // implementation requires an odd treatment.
946 // If we are in a class method, we must retrieve the
947 // _metaclass_ for the current class, pointed at by
948 // the class's "isa" pointer. The following assumes that
949 // isa" is the first ivar in a class (which it must be).
950 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
951 Target = CGF.Builder.CreateStructGEP(Target, 0);
952 Target = CGF.Builder.CreateLoad(Target);
953 }
954 else {
955 llvm::Value *MetaClassPtr = EmitMetaClassRef(Class);
956 llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1);
957 llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr);
958 Target = Super;
959 }
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000960 } else {
961 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
962 }
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000963 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
964 // and ObjCTypes types.
965 const llvm::Type *ClassTy =
966 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000967 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000968 CGF.Builder.CreateStore(Target,
969 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
970
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000971 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000972 ObjCSuper, ObjCTypes.SuperPtrCTy,
973 true, CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000974}
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000975
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000976/// Generate code for a message send expression.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000977CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000978 QualType ResultType,
979 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000980 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000981 bool IsClassMessage,
982 const CallArgList &CallArgs) {
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000983 llvm::Value *Arg0 =
984 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy, "tmp");
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000985 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000986 Arg0, CGF.getContext().getObjCIdType(),
987 false, CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000988}
989
990CodeGen::RValue CGObjCMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000991 QualType ResultType,
992 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000993 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000994 QualType Arg0Ty,
995 bool IsSuper,
996 const CallArgList &CallArgs) {
997 CallArgList ActualArgs;
Daniel Dunbar46f45b92008-09-09 01:06:48 +0000998 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
999 ActualArgs.push_back(std::make_pair(RValue::get(EmitSelector(CGF.Builder,
1000 Sel)),
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001001 CGF.getContext().getObjCSelType()));
1002 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001003
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001004 CodeGenTypes &Types = CGM.getTypes();
1005 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs);
1006 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo, false);
Daniel Dunbar5669e572008-10-17 03:24:53 +00001007
1008 llvm::Constant *Fn;
Daniel Dunbar88b53962009-02-02 22:03:45 +00001009 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Daniel Dunbar5669e572008-10-17 03:24:53 +00001010 Fn = ObjCTypes.getSendStretFn(IsSuper);
1011 } else if (ResultType->isFloatingType()) {
1012 // FIXME: Sadly, this is wrong. This actually depends on the
1013 // architecture. This happens to be right for x86-32 though.
1014 Fn = ObjCTypes.getSendFpretFn(IsSuper);
1015 } else {
1016 Fn = ObjCTypes.getSendFn(IsSuper);
1017 }
Daniel Dunbar62d5c1b2008-09-10 07:00:50 +00001018 Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy));
Daniel Dunbar88b53962009-02-02 22:03:45 +00001019 return CGF.EmitCall(FnInfo, Fn, ActualArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001020}
1021
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001022llvm::Value *CGObjCMac::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001023 const ObjCProtocolDecl *PD) {
Daniel Dunbarc67876d2008-09-04 04:33:15 +00001024 // FIXME: I don't understand why gcc generates this, or where it is
1025 // resolved. Investigate. Its also wasteful to look this up over and
1026 // over.
1027 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1028
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001029 return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
1030 ObjCTypes.ExternalProtocolPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001031}
1032
Fariborz Jahanianda320092009-01-29 19:24:30 +00001033void CGObjCCommonMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001034 // FIXME: We shouldn't need this, the protocol decl should contain
1035 // enough information to tell us whether this was a declaration or a
1036 // definition.
1037 DefinedProtocols.insert(PD->getIdentifier());
1038
1039 // If we have generated a forward reference to this protocol, emit
1040 // it now. Otherwise do nothing, the protocol objects are lazily
1041 // emitted.
1042 if (Protocols.count(PD->getIdentifier()))
1043 GetOrEmitProtocol(PD);
1044}
1045
Fariborz Jahanianda320092009-01-29 19:24:30 +00001046llvm::Constant *CGObjCCommonMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001047 if (DefinedProtocols.count(PD->getIdentifier()))
1048 return GetOrEmitProtocol(PD);
1049 return GetOrEmitProtocolRef(PD);
1050}
1051
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001052/*
1053 // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions
1054 struct _objc_protocol {
1055 struct _objc_protocol_extension *isa;
1056 char *protocol_name;
1057 struct _objc_protocol_list *protocol_list;
1058 struct _objc__method_prototype_list *instance_methods;
1059 struct _objc__method_prototype_list *class_methods
1060 };
1061
1062 See EmitProtocolExtension().
1063*/
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001064llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
1065 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1066
1067 // Early exit if a defining object has already been generated.
1068 if (Entry && Entry->hasInitializer())
1069 return Entry;
1070
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001071 // FIXME: I don't understand why gcc generates this, or where it is
1072 // resolved. Investigate. Its also wasteful to look this up over and
1073 // over.
1074 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1075
Chris Lattner8ec03f52008-11-24 03:54:41 +00001076 const char *ProtocolName = PD->getNameAsCString();
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001077
1078 // Construct method lists.
1079 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1080 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
1081 for (ObjCProtocolDecl::instmeth_iterator i = PD->instmeth_begin(),
1082 e = PD->instmeth_end(); i != e; ++i) {
1083 ObjCMethodDecl *MD = *i;
1084 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1085 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1086 OptInstanceMethods.push_back(C);
1087 } else {
1088 InstanceMethods.push_back(C);
1089 }
1090 }
1091
1092 for (ObjCProtocolDecl::classmeth_iterator i = PD->classmeth_begin(),
1093 e = PD->classmeth_end(); i != e; ++i) {
1094 ObjCMethodDecl *MD = *i;
1095 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1096 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1097 OptClassMethods.push_back(C);
1098 } else {
1099 ClassMethods.push_back(C);
1100 }
1101 }
1102
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001103 std::vector<llvm::Constant*> Values(5);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001104 Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001105 Values[1] = GetClassName(PD->getIdentifier());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001106 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001107 EmitProtocolList("\01L_OBJC_PROTOCOL_REFS_" + PD->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001108 PD->protocol_begin(),
1109 PD->protocol_end());
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001110 Values[3] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001111 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_"
1112 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001113 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1114 InstanceMethods);
1115 Values[4] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001116 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_"
1117 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001118 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1119 ClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001120 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
1121 Values);
1122
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001123 if (Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001124 // Already created, fix the linkage and update the initializer.
1125 Entry->setLinkage(llvm::GlobalValue::InternalLinkage);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001126 Entry->setInitializer(Init);
1127 } else {
1128 Entry =
1129 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
1130 llvm::GlobalValue::InternalLinkage,
1131 Init,
1132 std::string("\01L_OBJC_PROTOCOL_")+ProtocolName,
1133 &CGM.getModule());
1134 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001135 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001136 UsedGlobals.push_back(Entry);
1137 // FIXME: Is this necessary? Why only for protocol?
1138 Entry->setAlignment(4);
1139 }
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001140
1141 return Entry;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001142}
1143
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001144llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001145 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1146
1147 if (!Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001148 // We use the initializer as a marker of whether this is a forward
1149 // reference or not. At module finalization we add the empty
1150 // contents for protocols which were referenced but never defined.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001151 Entry =
1152 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001153 llvm::GlobalValue::ExternalLinkage,
1154 0,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001155 "\01L_OBJC_PROTOCOL_" + PD->getNameAsString(),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001156 &CGM.getModule());
1157 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001158 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001159 UsedGlobals.push_back(Entry);
1160 // FIXME: Is this necessary? Why only for protocol?
1161 Entry->setAlignment(4);
1162 }
1163
1164 return Entry;
1165}
1166
1167/*
1168 struct _objc_protocol_extension {
1169 uint32_t size;
1170 struct objc_method_description_list *optional_instance_methods;
1171 struct objc_method_description_list *optional_class_methods;
1172 struct objc_property_list *instance_properties;
1173 };
1174*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001175llvm::Constant *
1176CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
1177 const ConstantVector &OptInstanceMethods,
1178 const ConstantVector &OptClassMethods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001179 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001180 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolExtensionTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001181 std::vector<llvm::Constant*> Values(4);
1182 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001183 Values[1] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001184 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_"
1185 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001186 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1187 OptInstanceMethods);
1188 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001189 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_"
1190 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001191 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1192 OptClassMethods);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001193 Values[3] = EmitPropertyList("\01L_OBJC_$_PROP_PROTO_LIST_" +
1194 PD->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001195 0, PD, ObjCTypes);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001196
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001197 // Return null if no extension bits are used.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001198 if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
1199 Values[3]->isNullValue())
1200 return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
1201
1202 llvm::Constant *Init =
1203 llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001204
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001205 // No special section, but goes in llvm.used
1206 return CreateMetadataVar("\01L_OBJC_PROTOCOLEXT_" + PD->getNameAsString(),
1207 Init,
1208 0, 0, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001209}
1210
1211/*
1212 struct objc_protocol_list {
1213 struct objc_protocol_list *next;
1214 long count;
1215 Protocol *list[];
1216 };
1217*/
Daniel Dunbardbc933702008-08-21 21:57:41 +00001218llvm::Constant *
1219CGObjCMac::EmitProtocolList(const std::string &Name,
1220 ObjCProtocolDecl::protocol_iterator begin,
1221 ObjCProtocolDecl::protocol_iterator end) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001222 std::vector<llvm::Constant*> ProtocolRefs;
1223
Daniel Dunbardbc933702008-08-21 21:57:41 +00001224 for (; begin != end; ++begin)
1225 ProtocolRefs.push_back(GetProtocolRef(*begin));
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001226
1227 // Just return null for empty protocol lists
1228 if (ProtocolRefs.empty())
1229 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1230
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001231 // This list is null terminated.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001232 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
1233
1234 std::vector<llvm::Constant*> Values(3);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001235 // This field is only used by the runtime.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001236 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1237 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
1238 Values[2] =
1239 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
1240 ProtocolRefs.size()),
1241 ProtocolRefs);
1242
1243 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1244 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001245 CreateMetadataVar(Name, Init, "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001246 4, false);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001247 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
1248}
1249
1250/*
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001251 struct _objc_property {
1252 const char * const name;
1253 const char * const attributes;
1254 };
1255
1256 struct _objc_property_list {
1257 uint32_t entsize; // sizeof (struct _objc_property)
1258 uint32_t prop_count;
1259 struct _objc_property[prop_count];
1260 };
1261*/
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001262llvm::Constant *CGObjCCommonMac::EmitPropertyList(const std::string &Name,
1263 const Decl *Container,
1264 const ObjCContainerDecl *OCD,
1265 const ObjCCommonTypesHelper &ObjCTypes) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001266 std::vector<llvm::Constant*> Properties, Prop(2);
Steve Naroff93983f82009-01-11 12:47:58 +00001267 for (ObjCContainerDecl::prop_iterator I = OCD->prop_begin(),
1268 E = OCD->prop_end(); I != E; ++I) {
1269 const ObjCPropertyDecl *PD = *I;
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001270 Prop[0] = GetPropertyName(PD->getIdentifier());
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00001271 Prop[1] = GetPropertyTypeString(PD, Container);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001272 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
1273 Prop));
1274 }
1275
1276 // Return null for empty list.
1277 if (Properties.empty())
1278 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1279
1280 unsigned PropertySize =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001281 CGM.getTargetData().getTypePaddedSize(ObjCTypes.PropertyTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001282 std::vector<llvm::Constant*> Values(3);
1283 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
1284 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
1285 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
1286 Properties.size());
1287 Values[2] = llvm::ConstantArray::get(AT, Properties);
1288 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1289
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001290 // No special section on property lists?
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001291 llvm::GlobalVariable *GV =
1292 CreateMetadataVar(Name, Init, (ObjCABI == 2) ? "__DATA, __objc_const" : 0,
1293 0, true);
1294 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.PropertyListPtrTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001295}
1296
1297/*
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001298 struct objc_method_description_list {
1299 int count;
1300 struct objc_method_description list[];
1301 };
1302*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001303llvm::Constant *
1304CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
1305 std::vector<llvm::Constant*> Desc(2);
1306 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1307 ObjCTypes.SelectorPtrTy);
1308 Desc[1] = GetMethodVarType(MD);
1309 return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
1310 Desc);
1311}
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001312
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001313llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name,
1314 const char *Section,
1315 const ConstantVector &Methods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001316 // Return null for empty list.
1317 if (Methods.empty())
1318 return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
1319
1320 std::vector<llvm::Constant*> Values(2);
1321 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1322 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
1323 Methods.size());
1324 Values[1] = llvm::ConstantArray::get(AT, Methods);
1325 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1326
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001327 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 0, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001328 return llvm::ConstantExpr::getBitCast(GV,
1329 ObjCTypes.MethodDescriptionListPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001330}
1331
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001332/*
1333 struct _objc_category {
1334 char *category_name;
1335 char *class_name;
1336 struct _objc_method_list *instance_methods;
1337 struct _objc_method_list *class_methods;
1338 struct _objc_protocol_list *protocols;
1339 uint32_t size; // <rdar://4585769>
1340 struct _objc_property_list *instance_properties;
1341 };
1342 */
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001343void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001344 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.CategoryTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001345
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001346 // FIXME: This is poor design, the OCD should have a pointer to the
1347 // category decl. Additionally, note that Category can be null for
1348 // the @implementation w/o an @interface case. Sema should just
1349 // create one for us as it does for @implementation so everyone else
1350 // can live life under a clear blue sky.
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001351 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001352 const ObjCCategoryDecl *Category =
1353 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001354 std::string ExtName(Interface->getNameAsString() + "_" +
1355 OCD->getNameAsString());
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001356
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001357 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1358 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
1359 e = OCD->instmeth_end(); i != e; ++i) {
1360 // Instance methods should always be defined.
1361 InstanceMethods.push_back(GetMethodConstant(*i));
1362 }
1363 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
1364 e = OCD->classmeth_end(); i != e; ++i) {
1365 // Class methods should always be defined.
1366 ClassMethods.push_back(GetMethodConstant(*i));
1367 }
1368
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001369 std::vector<llvm::Constant*> Values(7);
1370 Values[0] = GetClassName(OCD->getIdentifier());
1371 Values[1] = GetClassName(Interface->getIdentifier());
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001372 Values[2] =
1373 EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") +
1374 ExtName,
1375 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001376 InstanceMethods);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001377 Values[3] =
1378 EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName,
1379 "__OBJC,__cat_class_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001380 ClassMethods);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001381 if (Category) {
1382 Values[4] =
1383 EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName,
1384 Category->protocol_begin(),
1385 Category->protocol_end());
1386 } else {
1387 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1388 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001389 Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001390
1391 // If there is no category @interface then there can be no properties.
1392 if (Category) {
1393 Values[6] = EmitPropertyList(std::string("\01L_OBJC_$_PROP_LIST_") + ExtName,
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001394 OCD, Category, ObjCTypes);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001395 } else {
1396 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1397 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001398
1399 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
1400 Values);
1401
1402 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001403 CreateMetadataVar(std::string("\01L_OBJC_CATEGORY_")+ExtName, Init,
1404 "__OBJC,__category,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001405 4, true);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001406 DefinedCategories.push_back(GV);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001407}
1408
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001409// FIXME: Get from somewhere?
1410enum ClassFlags {
1411 eClassFlags_Factory = 0x00001,
1412 eClassFlags_Meta = 0x00002,
1413 // <rdr://5142207>
1414 eClassFlags_HasCXXStructors = 0x02000,
1415 eClassFlags_Hidden = 0x20000,
1416 eClassFlags_ABI2_Hidden = 0x00010,
1417 eClassFlags_ABI2_HasCXXStructors = 0x00004 // <rdr://4923634>
1418};
1419
1420// <rdr://5142207&4705298&4843145>
1421static bool IsClassHidden(const ObjCInterfaceDecl *ID) {
1422 if (const VisibilityAttr *attr = ID->getAttr<VisibilityAttr>()) {
1423 // FIXME: Support -fvisibility
1424 switch (attr->getVisibility()) {
1425 default:
1426 assert(0 && "Unknown visibility");
1427 return false;
1428 case VisibilityAttr::DefaultVisibility:
1429 case VisibilityAttr::ProtectedVisibility: // FIXME: What do we do here?
1430 return false;
1431 case VisibilityAttr::HiddenVisibility:
1432 return true;
1433 }
1434 } else {
1435 return false; // FIXME: Support -fvisibility
1436 }
1437}
1438
1439/*
1440 struct _objc_class {
1441 Class isa;
1442 Class super_class;
1443 const char *name;
1444 long version;
1445 long info;
1446 long instance_size;
1447 struct _objc_ivar_list *ivars;
1448 struct _objc_method_list *methods;
1449 struct _objc_cache *cache;
1450 struct _objc_protocol_list *protocols;
1451 // Objective-C 1.0 extensions (<rdr://4585769>)
1452 const char *ivar_layout;
1453 struct _objc_class_ext *ext;
1454 };
1455
1456 See EmitClassExtension();
1457 */
1458void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001459 DefinedSymbols.insert(ID->getIdentifier());
1460
Chris Lattner8ec03f52008-11-24 03:54:41 +00001461 std::string ClassName = ID->getNameAsString();
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001462 // FIXME: Gross
1463 ObjCInterfaceDecl *Interface =
1464 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001465 llvm::Constant *Protocols =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001466 EmitProtocolList("\01L_OBJC_CLASS_PROTOCOLS_" + ID->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001467 Interface->protocol_begin(),
1468 Interface->protocol_end());
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001469 const llvm::Type *InterfaceTy =
Chris Lattner03d9f342009-04-01 06:23:52 +00001470 CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(Interface));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001471 unsigned Flags = eClassFlags_Factory;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001472 unsigned Size = CGM.getTargetData().getTypePaddedSize(InterfaceTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001473
1474 // FIXME: Set CXX-structors flag.
1475 if (IsClassHidden(ID->getClassInterface()))
1476 Flags |= eClassFlags_Hidden;
1477
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001478 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1479 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
1480 e = ID->instmeth_end(); i != e; ++i) {
1481 // Instance methods should always be defined.
1482 InstanceMethods.push_back(GetMethodConstant(*i));
1483 }
1484 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
1485 e = ID->classmeth_end(); i != e; ++i) {
1486 // Class methods should always be defined.
1487 ClassMethods.push_back(GetMethodConstant(*i));
1488 }
1489
1490 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
1491 e = ID->propimpl_end(); i != e; ++i) {
1492 ObjCPropertyImplDecl *PID = *i;
1493
1494 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1495 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1496
1497 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
1498 if (llvm::Constant *C = GetMethodConstant(MD))
1499 InstanceMethods.push_back(C);
1500 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
1501 if (llvm::Constant *C = GetMethodConstant(MD))
1502 InstanceMethods.push_back(C);
1503 }
1504 }
1505
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001506 std::vector<llvm::Constant*> Values(12);
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001507 Values[ 0] = EmitMetaClass(ID, Protocols, InterfaceTy, ClassMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001508 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001509 // Record a reference to the super class.
1510 LazySymbols.insert(Super->getIdentifier());
1511
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001512 Values[ 1] =
1513 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1514 ObjCTypes.ClassPtrTy);
1515 } else {
1516 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1517 }
1518 Values[ 2] = GetClassName(ID->getIdentifier());
1519 // Version is always 0.
1520 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1521 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1522 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001523 Values[ 6] = EmitIvarList(ID, false);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001524 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001525 EmitMethodList("\01L_OBJC_INSTANCE_METHODS_" + ID->getNameAsString(),
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001526 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001527 InstanceMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001528 // cache is always NULL.
1529 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1530 Values[ 9] = Protocols;
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001531 // FIXME: Set ivar_layout
Fariborz Jahanian667423a2009-03-25 22:36:49 +00001532 // Values[10] = BuildIvarLayout(ID, true);
1533 Values[10] = GetIvarLayoutName(0, ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001534 Values[11] = EmitClassExtension(ID);
1535 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1536 Values);
1537
1538 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001539 CreateMetadataVar(std::string("\01L_OBJC_CLASS_")+ClassName, Init,
1540 "__OBJC,__class,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001541 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001542 DefinedClasses.push_back(GV);
1543}
1544
1545llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
1546 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001547 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001548 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001549 unsigned Flags = eClassFlags_Meta;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001550 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001551
1552 if (IsClassHidden(ID->getClassInterface()))
1553 Flags |= eClassFlags_Hidden;
1554
1555 std::vector<llvm::Constant*> Values(12);
1556 // The isa for the metaclass is the root of the hierarchy.
1557 const ObjCInterfaceDecl *Root = ID->getClassInterface();
1558 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
1559 Root = Super;
1560 Values[ 0] =
1561 llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
1562 ObjCTypes.ClassPtrTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001563 // The super class for the metaclass is emitted as the name of the
1564 // super class. The runtime fixes this up to point to the
1565 // *metaclass* for the super class.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001566 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
1567 Values[ 1] =
1568 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1569 ObjCTypes.ClassPtrTy);
1570 } else {
1571 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1572 }
1573 Values[ 2] = GetClassName(ID->getIdentifier());
1574 // Version is always 0.
1575 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1576 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1577 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001578 Values[ 6] = EmitIvarList(ID, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001579 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001580 EmitMethodList("\01L_OBJC_CLASS_METHODS_" + ID->getNameAsString(),
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001581 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001582 Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001583 // cache is always NULL.
1584 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1585 Values[ 9] = Protocols;
1586 // ivar_layout for metaclass is always NULL.
1587 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1588 // The class extension is always unused for metaclasses.
1589 Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1590 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1591 Values);
1592
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001593 std::string Name("\01L_OBJC_METACLASS_");
Chris Lattner8ec03f52008-11-24 03:54:41 +00001594 Name += ID->getNameAsCString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001595
1596 // Check for a forward reference.
1597 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
1598 if (GV) {
1599 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1600 "Forward metaclass reference has incorrect type.");
1601 GV->setLinkage(llvm::GlobalValue::InternalLinkage);
1602 GV->setInitializer(Init);
1603 } else {
1604 GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1605 llvm::GlobalValue::InternalLinkage,
1606 Init, Name,
1607 &CGM.getModule());
1608 }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001609 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001610 GV->setAlignment(4);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001611 UsedGlobals.push_back(GV);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001612
1613 return GV;
1614}
1615
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001616llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001617 std::string Name = "\01L_OBJC_METACLASS_" + ID->getNameAsString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001618
1619 // FIXME: Should we look these up somewhere other than the
1620 // module. Its a bit silly since we only generate these while
1621 // processing an implementation, so exactly one pointer would work
1622 // if know when we entered/exitted an implementation block.
1623
1624 // Check for an existing forward reference.
Fariborz Jahanianb0d27942009-01-07 20:11:22 +00001625 // Previously, metaclass with internal linkage may have been defined.
1626 // pass 'true' as 2nd argument so it is returned.
1627 if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true)) {
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001628 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1629 "Forward metaclass reference has incorrect type.");
1630 return GV;
1631 } else {
1632 // Generate as an external reference to keep a consistent
1633 // module. This will be patched up when we emit the metaclass.
1634 return new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1635 llvm::GlobalValue::ExternalLinkage,
1636 0,
1637 Name,
1638 &CGM.getModule());
1639 }
1640}
1641
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001642/*
1643 struct objc_class_ext {
1644 uint32_t size;
1645 const char *weak_ivar_layout;
1646 struct _objc_property_list *properties;
1647 };
1648*/
1649llvm::Constant *
1650CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
1651 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001652 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassExtensionTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001653
1654 std::vector<llvm::Constant*> Values(3);
1655 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001656 // FIXME: Output weak_ivar_layout string.
Fariborz Jahanian667423a2009-03-25 22:36:49 +00001657 // Values[1] = BuildIvarLayout(ID, false);
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00001658 Values[1] = GetIvarLayoutName(0, ObjCTypes);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001659 Values[2] = EmitPropertyList("\01L_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001660 ID, ID->getClassInterface(), ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001661
1662 // Return null if no extension bits are used.
1663 if (Values[1]->isNullValue() && Values[2]->isNullValue())
1664 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1665
1666 llvm::Constant *Init =
1667 llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001668 return CreateMetadataVar("\01L_OBJC_CLASSEXT_" + ID->getNameAsString(),
1669 Init, 0, 0, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001670}
1671
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001672/// countInheritedIvars - count number of ivars in class and its super class(s)
1673///
1674static int countInheritedIvars(const ObjCInterfaceDecl *OI) {
1675 int count = 0;
1676 if (!OI)
1677 return 0;
1678 const ObjCInterfaceDecl *SuperClass = OI->getSuperClass();
1679 if (SuperClass)
1680 count += countInheritedIvars(SuperClass);
1681 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1682 E = OI->ivar_end(); I != E; ++I)
1683 ++count;
Fariborz Jahanian18191882009-03-31 18:11:23 +00001684 // look into properties.
1685 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
1686 E = OI->prop_end(); I != E; ++I) {
1687 if ((*I)->getPropertyIvarDecl())
1688 ++count;
1689 }
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001690 return count;
1691}
1692
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001693/// getInterfaceDeclForIvar - Get the interface declaration node where
1694/// this ivar is declared in.
1695/// FIXME. Ideally, this info should be in the ivar node. But currently
1696/// it is not and prevailing wisdom is that ASTs should not have more
1697/// info than is absolutely needed, even though this info reflects the
1698/// source language.
1699///
1700static const ObjCInterfaceDecl *getInterfaceDeclForIvar(
1701 const ObjCInterfaceDecl *OI,
1702 const ObjCIvarDecl *IVD) {
1703 if (!OI)
1704 return 0;
1705 assert(isa<ObjCInterfaceDecl>(OI) && "OI is not an interface");
1706 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1707 E = OI->ivar_end(); I != E; ++I)
1708 if ((*I)->getIdentifier() == IVD->getIdentifier())
1709 return OI;
Fariborz Jahanian5a4b4532009-03-31 17:00:52 +00001710 // look into properties.
1711 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
1712 E = OI->prop_end(); I != E; ++I) {
1713 ObjCPropertyDecl *PDecl = (*I);
1714 if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl())
1715 if (IV->getIdentifier() == IVD->getIdentifier())
1716 return OI;
1717 }
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001718 return getInterfaceDeclForIvar(OI->getSuperClass(), IVD);
1719}
1720
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001721/*
1722 struct objc_ivar {
1723 char *ivar_name;
1724 char *ivar_type;
1725 int ivar_offset;
1726 };
1727
1728 struct objc_ivar_list {
1729 int ivar_count;
1730 struct objc_ivar list[count];
1731 };
1732 */
1733llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001734 bool ForClass) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001735 std::vector<llvm::Constant*> Ivars, Ivar(3);
1736
1737 // When emitting the root class GCC emits ivar entries for the
1738 // actual class structure. It is not clear if we need to follow this
1739 // behavior; for now lets try and get away with not doing it. If so,
1740 // the cleanest solution would be to make up an ObjCInterfaceDecl
1741 // for the class.
1742 if (ForClass)
1743 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001744
1745 ObjCInterfaceDecl *OID =
1746 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00001747 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001748
1749 RecordDecl::field_iterator ifield, pfield;
1750 const RecordDecl *RD = GetFirstIvarInRecord(OID, ifield, pfield);
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001751 for (RecordDecl::field_iterator e = RD->field_end(); ifield != e; ++ifield) {
1752 FieldDecl *Field = *ifield;
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00001753 uint64_t Offset = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001754 if (Field->getIdentifier())
1755 Ivar[0] = GetMethodVarName(Field->getIdentifier());
1756 else
1757 Ivar[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Devang Patel7794bb82009-03-04 18:21:39 +00001758 Ivar[1] = GetMethodVarType(Field);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001759 Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy, Offset);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001760 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001761 }
1762
1763 // Return null for empty list.
1764 if (Ivars.empty())
1765 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
1766
1767 std::vector<llvm::Constant*> Values(2);
1768 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
1769 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
1770 Ivars.size());
1771 Values[1] = llvm::ConstantArray::get(AT, Ivars);
1772 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1773
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001774 llvm::GlobalVariable *GV;
1775 if (ForClass)
1776 GV = CreateMetadataVar("\01L_OBJC_CLASS_VARIABLES_" + ID->getNameAsString(),
Daniel Dunbar58a29122009-03-09 22:18:41 +00001777 Init, "__OBJC,__class_vars,regular,no_dead_strip",
1778 4, true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001779 else
1780 GV = CreateMetadataVar("\01L_OBJC_INSTANCE_VARIABLES_"
1781 + ID->getNameAsString(),
1782 Init, "__OBJC,__instance_vars,regular,no_dead_strip",
1783 0, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001784 return llvm::ConstantExpr::getBitCast(GV,
1785 ObjCTypes.IvarListPtrTy);
1786}
1787
1788/*
1789 struct objc_method {
1790 SEL method_name;
1791 char *method_types;
1792 void *method;
1793 };
1794
1795 struct objc_method_list {
1796 struct objc_method_list *obsolete;
1797 int count;
1798 struct objc_method methods_list[count];
1799 };
1800*/
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001801
1802/// GetMethodConstant - Return a struct objc_method constant for the
1803/// given method if it has been defined. The result is null if the
1804/// method has not been defined. The return value has type MethodPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001805llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001806 // FIXME: Use DenseMap::lookup
1807 llvm::Function *Fn = MethodDefinitions[MD];
1808 if (!Fn)
1809 return 0;
1810
1811 std::vector<llvm::Constant*> Method(3);
1812 Method[0] =
1813 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1814 ObjCTypes.SelectorPtrTy);
1815 Method[1] = GetMethodVarType(MD);
1816 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
1817 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
1818}
1819
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001820llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name,
1821 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001822 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001823 // Return null for empty list.
1824 if (Methods.empty())
1825 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
1826
1827 std::vector<llvm::Constant*> Values(3);
1828 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1829 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1830 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
1831 Methods.size());
1832 Values[2] = llvm::ConstantArray::get(AT, Methods);
1833 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1834
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001835 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 0, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001836 return llvm::ConstantExpr::getBitCast(GV,
1837 ObjCTypes.MethodListPtrTy);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001838}
1839
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001840llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD,
Daniel Dunbarbb36d332009-02-02 21:43:58 +00001841 const ObjCContainerDecl *CD) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001842 std::string Name;
Fariborz Jahanian679a5022009-01-10 21:06:09 +00001843 GetNameForMethod(OMD, CD, Name);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001844
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001845 CodeGenTypes &Types = CGM.getTypes();
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001846 const llvm::FunctionType *MethodTy =
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001847 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001848 llvm::Function *Method =
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001849 llvm::Function::Create(MethodTy,
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001850 llvm::GlobalValue::InternalLinkage,
1851 Name,
1852 &CGM.getModule());
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001853 MethodDefinitions.insert(std::make_pair(OMD, Method));
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001854
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001855 return Method;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001856}
1857
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00001858uint64_t CGObjCCommonMac::GetIvarBaseOffset(const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +00001859 const FieldDecl *Field) {
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00001860 if (!Field->isBitField())
1861 return Layout->getElementOffset(
1862 CGM.getTypes().getLLVMFieldNo(Field));
1863 // FIXME. Must be a better way of getting a bitfield base offset.
1864 uint64_t offset = CGM.getTypes().getLLVMFieldNo(Field);
1865 const llvm::Type *Ty = CGM.getTypes().ConvertTypeForMemRecursive(Field->getType());
1866 uint64_t size = CGM.getTypes().getTargetData().getTypePaddedSizeInBits(Ty);
1867 offset = (offset*size)/8;
1868 return offset;
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00001869}
1870
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00001871/// GetFieldBaseOffset - return's field byt offset.
1872uint64_t CGObjCCommonMac::GetFieldBaseOffset(const ObjCInterfaceDecl *OI,
1873 const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +00001874 const FieldDecl *Field) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00001875 const ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
Chris Lattnercd0ee142009-03-31 08:33:16 +00001876 const FieldDecl *FD = OI->lookupFieldDeclForIvar(CGM.getContext(), Ivar);
1877 return GetIvarBaseOffset(Layout, FD);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00001878}
1879
Daniel Dunbarfd65d372009-03-09 20:09:19 +00001880llvm::GlobalVariable *
1881CGObjCCommonMac::CreateMetadataVar(const std::string &Name,
1882 llvm::Constant *Init,
1883 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +00001884 unsigned Align,
1885 bool AddToUsed) {
Daniel Dunbarfd65d372009-03-09 20:09:19 +00001886 const llvm::Type *Ty = Init->getType();
1887 llvm::GlobalVariable *GV =
1888 new llvm::GlobalVariable(Ty, false,
1889 llvm::GlobalValue::InternalLinkage,
1890 Init,
1891 Name,
1892 &CGM.getModule());
1893 if (Section)
1894 GV->setSection(Section);
Daniel Dunbar35bd7632009-03-09 20:50:13 +00001895 if (Align)
1896 GV->setAlignment(Align);
1897 if (AddToUsed)
Daniel Dunbarfd65d372009-03-09 20:09:19 +00001898 UsedGlobals.push_back(GV);
1899 return GV;
1900}
1901
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001902llvm::Function *CGObjCMac::ModuleInitFunction() {
Daniel Dunbarf77ac862008-08-11 21:35:06 +00001903 // Abuse this interface function as a place to finalize.
1904 FinishModule();
1905
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001906 return NULL;
1907}
1908
Chris Lattner74391b42009-03-22 21:03:39 +00001909llvm::Constant *CGObjCMac::GetPropertyGetFunction() {
Daniel Dunbar49f66022008-09-24 03:38:44 +00001910 return ObjCTypes.GetPropertyFn;
1911}
1912
Chris Lattner74391b42009-03-22 21:03:39 +00001913llvm::Constant *CGObjCMac::GetPropertySetFunction() {
Daniel Dunbar49f66022008-09-24 03:38:44 +00001914 return ObjCTypes.SetPropertyFn;
1915}
1916
Chris Lattner74391b42009-03-22 21:03:39 +00001917llvm::Constant *CGObjCMac::EnumerationMutationFunction() {
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001918 return ObjCTypes.EnumerationMutationFn;
1919}
1920
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001921/*
1922
1923Objective-C setjmp-longjmp (sjlj) Exception Handling
1924--
1925
1926The basic framework for a @try-catch-finally is as follows:
1927{
1928 objc_exception_data d;
1929 id _rethrow = null;
Anders Carlsson190d00e2009-02-07 21:26:04 +00001930 bool _call_try_exit = true;
1931
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001932 objc_exception_try_enter(&d);
1933 if (!setjmp(d.jmp_buf)) {
1934 ... try body ...
1935 } else {
1936 // exception path
1937 id _caught = objc_exception_extract(&d);
1938
1939 // enter new try scope for handlers
1940 if (!setjmp(d.jmp_buf)) {
1941 ... match exception and execute catch blocks ...
1942
1943 // fell off end, rethrow.
1944 _rethrow = _caught;
Daniel Dunbar898d5082008-09-30 01:06:03 +00001945 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001946 } else {
1947 // exception in catch block
1948 _rethrow = objc_exception_extract(&d);
Anders Carlsson190d00e2009-02-07 21:26:04 +00001949 _call_try_exit = false;
1950 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001951 }
1952 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00001953 ... jump-through-finally to finally_end ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001954
1955finally:
Anders Carlsson190d00e2009-02-07 21:26:04 +00001956 if (_call_try_exit)
1957 objc_exception_try_exit(&d);
1958
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001959 ... finally block ....
Daniel Dunbar898d5082008-09-30 01:06:03 +00001960 ... dispatch to finally destination ...
1961
1962finally_rethrow:
1963 objc_exception_throw(_rethrow);
1964
1965finally_end:
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001966}
1967
1968This framework differs slightly from the one gcc uses, in that gcc
Daniel Dunbar898d5082008-09-30 01:06:03 +00001969uses _rethrow to determine if objc_exception_try_exit should be called
1970and if the object should be rethrown. This breaks in the face of
1971throwing nil and introduces unnecessary branches.
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001972
1973We specialize this framework for a few particular circumstances:
1974
1975 - If there are no catch blocks, then we avoid emitting the second
1976 exception handling context.
1977
1978 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
1979 e)) we avoid emitting the code to rethrow an uncaught exception.
1980
1981 - FIXME: If there is no @finally block we can do a few more
1982 simplifications.
1983
1984Rethrows and Jumps-Through-Finally
1985--
1986
1987Support for implicit rethrows and jumping through the finally block is
1988handled by storing the current exception-handling context in
1989ObjCEHStack.
1990
Daniel Dunbar898d5082008-09-30 01:06:03 +00001991In order to implement proper @finally semantics, we support one basic
1992mechanism for jumping through the finally block to an arbitrary
1993destination. Constructs which generate exits from a @try or @catch
1994block use this mechanism to implement the proper semantics by chaining
1995jumps, as necessary.
1996
1997This mechanism works like the one used for indirect goto: we
1998arbitrarily assign an ID to each destination and store the ID for the
1999destination in a variable prior to entering the finally block. At the
2000end of the finally block we simply create a switch to the proper
2001destination.
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002002
2003Code gen for @synchronized(expr) stmt;
2004Effectively generating code for:
2005objc_sync_enter(expr);
2006@try stmt @finally { objc_sync_exit(expr); }
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002007*/
2008
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002009void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
2010 const Stmt &S) {
2011 bool isTry = isa<ObjCAtTryStmt>(S);
Daniel Dunbar898d5082008-09-30 01:06:03 +00002012 // Create various blocks we refer to for handling @finally.
Daniel Dunbar55e87422008-11-11 02:29:29 +00002013 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002014 llvm::BasicBlock *FinallyExit = CGF.createBasicBlock("finally.exit");
Daniel Dunbar55e87422008-11-11 02:29:29 +00002015 llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
2016 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
2017 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
Daniel Dunbar1c566672009-02-24 01:43:46 +00002018
2019 // For @synchronized, call objc_sync_enter(sync.expr). The
2020 // evaluation of the expression must occur before we enter the
2021 // @synchronized. We can safely avoid a temp here because jumps into
2022 // @synchronized are illegal & this will dominate uses.
2023 llvm::Value *SyncArg = 0;
2024 if (!isTry) {
2025 SyncArg =
2026 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
2027 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00002028 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar1c566672009-02-24 01:43:46 +00002029 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00002030
2031 // Push an EH context entry, used for handling rethrows and jumps
2032 // through finally.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002033 CGF.PushCleanupBlock(FinallyBlock);
2034
Anders Carlsson273558f2009-02-07 21:37:21 +00002035 CGF.ObjCEHValueStack.push_back(0);
2036
Daniel Dunbar898d5082008-09-30 01:06:03 +00002037 // Allocate memory for the exception data and rethrow pointer.
Anders Carlsson80f25672008-09-09 17:59:25 +00002038 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
2039 "exceptiondata.ptr");
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002040 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
2041 "_rethrow");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002042 llvm::Value *CallTryExitPtr = CGF.CreateTempAlloca(llvm::Type::Int1Ty,
2043 "_call_try_exit");
2044 CGF.Builder.CreateStore(llvm::ConstantInt::getTrue(), CallTryExitPtr);
2045
Anders Carlsson80f25672008-09-09 17:59:25 +00002046 // Enter a new try block and call setjmp.
2047 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
2048 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
2049 "jmpbufarray");
2050 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
2051 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
2052 JmpBufPtr, "result");
Daniel Dunbar898d5082008-09-30 01:06:03 +00002053
Daniel Dunbar55e87422008-11-11 02:29:29 +00002054 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
2055 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002056 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002057 TryHandler, TryBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002058
2059 // Emit the @try block.
2060 CGF.EmitBlock(TryBlock);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002061 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
2062 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002063 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002064
2065 // Emit the "exception in @try" block.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002066 CGF.EmitBlock(TryHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002067
2068 // Retrieve the exception object. We may emit multiple blocks but
2069 // nothing can cross this so the value is already in SSA form.
2070 llvm::Value *Caught = CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
2071 ExceptionData,
2072 "caught");
Anders Carlsson273558f2009-02-07 21:37:21 +00002073 CGF.ObjCEHValueStack.back() = Caught;
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002074 if (!isTry)
2075 {
2076 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002077 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002078 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002079 }
2080 else if (const ObjCAtCatchStmt* CatchStmt =
2081 cast<ObjCAtTryStmt>(S).getCatchStmts())
2082 {
Daniel Dunbar55e40722008-09-27 07:03:52 +00002083 // Enter a new exception try block (in case a @catch block throws
2084 // an exception).
Anders Carlsson80f25672008-09-09 17:59:25 +00002085 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002086
Anders Carlsson80f25672008-09-09 17:59:25 +00002087 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
2088 JmpBufPtr, "result");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002089 llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw");
Anders Carlsson80f25672008-09-09 17:59:25 +00002090
Daniel Dunbar55e87422008-11-11 02:29:29 +00002091 llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch");
2092 llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler");
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002093 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002094
2095 CGF.EmitBlock(CatchBlock);
2096
Daniel Dunbar55e40722008-09-27 07:03:52 +00002097 // Handle catch list. As a special case we check if everything is
2098 // matched and avoid generating code for falling off the end if
2099 // so.
2100 bool AllMatched = false;
Anders Carlsson80f25672008-09-09 17:59:25 +00002101 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbar55e87422008-11-11 02:29:29 +00002102 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch");
Anders Carlsson80f25672008-09-09 17:59:25 +00002103
Steve Naroff7ba138a2009-03-03 19:52:17 +00002104 const ParmVarDecl *CatchParam = CatchStmt->getCatchParamDecl();
Daniel Dunbar129271a2008-09-27 07:36:24 +00002105 const PointerType *PT = 0;
2106
Anders Carlsson80f25672008-09-09 17:59:25 +00002107 // catch(...) always matches.
Daniel Dunbar55e40722008-09-27 07:03:52 +00002108 if (!CatchParam) {
2109 AllMatched = true;
2110 } else {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002111 PT = CatchParam->getType()->getAsPointerType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002112
Daniel Dunbar97f61d12008-09-27 22:21:14 +00002113 // catch(id e) always matches.
2114 // FIXME: For the time being we also match id<X>; this should
2115 // be rejected by Sema instead.
Steve Naroff389bf462009-02-12 17:52:19 +00002116 if ((PT && CGF.getContext().isObjCIdStructType(PT->getPointeeType())) ||
Steve Naroff7ba138a2009-03-03 19:52:17 +00002117 CatchParam->getType()->isObjCQualifiedIdType())
Daniel Dunbar55e40722008-09-27 07:03:52 +00002118 AllMatched = true;
Anders Carlsson80f25672008-09-09 17:59:25 +00002119 }
2120
Daniel Dunbar55e40722008-09-27 07:03:52 +00002121 if (AllMatched) {
Anders Carlssondde0a942008-09-11 09:15:33 +00002122 if (CatchParam) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002123 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002124 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002125 CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002126 }
Anders Carlsson1452f552008-09-11 08:21:54 +00002127
Anders Carlssondde0a942008-09-11 09:15:33 +00002128 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002129 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002130 break;
2131 }
2132
Daniel Dunbar129271a2008-09-27 07:36:24 +00002133 assert(PT && "Unexpected non-pointer type in @catch");
2134 QualType T = PT->getPointeeType();
Anders Carlsson4b7ff6e2008-09-11 06:35:14 +00002135 const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002136 assert(ObjCType && "Catch parameter must have Objective-C type!");
2137
2138 // Check if the @catch block matches the exception object.
2139 llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl());
2140
Anders Carlsson80f25672008-09-09 17:59:25 +00002141 llvm::Value *Match = CGF.Builder.CreateCall2(ObjCTypes.ExceptionMatchFn,
2142 Class, Caught, "match");
Anders Carlsson80f25672008-09-09 17:59:25 +00002143
Daniel Dunbar55e87422008-11-11 02:29:29 +00002144 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched");
Anders Carlsson80f25672008-09-09 17:59:25 +00002145
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002146 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002147 MatchedBlock, NextCatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002148
2149 // Emit the @catch block.
2150 CGF.EmitBlock(MatchedBlock);
Steve Naroff7ba138a2009-03-03 19:52:17 +00002151 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002152 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002153
2154 llvm::Value *Tmp =
Steve Naroff7ba138a2009-03-03 19:52:17 +00002155 CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(CatchParam->getType()),
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002156 "tmp");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002157 CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002158
2159 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002160 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002161
2162 CGF.EmitBlock(NextCatchBlock);
2163 }
2164
Daniel Dunbar55e40722008-09-27 07:03:52 +00002165 if (!AllMatched) {
2166 // None of the handlers caught the exception, so store it to be
2167 // rethrown at the end of the @finally block.
2168 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002169 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002170 }
2171
2172 // Emit the exception handler for the @catch blocks.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002173 CGF.EmitBlock(CatchHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002174 CGF.Builder.CreateStore(CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
2175 ExceptionData),
2176 RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002177 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002178 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002179 } else {
Anders Carlsson80f25672008-09-09 17:59:25 +00002180 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002181 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002182 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Anders Carlsson80f25672008-09-09 17:59:25 +00002183 }
2184
Daniel Dunbar898d5082008-09-30 01:06:03 +00002185 // Pop the exception-handling stack entry. It is important to do
2186 // this now, because the code in the @finally block is not in this
2187 // context.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002188 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
2189
Anders Carlsson273558f2009-02-07 21:37:21 +00002190 CGF.ObjCEHValueStack.pop_back();
2191
Anders Carlsson80f25672008-09-09 17:59:25 +00002192 // Emit the @finally block.
2193 CGF.EmitBlock(FinallyBlock);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002194 llvm::Value* CallTryExit = CGF.Builder.CreateLoad(CallTryExitPtr, "tmp");
2195
2196 CGF.Builder.CreateCondBr(CallTryExit, FinallyExit, FinallyNoExit);
2197
2198 CGF.EmitBlock(FinallyExit);
Anders Carlsson80f25672008-09-09 17:59:25 +00002199 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryExitFn, ExceptionData);
Daniel Dunbar129271a2008-09-27 07:36:24 +00002200
2201 CGF.EmitBlock(FinallyNoExit);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002202 if (isTry) {
2203 if (const ObjCAtFinallyStmt* FinallyStmt =
2204 cast<ObjCAtTryStmt>(S).getFinallyStmt())
2205 CGF.EmitStmt(FinallyStmt->getFinallyBody());
Daniel Dunbar1c566672009-02-24 01:43:46 +00002206 } else {
2207 // Emit objc_sync_exit(expr); as finally's sole statement for
2208 // @synchronized.
2209 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, SyncArg);
Fariborz Jahanianf2878e52008-11-21 19:21:53 +00002210 }
Anders Carlsson80f25672008-09-09 17:59:25 +00002211
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002212 // Emit the switch block
2213 if (Info.SwitchBlock)
2214 CGF.EmitBlock(Info.SwitchBlock);
2215 if (Info.EndBlock)
2216 CGF.EmitBlock(Info.EndBlock);
2217
Daniel Dunbar898d5082008-09-30 01:06:03 +00002218 CGF.EmitBlock(FinallyRethrow);
2219 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn,
2220 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002221 CGF.Builder.CreateUnreachable();
Daniel Dunbar898d5082008-09-30 01:06:03 +00002222
2223 CGF.EmitBlock(FinallyEnd);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002224}
2225
2226void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar898d5082008-09-30 01:06:03 +00002227 const ObjCAtThrowStmt &S) {
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002228 llvm::Value *ExceptionAsObject;
2229
2230 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2231 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
2232 ExceptionAsObject =
2233 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
2234 } else {
Anders Carlsson273558f2009-02-07 21:37:21 +00002235 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002236 "Unexpected rethrow outside @catch block.");
Anders Carlsson273558f2009-02-07 21:37:21 +00002237 ExceptionAsObject = CGF.ObjCEHValueStack.back();
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002238 }
2239
2240 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
Anders Carlsson80f25672008-09-09 17:59:25 +00002241 CGF.Builder.CreateUnreachable();
Daniel Dunbara448fb22008-11-11 23:11:34 +00002242
2243 // Clear the insertion point to indicate we are in unreachable code.
2244 CGF.Builder.ClearInsertionPoint();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002245}
2246
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002247/// EmitObjCWeakRead - Code gen for loading value of a __weak
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002248/// object: objc_read_weak (id *src)
2249///
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002250llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002251 llvm::Value *AddrWeakObj)
2252{
Eli Friedman8339b352009-03-07 03:57:15 +00002253 const llvm::Type* DestTy =
2254 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002255 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002256 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002257 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00002258 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002259 return read_weak;
2260}
2261
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002262/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
2263/// objc_assign_weak (id src, id *dst)
2264///
2265void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
2266 llvm::Value *src, llvm::Value *dst)
2267{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002268 const llvm::Type * SrcTy = src->getType();
2269 if (!isa<llvm::PointerType>(SrcTy)) {
2270 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2271 assert(Size <= 8 && "does not support size > 8");
2272 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2273 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002274 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2275 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002276 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2277 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002278 CGF.Builder.CreateCall2(ObjCTypes.GcAssignWeakFn,
2279 src, dst, "weakassign");
2280 return;
2281}
2282
Fariborz Jahanian58626502008-11-19 00:59:10 +00002283/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
2284/// objc_assign_global (id src, id *dst)
2285///
2286void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
2287 llvm::Value *src, llvm::Value *dst)
2288{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002289 const llvm::Type * SrcTy = src->getType();
2290 if (!isa<llvm::PointerType>(SrcTy)) {
2291 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2292 assert(Size <= 8 && "does not support size > 8");
2293 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2294 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002295 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2296 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002297 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2298 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian58626502008-11-19 00:59:10 +00002299 CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn,
2300 src, dst, "globalassign");
2301 return;
2302}
2303
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002304/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
2305/// objc_assign_ivar (id src, id *dst)
2306///
2307void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
2308 llvm::Value *src, llvm::Value *dst)
2309{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002310 const llvm::Type * SrcTy = src->getType();
2311 if (!isa<llvm::PointerType>(SrcTy)) {
2312 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2313 assert(Size <= 8 && "does not support size > 8");
2314 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2315 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002316 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2317 }
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002318 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2319 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
2320 CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn,
2321 src, dst, "assignivar");
2322 return;
2323}
2324
Fariborz Jahanian58626502008-11-19 00:59:10 +00002325/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
2326/// objc_assign_strongCast (id src, id *dst)
2327///
2328void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
2329 llvm::Value *src, llvm::Value *dst)
2330{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002331 const llvm::Type * SrcTy = src->getType();
2332 if (!isa<llvm::PointerType>(SrcTy)) {
2333 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2334 assert(Size <= 8 && "does not support size > 8");
2335 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2336 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002337 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2338 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002339 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2340 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian58626502008-11-19 00:59:10 +00002341 CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn,
2342 src, dst, "weakassign");
2343 return;
2344}
2345
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002346/// EmitObjCValueForIvar - Code Gen for ivar reference.
2347///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002348LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
2349 QualType ObjectTy,
2350 llvm::Value *BaseValue,
2351 const ObjCIvarDecl *Ivar,
2352 const FieldDecl *Field,
2353 unsigned CVRQualifiers) {
2354 if (Ivar->isBitField())
2355 return CGF.EmitLValueForBitfield(BaseValue, const_cast<FieldDecl *>(Field),
2356 CVRQualifiers);
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002357 // TODO: Add a special case for isa (index 0)
2358 unsigned Index = CGM.getTypes().getLLVMFieldNo(Field);
2359 llvm::Value *V = CGF.Builder.CreateStructGEP(BaseValue, Index, "tmp");
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002360 LValue LV = LValue::MakeAddr(V,
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00002361 Ivar->getType().getCVRQualifiers()|CVRQualifiers,
2362 CGM.getContext().getObjCGCAttrKind(Ivar->getType()));
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002363 LValue::SetObjCIvar(LV, true);
2364 return LV;
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002365}
2366
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002367llvm::Value *CGObjCMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
2368 ObjCInterfaceDecl *Interface,
2369 const ObjCIvarDecl *Ivar) {
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002370 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(Interface);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002371 FieldDecl *Field = Interface->lookupFieldDeclForIvar(CGM.getContext(), Ivar);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00002372 uint64_t Offset = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002373 return llvm::ConstantInt::get(
2374 CGM.getTypes().ConvertType(CGM.getContext().LongTy),
2375 Offset);
2376}
2377
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002378/* *** Private Interface *** */
2379
2380/// EmitImageInfo - Emit the image info marker used to encode some module
2381/// level information.
2382///
2383/// See: <rdr://4810609&4810587&4810587>
2384/// struct IMAGE_INFO {
2385/// unsigned version;
2386/// unsigned flags;
2387/// };
2388enum ImageInfoFlags {
2389 eImageInfo_FixAndContinue = (1 << 0), // FIXME: Not sure what this implies
2390 eImageInfo_GarbageCollected = (1 << 1),
2391 eImageInfo_GCOnly = (1 << 2)
2392};
2393
2394void CGObjCMac::EmitImageInfo() {
2395 unsigned version = 0; // Version is unused?
2396 unsigned flags = 0;
2397
2398 // FIXME: Fix and continue?
2399 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
2400 flags |= eImageInfo_GarbageCollected;
2401 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
2402 flags |= eImageInfo_GCOnly;
2403
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002404 // Emitted as int[2];
2405 llvm::Constant *values[2] = {
2406 llvm::ConstantInt::get(llvm::Type::Int32Ty, version),
2407 llvm::ConstantInt::get(llvm::Type::Int32Ty, flags)
2408 };
2409 llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002410
2411 const char *Section;
2412 if (ObjCABI == 1)
2413 Section = "__OBJC, __image_info,regular";
2414 else
2415 Section = "__DATA, __objc_imageinfo, regular, no_dead_strip";
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002416 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002417 CreateMetadataVar("\01L_OBJC_IMAGE_INFO",
2418 llvm::ConstantArray::get(AT, values, 2),
2419 Section,
2420 0,
2421 true);
2422 GV->setConstant(true);
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002423}
2424
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002425
2426// struct objc_module {
2427// unsigned long version;
2428// unsigned long size;
2429// const char *name;
2430// Symtab symtab;
2431// };
2432
2433// FIXME: Get from somewhere
2434static const int ModuleVersion = 7;
2435
2436void CGObjCMac::EmitModuleInfo() {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00002437 uint64_t Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ModuleTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002438
2439 std::vector<llvm::Constant*> Values(4);
2440 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
2441 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002442 // This used to be the filename, now it is unused. <rdr://4327263>
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002443 Values[2] = GetClassName(&CGM.getContext().Idents.get(""));
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002444 Values[3] = EmitModuleSymbols();
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002445 CreateMetadataVar("\01L_OBJC_MODULES",
2446 llvm::ConstantStruct::get(ObjCTypes.ModuleTy, Values),
2447 "__OBJC,__module_info,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00002448 4, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002449}
2450
2451llvm::Constant *CGObjCMac::EmitModuleSymbols() {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002452 unsigned NumClasses = DefinedClasses.size();
2453 unsigned NumCategories = DefinedCategories.size();
2454
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002455 // Return null if no symbols were defined.
2456 if (!NumClasses && !NumCategories)
2457 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
2458
2459 std::vector<llvm::Constant*> Values(5);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002460 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2461 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
2462 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
2463 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
2464
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002465 // The runtime expects exactly the list of defined classes followed
2466 // by the list of defined categories, in a single array.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002467 std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002468 for (unsigned i=0; i<NumClasses; i++)
2469 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
2470 ObjCTypes.Int8PtrTy);
2471 for (unsigned i=0; i<NumCategories; i++)
2472 Symbols[NumClasses + i] =
2473 llvm::ConstantExpr::getBitCast(DefinedCategories[i],
2474 ObjCTypes.Int8PtrTy);
2475
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002476 Values[4] =
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002477 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002478 NumClasses + NumCategories),
2479 Symbols);
2480
2481 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2482
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002483 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002484 CreateMetadataVar("\01L_OBJC_SYMBOLS", Init,
2485 "__OBJC,__symbols,regular,no_dead_strip",
2486 0, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002487 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
2488}
2489
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002490llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002491 const ObjCInterfaceDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002492 LazySymbols.insert(ID->getIdentifier());
2493
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002494 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
2495
2496 if (!Entry) {
2497 llvm::Constant *Casted =
2498 llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()),
2499 ObjCTypes.ClassPtrTy);
2500 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002501 CreateMetadataVar("\01L_OBJC_CLASS_REFERENCES_", Casted,
2502 "__OBJC,__cls_refs,literal_pointers,no_dead_strip",
2503 0, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002504 }
2505
2506 return Builder.CreateLoad(Entry, false, "tmp");
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002507}
2508
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002509llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002510 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
2511
2512 if (!Entry) {
2513 llvm::Constant *Casted =
2514 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
2515 ObjCTypes.SelectorPtrTy);
2516 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002517 CreateMetadataVar("\01L_OBJC_SELECTOR_REFERENCES_", Casted,
2518 "__OBJC,__message_refs,literal_pointers,no_dead_strip",
2519 0, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002520 }
2521
2522 return Builder.CreateLoad(Entry, false, "tmp");
2523}
2524
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00002525llvm::Constant *CGObjCCommonMac::GetClassName(IdentifierInfo *Ident) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002526 llvm::GlobalVariable *&Entry = ClassNames[Ident];
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002527
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002528 if (!Entry)
2529 Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
2530 llvm::ConstantArray::get(Ident->getName()),
2531 "__TEXT,__cstring,cstring_literals",
2532 0, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002533
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002534 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002535}
2536
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002537/// GetInterfaceDeclStructLayout - Get layout for ivars of given
2538/// interface declaration.
2539const llvm::StructLayout *CGObjCCommonMac::GetInterfaceDeclStructLayout(
2540 const ObjCInterfaceDecl *OID) const {
2541 const llvm::Type *InterfaceTy =
2542 CGM.getTypes().ConvertType(
2543 CGM.getContext().getObjCInterfaceType(
2544 const_cast<ObjCInterfaceDecl*>(OID)));
2545 const llvm::StructLayout *Layout =
2546 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceTy));
2547 return Layout;
2548}
2549
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00002550/// GetIvarLayoutName - Returns a unique constant for the given
2551/// ivar layout bitmap.
2552llvm::Constant *CGObjCCommonMac::GetIvarLayoutName(IdentifierInfo *Ident,
2553 const ObjCCommonTypesHelper &ObjCTypes) {
2554 return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2555}
2556
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002557void CGObjCCommonMac::BuildAggrIvarLayout(const ObjCInterfaceDecl *OI,
2558 const llvm::StructLayout *Layout,
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002559 const RecordDecl *RD,
Chris Lattnerf1690852009-03-31 08:48:01 +00002560 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002561 unsigned int BytePos, bool ForStrongLayout,
2562 int &Index, int &SkIndex, bool &HasUnion) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002563 bool IsUnion = (RD && RD->isUnion());
2564 uint64_t MaxUnionIvarSize = 0;
2565 uint64_t MaxSkippedUnionIvarSize = 0;
2566 FieldDecl *MaxField = 0;
2567 FieldDecl *MaxSkippedField = 0;
Chris Lattnerf1690852009-03-31 08:48:01 +00002568 unsigned base = 0;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002569 if (RecFields.empty())
2570 return;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002571 if (IsUnion)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002572 base = BytePos + GetFieldBaseOffset(OI, Layout, RecFields[0]);
Chris Lattnerf1690852009-03-31 08:48:01 +00002573 unsigned WordSizeInBits = CGM.getContext().Target.getPointerWidth(0);
2574 unsigned ByteSizeInBits = CGM.getContext().Target.getCharWidth();
2575
2576 llvm::SmallVector<FieldDecl*, 16> TmpRecFields;
2577
2578 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002579 FieldDecl *Field = RecFields[i];
2580 // Skip over unnamed or bitfields
2581 if (!Field->getIdentifier() || Field->isBitField())
2582 continue;
2583 QualType FQT = Field->getType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002584 if (FQT->isRecordType() || FQT->isUnionType()) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002585 if (FQT->isUnionType())
2586 HasUnion = true;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002587 else
2588 assert(FQT->isRecordType() &&
2589 "only union/record is supported for ivar layout bitmap");
2590
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002591 const RecordType *RT = FQT->getAsRecordType();
2592 const RecordDecl *RD = RT->getDecl();
2593 // FIXME - Find a more efficiant way of passing records down.
Chris Lattnerf1690852009-03-31 08:48:01 +00002594 TmpRecFields.append(RD->field_begin(), RD->field_end());
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002595 // FIXME - Is Layout correct?
Chris Lattnerf1690852009-03-31 08:48:01 +00002596 BuildAggrIvarLayout(OI, Layout, RD, TmpRecFields,
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002597 BytePos + GetFieldBaseOffset(OI, Layout, Field),
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002598 ForStrongLayout, Index, SkIndex,
2599 HasUnion);
Chris Lattnerf1690852009-03-31 08:48:01 +00002600 TmpRecFields.clear();
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002601 continue;
2602 }
Chris Lattnerf1690852009-03-31 08:48:01 +00002603
2604 if (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002605 const ConstantArrayType *CArray =
2606 dyn_cast_or_null<ConstantArrayType>(Array);
2607 assert(CArray && "only array with know element size is supported");
2608 FQT = CArray->getElementType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002609 while (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
2610 const ConstantArrayType *CArray =
2611 dyn_cast_or_null<ConstantArrayType>(Array);
2612 FQT = CArray->getElementType();
2613 }
2614
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002615 assert(!FQT->isUnionType() &&
2616 "layout for array of unions not supported");
2617 if (FQT->isRecordType()) {
2618 uint64_t ElCount = CArray->getSize().getZExtValue();
2619 int OldIndex = Index;
2620 int OldSkIndex = SkIndex;
2621
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002622 // FIXME - Use a common routine with the above!
2623 const RecordType *RT = FQT->getAsRecordType();
2624 const RecordDecl *RD = RT->getDecl();
2625 // FIXME - Find a more efficiant way of passing records down.
Chris Lattnerf1690852009-03-31 08:48:01 +00002626 TmpRecFields.append(RD->field_begin(), RD->field_end());
2627
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002628 BuildAggrIvarLayout(OI, Layout, RD,
Chris Lattnerf1690852009-03-31 08:48:01 +00002629 TmpRecFields,
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002630 BytePos + GetFieldBaseOffset(OI, Layout, Field),
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002631 ForStrongLayout, Index, SkIndex,
2632 HasUnion);
Chris Lattnerf1690852009-03-31 08:48:01 +00002633 TmpRecFields.clear();
2634
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002635 // Replicate layout information for each array element. Note that
2636 // one element is already done.
2637 uint64_t ElIx = 1;
2638 for (int FirstIndex = Index, FirstSkIndex = SkIndex;
2639 ElIx < ElCount; ElIx++) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002640 uint64_t Size = CGM.getContext().getTypeSize(RT)/ByteSizeInBits;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002641 for (int i = OldIndex+1; i <= FirstIndex; ++i)
2642 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002643 GC_IVAR gcivar;
2644 gcivar.ivar_bytepos = IvarsInfo[i].ivar_bytepos + Size*ElIx;
2645 gcivar.ivar_size = IvarsInfo[i].ivar_size;
2646 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002647 }
2648
Chris Lattnerf1690852009-03-31 08:48:01 +00002649 for (int i = OldSkIndex+1; i <= FirstSkIndex; ++i) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002650 GC_IVAR skivar;
2651 skivar.ivar_bytepos = SkipIvars[i].ivar_bytepos + Size*ElIx;
2652 skivar.ivar_size = SkipIvars[i].ivar_size;
2653 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002654 }
2655 }
2656 continue;
2657 }
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002658 }
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002659 // At this point, we are done with Record/Union and array there of.
2660 // For other arrays we are down to its element type.
2661 QualType::GCAttrTypes GCAttr = QualType::GCNone;
2662 do {
2663 if (FQT.isObjCGCStrong() || FQT.isObjCGCWeak()) {
2664 GCAttr = FQT.isObjCGCStrong() ? QualType::Strong : QualType::Weak;
2665 break;
2666 }
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002667 else if (CGM.getContext().isObjCObjectPointerType(FQT)) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002668 GCAttr = QualType::Strong;
2669 break;
2670 }
2671 else if (const PointerType *PT = FQT->getAsPointerType()) {
2672 FQT = PT->getPointeeType();
2673 }
2674 else {
2675 break;
2676 }
2677 } while (true);
Chris Lattnerf1690852009-03-31 08:48:01 +00002678
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002679 if ((ForStrongLayout && GCAttr == QualType::Strong)
2680 || (!ForStrongLayout && GCAttr == QualType::Weak)) {
2681 if (IsUnion)
2682 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002683 uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType())
2684 / WordSizeInBits;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002685 if (UnionIvarSize > MaxUnionIvarSize)
2686 {
2687 MaxUnionIvarSize = UnionIvarSize;
2688 MaxField = Field;
2689 }
2690 }
2691 else
2692 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002693 GC_IVAR gcivar;
2694 gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field);
2695 gcivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) /
2696 WordSizeInBits;
2697 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002698 }
2699 }
2700 else if ((ForStrongLayout &&
2701 (GCAttr == QualType::GCNone || GCAttr == QualType::Weak))
2702 || (!ForStrongLayout && GCAttr != QualType::Weak)) {
2703 if (IsUnion)
2704 {
2705 uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType());
2706 if (UnionIvarSize > MaxSkippedUnionIvarSize)
2707 {
2708 MaxSkippedUnionIvarSize = UnionIvarSize;
2709 MaxSkippedField = Field;
2710 }
2711 }
2712 else
2713 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002714 GC_IVAR skivar;
2715 skivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field);
2716 skivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) /
2717 WordSizeInBits;
2718 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002719 }
2720 }
2721 }
Chris Lattnerf1690852009-03-31 08:48:01 +00002722 if (MaxField) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002723 GC_IVAR gcivar;
2724 gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, MaxField);
2725 gcivar.ivar_size = MaxUnionIvarSize;
2726 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002727 }
Chris Lattnerf1690852009-03-31 08:48:01 +00002728
2729 if (MaxSkippedField) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002730 GC_IVAR skivar;
2731 skivar.ivar_bytepos = BytePos +
2732 GetFieldBaseOffset(OI, Layout, MaxSkippedField);
2733 skivar.ivar_size = MaxSkippedUnionIvarSize;
2734 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002735 }
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002736}
2737
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002738static int
Chris Lattnerf1690852009-03-31 08:48:01 +00002739IvarBytePosCompare(const void *a, const void *b)
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002740{
2741 unsigned int sa = ((CGObjCCommonMac::GC_IVAR *)a)->ivar_bytepos;
2742 unsigned int sb = ((CGObjCCommonMac::GC_IVAR *)b)->ivar_bytepos;
2743
2744 if (sa < sb)
2745 return -1;
2746 if (sa > sb)
2747 return 1;
2748 return 0;
2749}
2750
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002751/// BuildIvarLayout - Builds ivar layout bitmap for the class
2752/// implementation for the __strong or __weak case.
2753/// The layout map displays which words in ivar list must be skipped
2754/// and which must be scanned by GC (see below). String is built of bytes.
2755/// Each byte is divided up in two nibbles (4-bit each). Left nibble is count
2756/// of words to skip and right nibble is count of words to scan. So, each
2757/// nibble represents up to 15 workds to skip or scan. Skipping the rest is
2758/// represented by a 0x00 byte which also ends the string.
2759/// 1. when ForStrongLayout is true, following ivars are scanned:
2760/// - id, Class
2761/// - object *
2762/// - __strong anything
2763///
2764/// 2. When ForStrongLayout is false, following ivars are scanned:
2765/// - __weak anything
2766///
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002767llvm::Constant *CGObjCCommonMac::BuildIvarLayout(
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002768 const ObjCImplementationDecl *OMD,
2769 bool ForStrongLayout) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002770 int Index = -1;
2771 int SkIndex = -1;
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002772 bool hasUnion = false;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002773 int SkipScan;
2774 unsigned int WordsToScan, WordsToSkip;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002775 const llvm::Type *PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
2776 if (CGM.getLangOptions().getGCMode() == LangOptions::NonGC)
2777 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002778
Chris Lattnerf1690852009-03-31 08:48:01 +00002779 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002780 const ObjCInterfaceDecl *OI = OMD->getClassInterface();
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002781 CGM.getContext().CollectObjCIvars(OI, RecFields);
2782 if (RecFields.empty())
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002783 return llvm::Constant::getNullValue(PtrTy);
Chris Lattnerf1690852009-03-31 08:48:01 +00002784
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002785 SkipIvars.clear();
2786 IvarsInfo.clear();
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002787
2788 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OI);
Chris Lattnerf1690852009-03-31 08:48:01 +00002789 BuildAggrIvarLayout(OI, Layout, 0, RecFields, 0, ForStrongLayout,
2790 Index, SkIndex, hasUnion);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002791 if (Index == -1)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002792 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002793
2794 // Sort on byte position in case we encounterred a union nested in
2795 // the ivar list.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002796 if (hasUnion && !IvarsInfo.empty())
2797 qsort(&IvarsInfo[0], Index+1, sizeof(GC_IVAR), IvarBytePosCompare);
2798 if (hasUnion && !SkipIvars.empty())
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002799 qsort(&SkipIvars[0], Index+1, sizeof(GC_IVAR), IvarBytePosCompare);
2800
2801 // Build the string of skip/scan nibbles
2802 SkipScan = -1;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002803 SkipScanIvars.clear();
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002804 unsigned int WordSize =
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002805 CGM.getTypes().getTargetData().getTypePaddedSize(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002806 if (IvarsInfo[0].ivar_bytepos == 0) {
2807 WordsToSkip = 0;
2808 WordsToScan = IvarsInfo[0].ivar_size;
2809 }
2810 else {
2811 WordsToSkip = IvarsInfo[0].ivar_bytepos/WordSize;
2812 WordsToScan = IvarsInfo[0].ivar_size;
2813 }
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002814 for (unsigned int i=1, Last=IvarsInfo.size(); i != Last; i++)
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002815 {
2816 unsigned int TailPrevGCObjC =
2817 IvarsInfo[i-1].ivar_bytepos + IvarsInfo[i-1].ivar_size * WordSize;
2818 if (IvarsInfo[i].ivar_bytepos == TailPrevGCObjC)
2819 {
2820 // consecutive 'scanned' object pointers.
2821 WordsToScan += IvarsInfo[i].ivar_size;
2822 }
2823 else
2824 {
2825 // Skip over 'gc'able object pointer which lay over each other.
2826 if (TailPrevGCObjC > IvarsInfo[i].ivar_bytepos)
2827 continue;
2828 // Must skip over 1 or more words. We save current skip/scan values
2829 // and start a new pair.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002830 SKIP_SCAN SkScan;
2831 SkScan.skip = WordsToSkip;
2832 SkScan.scan = WordsToScan;
2833 SkipScanIvars.push_back(SkScan); ++SkipScan;
2834
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002835 // Skip the hole.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002836 SkScan.skip = (IvarsInfo[i].ivar_bytepos - TailPrevGCObjC) / WordSize;
2837 SkScan.scan = 0;
2838 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002839 WordsToSkip = 0;
2840 WordsToScan = IvarsInfo[i].ivar_size;
2841 }
2842 }
2843 if (WordsToScan > 0)
2844 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002845 SKIP_SCAN SkScan;
2846 SkScan.skip = WordsToSkip;
2847 SkScan.scan = WordsToScan;
2848 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002849 }
2850
2851 bool BytesSkipped = false;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002852 if (!SkipIvars.empty())
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002853 {
2854 int LastByteSkipped =
2855 SkipIvars[SkIndex].ivar_bytepos + SkipIvars[SkIndex].ivar_size;
2856 int LastByteScanned =
2857 IvarsInfo[Index].ivar_bytepos + IvarsInfo[Index].ivar_size * WordSize;
2858 BytesSkipped = (LastByteSkipped > LastByteScanned);
2859 // Compute number of bytes to skip at the tail end of the last ivar scanned.
2860 if (BytesSkipped)
2861 {
2862 unsigned int TotalWords = (LastByteSkipped + (WordSize -1)) / WordSize;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002863 SKIP_SCAN SkScan;
2864 SkScan.skip = TotalWords - (LastByteScanned/WordSize);
2865 SkScan.scan = 0;
2866 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002867 }
2868 }
2869 // Mini optimization of nibbles such that an 0xM0 followed by 0x0N is produced
2870 // as 0xMN.
2871 for (int i = 0; i <= SkipScan; i++)
2872 {
2873 if ((i < SkipScan) && SkipScanIvars[i].skip && SkipScanIvars[i].scan == 0
2874 && SkipScanIvars[i+1].skip == 0 && SkipScanIvars[i+1].scan) {
2875 // 0xM0 followed by 0x0N detected.
2876 SkipScanIvars[i].scan = SkipScanIvars[i+1].scan;
2877 for (int j = i+1; j < SkipScan; j++)
2878 SkipScanIvars[j] = SkipScanIvars[j+1];
2879 --SkipScan;
2880 }
2881 }
2882
2883 // Generate the string.
2884 std::string BitMap;
2885 for (int i = 0; i <= SkipScan; i++)
2886 {
2887 unsigned char byte;
2888 unsigned int skip_small = SkipScanIvars[i].skip % 0xf;
2889 unsigned int scan_small = SkipScanIvars[i].scan % 0xf;
2890 unsigned int skip_big = SkipScanIvars[i].skip / 0xf;
2891 unsigned int scan_big = SkipScanIvars[i].scan / 0xf;
2892
2893 if (skip_small > 0 || skip_big > 0)
2894 BytesSkipped = true;
2895 // first skip big.
2896 for (unsigned int ix = 0; ix < skip_big; ix++)
2897 BitMap += (unsigned char)(0xf0);
2898
2899 // next (skip small, scan)
2900 if (skip_small)
2901 {
2902 byte = skip_small << 4;
2903 if (scan_big > 0)
2904 {
2905 byte |= 0xf;
2906 --scan_big;
2907 }
2908 else if (scan_small)
2909 {
2910 byte |= scan_small;
2911 scan_small = 0;
2912 }
2913 BitMap += byte;
2914 }
2915 // next scan big
2916 for (unsigned int ix = 0; ix < scan_big; ix++)
2917 BitMap += (unsigned char)(0x0f);
2918 // last scan small
2919 if (scan_small)
2920 {
2921 byte = scan_small;
2922 BitMap += byte;
2923 }
2924 }
2925 // null terminate string.
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002926 unsigned char zero = 0;
2927 BitMap += zero;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002928 // if ivar_layout bitmap is all 1 bits (nothing skipped) then use NULL as
2929 // final layout.
2930 if (ForStrongLayout && !BytesSkipped)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002931 return llvm::Constant::getNullValue(PtrTy);
2932 llvm::GlobalVariable * Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
2933 llvm::ConstantArray::get(BitMap.c_str()),
2934 "__TEXT,__cstring,cstring_literals",
2935 0, true);
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002936 // FIXME. Need a commomand-line option for this eventually.
2937 if (ForStrongLayout)
2938 printf("\nstrong ivar layout: ");
2939 else
2940 printf("\nweak ivar layout: ");
2941 const unsigned char *s = (unsigned char*)BitMap.c_str();
2942 for (unsigned i = 0; i < BitMap.size(); i++)
Fariborz Jahaniandbf15cb2009-03-26 19:10:36 +00002943 if (!(s[i] & 0xf0))
2944 printf("0x0%x%s", s[i], s[i] != 0 ? ", " : "");
2945 else
2946 printf("0x%x%s", s[i], s[i] != 0 ? ", " : "");
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002947 printf("\n");
2948
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002949 return getConstantGEP(Entry, 0, 0);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002950}
2951
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002952llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002953 llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
2954
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002955 // FIXME: Avoid std::string copying.
2956 if (!Entry)
2957 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_NAME_",
2958 llvm::ConstantArray::get(Sel.getAsString()),
2959 "__TEXT,__cstring,cstring_literals",
2960 0, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002961
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002962 return getConstantGEP(Entry, 0, 0);
2963}
2964
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002965// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002966llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002967 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
2968}
2969
2970// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002971llvm::Constant *CGObjCCommonMac::GetMethodVarName(const std::string &Name) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002972 return GetMethodVarName(&CGM.getContext().Idents.get(Name));
2973}
2974
Devang Patel7794bb82009-03-04 18:21:39 +00002975llvm::Constant *CGObjCCommonMac::GetMethodVarType(FieldDecl *Field) {
2976 std::string TypeStr;
2977 CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
2978
2979 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002980
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002981 if (!Entry)
2982 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
2983 llvm::ConstantArray::get(TypeStr),
2984 "__TEXT,__cstring,cstring_literals",
2985 0, true);
2986
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002987 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002988}
2989
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002990llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002991 std::string TypeStr;
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002992 CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D),
2993 TypeStr);
Devang Patel7794bb82009-03-04 18:21:39 +00002994
2995 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
2996
2997 if (!Entry) {
2998 llvm::Constant *C = llvm::ConstantArray::get(TypeStr);
2999 Entry =
3000 new llvm::GlobalVariable(C->getType(), false,
3001 llvm::GlobalValue::InternalLinkage,
3002 C, "\01L_OBJC_METH_VAR_TYPE_",
3003 &CGM.getModule());
3004 Entry->setSection("__TEXT,__cstring,cstring_literals");
3005 UsedGlobals.push_back(Entry);
3006 }
3007
3008 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003009}
3010
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003011// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003012llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003013 llvm::GlobalVariable *&Entry = PropertyNames[Ident];
3014
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003015 if (!Entry)
3016 Entry = CreateMetadataVar("\01L_OBJC_PROP_NAME_ATTR_",
3017 llvm::ConstantArray::get(Ident->getName()),
3018 "__TEXT,__cstring,cstring_literals",
3019 0, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003020
3021 return getConstantGEP(Entry, 0, 0);
3022}
3023
3024// FIXME: Merge into a single cstring creation function.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003025// FIXME: This Decl should be more precise.
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003026llvm::Constant *
3027 CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
3028 const Decl *Container) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003029 std::string TypeStr;
3030 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003031 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
3032}
3033
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003034void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D,
3035 const ObjCContainerDecl *CD,
3036 std::string &NameOut) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00003037 // FIXME: Find the mangling GCC uses.
Douglas Gregorf8d49f62009-01-09 17:18:27 +00003038 NameOut = (D->isInstanceMethod() ? "-" : "+");
Chris Lattner077bf5e2008-11-24 03:33:13 +00003039 NameOut += '[';
Fariborz Jahanian679a5022009-01-10 21:06:09 +00003040 assert (CD && "Missing container decl in GetNameForMethod");
3041 NameOut += CD->getNameAsString();
Fariborz Jahanian52847332009-01-26 23:49:05 +00003042 // FIXME. For a method in a category, (CAT_NAME) is inserted here.
3043 // Right now! there is not enough info. to do this.
Chris Lattner077bf5e2008-11-24 03:33:13 +00003044 NameOut += ' ';
3045 NameOut += D->getSelector().getAsString();
3046 NameOut += ']';
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00003047}
3048
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00003049/// GetFirstIvarInRecord - This routine returns the record for the
3050/// implementation of the fiven class OID. It also returns field
3051/// corresponding to the first ivar in the class in FIV. It also
3052/// returns the one before the first ivar.
3053///
3054const RecordDecl *CGObjCCommonMac::GetFirstIvarInRecord(
3055 const ObjCInterfaceDecl *OID,
3056 RecordDecl::field_iterator &FIV,
3057 RecordDecl::field_iterator &PIV) {
3058 int countSuperClassIvars = countInheritedIvars(OID->getSuperClass());
3059 const RecordDecl *RD = CGM.getContext().addRecordToClass(OID);
3060 RecordDecl::field_iterator ifield = RD->field_begin();
3061 RecordDecl::field_iterator pfield = RD->field_end();
3062 while (countSuperClassIvars-- > 0) {
3063 pfield = ifield;
3064 ++ifield;
3065 }
3066 FIV = ifield;
3067 PIV = pfield;
3068 return RD;
3069}
3070
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003071void CGObjCMac::FinishModule() {
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003072 EmitModuleInfo();
3073
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003074 // Emit the dummy bodies for any protocols which were referenced but
3075 // never defined.
3076 for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
3077 i = Protocols.begin(), e = Protocols.end(); i != e; ++i) {
3078 if (i->second->hasInitializer())
3079 continue;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003080
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003081 std::vector<llvm::Constant*> Values(5);
3082 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
3083 Values[1] = GetClassName(i->first);
3084 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
3085 Values[3] = Values[4] =
3086 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
3087 i->second->setLinkage(llvm::GlobalValue::InternalLinkage);
3088 i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
3089 Values));
3090 }
3091
3092 std::vector<llvm::Constant*> Used;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003093 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003094 e = UsedGlobals.end(); i != e; ++i) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003095 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003096 }
3097
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003098 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003099 llvm::GlobalValue *GV =
3100 new llvm::GlobalVariable(AT, false,
3101 llvm::GlobalValue::AppendingLinkage,
3102 llvm::ConstantArray::get(AT, Used),
3103 "llvm.used",
3104 &CGM.getModule());
3105
3106 GV->setSection("llvm.metadata");
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003107
3108 // Add assembler directives to add lazy undefined symbol references
3109 // for classes which are referenced but not defined. This is
3110 // important for correct linker interaction.
3111
3112 // FIXME: Uh, this isn't particularly portable.
3113 std::stringstream s;
Anders Carlsson565c99f2008-12-10 02:21:04 +00003114
3115 if (!CGM.getModule().getModuleInlineAsm().empty())
3116 s << "\n";
3117
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003118 for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(),
3119 e = LazySymbols.end(); i != e; ++i) {
3120 s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n";
3121 }
3122 for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(),
3123 e = DefinedSymbols.end(); i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003124 s << "\t.objc_class_name_" << (*i)->getName() << "=0\n"
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003125 << "\t.globl .objc_class_name_" << (*i)->getName() << "\n";
3126 }
Anders Carlsson565c99f2008-12-10 02:21:04 +00003127
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003128 CGM.getModule().appendModuleInlineAsm(s.str());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003129}
3130
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003131CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003132 : CGObjCCommonMac(cgm),
3133 ObjCTypes(cgm)
3134{
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003135 ObjCEmptyCacheVar = ObjCEmptyVtableVar = NULL;
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003136 ObjCABI = 2;
3137}
3138
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003139/* *** */
3140
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003141ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm)
3142: CGM(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003143{
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003144 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3145 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003146
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003147 ShortTy = Types.ConvertType(Ctx.ShortTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003148 IntTy = Types.ConvertType(Ctx.IntTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003149 LongTy = Types.ConvertType(Ctx.LongTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00003150 LongLongTy = Types.ConvertType(Ctx.LongLongTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003151 Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3152
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003153 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00003154 PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003155 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003156
3157 // FIXME: It would be nice to unify this with the opaque type, so
3158 // that the IR comes out a bit cleaner.
3159 const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
3160 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003161
3162 // I'm not sure I like this. The implicit coordination is a bit
3163 // gross. We should solve this in a reasonable fashion because this
3164 // is a pretty common task (match some runtime data structure with
3165 // an LLVM data structure).
3166
3167 // FIXME: This is leaked.
3168 // FIXME: Merge with rewriter code?
3169
3170 // struct _objc_super {
3171 // id self;
3172 // Class cls;
3173 // }
3174 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3175 SourceLocation(),
3176 &Ctx.Idents.get("_objc_super"));
3177 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3178 Ctx.getObjCIdType(), 0, false));
3179 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3180 Ctx.getObjCClassType(), 0, false));
3181 RD->completeDefinition(Ctx);
3182
3183 SuperCTy = Ctx.getTagDeclType(RD);
3184 SuperPtrCTy = Ctx.getPointerType(SuperCTy);
3185
3186 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003187 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
3188
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003189 // struct _prop_t {
3190 // char *name;
3191 // char *attributes;
3192 // }
3193 PropertyTy = llvm::StructType::get(Int8PtrTy,
3194 Int8PtrTy,
3195 NULL);
3196 CGM.getModule().addTypeName("struct._prop_t",
3197 PropertyTy);
3198
3199 // struct _prop_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003200 // uint32_t entsize; // sizeof(struct _prop_t)
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003201 // uint32_t count_of_properties;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003202 // struct _prop_t prop_list[count_of_properties];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003203 // }
3204 PropertyListTy = llvm::StructType::get(IntTy,
3205 IntTy,
3206 llvm::ArrayType::get(PropertyTy, 0),
3207 NULL);
3208 CGM.getModule().addTypeName("struct._prop_list_t",
3209 PropertyListTy);
3210 // struct _prop_list_t *
3211 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
3212
3213 // struct _objc_method {
3214 // SEL _cmd;
3215 // char *method_type;
3216 // char *_imp;
3217 // }
3218 MethodTy = llvm::StructType::get(SelectorPtrTy,
3219 Int8PtrTy,
3220 Int8PtrTy,
3221 NULL);
3222 CGM.getModule().addTypeName("struct._objc_method", MethodTy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003223
3224 // struct _objc_cache *
3225 CacheTy = llvm::OpaqueType::get();
3226 CGM.getModule().addTypeName("struct._objc_cache", CacheTy);
3227 CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003228
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003229 // Property manipulation functions.
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003230
3231 QualType IdType = Ctx.getObjCIdType();
3232 QualType SelType = Ctx.getObjCSelType();
3233 llvm::SmallVector<QualType,16> Params;
3234 const llvm::FunctionType *FTy;
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003235
3236 // id objc_getProperty (id, SEL, ptrdiff_t, bool)
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003237 Params.push_back(IdType);
3238 Params.push_back(SelType);
3239 Params.push_back(Ctx.LongTy);
3240 Params.push_back(Ctx.BoolTy);
3241 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params),
3242 false);
3243 GetPropertyFn = CGM.CreateRuntimeFunction(FTy, "objc_getProperty");
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003244
3245 // void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool)
3246 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003247 Params.push_back(IdType);
3248 Params.push_back(SelType);
3249 Params.push_back(Ctx.LongTy);
3250 Params.push_back(IdType);
3251 Params.push_back(Ctx.BoolTy);
3252 Params.push_back(Ctx.BoolTy);
3253 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
3254 SetPropertyFn = CGM.CreateRuntimeFunction(FTy, "objc_setProperty");
3255
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003256 // Enumeration mutation.
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003257
3258 // void objc_enumerationMutation (id)
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003259 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003260 Params.push_back(IdType);
3261 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
3262 EnumerationMutationFn = CGM.CreateRuntimeFunction(FTy,
3263 "objc_enumerationMutation");
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003264
3265 // gc's API
3266 // id objc_read_weak (id *)
3267 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003268 Params.push_back(Ctx.getPointerType(IdType));
3269 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
3270 GcReadWeakFn = CGM.CreateRuntimeFunction(FTy, "objc_read_weak");
3271
3272 // id objc_assign_weak (id, id *)
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003273 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003274 Params.push_back(IdType);
3275 Params.push_back(Ctx.getPointerType(IdType));
3276
3277 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
3278 GcAssignWeakFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_weak");
3279 GcAssignGlobalFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_global");
3280 GcAssignIvarFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_ivar");
3281 GcAssignStrongCastFn =
3282 CGM.CreateRuntimeFunction(FTy, "objc_assign_strongCast");
Anders Carlssonf57c5b22009-02-16 22:59:18 +00003283
3284 // void objc_exception_throw(id)
3285 Params.clear();
3286 Params.push_back(IdType);
3287
3288 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00003289 ExceptionThrowFn =
3290 CGM.CreateRuntimeFunction(FTy, "objc_exception_throw");
Daniel Dunbar1c566672009-02-24 01:43:46 +00003291
3292 // synchronized APIs
Daniel Dunbar1c566672009-02-24 01:43:46 +00003293 // void objc_sync_exit (id)
3294 Params.clear();
3295 Params.push_back(IdType);
3296
3297 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
Daniel Dunbar1c566672009-02-24 01:43:46 +00003298 SyncExitFn = CGM.CreateRuntimeFunction(FTy, "objc_sync_exit");
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003299}
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003300
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003301ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
3302 : ObjCCommonTypesHelper(cgm)
3303{
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003304 // struct _objc_method_description {
3305 // SEL name;
3306 // char *types;
3307 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003308 MethodDescriptionTy =
3309 llvm::StructType::get(SelectorPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003310 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003311 NULL);
3312 CGM.getModule().addTypeName("struct._objc_method_description",
3313 MethodDescriptionTy);
3314
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003315 // struct _objc_method_description_list {
3316 // int count;
3317 // struct _objc_method_description[1];
3318 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003319 MethodDescriptionListTy =
3320 llvm::StructType::get(IntTy,
3321 llvm::ArrayType::get(MethodDescriptionTy, 0),
3322 NULL);
3323 CGM.getModule().addTypeName("struct._objc_method_description_list",
3324 MethodDescriptionListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003325
3326 // struct _objc_method_description_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003327 MethodDescriptionListPtrTy =
3328 llvm::PointerType::getUnqual(MethodDescriptionListTy);
3329
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003330 // Protocol description structures
3331
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003332 // struct _objc_protocol_extension {
3333 // uint32_t size; // sizeof(struct _objc_protocol_extension)
3334 // struct _objc_method_description_list *optional_instance_methods;
3335 // struct _objc_method_description_list *optional_class_methods;
3336 // struct _objc_property_list *instance_properties;
3337 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003338 ProtocolExtensionTy =
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003339 llvm::StructType::get(IntTy,
3340 MethodDescriptionListPtrTy,
3341 MethodDescriptionListPtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003342 PropertyListPtrTy,
3343 NULL);
3344 CGM.getModule().addTypeName("struct._objc_protocol_extension",
3345 ProtocolExtensionTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003346
3347 // struct _objc_protocol_extension *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003348 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
3349
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003350 // Handle recursive construction of Protocol and ProtocolList types
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003351
3352 llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get();
3353 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3354
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003355 const llvm::Type *T =
3356 llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder),
3357 LongTy,
3358 llvm::ArrayType::get(ProtocolTyHolder, 0),
3359 NULL);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003360 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T);
3361
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003362 // struct _objc_protocol {
3363 // struct _objc_protocol_extension *isa;
3364 // char *protocol_name;
3365 // struct _objc_protocol **_objc_protocol_list;
3366 // struct _objc_method_description_list *instance_methods;
3367 // struct _objc_method_description_list *class_methods;
3368 // }
3369 T = llvm::StructType::get(ProtocolExtensionPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003370 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003371 llvm::PointerType::getUnqual(ProtocolListTyHolder),
3372 MethodDescriptionListPtrTy,
3373 MethodDescriptionListPtrTy,
3374 NULL);
3375 cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T);
3376
3377 ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get());
3378 CGM.getModule().addTypeName("struct._objc_protocol_list",
3379 ProtocolListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003380 // struct _objc_protocol_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003381 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
3382
3383 ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get());
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003384 CGM.getModule().addTypeName("struct._objc_protocol", ProtocolTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003385 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003386
3387 // Class description structures
3388
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003389 // struct _objc_ivar {
3390 // char *ivar_name;
3391 // char *ivar_type;
3392 // int ivar_offset;
3393 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003394 IvarTy = llvm::StructType::get(Int8PtrTy,
3395 Int8PtrTy,
3396 IntTy,
3397 NULL);
3398 CGM.getModule().addTypeName("struct._objc_ivar", IvarTy);
3399
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003400 // struct _objc_ivar_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003401 IvarListTy = llvm::OpaqueType::get();
3402 CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy);
3403 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
3404
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003405 // struct _objc_method_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003406 MethodListTy = llvm::OpaqueType::get();
3407 CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy);
3408 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
3409
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003410 // struct _objc_class_extension *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003411 ClassExtensionTy =
3412 llvm::StructType::get(IntTy,
3413 Int8PtrTy,
3414 PropertyListPtrTy,
3415 NULL);
3416 CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy);
3417 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
3418
3419 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3420
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003421 // struct _objc_class {
3422 // Class isa;
3423 // Class super_class;
3424 // char *name;
3425 // long version;
3426 // long info;
3427 // long instance_size;
3428 // struct _objc_ivar_list *ivars;
3429 // struct _objc_method_list *methods;
3430 // struct _objc_cache *cache;
3431 // struct _objc_protocol_list *protocols;
3432 // char *ivar_layout;
3433 // struct _objc_class_ext *ext;
3434 // };
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003435 T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3436 llvm::PointerType::getUnqual(ClassTyHolder),
3437 Int8PtrTy,
3438 LongTy,
3439 LongTy,
3440 LongTy,
3441 IvarListPtrTy,
3442 MethodListPtrTy,
3443 CachePtrTy,
3444 ProtocolListPtrTy,
3445 Int8PtrTy,
3446 ClassExtensionPtrTy,
3447 NULL);
3448 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T);
3449
3450 ClassTy = cast<llvm::StructType>(ClassTyHolder.get());
3451 CGM.getModule().addTypeName("struct._objc_class", ClassTy);
3452 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
3453
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003454 // struct _objc_category {
3455 // char *category_name;
3456 // char *class_name;
3457 // struct _objc_method_list *instance_method;
3458 // struct _objc_method_list *class_method;
3459 // uint32_t size; // sizeof(struct _objc_category)
3460 // struct _objc_property_list *instance_properties;// category's @property
3461 // }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003462 CategoryTy = llvm::StructType::get(Int8PtrTy,
3463 Int8PtrTy,
3464 MethodListPtrTy,
3465 MethodListPtrTy,
3466 ProtocolListPtrTy,
3467 IntTy,
3468 PropertyListPtrTy,
3469 NULL);
3470 CGM.getModule().addTypeName("struct._objc_category", CategoryTy);
3471
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003472 // Global metadata structures
3473
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003474 // struct _objc_symtab {
3475 // long sel_ref_cnt;
3476 // SEL *refs;
3477 // short cls_def_cnt;
3478 // short cat_def_cnt;
3479 // char *defs[cls_def_cnt + cat_def_cnt];
3480 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003481 SymtabTy = llvm::StructType::get(LongTy,
3482 SelectorPtrTy,
3483 ShortTy,
3484 ShortTy,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003485 llvm::ArrayType::get(Int8PtrTy, 0),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003486 NULL);
3487 CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy);
3488 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
3489
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003490 // struct _objc_module {
3491 // long version;
3492 // long size; // sizeof(struct _objc_module)
3493 // char *name;
3494 // struct _objc_symtab* symtab;
3495 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003496 ModuleTy =
3497 llvm::StructType::get(LongTy,
3498 LongTy,
3499 Int8PtrTy,
3500 SymtabPtrTy,
3501 NULL);
3502 CGM.getModule().addTypeName("struct._objc_module", ModuleTy);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003503
Daniel Dunbar49f66022008-09-24 03:38:44 +00003504 // Message send functions.
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003505
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003506 // id objc_msgSend (id, SEL, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003507 std::vector<const llvm::Type*> Params;
3508 Params.push_back(ObjectPtrTy);
3509 Params.push_back(SelectorPtrTy);
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003510 MessageSendFn =
3511 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3512 Params,
3513 true),
3514 "objc_msgSend");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003515
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003516 // id objc_msgSend_stret (id, SEL, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003517 Params.clear();
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003518 Params.push_back(ObjectPtrTy);
3519 Params.push_back(SelectorPtrTy);
3520 MessageSendStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003521 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3522 Params,
3523 true),
3524 "objc_msgSend_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00003525
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003526 //
Daniel Dunbar5669e572008-10-17 03:24:53 +00003527 Params.clear();
3528 Params.push_back(ObjectPtrTy);
3529 Params.push_back(SelectorPtrTy);
3530 // FIXME: This should be long double on x86_64?
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003531 // [double | long double] objc_msgSend_fpret(id self, SEL op, ...)
Daniel Dunbar5669e572008-10-17 03:24:53 +00003532 MessageSendFpretFn =
3533 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::DoubleTy,
3534 Params,
3535 true),
3536 "objc_msgSend_fpret");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003537
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003538 // id objc_msgSendSuper(struct objc_super *super, SEL op, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003539 Params.clear();
3540 Params.push_back(SuperPtrTy);
3541 Params.push_back(SelectorPtrTy);
3542 MessageSendSuperFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003543 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3544 Params,
3545 true),
3546 "objc_msgSendSuper");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003547
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003548 // void objc_msgSendSuper_stret(void * stretAddr, struct objc_super *super,
3549 // SEL op, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003550 Params.clear();
3551 Params.push_back(Int8PtrTy);
3552 Params.push_back(SuperPtrTy);
3553 Params.push_back(SelectorPtrTy);
3554 MessageSendSuperStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003555 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3556 Params,
3557 true),
3558 "objc_msgSendSuper_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00003559
3560 // There is no objc_msgSendSuper_fpret? How can that work?
3561 MessageSendSuperFpretFn = MessageSendSuperFn;
Anders Carlsson2abd89c2008-08-31 04:05:03 +00003562
Anders Carlsson124526b2008-09-09 10:10:21 +00003563 // FIXME: This is the size of the setjmp buffer and should be
3564 // target specific. 18 is what's used on 32-bit X86.
3565 uint64_t SetJmpBufferSize = 18;
3566
3567 // Exceptions
3568 const llvm::Type *StackPtrTy =
Daniel Dunbar10004912008-09-27 06:32:25 +00003569 llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4);
Anders Carlsson124526b2008-09-09 10:10:21 +00003570
3571 ExceptionDataTy =
3572 llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty,
3573 SetJmpBufferSize),
3574 StackPtrTy, NULL);
3575 CGM.getModule().addTypeName("struct._objc_exception_data",
3576 ExceptionDataTy);
3577
3578 Params.clear();
Anders Carlsson124526b2008-09-09 10:10:21 +00003579 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
3580 ExceptionTryEnterFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003581 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3582 Params,
3583 false),
3584 "objc_exception_try_enter");
Anders Carlsson124526b2008-09-09 10:10:21 +00003585 ExceptionTryExitFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003586 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3587 Params,
3588 false),
3589 "objc_exception_try_exit");
Anders Carlsson124526b2008-09-09 10:10:21 +00003590 ExceptionExtractFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003591 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3592 Params,
3593 false),
3594 "objc_exception_extract");
Anders Carlsson124526b2008-09-09 10:10:21 +00003595
3596 Params.clear();
3597 Params.push_back(ClassPtrTy);
3598 Params.push_back(ObjectPtrTy);
3599 ExceptionMatchFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003600 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
3601 Params,
3602 false),
3603 "objc_exception_match");
Chris Lattner10cac6f2008-11-15 21:26:17 +00003604
Anders Carlsson124526b2008-09-09 10:10:21 +00003605 Params.clear();
3606 Params.push_back(llvm::PointerType::getUnqual(llvm::Type::Int32Ty));
3607 SetJmpFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003608 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
3609 Params,
3610 false),
3611 "_setjmp");
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00003612
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003613}
3614
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003615ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003616: ObjCCommonTypesHelper(cgm)
3617{
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003618 // struct _method_list_t {
3619 // uint32_t entsize; // sizeof(struct _objc_method)
3620 // uint32_t method_count;
3621 // struct _objc_method method_list[method_count];
3622 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003623 MethodListnfABITy = llvm::StructType::get(IntTy,
3624 IntTy,
3625 llvm::ArrayType::get(MethodTy, 0),
3626 NULL);
3627 CGM.getModule().addTypeName("struct.__method_list_t",
3628 MethodListnfABITy);
3629 // struct method_list_t *
3630 MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003631
3632 // struct _protocol_t {
3633 // id isa; // NULL
3634 // const char * const protocol_name;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003635 // const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003636 // const struct method_list_t * const instance_methods;
3637 // const struct method_list_t * const class_methods;
3638 // const struct method_list_t *optionalInstanceMethods;
3639 // const struct method_list_t *optionalClassMethods;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003640 // const struct _prop_list_t * properties;
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003641 // const uint32_t size; // sizeof(struct _protocol_t)
3642 // const uint32_t flags; // = 0
3643 // }
3644
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003645 // Holder for struct _protocol_list_t *
3646 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3647
3648 ProtocolnfABITy = llvm::StructType::get(ObjectPtrTy,
3649 Int8PtrTy,
3650 llvm::PointerType::getUnqual(
3651 ProtocolListTyHolder),
3652 MethodListnfABIPtrTy,
3653 MethodListnfABIPtrTy,
3654 MethodListnfABIPtrTy,
3655 MethodListnfABIPtrTy,
3656 PropertyListPtrTy,
3657 IntTy,
3658 IntTy,
3659 NULL);
3660 CGM.getModule().addTypeName("struct._protocol_t",
3661 ProtocolnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003662
3663 // struct _protocol_t*
3664 ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003665
Fariborz Jahanianda320092009-01-29 19:24:30 +00003666 // struct _protocol_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003667 // long protocol_count; // Note, this is 32/64 bit
Daniel Dunbar948e2582009-02-15 07:36:20 +00003668 // struct _protocol_t *[protocol_count];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003669 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003670 ProtocolListnfABITy = llvm::StructType::get(LongTy,
3671 llvm::ArrayType::get(
Daniel Dunbar948e2582009-02-15 07:36:20 +00003672 ProtocolnfABIPtrTy, 0),
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003673 NULL);
3674 CGM.getModule().addTypeName("struct._objc_protocol_list",
3675 ProtocolListnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003676 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(
3677 ProtocolListnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003678
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003679 // struct _objc_protocol_list*
3680 ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003681
3682 // struct _ivar_t {
3683 // unsigned long int *offset; // pointer to ivar offset location
3684 // char *name;
3685 // char *type;
3686 // uint32_t alignment;
3687 // uint32_t size;
3688 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003689 IvarnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(LongTy),
3690 Int8PtrTy,
3691 Int8PtrTy,
3692 IntTy,
3693 IntTy,
3694 NULL);
3695 CGM.getModule().addTypeName("struct._ivar_t", IvarnfABITy);
3696
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003697 // struct _ivar_list_t {
3698 // uint32 entsize; // sizeof(struct _ivar_t)
3699 // uint32 count;
3700 // struct _iver_t list[count];
3701 // }
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003702 IvarListnfABITy = llvm::StructType::get(IntTy,
3703 IntTy,
3704 llvm::ArrayType::get(
3705 IvarnfABITy, 0),
3706 NULL);
3707 CGM.getModule().addTypeName("struct._ivar_list_t", IvarListnfABITy);
3708
3709 IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003710
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003711 // struct _class_ro_t {
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003712 // uint32_t const flags;
3713 // uint32_t const instanceStart;
3714 // uint32_t const instanceSize;
3715 // uint32_t const reserved; // only when building for 64bit targets
3716 // const uint8_t * const ivarLayout;
3717 // const char *const name;
3718 // const struct _method_list_t * const baseMethods;
3719 // const struct _objc_protocol_list *const baseProtocols;
3720 // const struct _ivar_list_t *const ivars;
3721 // const uint8_t * const weakIvarLayout;
3722 // const struct _prop_list_t * const properties;
3723 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003724
3725 // FIXME. Add 'reserved' field in 64bit abi mode!
3726 ClassRonfABITy = llvm::StructType::get(IntTy,
3727 IntTy,
3728 IntTy,
3729 Int8PtrTy,
3730 Int8PtrTy,
3731 MethodListnfABIPtrTy,
3732 ProtocolListnfABIPtrTy,
3733 IvarListnfABIPtrTy,
3734 Int8PtrTy,
3735 PropertyListPtrTy,
3736 NULL);
3737 CGM.getModule().addTypeName("struct._class_ro_t",
3738 ClassRonfABITy);
3739
3740 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
3741 std::vector<const llvm::Type*> Params;
3742 Params.push_back(ObjectPtrTy);
3743 Params.push_back(SelectorPtrTy);
3744 ImpnfABITy = llvm::PointerType::getUnqual(
3745 llvm::FunctionType::get(ObjectPtrTy, Params, false));
3746
3747 // struct _class_t {
3748 // struct _class_t *isa;
3749 // struct _class_t * const superclass;
3750 // void *cache;
3751 // IMP *vtable;
3752 // struct class_ro_t *ro;
3753 // }
3754
3755 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3756 ClassnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3757 llvm::PointerType::getUnqual(ClassTyHolder),
3758 CachePtrTy,
3759 llvm::PointerType::getUnqual(ImpnfABITy),
3760 llvm::PointerType::getUnqual(
3761 ClassRonfABITy),
3762 NULL);
3763 CGM.getModule().addTypeName("struct._class_t", ClassnfABITy);
3764
3765 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(
3766 ClassnfABITy);
3767
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003768 // LLVM for struct _class_t *
3769 ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy);
3770
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003771 // struct _category_t {
3772 // const char * const name;
3773 // struct _class_t *const cls;
3774 // const struct _method_list_t * const instance_methods;
3775 // const struct _method_list_t * const class_methods;
3776 // const struct _protocol_list_t * const protocols;
3777 // const struct _prop_list_t * const properties;
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003778 // }
3779 CategorynfABITy = llvm::StructType::get(Int8PtrTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003780 ClassnfABIPtrTy,
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003781 MethodListnfABIPtrTy,
3782 MethodListnfABIPtrTy,
3783 ProtocolListnfABIPtrTy,
3784 PropertyListPtrTy,
3785 NULL);
3786 CGM.getModule().addTypeName("struct._category_t", CategorynfABITy);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003787
3788 // New types for nonfragile abi messaging.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003789 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3790 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003791
3792 // MessageRefTy - LLVM for:
3793 // struct _message_ref_t {
3794 // IMP messenger;
3795 // SEL name;
3796 // };
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003797
3798 // First the clang type for struct _message_ref_t
3799 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3800 SourceLocation(),
3801 &Ctx.Idents.get("_message_ref_t"));
3802 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3803 Ctx.VoidPtrTy, 0, false));
3804 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3805 Ctx.getObjCSelType(), 0, false));
3806 RD->completeDefinition(Ctx);
3807
3808 MessageRefCTy = Ctx.getTagDeclType(RD);
3809 MessageRefCPtrTy = Ctx.getPointerType(MessageRefCTy);
3810 MessageRefTy = cast<llvm::StructType>(Types.ConvertType(MessageRefCTy));
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003811
3812 // MessageRefPtrTy - LLVM for struct _message_ref_t*
3813 MessageRefPtrTy = llvm::PointerType::getUnqual(MessageRefTy);
3814
3815 // SuperMessageRefTy - LLVM for:
3816 // struct _super_message_ref_t {
3817 // SUPER_IMP messenger;
3818 // SEL name;
3819 // };
3820 SuperMessageRefTy = llvm::StructType::get(ImpnfABITy,
3821 SelectorPtrTy,
3822 NULL);
3823 CGM.getModule().addTypeName("struct._super_message_ref_t", SuperMessageRefTy);
3824
3825 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
3826 SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy);
3827
3828 // id objc_msgSend_fixup (id, struct message_ref_t*, ...)
3829 Params.clear();
3830 Params.push_back(ObjectPtrTy);
3831 Params.push_back(MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00003832 MessengerTy = llvm::FunctionType::get(ObjectPtrTy,
3833 Params,
3834 true);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003835 MessageSendFixupFn =
Fariborz Jahanianef163782009-02-05 01:13:09 +00003836 CGM.CreateRuntimeFunction(MessengerTy,
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003837 "objc_msgSend_fixup");
3838
3839 // id objc_msgSend_fpret_fixup (id, struct message_ref_t*, ...)
3840 MessageSendFpretFixupFn =
3841 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3842 Params,
3843 true),
3844 "objc_msgSend_fpret_fixup");
3845
3846 // id objc_msgSend_stret_fixup (id, struct message_ref_t*, ...)
3847 MessageSendStretFixupFn =
3848 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3849 Params,
3850 true),
3851 "objc_msgSend_stret_fixup");
3852
3853 // id objc_msgSendId_fixup (id, struct message_ref_t*, ...)
3854 MessageSendIdFixupFn =
3855 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3856 Params,
3857 true),
3858 "objc_msgSendId_fixup");
3859
3860
3861 // id objc_msgSendId_stret_fixup (id, struct message_ref_t*, ...)
3862 MessageSendIdStretFixupFn =
3863 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3864 Params,
3865 true),
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003866 "objc_msgSendId_stret_fixup");
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003867
3868 // id objc_msgSendSuper2_fixup (struct objc_super *,
3869 // struct _super_message_ref_t*, ...)
3870 Params.clear();
3871 Params.push_back(SuperPtrTy);
3872 Params.push_back(SuperMessageRefPtrTy);
3873 MessageSendSuper2FixupFn =
3874 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3875 Params,
3876 true),
3877 "objc_msgSendSuper2_fixup");
3878
3879
3880 // id objc_msgSendSuper2_stret_fixup (struct objc_super *,
3881 // struct _super_message_ref_t*, ...)
3882 MessageSendSuper2StretFixupFn =
3883 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3884 Params,
3885 true),
3886 "objc_msgSendSuper2_stret_fixup");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00003887
3888 Params.clear();
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00003889 Params.push_back(Int8PtrTy);
3890 UnwindResumeOrRethrowFn =
3891 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3892 Params,
3893 false),
3894 "_Unwind_Resume_or_Rethrow");
Daniel Dunbare588b992009-03-01 04:46:24 +00003895 ObjCBeginCatchFn =
3896 CGM.CreateRuntimeFunction(llvm::FunctionType::get(Int8PtrTy,
3897 Params,
3898 false),
3899 "objc_begin_catch");
3900
3901 Params.clear();
3902 ObjCEndCatchFn =
3903 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3904 Params,
3905 false),
3906 "objc_end_catch");
3907
3908 // struct objc_typeinfo {
3909 // const void** vtable; // objc_ehtype_vtable + 2
3910 // const char* name; // c++ typeinfo string
3911 // Class cls;
3912 // };
3913 EHTypeTy = llvm::StructType::get(llvm::PointerType::getUnqual(Int8PtrTy),
3914 Int8PtrTy,
3915 ClassnfABIPtrTy,
3916 NULL);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00003917 CGM.getModule().addTypeName("struct._objc_typeinfo", EHTypeTy);
Daniel Dunbare588b992009-03-01 04:46:24 +00003918 EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy);
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003919}
3920
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003921llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() {
3922 FinishNonFragileABIModule();
3923
3924 return NULL;
3925}
3926
3927void CGObjCNonFragileABIMac::FinishNonFragileABIModule() {
3928 // nonfragile abi has no module definition.
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003929
3930 // Build list of all implemented classe addresses in array
3931 // L_OBJC_LABEL_CLASS_$.
3932 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CLASS_$
3933 // list of 'nonlazy' implementations (defined as those with a +load{}
3934 // method!!).
3935 unsigned NumClasses = DefinedClasses.size();
3936 if (NumClasses) {
3937 std::vector<llvm::Constant*> Symbols(NumClasses);
3938 for (unsigned i=0; i<NumClasses; i++)
3939 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
3940 ObjCTypes.Int8PtrTy);
3941 llvm::Constant* Init =
3942 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
3943 NumClasses),
3944 Symbols);
3945
3946 llvm::GlobalVariable *GV =
3947 new llvm::GlobalVariable(Init->getType(), false,
3948 llvm::GlobalValue::InternalLinkage,
3949 Init,
3950 "\01L_OBJC_LABEL_CLASS_$",
3951 &CGM.getModule());
Daniel Dunbar58a29122009-03-09 22:18:41 +00003952 GV->setAlignment(8);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003953 GV->setSection("__DATA, __objc_classlist, regular, no_dead_strip");
3954 UsedGlobals.push_back(GV);
3955 }
3956
3957 // Build list of all implemented category addresses in array
3958 // L_OBJC_LABEL_CATEGORY_$.
3959 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CATEGORY_$
3960 // list of 'nonlazy' category implementations (defined as those with a +load{}
3961 // method!!).
3962 unsigned NumCategory = DefinedCategories.size();
3963 if (NumCategory) {
3964 std::vector<llvm::Constant*> Symbols(NumCategory);
3965 for (unsigned i=0; i<NumCategory; i++)
3966 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedCategories[i],
3967 ObjCTypes.Int8PtrTy);
3968 llvm::Constant* Init =
3969 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
3970 NumCategory),
3971 Symbols);
3972
3973 llvm::GlobalVariable *GV =
3974 new llvm::GlobalVariable(Init->getType(), false,
3975 llvm::GlobalValue::InternalLinkage,
3976 Init,
3977 "\01L_OBJC_LABEL_CATEGORY_$",
3978 &CGM.getModule());
Daniel Dunbar58a29122009-03-09 22:18:41 +00003979 GV->setAlignment(8);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003980 GV->setSection("__DATA, __objc_catlist, regular, no_dead_strip");
3981 UsedGlobals.push_back(GV);
3982 }
3983
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00003984 // static int L_OBJC_IMAGE_INFO[2] = { 0, flags };
3985 // FIXME. flags can be 0 | 1 | 2 | 6. For now just use 0
3986 std::vector<llvm::Constant*> Values(2);
3987 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, 0);
Fariborz Jahanian067986e2009-02-24 21:08:09 +00003988 unsigned int flags = 0;
Fariborz Jahanian66a5c2c2009-02-24 23:34:44 +00003989 // FIXME: Fix and continue?
3990 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
3991 flags |= eImageInfo_GarbageCollected;
3992 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
3993 flags |= eImageInfo_GCOnly;
Fariborz Jahanian067986e2009-02-24 21:08:09 +00003994 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00003995 llvm::Constant* Init = llvm::ConstantArray::get(
3996 llvm::ArrayType::get(ObjCTypes.IntTy, 2),
3997 Values);
3998 llvm::GlobalVariable *IMGV =
3999 new llvm::GlobalVariable(Init->getType(), false,
4000 llvm::GlobalValue::InternalLinkage,
4001 Init,
4002 "\01L_OBJC_IMAGE_INFO",
4003 &CGM.getModule());
4004 IMGV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
4005 UsedGlobals.push_back(IMGV);
4006
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004007 std::vector<llvm::Constant*> Used;
4008 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
4009 e = UsedGlobals.end(); i != e; ++i) {
4010 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
4011 }
4012
4013 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
4014 llvm::GlobalValue *GV =
4015 new llvm::GlobalVariable(AT, false,
4016 llvm::GlobalValue::AppendingLinkage,
4017 llvm::ConstantArray::get(AT, Used),
4018 "llvm.used",
4019 &CGM.getModule());
4020
4021 GV->setSection("llvm.metadata");
4022
4023}
4024
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004025// Metadata flags
4026enum MetaDataDlags {
4027 CLS = 0x0,
4028 CLS_META = 0x1,
4029 CLS_ROOT = 0x2,
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004030 OBJC2_CLS_HIDDEN = 0x10,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004031 CLS_EXCEPTION = 0x20
4032};
4033/// BuildClassRoTInitializer - generate meta-data for:
4034/// struct _class_ro_t {
4035/// uint32_t const flags;
4036/// uint32_t const instanceStart;
4037/// uint32_t const instanceSize;
4038/// uint32_t const reserved; // only when building for 64bit targets
4039/// const uint8_t * const ivarLayout;
4040/// const char *const name;
4041/// const struct _method_list_t * const baseMethods;
Fariborz Jahanianda320092009-01-29 19:24:30 +00004042/// const struct _protocol_list_t *const baseProtocols;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004043/// const struct _ivar_list_t *const ivars;
4044/// const uint8_t * const weakIvarLayout;
4045/// const struct _prop_list_t * const properties;
4046/// }
4047///
4048llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer(
4049 unsigned flags,
4050 unsigned InstanceStart,
4051 unsigned InstanceSize,
4052 const ObjCImplementationDecl *ID) {
4053 std::string ClassName = ID->getNameAsString();
4054 std::vector<llvm::Constant*> Values(10); // 11 for 64bit targets!
4055 Values[ 0] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
4056 Values[ 1] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceStart);
4057 Values[ 2] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceSize);
4058 // FIXME. For 64bit targets add 0 here.
Fariborz Jahanianda320092009-01-29 19:24:30 +00004059 // FIXME. ivarLayout is currently null!
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00004060 Values[ 3] = GetIvarLayoutName(0, ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004061 Values[ 4] = GetClassName(ID->getIdentifier());
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004062 // const struct _method_list_t * const baseMethods;
4063 std::vector<llvm::Constant*> Methods;
4064 std::string MethodListName("\01l_OBJC_$_");
4065 if (flags & CLS_META) {
4066 MethodListName += "CLASS_METHODS_" + ID->getNameAsString();
4067 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
4068 e = ID->classmeth_end(); i != e; ++i) {
4069 // Class methods should always be defined.
4070 Methods.push_back(GetMethodConstant(*i));
4071 }
4072 } else {
4073 MethodListName += "INSTANCE_METHODS_" + ID->getNameAsString();
4074 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
4075 e = ID->instmeth_end(); i != e; ++i) {
4076 // Instance methods should always be defined.
4077 Methods.push_back(GetMethodConstant(*i));
4078 }
Fariborz Jahanian939abce2009-01-28 22:46:49 +00004079 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
4080 e = ID->propimpl_end(); i != e; ++i) {
4081 ObjCPropertyImplDecl *PID = *i;
4082
4083 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize){
4084 ObjCPropertyDecl *PD = PID->getPropertyDecl();
4085
4086 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
4087 if (llvm::Constant *C = GetMethodConstant(MD))
4088 Methods.push_back(C);
4089 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
4090 if (llvm::Constant *C = GetMethodConstant(MD))
4091 Methods.push_back(C);
4092 }
4093 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004094 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004095 Values[ 5] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004096 "__DATA, __objc_const", Methods);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004097
4098 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4099 assert(OID && "CGObjCNonFragileABIMac::BuildClassRoTInitializer");
4100 Values[ 6] = EmitProtocolList("\01l_OBJC_CLASS_PROTOCOLS_$_"
4101 + OID->getNameAsString(),
4102 OID->protocol_begin(),
4103 OID->protocol_end());
4104
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004105 if (flags & CLS_META)
4106 Values[ 7] = llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4107 else
4108 Values[ 7] = EmitIvarList(ID);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004109 // FIXME. weakIvarLayout is currently null.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00004110 Values[ 8] = GetIvarLayoutName(0, ObjCTypes);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004111 if (flags & CLS_META)
4112 Values[ 9] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4113 else
4114 Values[ 9] =
4115 EmitPropertyList(
4116 "\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
4117 ID, ID->getClassInterface(), ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004118 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassRonfABITy,
4119 Values);
4120 llvm::GlobalVariable *CLASS_RO_GV =
4121 new llvm::GlobalVariable(ObjCTypes.ClassRonfABITy, false,
4122 llvm::GlobalValue::InternalLinkage,
4123 Init,
4124 (flags & CLS_META) ?
4125 std::string("\01l_OBJC_METACLASS_RO_$_")+ClassName :
4126 std::string("\01l_OBJC_CLASS_RO_$_")+ClassName,
4127 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004128 CLASS_RO_GV->setAlignment(
4129 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassRonfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004130 CLASS_RO_GV->setSection("__DATA, __objc_const");
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004131 UsedGlobals.push_back(CLASS_RO_GV);
4132 return CLASS_RO_GV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004133
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004134}
4135
4136/// BuildClassMetaData - This routine defines that to-level meta-data
4137/// for the given ClassName for:
4138/// struct _class_t {
4139/// struct _class_t *isa;
4140/// struct _class_t * const superclass;
4141/// void *cache;
4142/// IMP *vtable;
4143/// struct class_ro_t *ro;
4144/// }
4145///
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004146llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassMetaData(
4147 std::string &ClassName,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004148 llvm::Constant *IsAGV,
4149 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004150 llvm::Constant *ClassRoGV,
4151 bool HiddenVisibility) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004152 std::vector<llvm::Constant*> Values(5);
4153 Values[0] = IsAGV;
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004154 Values[1] = SuperClassGV
4155 ? SuperClassGV
4156 : llvm::Constant::getNullValue(ObjCTypes.ClassnfABIPtrTy);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004157 Values[2] = ObjCEmptyCacheVar; // &ObjCEmptyCacheVar
4158 Values[3] = ObjCEmptyVtableVar; // &ObjCEmptyVtableVar
4159 Values[4] = ClassRoGV; // &CLASS_RO_GV
4160 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassnfABITy,
4161 Values);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004162 llvm::GlobalVariable *GV = GetClassGlobal(ClassName);
4163 GV->setInitializer(Init);
Fariborz Jahaniandd0db2a2009-01-31 01:07:39 +00004164 GV->setSection("__DATA, __objc_data");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004165 GV->setAlignment(
4166 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassnfABITy));
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004167 if (HiddenVisibility)
4168 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004169 UsedGlobals.push_back(GV);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004170 return GV;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004171}
4172
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004173void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) {
4174 std::string ClassName = ID->getNameAsString();
4175 if (!ObjCEmptyCacheVar) {
4176 ObjCEmptyCacheVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004177 ObjCTypes.CacheTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004178 false,
4179 llvm::GlobalValue::ExternalLinkage,
4180 0,
Fariborz Jahanian07da3672009-02-03 17:34:34 +00004181 "\01__objc_empty_cache",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004182 &CGM.getModule());
4183 UsedGlobals.push_back(ObjCEmptyCacheVar);
4184
4185 ObjCEmptyVtableVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004186 ObjCTypes.ImpnfABITy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004187 false,
4188 llvm::GlobalValue::ExternalLinkage,
4189 0,
Fariborz Jahanian07da3672009-02-03 17:34:34 +00004190 "\01__objc_empty_vtable",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004191 &CGM.getModule());
4192 UsedGlobals.push_back(ObjCEmptyVtableVar);
4193 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004194 assert(ID->getClassInterface() &&
4195 "CGObjCNonFragileABIMac::GenerateClass - class is 0");
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004196 uint32_t InstanceStart =
4197 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassnfABITy);
4198 uint32_t InstanceSize = InstanceStart;
4199 uint32_t flags = CLS_META;
4200 std::string ObjCMetaClassName("\01_OBJC_METACLASS_$_");
4201 std::string ObjCClassName("\01_OBJC_CLASS_$_");
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004202
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004203 llvm::GlobalVariable *SuperClassGV, *IsAGV;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004204
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004205 bool classIsHidden = IsClassHidden(ID->getClassInterface());
4206 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004207 flags |= OBJC2_CLS_HIDDEN;
4208 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004209 // class is root
4210 flags |= CLS_ROOT;
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004211 SuperClassGV = GetClassGlobal(ObjCClassName + ClassName);
4212 IsAGV = GetClassGlobal(ObjCMetaClassName + ClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004213 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004214 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004215 const ObjCInterfaceDecl *Root = ID->getClassInterface();
4216 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
4217 Root = Super;
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004218 IsAGV = GetClassGlobal(ObjCMetaClassName + Root->getNameAsString());
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004219 // work on super class metadata symbol.
4220 std::string SuperClassName =
4221 ObjCMetaClassName + ID->getClassInterface()->getSuperClass()->getNameAsString();
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004222 SuperClassGV = GetClassGlobal(SuperClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004223 }
4224 llvm::GlobalVariable *CLASS_RO_GV = BuildClassRoTInitializer(flags,
4225 InstanceStart,
4226 InstanceSize,ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004227 std::string TClassName = ObjCMetaClassName + ClassName;
4228 llvm::GlobalVariable *MetaTClass =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004229 BuildClassMetaData(TClassName, IsAGV, SuperClassGV, CLASS_RO_GV,
4230 classIsHidden);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004231
4232 // Metadata for the class
4233 flags = CLS;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004234 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004235 flags |= OBJC2_CLS_HIDDEN;
4236 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004237 flags |= CLS_ROOT;
4238 SuperClassGV = 0;
4239 }
4240 else {
4241 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004242 std::string RootClassName =
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004243 ID->getClassInterface()->getSuperClass()->getNameAsString();
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004244 SuperClassGV = GetClassGlobal(ObjCClassName + RootClassName);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004245 }
Fariborz Jahanianebf9ed32009-03-20 20:48:19 +00004246 // FIXME: Gross
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004247 InstanceStart = InstanceSize = 0;
4248 if (ObjCInterfaceDecl *OID =
4249 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface())) {
4250 // FIXME. Share this with the one in EmitIvarList.
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00004251 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID);
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004252
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00004253 RecordDecl::field_iterator firstField, lastField;
4254 const RecordDecl *RD = GetFirstIvarInRecord(OID, firstField, lastField);
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004255
4256 for (RecordDecl::field_iterator e = RD->field_end(),
4257 ifield = firstField; ifield != e; ++ifield)
4258 lastField = ifield;
4259
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004260 if (lastField != RD->field_end()) {
4261 FieldDecl *Field = *lastField;
4262 const llvm::Type *FieldTy =
4263 CGM.getTypes().ConvertTypeForMem(Field->getType());
4264 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00004265 InstanceSize = GetIvarBaseOffset(Layout, Field) + Size;
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004266 if (firstField == RD->field_end())
4267 InstanceStart = InstanceSize;
Fariborz Jahanian11894a42009-03-07 19:43:20 +00004268 else {
4269 Field = *firstField;
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00004270 InstanceStart = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanian11894a42009-03-07 19:43:20 +00004271 }
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004272 }
4273 }
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004274 CLASS_RO_GV = BuildClassRoTInitializer(flags,
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004275 InstanceStart,
4276 InstanceSize,
4277 ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004278
4279 TClassName = ObjCClassName + ClassName;
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004280 llvm::GlobalVariable *ClassMD =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004281 BuildClassMetaData(TClassName, MetaTClass, SuperClassGV, CLASS_RO_GV,
4282 classIsHidden);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004283 DefinedClasses.push_back(ClassMD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004284}
4285
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004286/// GenerateProtocolRef - This routine is called to generate code for
4287/// a protocol reference expression; as in:
4288/// @code
4289/// @protocol(Proto1);
4290/// @endcode
4291/// It generates a weak reference to l_OBJC_PROTOCOL_REFERENCE_$_Proto1
4292/// which will hold address of the protocol meta-data.
4293///
4294llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CGBuilderTy &Builder,
4295 const ObjCProtocolDecl *PD) {
4296
4297 llvm::Constant *Init = llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
4298 ObjCTypes.ExternalProtocolPtrTy);
4299
4300 std::string ProtocolName("\01l_OBJC_PROTOCOL_REFERENCE_$_");
4301 ProtocolName += PD->getNameAsCString();
4302
4303 llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName);
4304 if (PTGV)
4305 return Builder.CreateLoad(PTGV, false, "tmp");
4306 PTGV = new llvm::GlobalVariable(
4307 Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00004308 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004309 Init,
4310 ProtocolName,
4311 &CGM.getModule());
4312 PTGV->setSection("__DATA, __objc_protorefs, coalesced, no_dead_strip");
4313 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4314 UsedGlobals.push_back(PTGV);
4315 return Builder.CreateLoad(PTGV, false, "tmp");
4316}
4317
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004318/// GenerateCategory - Build metadata for a category implementation.
4319/// struct _category_t {
4320/// const char * const name;
4321/// struct _class_t *const cls;
4322/// const struct _method_list_t * const instance_methods;
4323/// const struct _method_list_t * const class_methods;
4324/// const struct _protocol_list_t * const protocols;
4325/// const struct _prop_list_t * const properties;
4326/// }
4327///
4328void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD)
4329{
4330 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004331 const char *Prefix = "\01l_OBJC_$_CATEGORY_";
4332 std::string ExtCatName(Prefix + Interface->getNameAsString()+
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004333 "_$_" + OCD->getNameAsString());
4334 std::string ExtClassName("\01_OBJC_CLASS_$_" + Interface->getNameAsString());
4335
4336 std::vector<llvm::Constant*> Values(6);
4337 Values[0] = GetClassName(OCD->getIdentifier());
4338 // meta-class entry symbol
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004339 llvm::GlobalVariable *ClassGV = GetClassGlobal(ExtClassName);
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004340 Values[1] = ClassGV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004341 std::vector<llvm::Constant*> Methods;
4342 std::string MethodListName(Prefix);
4343 MethodListName += "INSTANCE_METHODS_" + Interface->getNameAsString() +
4344 "_$_" + OCD->getNameAsString();
4345
4346 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
4347 e = OCD->instmeth_end(); i != e; ++i) {
4348 // Instance methods should always be defined.
4349 Methods.push_back(GetMethodConstant(*i));
4350 }
4351
4352 Values[2] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004353 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004354 Methods);
4355
4356 MethodListName = Prefix;
4357 MethodListName += "CLASS_METHODS_" + Interface->getNameAsString() + "_$_" +
4358 OCD->getNameAsString();
4359 Methods.clear();
4360 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
4361 e = OCD->classmeth_end(); i != e; ++i) {
4362 // Class methods should always be defined.
4363 Methods.push_back(GetMethodConstant(*i));
4364 }
4365
4366 Values[3] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004367 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004368 Methods);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004369 const ObjCCategoryDecl *Category =
4370 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Fariborz Jahanian943ed6f2009-02-13 17:52:22 +00004371 if (Category) {
4372 std::string ExtName(Interface->getNameAsString() + "_$_" +
4373 OCD->getNameAsString());
4374 Values[4] = EmitProtocolList("\01l_OBJC_CATEGORY_PROTOCOLS_$_"
4375 + Interface->getNameAsString() + "_$_"
4376 + Category->getNameAsString(),
4377 Category->protocol_begin(),
4378 Category->protocol_end());
4379 Values[5] =
4380 EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
4381 OCD, Category, ObjCTypes);
4382 }
4383 else {
4384 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4385 Values[5] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4386 }
4387
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004388 llvm::Constant *Init =
4389 llvm::ConstantStruct::get(ObjCTypes.CategorynfABITy,
4390 Values);
4391 llvm::GlobalVariable *GCATV
4392 = new llvm::GlobalVariable(ObjCTypes.CategorynfABITy,
4393 false,
4394 llvm::GlobalValue::InternalLinkage,
4395 Init,
4396 ExtCatName,
4397 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004398 GCATV->setAlignment(
4399 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.CategorynfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004400 GCATV->setSection("__DATA, __objc_const");
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004401 UsedGlobals.push_back(GCATV);
4402 DefinedCategories.push_back(GCATV);
4403}
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004404
4405/// GetMethodConstant - Return a struct objc_method constant for the
4406/// given method if it has been defined. The result is null if the
4407/// method has not been defined. The return value has type MethodPtrTy.
4408llvm::Constant *CGObjCNonFragileABIMac::GetMethodConstant(
4409 const ObjCMethodDecl *MD) {
4410 // FIXME: Use DenseMap::lookup
4411 llvm::Function *Fn = MethodDefinitions[MD];
4412 if (!Fn)
4413 return 0;
4414
4415 std::vector<llvm::Constant*> Method(3);
4416 Method[0] =
4417 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4418 ObjCTypes.SelectorPtrTy);
4419 Method[1] = GetMethodVarType(MD);
4420 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
4421 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
4422}
4423
4424/// EmitMethodList - Build meta-data for method declarations
4425/// struct _method_list_t {
4426/// uint32_t entsize; // sizeof(struct _objc_method)
4427/// uint32_t method_count;
4428/// struct _objc_method method_list[method_count];
4429/// }
4430///
4431llvm::Constant *CGObjCNonFragileABIMac::EmitMethodList(
4432 const std::string &Name,
4433 const char *Section,
4434 const ConstantVector &Methods) {
4435 // Return null for empty list.
4436 if (Methods.empty())
4437 return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy);
4438
4439 std::vector<llvm::Constant*> Values(3);
4440 // sizeof(struct _objc_method)
4441 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.MethodTy);
4442 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4443 // method_count
4444 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
4445 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
4446 Methods.size());
4447 Values[2] = llvm::ConstantArray::get(AT, Methods);
4448 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4449
4450 llvm::GlobalVariable *GV =
4451 new llvm::GlobalVariable(Init->getType(), false,
4452 llvm::GlobalValue::InternalLinkage,
4453 Init,
4454 Name,
4455 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004456 GV->setAlignment(
4457 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004458 GV->setSection(Section);
4459 UsedGlobals.push_back(GV);
4460 return llvm::ConstantExpr::getBitCast(GV,
4461 ObjCTypes.MethodListnfABIPtrTy);
4462}
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004463
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004464/// ObjCIvarOffsetVariable - Returns the ivar offset variable for
4465/// the given ivar.
4466///
4467llvm::GlobalVariable * CGObjCNonFragileABIMac::ObjCIvarOffsetVariable(
4468 std::string &Name,
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004469 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004470 const ObjCIvarDecl *Ivar) {
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004471 Name += "\01_OBJC_IVAR_$_" +
4472 getInterfaceDeclForIvar(ID, Ivar)->getNameAsString() + '.'
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004473 + Ivar->getNameAsString();
4474 llvm::GlobalVariable *IvarOffsetGV =
4475 CGM.getModule().getGlobalVariable(Name);
4476 if (!IvarOffsetGV)
4477 IvarOffsetGV =
4478 new llvm::GlobalVariable(ObjCTypes.LongTy,
4479 false,
4480 llvm::GlobalValue::ExternalLinkage,
4481 0,
4482 Name,
4483 &CGM.getModule());
4484 return IvarOffsetGV;
4485}
4486
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004487llvm::Constant * CGObjCNonFragileABIMac::EmitIvarOffsetVar(
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004488 const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004489 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004490 unsigned long int Offset) {
4491
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004492 assert(ID && "EmitIvarOffsetVar - null interface decl.");
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004493 std::string ExternalName("\01_OBJC_IVAR_$_" + ID->getNameAsString() + '.'
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004494 + Ivar->getNameAsString());
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004495 llvm::Constant *Init = llvm::ConstantInt::get(ObjCTypes.LongTy, Offset);
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004496 llvm::GlobalVariable *IvarOffsetGV =
4497 CGM.getModule().getGlobalVariable(ExternalName);
Fariborz Jahanian77c9fd22009-04-06 18:30:00 +00004498 if (IvarOffsetGV)
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004499 // ivar offset symbol already built due to user code referencing it.
4500 IvarOffsetGV->setInitializer(Init);
Fariborz Jahanian77c9fd22009-04-06 18:30:00 +00004501 else
4502 IvarOffsetGV =
4503 new llvm::GlobalVariable(Init->getType(),
4504 false,
4505 llvm::GlobalValue::ExternalLinkage,
4506 Init,
4507 ExternalName,
4508 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004509 IvarOffsetGV->setAlignment(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004510 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.LongTy));
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004511 // @private and @package have hidden visibility.
4512 bool globalVisibility = (Ivar->getAccessControl() == ObjCIvarDecl::Public ||
Fariborz Jahanian77c9fd22009-04-06 18:30:00 +00004513 Ivar->getAccessControl() == ObjCIvarDecl::Protected);
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004514 if (!globalVisibility)
4515 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahanian77c9fd22009-04-06 18:30:00 +00004516 else if (IsClassHidden(ID))
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004517 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahanian77c9fd22009-04-06 18:30:00 +00004518 else if (CGM.getLangOptions().getVisibilityMode() ==
4519 LangOptions::HiddenVisibility)
4520 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4521 else if (CGM.getLangOptions().getVisibilityMode() ==
4522 LangOptions::DefaultVisibility)
4523 IvarOffsetGV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004524 IvarOffsetGV->setSection("__DATA, __objc_const");
4525 UsedGlobals.push_back(IvarOffsetGV);
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004526 return IvarOffsetGV;
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004527}
4528
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004529/// EmitIvarList - Emit the ivar list for the given
4530/// implementation. If ForClass is true the list of class ivars
4531/// (i.e. metaclass ivars) is emitted, otherwise the list of
4532/// interface ivars will be emitted. The return value has type
4533/// IvarListnfABIPtrTy.
4534/// struct _ivar_t {
4535/// unsigned long int *offset; // pointer to ivar offset location
4536/// char *name;
4537/// char *type;
4538/// uint32_t alignment;
4539/// uint32_t size;
4540/// }
4541/// struct _ivar_list_t {
4542/// uint32 entsize; // sizeof(struct _ivar_t)
4543/// uint32 count;
4544/// struct _iver_t list[count];
4545/// }
4546///
4547llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList(
4548 const ObjCImplementationDecl *ID) {
4549
4550 std::vector<llvm::Constant*> Ivars, Ivar(5);
4551
4552 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4553 assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface");
4554
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004555 // FIXME. Consolidate this with similar code in GenerateClass.
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00004556 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00004557
4558 RecordDecl::field_iterator i,p;
4559 const RecordDecl *RD = GetFirstIvarInRecord(OID, i,p);
Fariborz Jahanian18191882009-03-31 18:11:23 +00004560 // collect declared and synthesized ivars in a small vector.
4561 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
4562 for (ObjCInterfaceDecl::ivar_iterator I = OID->ivar_begin(),
4563 E = OID->ivar_end(); I != E; ++I)
4564 OIvars.push_back(*I);
4565 for (ObjCInterfaceDecl::prop_iterator I = OID->prop_begin(),
4566 E = OID->prop_end(); I != E; ++I)
4567 if (ObjCIvarDecl *IV = (*I)->getPropertyIvarDecl())
4568 OIvars.push_back(IV);
Fariborz Jahanian99eee362009-04-01 19:37:34 +00004569
Fariborz Jahanian18191882009-03-31 18:11:23 +00004570 unsigned iv = 0;
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004571 for (RecordDecl::field_iterator e = RD->field_end(); i != e; ++i) {
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004572 FieldDecl *Field = *i;
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00004573 uint64_t offset = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanian18191882009-03-31 18:11:23 +00004574 Ivar[0] = EmitIvarOffsetVar(ID->getClassInterface(), OIvars[iv++], offset);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004575 if (Field->getIdentifier())
4576 Ivar[1] = GetMethodVarName(Field->getIdentifier());
4577 else
4578 Ivar[1] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Devang Patel7794bb82009-03-04 18:21:39 +00004579 Ivar[2] = GetMethodVarType(Field);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004580 const llvm::Type *FieldTy =
4581 CGM.getTypes().ConvertTypeForMem(Field->getType());
4582 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
4583 unsigned Align = CGM.getContext().getPreferredTypeAlign(
4584 Field->getType().getTypePtr()) >> 3;
4585 Align = llvm::Log2_32(Align);
4586 Ivar[3] = llvm::ConstantInt::get(ObjCTypes.IntTy, Align);
Fariborz Jahanian07236ba2009-01-27 22:27:56 +00004587 // NOTE. Size of a bitfield does not match gcc's, because of the way
4588 // bitfields are treated special in each. But I am told that 'size'
4589 // for bitfield ivars is ignored by the runtime so it does not matter.
4590 // (even if it matters, some day, there is enough info. to get the bitfield
4591 // right!
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004592 Ivar[4] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4593 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarnfABITy, Ivar));
4594 }
4595 // Return null for empty list.
4596 if (Ivars.empty())
4597 return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4598 std::vector<llvm::Constant*> Values(3);
4599 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.IvarnfABITy);
4600 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4601 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
4602 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarnfABITy,
4603 Ivars.size());
4604 Values[2] = llvm::ConstantArray::get(AT, Ivars);
4605 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4606 const char *Prefix = "\01l_OBJC_$_INSTANCE_VARIABLES_";
4607 llvm::GlobalVariable *GV =
4608 new llvm::GlobalVariable(Init->getType(), false,
4609 llvm::GlobalValue::InternalLinkage,
4610 Init,
4611 Prefix + OID->getNameAsString(),
4612 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004613 GV->setAlignment(
4614 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004615 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004616
4617 UsedGlobals.push_back(GV);
4618 return llvm::ConstantExpr::getBitCast(GV,
4619 ObjCTypes.IvarListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004620}
4621
4622llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef(
4623 const ObjCProtocolDecl *PD) {
4624 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4625
4626 if (!Entry) {
4627 // We use the initializer as a marker of whether this is a forward
4628 // reference or not. At module finalization we add the empty
4629 // contents for protocols which were referenced but never defined.
4630 Entry =
4631 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
4632 llvm::GlobalValue::ExternalLinkage,
4633 0,
4634 "\01l_OBJC_PROTOCOL_$_" + PD->getNameAsString(),
4635 &CGM.getModule());
4636 Entry->setSection("__DATA,__datacoal_nt,coalesced");
4637 UsedGlobals.push_back(Entry);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004638 }
4639
4640 return Entry;
4641}
4642
4643/// GetOrEmitProtocol - Generate the protocol meta-data:
4644/// @code
4645/// struct _protocol_t {
4646/// id isa; // NULL
4647/// const char * const protocol_name;
4648/// const struct _protocol_list_t * protocol_list; // super protocols
4649/// const struct method_list_t * const instance_methods;
4650/// const struct method_list_t * const class_methods;
4651/// const struct method_list_t *optionalInstanceMethods;
4652/// const struct method_list_t *optionalClassMethods;
4653/// const struct _prop_list_t * properties;
4654/// const uint32_t size; // sizeof(struct _protocol_t)
4655/// const uint32_t flags; // = 0
4656/// }
4657/// @endcode
4658///
4659
4660llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol(
4661 const ObjCProtocolDecl *PD) {
4662 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4663
4664 // Early exit if a defining object has already been generated.
4665 if (Entry && Entry->hasInitializer())
4666 return Entry;
4667
4668 const char *ProtocolName = PD->getNameAsCString();
4669
4670 // Construct method lists.
4671 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
4672 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
4673 for (ObjCProtocolDecl::instmeth_iterator i = PD->instmeth_begin(),
4674 e = PD->instmeth_end(); i != e; ++i) {
4675 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004676 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004677 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4678 OptInstanceMethods.push_back(C);
4679 } else {
4680 InstanceMethods.push_back(C);
4681 }
4682 }
4683
4684 for (ObjCProtocolDecl::classmeth_iterator i = PD->classmeth_begin(),
4685 e = PD->classmeth_end(); i != e; ++i) {
4686 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004687 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004688 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4689 OptClassMethods.push_back(C);
4690 } else {
4691 ClassMethods.push_back(C);
4692 }
4693 }
4694
4695 std::vector<llvm::Constant*> Values(10);
4696 // isa is NULL
4697 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ObjectPtrTy);
4698 Values[1] = GetClassName(PD->getIdentifier());
4699 Values[2] = EmitProtocolList(
4700 "\01l_OBJC_$_PROTOCOL_REFS_" + PD->getNameAsString(),
4701 PD->protocol_begin(),
4702 PD->protocol_end());
4703
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004704 Values[3] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004705 + PD->getNameAsString(),
4706 "__DATA, __objc_const",
4707 InstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004708 Values[4] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004709 + PD->getNameAsString(),
4710 "__DATA, __objc_const",
4711 ClassMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004712 Values[5] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004713 + PD->getNameAsString(),
4714 "__DATA, __objc_const",
4715 OptInstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004716 Values[6] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004717 + PD->getNameAsString(),
4718 "__DATA, __objc_const",
4719 OptClassMethods);
4720 Values[7] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + PD->getNameAsString(),
4721 0, PD, ObjCTypes);
4722 uint32_t Size =
4723 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolnfABITy);
4724 Values[8] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4725 Values[9] = llvm::Constant::getNullValue(ObjCTypes.IntTy);
4726 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolnfABITy,
4727 Values);
4728
4729 if (Entry) {
4730 // Already created, fix the linkage and update the initializer.
Mike Stump286acbd2009-03-07 16:33:28 +00004731 Entry->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004732 Entry->setInitializer(Init);
4733 } else {
4734 Entry =
4735 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004736 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004737 Init,
4738 std::string("\01l_OBJC_PROTOCOL_$_")+ProtocolName,
4739 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004740 Entry->setAlignment(
4741 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABITy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004742 Entry->setSection("__DATA,__datacoal_nt,coalesced");
Fariborz Jahanianda320092009-01-29 19:24:30 +00004743 }
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004744 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
4745
4746 // Use this protocol meta-data to build protocol list table in section
4747 // __DATA, __objc_protolist
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004748 llvm::GlobalVariable *PTGV = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004749 ObjCTypes.ProtocolnfABIPtrTy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004750 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004751 Entry,
4752 std::string("\01l_OBJC_LABEL_PROTOCOL_$_")
4753 +ProtocolName,
4754 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004755 PTGV->setAlignment(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004756 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABIPtrTy));
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004757 PTGV->setSection("__DATA, __objc_protolist");
4758 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4759 UsedGlobals.push_back(PTGV);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004760 return Entry;
4761}
4762
4763/// EmitProtocolList - Generate protocol list meta-data:
4764/// @code
4765/// struct _protocol_list_t {
4766/// long protocol_count; // Note, this is 32/64 bit
4767/// struct _protocol_t[protocol_count];
4768/// }
4769/// @endcode
4770///
4771llvm::Constant *
4772CGObjCNonFragileABIMac::EmitProtocolList(const std::string &Name,
4773 ObjCProtocolDecl::protocol_iterator begin,
4774 ObjCProtocolDecl::protocol_iterator end) {
4775 std::vector<llvm::Constant*> ProtocolRefs;
4776
Fariborz Jahanianda320092009-01-29 19:24:30 +00004777 // Just return null for empty protocol lists
Daniel Dunbar948e2582009-02-15 07:36:20 +00004778 if (begin == end)
Fariborz Jahanianda320092009-01-29 19:24:30 +00004779 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4780
Daniel Dunbar948e2582009-02-15 07:36:20 +00004781 // FIXME: We shouldn't need to do this lookup here, should we?
Fariborz Jahanianda320092009-01-29 19:24:30 +00004782 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
4783 if (GV)
Daniel Dunbar948e2582009-02-15 07:36:20 +00004784 return llvm::ConstantExpr::getBitCast(GV,
4785 ObjCTypes.ProtocolListnfABIPtrTy);
4786
4787 for (; begin != end; ++begin)
4788 ProtocolRefs.push_back(GetProtocolRef(*begin)); // Implemented???
4789
Fariborz Jahanianda320092009-01-29 19:24:30 +00004790 // This list is null terminated.
4791 ProtocolRefs.push_back(llvm::Constant::getNullValue(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004792 ObjCTypes.ProtocolnfABIPtrTy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004793
4794 std::vector<llvm::Constant*> Values(2);
4795 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
4796 Values[1] =
Daniel Dunbar948e2582009-02-15 07:36:20 +00004797 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolnfABIPtrTy,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004798 ProtocolRefs.size()),
4799 ProtocolRefs);
4800
4801 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4802 GV = new llvm::GlobalVariable(Init->getType(), false,
4803 llvm::GlobalValue::InternalLinkage,
4804 Init,
4805 Name,
4806 &CGM.getModule());
4807 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004808 GV->setAlignment(
4809 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004810 UsedGlobals.push_back(GV);
Daniel Dunbar948e2582009-02-15 07:36:20 +00004811 return llvm::ConstantExpr::getBitCast(GV,
4812 ObjCTypes.ProtocolListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004813}
4814
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004815/// GetMethodDescriptionConstant - This routine build following meta-data:
4816/// struct _objc_method {
4817/// SEL _cmd;
4818/// char *method_type;
4819/// char *_imp;
4820/// }
4821
4822llvm::Constant *
4823CGObjCNonFragileABIMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
4824 std::vector<llvm::Constant*> Desc(3);
4825 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4826 ObjCTypes.SelectorPtrTy);
4827 Desc[1] = GetMethodVarType(MD);
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004828 // Protocol methods have no implementation. So, this entry is always NULL.
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004829 Desc[2] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
4830 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Desc);
4831}
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004832
4833/// EmitObjCValueForIvar - Code Gen for nonfragile ivar reference.
4834/// This code gen. amounts to generating code for:
4835/// @code
4836/// (type *)((char *)base + _OBJC_IVAR_$_.ivar;
4837/// @encode
4838///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004839LValue CGObjCNonFragileABIMac::EmitObjCValueForIvar(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004840 CodeGen::CodeGenFunction &CGF,
4841 QualType ObjectTy,
4842 llvm::Value *BaseValue,
4843 const ObjCIvarDecl *Ivar,
4844 const FieldDecl *Field,
4845 unsigned CVRQualifiers) {
4846 assert(ObjectTy->isObjCInterfaceType() &&
4847 "CGObjCNonFragileABIMac::EmitObjCValueForIvar");
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004848 ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004849 std::string ExternalName;
4850 llvm::GlobalVariable *IvarOffsetGV =
4851 ObjCIvarOffsetVariable(ExternalName, ID, Ivar);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004852
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004853 // (char *) BaseValue
4854 llvm::Value *V = CGF.Builder.CreateBitCast(BaseValue,
4855 ObjCTypes.Int8PtrTy);
4856 llvm::Value *Offset = CGF.Builder.CreateLoad(IvarOffsetGV);
4857 // (char*)BaseValue + Offset_symbol
4858 V = CGF.Builder.CreateGEP(V, Offset, "add.ptr");
4859 // (type *)((char*)BaseValue + Offset_symbol)
4860 const llvm::Type *IvarTy =
4861 CGM.getTypes().ConvertType(Ivar->getType());
4862 llvm::Type *ptrIvarTy = llvm::PointerType::getUnqual(IvarTy);
4863 V = CGF.Builder.CreateBitCast(V, ptrIvarTy);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004864
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00004865 if (Ivar->isBitField()) {
4866 CodeGenTypes::BitFieldInfo bitFieldInfo =
4867 CGM.getTypes().getBitFieldInfo(Field);
4868 return LValue::MakeBitfield(V, bitFieldInfo.Begin, bitFieldInfo.Size,
4869 Field->getType()->isSignedIntegerType(),
4870 Field->getType().getCVRQualifiers()|CVRQualifiers);
4871 }
4872
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004873 LValue LV = LValue::MakeAddr(V,
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004874 Ivar->getType().getCVRQualifiers()|CVRQualifiers,
4875 CGM.getContext().getObjCGCAttrKind(Ivar->getType()));
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004876 LValue::SetObjCIvar(LV, true);
4877 return LV;
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004878}
4879
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004880llvm::Value *CGObjCNonFragileABIMac::EmitIvarOffset(
4881 CodeGen::CodeGenFunction &CGF,
4882 ObjCInterfaceDecl *Interface,
4883 const ObjCIvarDecl *Ivar) {
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004884 std::string ExternalName;
4885 llvm::GlobalVariable *IvarOffsetGV =
4886 ObjCIvarOffsetVariable(ExternalName, Interface, Ivar);
4887
4888 return CGF.Builder.CreateLoad(IvarOffsetGV, false, "ivar");
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004889}
4890
Fariborz Jahanian46551122009-02-04 00:22:57 +00004891CodeGen::RValue CGObjCNonFragileABIMac::EmitMessageSend(
4892 CodeGen::CodeGenFunction &CGF,
4893 QualType ResultType,
4894 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004895 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +00004896 QualType Arg0Ty,
4897 bool IsSuper,
4898 const CallArgList &CallArgs) {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004899 // FIXME. Even though IsSuper is passes. This function doese not
4900 // handle calls to 'super' receivers.
4901 CodeGenTypes &Types = CGM.getTypes();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004902 llvm::Value *Arg0 = Receiver;
4903 if (!IsSuper)
4904 Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy, "tmp");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004905
4906 // Find the message function name.
Fariborz Jahanianef163782009-02-05 01:13:09 +00004907 // FIXME. This is too much work to get the ABI-specific result type
4908 // needed to find the message name.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004909 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType,
4910 llvm::SmallVector<QualType, 16>());
4911 llvm::Constant *Fn;
4912 std::string Name("\01l_");
4913 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004914#if 0
4915 // unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004916 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
4917 Fn = ObjCTypes.MessageSendIdStretFixupFn;
4918 // FIXME. Is there a better way of getting these names.
4919 // They are available in RuntimeFunctions vector pair.
4920 Name += "objc_msgSendId_stret_fixup";
4921 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004922 else
4923#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004924 if (IsSuper) {
4925 Fn = ObjCTypes.MessageSendSuper2StretFixupFn;
4926 Name += "objc_msgSendSuper2_stret_fixup";
4927 }
4928 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004929 {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004930 Fn = ObjCTypes.MessageSendStretFixupFn;
4931 Name += "objc_msgSend_stret_fixup";
4932 }
4933 }
Fariborz Jahanian1a6b3682009-02-05 19:35:43 +00004934 else if (ResultType->isFloatingType() &&
4935 // Selection of frret API only happens in 32bit nonfragile ABI.
4936 CGM.getTargetData().getTypePaddedSize(ObjCTypes.LongTy) == 4) {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004937 Fn = ObjCTypes.MessageSendFpretFixupFn;
4938 Name += "objc_msgSend_fpret_fixup";
4939 }
4940 else {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004941#if 0
4942// unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004943 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
4944 Fn = ObjCTypes.MessageSendIdFixupFn;
4945 Name += "objc_msgSendId_fixup";
4946 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004947 else
4948#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004949 if (IsSuper) {
4950 Fn = ObjCTypes.MessageSendSuper2FixupFn;
4951 Name += "objc_msgSendSuper2_fixup";
4952 }
4953 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004954 {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004955 Fn = ObjCTypes.MessageSendFixupFn;
4956 Name += "objc_msgSend_fixup";
4957 }
4958 }
4959 Name += '_';
4960 std::string SelName(Sel.getAsString());
4961 // Replace all ':' in selector name with '_' ouch!
4962 for(unsigned i = 0; i < SelName.size(); i++)
4963 if (SelName[i] == ':')
4964 SelName[i] = '_';
4965 Name += SelName;
4966 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
4967 if (!GV) {
4968 // Build messafe ref table entry.
4969 std::vector<llvm::Constant*> Values(2);
4970 Values[0] = Fn;
4971 Values[1] = GetMethodVarName(Sel);
4972 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4973 GV = new llvm::GlobalVariable(Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00004974 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004975 Init,
4976 Name,
4977 &CGM.getModule());
4978 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4979 GV->setAlignment(
4980 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.MessageRefTy));
4981 GV->setSection("__DATA, __objc_msgrefs, coalesced");
4982 UsedGlobals.push_back(GV);
4983 }
4984 llvm::Value *Arg1 = CGF.Builder.CreateBitCast(GV, ObjCTypes.MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00004985
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004986 CallArgList ActualArgs;
4987 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
4988 ActualArgs.push_back(std::make_pair(RValue::get(Arg1),
4989 ObjCTypes.MessageRefCPtrTy));
4990 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Fariborz Jahanianef163782009-02-05 01:13:09 +00004991 const CGFunctionInfo &FnInfo1 = Types.getFunctionInfo(ResultType, ActualArgs);
4992 llvm::Value *Callee = CGF.Builder.CreateStructGEP(Arg1, 0);
4993 Callee = CGF.Builder.CreateLoad(Callee);
Fariborz Jahanian3ab75bd2009-02-14 21:25:36 +00004994 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo1, true);
Fariborz Jahanianef163782009-02-05 01:13:09 +00004995 Callee = CGF.Builder.CreateBitCast(Callee,
4996 llvm::PointerType::getUnqual(FTy));
4997 return CGF.EmitCall(FnInfo1, Callee, ActualArgs);
Fariborz Jahanian46551122009-02-04 00:22:57 +00004998}
4999
5000/// Generate code for a message send expression in the nonfragile abi.
5001CodeGen::RValue CGObjCNonFragileABIMac::GenerateMessageSend(
5002 CodeGen::CodeGenFunction &CGF,
5003 QualType ResultType,
5004 Selector Sel,
5005 llvm::Value *Receiver,
5006 bool IsClassMessage,
5007 const CallArgList &CallArgs) {
Fariborz Jahanian46551122009-02-04 00:22:57 +00005008 return EmitMessageSend(CGF, ResultType, Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005009 Receiver, CGF.getContext().getObjCIdType(),
Fariborz Jahanian46551122009-02-04 00:22:57 +00005010 false, CallArgs);
5011}
5012
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005013llvm::GlobalVariable *
5014CGObjCNonFragileABIMac::GetClassGlobal(const std::string &Name) {
5015 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5016
Daniel Dunbardfff2302009-03-02 05:18:14 +00005017 if (!GV) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005018 GV = new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
5019 llvm::GlobalValue::ExternalLinkage,
5020 0, Name, &CGM.getModule());
5021 UsedGlobals.push_back(GV);
5022 }
5023
5024 return GV;
5025}
5026
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005027llvm::Value *CGObjCNonFragileABIMac::EmitClassRef(CGBuilderTy &Builder,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005028 const ObjCInterfaceDecl *ID,
5029 bool IsSuper) {
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005030
5031 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
5032
5033 if (!Entry) {
5034 std::string ClassName("\01_OBJC_CLASS_$_" + ID->getNameAsString());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005035 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005036 Entry =
5037 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5038 llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005039 ClassGV,
5040 IsSuper ? "\01L_OBJC_CLASSLIST_SUP_REFS_$_"
5041 : "\01L_OBJC_CLASSLIST_REFERENCES_$_",
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005042 &CGM.getModule());
5043 Entry->setAlignment(
5044 CGM.getTargetData().getPrefTypeAlignment(
5045 ObjCTypes.ClassnfABIPtrTy));
5046
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005047 if (IsSuper)
Fariborz Jahanian21228b72009-02-26 22:30:39 +00005048 Entry->setSection("__DATA,__objc_superrefs,regular,no_dead_strip");
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005049 else
Fariborz Jahanian21228b72009-02-26 22:30:39 +00005050 Entry->setSection("__DATA,__objc_classrefs,regular,no_dead_strip");
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005051 UsedGlobals.push_back(Entry);
5052 }
5053
5054 return Builder.CreateLoad(Entry, false, "tmp");
5055}
5056
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005057/// EmitMetaClassRef - Return a Value * of the address of _class_t
5058/// meta-data
5059///
5060llvm::Value *CGObjCNonFragileABIMac::EmitMetaClassRef(CGBuilderTy &Builder,
5061 const ObjCInterfaceDecl *ID) {
5062 llvm::GlobalVariable * &Entry = MetaClassReferences[ID->getIdentifier()];
5063 if (Entry)
5064 return Builder.CreateLoad(Entry, false, "tmp");
5065
5066 std::string MetaClassName("\01_OBJC_METACLASS_$_" + ID->getNameAsString());
Daniel Dunbar8def7992009-03-01 04:51:18 +00005067 llvm::GlobalVariable *MetaClassGV = GetClassGlobal(MetaClassName);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005068 Entry =
5069 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5070 llvm::GlobalValue::InternalLinkage,
5071 MetaClassGV,
5072 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5073 &CGM.getModule());
5074 Entry->setAlignment(
5075 CGM.getTargetData().getPrefTypeAlignment(
5076 ObjCTypes.ClassnfABIPtrTy));
5077
5078 Entry->setSection("__OBJC,__objc_superrefs,regular,no_dead_strip");
5079 UsedGlobals.push_back(Entry);
5080
5081 return Builder.CreateLoad(Entry, false, "tmp");
5082}
5083
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005084/// GetClass - Return a reference to the class for the given interface
5085/// decl.
5086llvm::Value *CGObjCNonFragileABIMac::GetClass(CGBuilderTy &Builder,
5087 const ObjCInterfaceDecl *ID) {
5088 return EmitClassRef(Builder, ID);
5089}
5090
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005091/// Generates a message send where the super is the receiver. This is
5092/// a message send to self with special delivery semantics indicating
5093/// which class's method should be called.
5094CodeGen::RValue
5095CGObjCNonFragileABIMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
5096 QualType ResultType,
5097 Selector Sel,
5098 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005099 bool isCategoryImpl,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005100 llvm::Value *Receiver,
5101 bool IsClassMessage,
5102 const CodeGen::CallArgList &CallArgs) {
5103 // ...
5104 // Create and init a super structure; this is a (receiver, class)
5105 // pair we will pass to objc_msgSendSuper.
5106 llvm::Value *ObjCSuper =
5107 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
5108
5109 llvm::Value *ReceiverAsObject =
5110 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
5111 CGF.Builder.CreateStore(ReceiverAsObject,
5112 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
5113
5114 // If this is a class message the metaclass is passed as the target.
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005115 llvm::Value *Target;
5116 if (IsClassMessage) {
5117 if (isCategoryImpl) {
5118 // Message sent to "super' in a class method defined in
5119 // a category implementation.
5120 Target = EmitClassRef(CGF.Builder, Class, false);
5121 Target = CGF.Builder.CreateStructGEP(Target, 0);
5122 Target = CGF.Builder.CreateLoad(Target);
5123 }
5124 else
5125 Target = EmitMetaClassRef(CGF.Builder, Class);
5126 }
5127 else
5128 Target = EmitClassRef(CGF.Builder, Class, true);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005129
5130 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
5131 // and ObjCTypes types.
5132 const llvm::Type *ClassTy =
5133 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
5134 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
5135 CGF.Builder.CreateStore(Target,
5136 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
5137
5138 return EmitMessageSend(CGF, ResultType, Sel,
5139 ObjCSuper, ObjCTypes.SuperPtrCTy,
5140 true, CallArgs);
5141}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005142
5143llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CGBuilderTy &Builder,
5144 Selector Sel) {
5145 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
5146
5147 if (!Entry) {
5148 llvm::Constant *Casted =
5149 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
5150 ObjCTypes.SelectorPtrTy);
5151 Entry =
5152 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
5153 llvm::GlobalValue::InternalLinkage,
5154 Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
5155 &CGM.getModule());
5156 Entry->setSection("__DATA,__objc_selrefs,literal_pointers,no_dead_strip");
5157 UsedGlobals.push_back(Entry);
5158 }
5159
5160 return Builder.CreateLoad(Entry, false, "tmp");
5161}
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005162/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
5163/// objc_assign_ivar (id src, id *dst)
5164///
5165void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
5166 llvm::Value *src, llvm::Value *dst)
5167{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005168 const llvm::Type * SrcTy = src->getType();
5169 if (!isa<llvm::PointerType>(SrcTy)) {
5170 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5171 assert(Size <= 8 && "does not support size > 8");
5172 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5173 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005174 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5175 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005176 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5177 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5178 CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn,
5179 src, dst, "assignivar");
5180 return;
5181}
5182
5183/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
5184/// objc_assign_strongCast (id src, id *dst)
5185///
5186void CGObjCNonFragileABIMac::EmitObjCStrongCastAssign(
5187 CodeGen::CodeGenFunction &CGF,
5188 llvm::Value *src, llvm::Value *dst)
5189{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005190 const llvm::Type * SrcTy = src->getType();
5191 if (!isa<llvm::PointerType>(SrcTy)) {
5192 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5193 assert(Size <= 8 && "does not support size > 8");
5194 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5195 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005196 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5197 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005198 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5199 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5200 CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn,
5201 src, dst, "weakassign");
5202 return;
5203}
5204
5205/// EmitObjCWeakRead - Code gen for loading value of a __weak
5206/// object: objc_read_weak (id *src)
5207///
5208llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead(
5209 CodeGen::CodeGenFunction &CGF,
5210 llvm::Value *AddrWeakObj)
5211{
Eli Friedman8339b352009-03-07 03:57:15 +00005212 const llvm::Type* DestTy =
5213 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005214 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
5215 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
5216 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00005217 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005218 return read_weak;
5219}
5220
5221/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
5222/// objc_assign_weak (id src, id *dst)
5223///
5224void CGObjCNonFragileABIMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
5225 llvm::Value *src, llvm::Value *dst)
5226{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005227 const llvm::Type * SrcTy = src->getType();
5228 if (!isa<llvm::PointerType>(SrcTy)) {
5229 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5230 assert(Size <= 8 && "does not support size > 8");
5231 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5232 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005233 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5234 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005235 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5236 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5237 CGF.Builder.CreateCall2(ObjCTypes.GcAssignWeakFn,
5238 src, dst, "weakassign");
5239 return;
5240}
5241
5242/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
5243/// objc_assign_global (id src, id *dst)
5244///
5245void CGObjCNonFragileABIMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
5246 llvm::Value *src, llvm::Value *dst)
5247{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005248 const llvm::Type * SrcTy = src->getType();
5249 if (!isa<llvm::PointerType>(SrcTy)) {
5250 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5251 assert(Size <= 8 && "does not support size > 8");
5252 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5253 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005254 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5255 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005256 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5257 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5258 CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn,
5259 src, dst, "globalassign");
5260 return;
5261}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005262
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005263void
5264CGObjCNonFragileABIMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
5265 const Stmt &S) {
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005266 bool isTry = isa<ObjCAtTryStmt>(S);
5267 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
5268 llvm::BasicBlock *PrevLandingPad = CGF.getInvokeDest();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005269 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005270 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005271 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005272 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
5273
5274 // For @synchronized, call objc_sync_enter(sync.expr). The
5275 // evaluation of the expression must occur before we enter the
5276 // @synchronized. We can safely avoid a temp here because jumps into
5277 // @synchronized are illegal & this will dominate uses.
5278 llvm::Value *SyncArg = 0;
5279 if (!isTry) {
5280 SyncArg =
5281 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
5282 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005283 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005284 }
5285
5286 // Push an EH context entry, used for handling rethrows and jumps
5287 // through finally.
5288 CGF.PushCleanupBlock(FinallyBlock);
5289
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005290 CGF.setInvokeDest(TryHandler);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005291
5292 CGF.EmitBlock(TryBlock);
5293 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
5294 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
5295 CGF.EmitBranchThroughCleanup(FinallyEnd);
5296
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005297 // Emit the exception handler.
5298
5299 CGF.EmitBlock(TryHandler);
5300
5301 llvm::Value *llvm_eh_exception =
5302 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_exception);
5303 llvm::Value *llvm_eh_selector_i64 =
5304 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector_i64);
5305 llvm::Value *llvm_eh_typeid_for_i64 =
5306 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for_i64);
5307 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5308 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(Exc->getType(), "_rethrow");
5309
5310 llvm::SmallVector<llvm::Value*, 8> SelectorArgs;
5311 SelectorArgs.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005312 SelectorArgs.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005313
5314 // Construct the lists of (type, catch body) to handle.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005315 llvm::SmallVector<std::pair<const ParmVarDecl*, const Stmt*>, 8> Handlers;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005316 bool HasCatchAll = false;
5317 if (isTry) {
5318 if (const ObjCAtCatchStmt* CatchStmt =
5319 cast<ObjCAtTryStmt>(S).getCatchStmts()) {
5320 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005321 const ParmVarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
Steve Naroff7ba138a2009-03-03 19:52:17 +00005322 Handlers.push_back(std::make_pair(CatchDecl, CatchStmt->getCatchBody()));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005323
5324 // catch(...) always matches.
Steve Naroff7ba138a2009-03-03 19:52:17 +00005325 if (!CatchDecl) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005326 // Use i8* null here to signal this is a catch all, not a cleanup.
5327 llvm::Value *Null = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
5328 SelectorArgs.push_back(Null);
5329 HasCatchAll = true;
5330 break;
5331 }
5332
Daniel Dunbarede8de92009-03-06 00:01:21 +00005333 if (CGF.getContext().isObjCIdType(CatchDecl->getType()) ||
5334 CatchDecl->getType()->isObjCQualifiedIdType()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005335 llvm::Value *IDEHType =
5336 CGM.getModule().getGlobalVariable("OBJC_EHTYPE_id");
5337 if (!IDEHType)
5338 IDEHType =
5339 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5340 llvm::GlobalValue::ExternalLinkage,
5341 0, "OBJC_EHTYPE_id", &CGM.getModule());
5342 SelectorArgs.push_back(IDEHType);
5343 HasCatchAll = true;
5344 break;
5345 }
5346
5347 // All other types should be Objective-C interface pointer types.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005348 const PointerType *PT = CatchDecl->getType()->getAsPointerType();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005349 assert(PT && "Invalid @catch type.");
5350 const ObjCInterfaceType *IT =
5351 PT->getPointeeType()->getAsObjCInterfaceType();
5352 assert(IT && "Invalid @catch type.");
5353 llvm::Value *EHType = GetInterfaceEHType(IT);
5354 SelectorArgs.push_back(EHType);
5355 }
5356 }
5357 }
5358
5359 // We use a cleanup unless there was already a catch all.
5360 if (!HasCatchAll) {
5361 SelectorArgs.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
Daniel Dunbarede8de92009-03-06 00:01:21 +00005362 Handlers.push_back(std::make_pair((const ParmVarDecl*) 0, (const Stmt*) 0));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005363 }
5364
5365 llvm::Value *Selector =
5366 CGF.Builder.CreateCall(llvm_eh_selector_i64,
5367 SelectorArgs.begin(), SelectorArgs.end(),
5368 "selector");
5369 for (unsigned i = 0, e = Handlers.size(); i != e; ++i) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005370 const ParmVarDecl *CatchParam = Handlers[i].first;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005371 const Stmt *CatchBody = Handlers[i].second;
5372
5373 llvm::BasicBlock *Next = 0;
5374
5375 // The last handler always matches.
5376 if (i + 1 != e) {
5377 assert(CatchParam && "Only last handler can be a catch all.");
5378
5379 llvm::BasicBlock *Match = CGF.createBasicBlock("match");
5380 Next = CGF.createBasicBlock("catch.next");
5381 llvm::Value *Id =
5382 CGF.Builder.CreateCall(llvm_eh_typeid_for_i64,
5383 CGF.Builder.CreateBitCast(SelectorArgs[i+2],
5384 ObjCTypes.Int8PtrTy));
5385 CGF.Builder.CreateCondBr(CGF.Builder.CreateICmpEQ(Selector, Id),
5386 Match, Next);
5387
5388 CGF.EmitBlock(Match);
5389 }
5390
5391 if (CatchBody) {
5392 llvm::BasicBlock *MatchEnd = CGF.createBasicBlock("match.end");
5393 llvm::BasicBlock *MatchHandler = CGF.createBasicBlock("match.handler");
5394
5395 // Cleanups must call objc_end_catch.
5396 //
5397 // FIXME: It seems incorrect for objc_begin_catch to be inside
5398 // this context, but this matches gcc.
5399 CGF.PushCleanupBlock(MatchEnd);
5400 CGF.setInvokeDest(MatchHandler);
5401
5402 llvm::Value *ExcObject =
5403 CGF.Builder.CreateCall(ObjCTypes.ObjCBeginCatchFn, Exc);
5404
5405 // Bind the catch parameter if it exists.
5406 if (CatchParam) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005407 ExcObject =
5408 CGF.Builder.CreateBitCast(ExcObject,
5409 CGF.ConvertType(CatchParam->getType()));
5410 // CatchParam is a ParmVarDecl because of the grammar
5411 // construction used to handle this, but for codegen purposes
5412 // we treat this as a local decl.
5413 CGF.EmitLocalBlockVarDecl(*CatchParam);
5414 CGF.Builder.CreateStore(ExcObject, CGF.GetAddrOfLocalVar(CatchParam));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005415 }
5416
5417 CGF.ObjCEHValueStack.push_back(ExcObject);
5418 CGF.EmitStmt(CatchBody);
5419 CGF.ObjCEHValueStack.pop_back();
5420
5421 CGF.EmitBranchThroughCleanup(FinallyEnd);
5422
5423 CGF.EmitBlock(MatchHandler);
5424
5425 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5426 // We are required to emit this call to satisfy LLVM, even
5427 // though we don't use the result.
5428 llvm::SmallVector<llvm::Value*, 8> Args;
5429 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005430 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005431 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5432 0));
5433 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5434 CGF.Builder.CreateStore(Exc, RethrowPtr);
5435 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5436
5437 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5438
5439 CGF.EmitBlock(MatchEnd);
5440
5441 // Unfortunately, we also have to generate another EH frame here
5442 // in case this throws.
5443 llvm::BasicBlock *MatchEndHandler =
5444 CGF.createBasicBlock("match.end.handler");
5445 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
5446 CGF.Builder.CreateInvoke(ObjCTypes.ObjCEndCatchFn,
5447 Cont, MatchEndHandler,
5448 Args.begin(), Args.begin());
5449
5450 CGF.EmitBlock(Cont);
5451 if (Info.SwitchBlock)
5452 CGF.EmitBlock(Info.SwitchBlock);
5453 if (Info.EndBlock)
5454 CGF.EmitBlock(Info.EndBlock);
5455
5456 CGF.EmitBlock(MatchEndHandler);
5457 Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5458 // We are required to emit this call to satisfy LLVM, even
5459 // though we don't use the result.
5460 Args.clear();
5461 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005462 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005463 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5464 0));
5465 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5466 CGF.Builder.CreateStore(Exc, RethrowPtr);
5467 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5468
5469 if (Next)
5470 CGF.EmitBlock(Next);
5471 } else {
5472 assert(!Next && "catchup should be last handler.");
5473
5474 CGF.Builder.CreateStore(Exc, RethrowPtr);
5475 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5476 }
5477 }
5478
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005479 // Pop the cleanup entry, the @finally is outside this cleanup
5480 // scope.
5481 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5482 CGF.setInvokeDest(PrevLandingPad);
5483
5484 CGF.EmitBlock(FinallyBlock);
5485
5486 if (isTry) {
5487 if (const ObjCAtFinallyStmt* FinallyStmt =
5488 cast<ObjCAtTryStmt>(S).getFinallyStmt())
5489 CGF.EmitStmt(FinallyStmt->getFinallyBody());
5490 } else {
5491 // Emit 'objc_sync_exit(expr)' as finally's sole statement for
5492 // @synchronized.
5493 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, SyncArg);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005494 }
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005495
5496 if (Info.SwitchBlock)
5497 CGF.EmitBlock(Info.SwitchBlock);
5498 if (Info.EndBlock)
5499 CGF.EmitBlock(Info.EndBlock);
5500
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005501 // Branch around the rethrow code.
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005502 CGF.EmitBranch(FinallyEnd);
5503
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005504 CGF.EmitBlock(FinallyRethrow);
5505 CGF.Builder.CreateCall(ObjCTypes.UnwindResumeOrRethrowFn,
5506 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005507 CGF.Builder.CreateUnreachable();
5508
5509 CGF.EmitBlock(FinallyEnd);
5510}
5511
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005512/// EmitThrowStmt - Generate code for a throw statement.
5513void CGObjCNonFragileABIMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
5514 const ObjCAtThrowStmt &S) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005515 llvm::Value *Exception;
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005516 if (const Expr *ThrowExpr = S.getThrowExpr()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005517 Exception = CGF.EmitScalarExpr(ThrowExpr);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005518 } else {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005519 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
5520 "Unexpected rethrow outside @catch block.");
5521 Exception = CGF.ObjCEHValueStack.back();
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005522 }
5523
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005524 llvm::Value *ExceptionAsObject =
5525 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
5526 llvm::BasicBlock *InvokeDest = CGF.getInvokeDest();
5527 if (InvokeDest) {
5528 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
5529 CGF.Builder.CreateInvoke(ObjCTypes.ExceptionThrowFn,
5530 Cont, InvokeDest,
5531 &ExceptionAsObject, &ExceptionAsObject + 1);
5532 CGF.EmitBlock(Cont);
5533 } else
5534 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
5535 CGF.Builder.CreateUnreachable();
5536
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005537 // Clear the insertion point to indicate we are in unreachable code.
5538 CGF.Builder.ClearInsertionPoint();
5539}
Daniel Dunbare588b992009-03-01 04:46:24 +00005540
5541llvm::Value *
5542CGObjCNonFragileABIMac::GetInterfaceEHType(const ObjCInterfaceType *IT) {
5543 const ObjCInterfaceDecl *ID = IT->getDecl();
5544 llvm::GlobalVariable * &Entry = EHTypeReferences[ID->getIdentifier()];
5545 if (Entry)
5546 return Entry;
5547
5548 std::string ClassName("\01_OBJC_CLASS_$_" + ID->getNameAsString());
5549 std::string VTableName = "objc_ehtype_vtable";
5550 llvm::GlobalVariable *VTableGV =
5551 CGM.getModule().getGlobalVariable(VTableName);
5552 if (!VTableGV)
5553 VTableGV = new llvm::GlobalVariable(ObjCTypes.Int8PtrTy, false,
5554 llvm::GlobalValue::ExternalLinkage,
5555 0, VTableName, &CGM.getModule());
5556
5557 llvm::Value *VTableIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, 2);
5558
5559 std::vector<llvm::Constant*> Values(3);
5560 Values[0] = llvm::ConstantExpr::getGetElementPtr(VTableGV, &VTableIdx, 1);
5561 Values[1] = GetClassName(ID->getIdentifier());
5562 Values[2] = GetClassGlobal(ClassName);
5563 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.EHTypeTy, Values);
5564
5565 Entry =
5566 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00005567 llvm::GlobalValue::WeakAnyLinkage,
Daniel Dunbare588b992009-03-01 04:46:24 +00005568 Init,
5569 (std::string("OBJC_EHTYPE_$_") +
5570 ID->getIdentifier()->getName()),
5571 &CGM.getModule());
5572
5573 return Entry;
5574}
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005575
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00005576/* *** */
5577
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00005578CodeGen::CGObjCRuntime *
5579CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00005580 return new CGObjCMac(CGM);
5581}
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005582
5583CodeGen::CGObjCRuntime *
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00005584CodeGen::CreateMacNonFragileABIObjCRuntime(CodeGen::CodeGenModule &CGM) {
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00005585 return new CGObjCNonFragileABIMac(CGM);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005586}