blob: a06959f1de778044d785e2826b67bf01f93b770c [file] [log] [blame]
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001//===------- CGObjCMac.cpp - Interface to Apple Objective-C Runtime -------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This provides Objective-C code generation targetting the Apple runtime.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CGObjCRuntime.h"
Daniel Dunbarf77ac862008-08-11 21:35:06 +000015
16#include "CodeGenModule.h"
Daniel Dunbarb7ec2462008-08-16 03:19:19 +000017#include "CodeGenFunction.h"
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000018#include "clang/AST/ASTContext.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000019#include "clang/AST/Decl.h"
Daniel Dunbar6efc0c52008-08-13 03:21:16 +000020#include "clang/AST/DeclObjC.h"
Daniel Dunbarf77ac862008-08-11 21:35:06 +000021#include "clang/Basic/LangOptions.h"
22
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +000023#include "llvm/Intrinsics.h"
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000024#include "llvm/Module.h"
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +000025#include "llvm/ADT/DenseSet.h"
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +000026#include "llvm/Target/TargetData.h"
Daniel Dunbarb7ec2462008-08-16 03:19:19 +000027#include <sstream>
Daniel Dunbarc17a4d32008-08-11 02:45:11 +000028
29using namespace clang;
Daniel Dunbar46f45b92008-09-09 01:06:48 +000030using namespace CodeGen;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +000031
32namespace {
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000033
Daniel Dunbarae226fa2008-08-27 02:31:56 +000034 typedef std::vector<llvm::Constant*> ConstantVector;
35
Daniel Dunbar6efc0c52008-08-13 03:21:16 +000036 // FIXME: We should find a nicer way to make the labels for
37 // metadata, string concatenation is lame.
38
Fariborz Jahanianee0af742009-01-21 22:04:16 +000039class ObjCCommonTypesHelper {
40protected:
41 CodeGen::CodeGenModule &CGM;
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000042
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000043public:
Fariborz Jahanian0a855d02009-03-23 19:10:40 +000044 const llvm::Type *ShortTy, *IntTy, *LongTy, *LongLongTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +000045 const llvm::Type *Int8PtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +000046
Daniel Dunbar2bedbf82008-08-12 05:28:47 +000047 /// ObjectPtrTy - LLVM type for object handles (typeof(id))
48 const llvm::Type *ObjectPtrTy;
Fariborz Jahanian6d657c42008-11-18 20:18:11 +000049
50 /// PtrObjectPtrTy - LLVM type for id *
51 const llvm::Type *PtrObjectPtrTy;
52
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +000053 /// SelectorPtrTy - LLVM type for selector handles (typeof(SEL))
Daniel Dunbar2bedbf82008-08-12 05:28:47 +000054 const llvm::Type *SelectorPtrTy;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +000055 /// ProtocolPtrTy - LLVM type for external protocol handles
56 /// (typeof(Protocol))
57 const llvm::Type *ExternalProtocolPtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +000058
Daniel Dunbar19cd87e2008-08-30 03:02:31 +000059 // SuperCTy - clang type for struct objc_super.
60 QualType SuperCTy;
61 // SuperPtrCTy - clang type for struct objc_super *.
62 QualType SuperPtrCTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +000063
Daniel Dunbare8b470d2008-08-23 04:28:29 +000064 /// SuperTy - LLVM type for struct objc_super.
65 const llvm::StructType *SuperTy;
Daniel Dunbar14c80b72008-08-23 09:25:55 +000066 /// SuperPtrTy - LLVM type for struct objc_super *.
67 const llvm::Type *SuperPtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +000068
Fariborz Jahanian30bc5712009-01-22 23:02:58 +000069 /// PropertyTy - LLVM type for struct objc_property (struct _prop_t
70 /// in GCC parlance).
71 const llvm::StructType *PropertyTy;
72
73 /// PropertyListTy - LLVM type for struct objc_property_list
74 /// (_prop_list_t in GCC parlance).
75 const llvm::StructType *PropertyListTy;
76 /// PropertyListPtrTy - LLVM type for struct objc_property_list*.
77 const llvm::Type *PropertyListPtrTy;
78
79 // MethodTy - LLVM type for struct objc_method.
80 const llvm::StructType *MethodTy;
81
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +000082 /// CacheTy - LLVM type for struct objc_cache.
83 const llvm::Type *CacheTy;
84 /// CachePtrTy - LLVM type for struct objc_cache *.
85 const llvm::Type *CachePtrTy;
86
Chris Lattner74391b42009-03-22 21:03:39 +000087 llvm::Constant *GetPropertyFn, *SetPropertyFn;
Fariborz Jahaniandb286862009-01-22 00:37:21 +000088
Chris Lattner74391b42009-03-22 21:03:39 +000089 llvm::Constant *EnumerationMutationFn;
Fariborz Jahaniandb286862009-01-22 00:37:21 +000090
91 /// GcReadWeakFn -- LLVM objc_read_weak (id *src) function.
Chris Lattner74391b42009-03-22 21:03:39 +000092 llvm::Constant *GcReadWeakFn;
Fariborz Jahaniandb286862009-01-22 00:37:21 +000093
94 /// GcAssignWeakFn -- LLVM objc_assign_weak function.
Chris Lattner74391b42009-03-22 21:03:39 +000095 llvm::Constant *GcAssignWeakFn;
Fariborz Jahaniandb286862009-01-22 00:37:21 +000096
97 /// GcAssignGlobalFn -- LLVM objc_assign_global function.
Chris Lattner74391b42009-03-22 21:03:39 +000098 llvm::Constant *GcAssignGlobalFn;
Fariborz Jahaniandb286862009-01-22 00:37:21 +000099
100 /// GcAssignIvarFn -- LLVM objc_assign_ivar function.
Chris Lattner74391b42009-03-22 21:03:39 +0000101 llvm::Constant *GcAssignIvarFn;
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000102
103 /// GcAssignStrongCastFn -- LLVM objc_assign_strongCast function.
Chris Lattner74391b42009-03-22 21:03:39 +0000104 llvm::Constant *GcAssignStrongCastFn;
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000105
106 /// ExceptionThrowFn - LLVM objc_exception_throw function.
Chris Lattner74391b42009-03-22 21:03:39 +0000107 llvm::Constant *ExceptionThrowFn;
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000108
Daniel Dunbar1c566672009-02-24 01:43:46 +0000109 /// SyncEnterFn - LLVM object_sync_enter function.
Chris Lattnerb02e53b2009-04-06 16:53:45 +0000110 llvm::Constant *getSyncEnterFn() {
111 // void objc_sync_enter (id)
112 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
113 llvm::FunctionType *FTy =
114 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
115 return CGM.CreateRuntimeFunction(FTy, "objc_sync_enter");
116 }
Daniel Dunbar1c566672009-02-24 01:43:46 +0000117
118 /// SyncExitFn - LLVM object_sync_exit function.
Chris Lattner74391b42009-03-22 21:03:39 +0000119 llvm::Constant *SyncExitFn;
Daniel Dunbar1c566672009-02-24 01:43:46 +0000120
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000121 ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm);
122 ~ObjCCommonTypesHelper(){}
123};
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000124
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000125/// ObjCTypesHelper - Helper class that encapsulates lazy
126/// construction of varies types used during ObjC generation.
127class ObjCTypesHelper : public ObjCCommonTypesHelper {
128private:
129
Chris Lattner74391b42009-03-22 21:03:39 +0000130 llvm::Constant *MessageSendFn, *MessageSendStretFn, *MessageSendFpretFn;
131 llvm::Constant *MessageSendSuperFn, *MessageSendSuperStretFn,
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000132 *MessageSendSuperFpretFn;
133
134public:
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000135 /// SymtabTy - LLVM type for struct objc_symtab.
136 const llvm::StructType *SymtabTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000137 /// SymtabPtrTy - LLVM type for struct objc_symtab *.
138 const llvm::Type *SymtabPtrTy;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000139 /// ModuleTy - LLVM type for struct objc_module.
140 const llvm::StructType *ModuleTy;
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000141
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000142 /// ProtocolTy - LLVM type for struct objc_protocol.
143 const llvm::StructType *ProtocolTy;
144 /// ProtocolPtrTy - LLVM type for struct objc_protocol *.
145 const llvm::Type *ProtocolPtrTy;
146 /// ProtocolExtensionTy - LLVM type for struct
147 /// objc_protocol_extension.
148 const llvm::StructType *ProtocolExtensionTy;
149 /// ProtocolExtensionTy - LLVM type for struct
150 /// objc_protocol_extension *.
151 const llvm::Type *ProtocolExtensionPtrTy;
152 /// MethodDescriptionTy - LLVM type for struct
153 /// objc_method_description.
154 const llvm::StructType *MethodDescriptionTy;
155 /// MethodDescriptionListTy - LLVM type for struct
156 /// objc_method_description_list.
157 const llvm::StructType *MethodDescriptionListTy;
158 /// MethodDescriptionListPtrTy - LLVM type for struct
159 /// objc_method_description_list *.
160 const llvm::Type *MethodDescriptionListPtrTy;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000161 /// ProtocolListTy - LLVM type for struct objc_property_list.
162 const llvm::Type *ProtocolListTy;
163 /// ProtocolListPtrTy - LLVM type for struct objc_property_list*.
164 const llvm::Type *ProtocolListPtrTy;
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000165 /// CategoryTy - LLVM type for struct objc_category.
166 const llvm::StructType *CategoryTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000167 /// ClassTy - LLVM type for struct objc_class.
168 const llvm::StructType *ClassTy;
169 /// ClassPtrTy - LLVM type for struct objc_class *.
170 const llvm::Type *ClassPtrTy;
171 /// ClassExtensionTy - LLVM type for struct objc_class_ext.
172 const llvm::StructType *ClassExtensionTy;
173 /// ClassExtensionPtrTy - LLVM type for struct objc_class_ext *.
174 const llvm::Type *ClassExtensionPtrTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000175 // IvarTy - LLVM type for struct objc_ivar.
176 const llvm::StructType *IvarTy;
177 /// IvarListTy - LLVM type for struct objc_ivar_list.
178 const llvm::Type *IvarListTy;
179 /// IvarListPtrTy - LLVM type for struct objc_ivar_list *.
180 const llvm::Type *IvarListPtrTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000181 /// MethodListTy - LLVM type for struct objc_method_list.
182 const llvm::Type *MethodListTy;
183 /// MethodListPtrTy - LLVM type for struct objc_method_list *.
184 const llvm::Type *MethodListPtrTy;
Anders Carlsson124526b2008-09-09 10:10:21 +0000185
186 /// ExceptionDataTy - LLVM type for struct _objc_exception_data.
187 const llvm::Type *ExceptionDataTy;
188
Anders Carlsson124526b2008-09-09 10:10:21 +0000189 /// ExceptionTryEnterFn - LLVM objc_exception_try_enter function.
Chris Lattner74391b42009-03-22 21:03:39 +0000190 llvm::Constant *ExceptionTryEnterFn;
Anders Carlsson124526b2008-09-09 10:10:21 +0000191
192 /// ExceptionTryExitFn - LLVM objc_exception_try_exit function.
Chris Lattner74391b42009-03-22 21:03:39 +0000193 llvm::Constant *ExceptionTryExitFn;
Anders Carlsson124526b2008-09-09 10:10:21 +0000194
195 /// ExceptionExtractFn - LLVM objc_exception_extract function.
Chris Lattner74391b42009-03-22 21:03:39 +0000196 llvm::Constant *ExceptionExtractFn;
Anders Carlsson124526b2008-09-09 10:10:21 +0000197
198 /// ExceptionMatchFn - LLVM objc_exception_match function.
Chris Lattner74391b42009-03-22 21:03:39 +0000199 llvm::Constant *ExceptionMatchFn;
Anders Carlsson124526b2008-09-09 10:10:21 +0000200
201 /// SetJmpFn - LLVM _setjmp function.
Chris Lattner74391b42009-03-22 21:03:39 +0000202 llvm::Constant *SetJmpFn;
Chris Lattner10cac6f2008-11-15 21:26:17 +0000203
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000204public:
205 ObjCTypesHelper(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000206 ~ObjCTypesHelper() {}
Daniel Dunbar5669e572008-10-17 03:24:53 +0000207
208
Chris Lattner74391b42009-03-22 21:03:39 +0000209 llvm::Constant *getSendFn(bool IsSuper) {
Daniel Dunbar5669e572008-10-17 03:24:53 +0000210 return IsSuper ? MessageSendSuperFn : MessageSendFn;
211 }
212
Chris Lattner74391b42009-03-22 21:03:39 +0000213 llvm::Constant *getSendStretFn(bool IsSuper) {
Daniel Dunbar5669e572008-10-17 03:24:53 +0000214 return IsSuper ? MessageSendSuperStretFn : MessageSendStretFn;
215 }
216
Chris Lattner74391b42009-03-22 21:03:39 +0000217 llvm::Constant *getSendFpretFn(bool IsSuper) {
Daniel Dunbar5669e572008-10-17 03:24:53 +0000218 return IsSuper ? MessageSendSuperFpretFn : MessageSendFpretFn;
219 }
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000220};
221
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000222/// ObjCNonFragileABITypesHelper - will have all types needed by objective-c's
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000223/// modern abi
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000224class ObjCNonFragileABITypesHelper : public ObjCCommonTypesHelper {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000225public:
Chris Lattner74391b42009-03-22 21:03:39 +0000226 llvm::Constant *MessageSendFixupFn, *MessageSendFpretFixupFn,
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000227 *MessageSendStretFixupFn, *MessageSendIdFixupFn,
228 *MessageSendIdStretFixupFn, *MessageSendSuper2FixupFn,
229 *MessageSendSuper2StretFixupFn;
230
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000231 // MethodListnfABITy - LLVM for struct _method_list_t
232 const llvm::StructType *MethodListnfABITy;
233
234 // MethodListnfABIPtrTy - LLVM for struct _method_list_t*
235 const llvm::Type *MethodListnfABIPtrTy;
236
237 // ProtocolnfABITy = LLVM for struct _protocol_t
238 const llvm::StructType *ProtocolnfABITy;
239
Daniel Dunbar948e2582009-02-15 07:36:20 +0000240 // ProtocolnfABIPtrTy = LLVM for struct _protocol_t*
241 const llvm::Type *ProtocolnfABIPtrTy;
242
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000243 // ProtocolListnfABITy - LLVM for struct _objc_protocol_list
244 const llvm::StructType *ProtocolListnfABITy;
245
246 // ProtocolListnfABIPtrTy - LLVM for struct _objc_protocol_list*
247 const llvm::Type *ProtocolListnfABIPtrTy;
248
249 // ClassnfABITy - LLVM for struct _class_t
250 const llvm::StructType *ClassnfABITy;
251
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000252 // ClassnfABIPtrTy - LLVM for struct _class_t*
253 const llvm::Type *ClassnfABIPtrTy;
254
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000255 // IvarnfABITy - LLVM for struct _ivar_t
256 const llvm::StructType *IvarnfABITy;
257
258 // IvarListnfABITy - LLVM for struct _ivar_list_t
259 const llvm::StructType *IvarListnfABITy;
260
261 // IvarListnfABIPtrTy = LLVM for struct _ivar_list_t*
262 const llvm::Type *IvarListnfABIPtrTy;
263
264 // ClassRonfABITy - LLVM for struct _class_ro_t
265 const llvm::StructType *ClassRonfABITy;
266
267 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
268 const llvm::Type *ImpnfABITy;
269
270 // CategorynfABITy - LLVM for struct _category_t
271 const llvm::StructType *CategorynfABITy;
272
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000273 // New types for nonfragile abi messaging.
274
275 // MessageRefTy - LLVM for:
276 // struct _message_ref_t {
277 // IMP messenger;
278 // SEL name;
279 // };
280 const llvm::StructType *MessageRefTy;
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000281 // MessageRefCTy - clang type for struct _message_ref_t
282 QualType MessageRefCTy;
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000283
284 // MessageRefPtrTy - LLVM for struct _message_ref_t*
285 const llvm::Type *MessageRefPtrTy;
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000286 // MessageRefCPtrTy - clang type for struct _message_ref_t*
287 QualType MessageRefCPtrTy;
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000288
Fariborz Jahanianef163782009-02-05 01:13:09 +0000289 // MessengerTy - Type of the messenger (shown as IMP above)
290 const llvm::FunctionType *MessengerTy;
291
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000292 // SuperMessageRefTy - LLVM for:
293 // struct _super_message_ref_t {
294 // SUPER_IMP messenger;
295 // SEL name;
296 // };
297 const llvm::StructType *SuperMessageRefTy;
298
299 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
300 const llvm::Type *SuperMessageRefPtrTy;
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000301
302 /// EHPersonalityPtr - LLVM value for an i8* to the Objective-C
303 /// exception personality function.
Chris Lattnerb02e53b2009-04-06 16:53:45 +0000304 llvm::Value *getEHPersonalityPtr() {
305 llvm::Constant *Personality =
306 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
307 std::vector<const llvm::Type*>(),
308 true),
309 "__objc_personality_v0");
310 return llvm::ConstantExpr::getBitCast(Personality, Int8PtrTy);
311 }
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000312
Chris Lattner74391b42009-03-22 21:03:39 +0000313 llvm::Constant *UnwindResumeOrRethrowFn, *ObjCBeginCatchFn, *ObjCEndCatchFn;
Daniel Dunbare588b992009-03-01 04:46:24 +0000314
315 const llvm::StructType *EHTypeTy;
316 const llvm::Type *EHTypePtrTy;
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000317
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000318 ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm);
319 ~ObjCNonFragileABITypesHelper(){}
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000320};
321
322class CGObjCCommonMac : public CodeGen::CGObjCRuntime {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000323public:
324 // FIXME - accessibility
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000325 class GC_IVAR {
Fariborz Jahanian820e0202009-03-11 00:07:04 +0000326 public:
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000327 unsigned int ivar_bytepos;
328 unsigned int ivar_size;
329 GC_IVAR() : ivar_bytepos(0), ivar_size(0) {}
330 };
331
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000332 class SKIP_SCAN {
333 public:
334 unsigned int skip;
335 unsigned int scan;
336 SKIP_SCAN() : skip(0), scan(0) {}
337 };
338
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000339protected:
340 CodeGen::CodeGenModule &CGM;
341 // FIXME! May not be needing this after all.
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000342 unsigned ObjCABI;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000343
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000344 // gc ivar layout bitmap calculation helper caches.
345 llvm::SmallVector<GC_IVAR, 16> SkipIvars;
346 llvm::SmallVector<GC_IVAR, 16> IvarsInfo;
347 llvm::SmallVector<SKIP_SCAN, 32> SkipScanIvars;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000348
Daniel Dunbar242d4dc2008-08-25 06:02:07 +0000349 /// LazySymbols - Symbols to generate a lazy reference for. See
350 /// DefinedSymbols and FinishModule().
351 std::set<IdentifierInfo*> LazySymbols;
352
353 /// DefinedSymbols - External symbols which are defined by this
354 /// module. The symbols in this list and LazySymbols are used to add
355 /// special linker symbols which ensure that Objective-C modules are
356 /// linked properly.
357 std::set<IdentifierInfo*> DefinedSymbols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000358
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000359 /// ClassNames - uniqued class names.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000360 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000361
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000362 /// MethodVarNames - uniqued method variable names.
363 llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000364
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000365 /// MethodVarTypes - uniqued method type signatures. We have to use
366 /// a StringMap here because have no other unique reference.
367 llvm::StringMap<llvm::GlobalVariable*> MethodVarTypes;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000368
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000369 /// MethodDefinitions - map of methods which have been defined in
370 /// this translation unit.
371 llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> MethodDefinitions;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000372
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000373 /// PropertyNames - uniqued method variable names.
374 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000375
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000376 /// ClassReferences - uniqued class references.
377 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000378
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000379 /// SelectorReferences - uniqued selector references.
380 llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000381
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000382 /// Protocols - Protocols for which an objc_protocol structure has
383 /// been emitted. Forward declarations are handled by creating an
384 /// empty structure whose initializer is filled in when/if defined.
385 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> Protocols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000386
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000387 /// DefinedProtocols - Protocols which have actually been
388 /// defined. We should not need this, see FIXME in GenerateProtocol.
389 llvm::DenseSet<IdentifierInfo*> DefinedProtocols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000390
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000391 /// DefinedClasses - List of defined classes.
392 std::vector<llvm::GlobalValue*> DefinedClasses;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000393
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000394 /// DefinedCategories - List of defined categories.
395 std::vector<llvm::GlobalValue*> DefinedCategories;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000396
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000397 /// UsedGlobals - List of globals to pack into the llvm.used metadata
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000398 /// to prevent them from being clobbered.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000399 std::vector<llvm::GlobalVariable*> UsedGlobals;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000400
Fariborz Jahanian56210f72009-01-21 23:34:32 +0000401 /// GetNameForMethod - Return a name for the given method.
402 /// \param[out] NameOut - The return value.
403 void GetNameForMethod(const ObjCMethodDecl *OMD,
404 const ObjCContainerDecl *CD,
405 std::string &NameOut);
406
407 /// GetMethodVarName - Return a unique constant for the given
408 /// selector's name. The return value has type char *.
409 llvm::Constant *GetMethodVarName(Selector Sel);
410 llvm::Constant *GetMethodVarName(IdentifierInfo *Ident);
411 llvm::Constant *GetMethodVarName(const std::string &Name);
412
413 /// GetMethodVarType - Return a unique constant for the given
414 /// selector's name. The return value has type char *.
415
416 // FIXME: This is a horrible name.
417 llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D);
Devang Patel7794bb82009-03-04 18:21:39 +0000418 llvm::Constant *GetMethodVarType(FieldDecl *D);
Fariborz Jahanian56210f72009-01-21 23:34:32 +0000419
420 /// GetPropertyName - Return a unique constant for the given
421 /// name. The return value has type char *.
422 llvm::Constant *GetPropertyName(IdentifierInfo *Ident);
423
424 // FIXME: This can be dropped once string functions are unified.
425 llvm::Constant *GetPropertyTypeString(const ObjCPropertyDecl *PD,
426 const Decl *Container);
427
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000428 /// GetClassName - Return a unique constant for the given selector's
429 /// name. The return value has type char *.
430 llvm::Constant *GetClassName(IdentifierInfo *Ident);
431
Fariborz Jahanian21e6f172009-03-11 21:42:00 +0000432 /// GetInterfaceDeclStructLayout - Get layout for ivars of given
433 /// interface declaration.
434 const llvm::StructLayout *GetInterfaceDeclStructLayout(
435 const ObjCInterfaceDecl *ID) const;
436
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000437 /// BuildIvarLayout - Builds ivar layout bitmap for the class
438 /// implementation for the __strong or __weak case.
439 ///
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000440 llvm::Constant *BuildIvarLayout(const ObjCImplementationDecl *OI,
441 bool ForStrongLayout);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000442
Fariborz Jahaniancf71dd42009-04-07 20:26:30 +0000443 bool IsClassHidden(const ObjCInterfaceDecl *ID);
444
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000445 void BuildAggrIvarLayout(const ObjCInterfaceDecl *OI,
446 const llvm::StructLayout *Layout,
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000447 const RecordDecl *RD,
Chris Lattnerf1690852009-03-31 08:48:01 +0000448 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000449 unsigned int BytePos, bool ForStrongLayout,
450 int &Index, int &SkIndex, bool &HasUnion);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000451
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +0000452 /// GetIvarLayoutName - Returns a unique constant for the given
453 /// ivar layout bitmap.
454 llvm::Constant *GetIvarLayoutName(IdentifierInfo *Ident,
455 const ObjCCommonTypesHelper &ObjCTypes);
456
Fariborz Jahanian46b86c62009-01-28 19:12:34 +0000457 const RecordDecl *GetFirstIvarInRecord(const ObjCInterfaceDecl *OID,
458 RecordDecl::field_iterator &FIV,
459 RecordDecl::field_iterator &PIV);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +0000460 /// EmitPropertyList - Emit the given property list. The return
461 /// value has type PropertyListPtrTy.
462 llvm::Constant *EmitPropertyList(const std::string &Name,
463 const Decl *Container,
464 const ObjCContainerDecl *OCD,
465 const ObjCCommonTypesHelper &ObjCTypes);
466
Fariborz Jahanianda320092009-01-29 19:24:30 +0000467 /// GetProtocolRef - Return a reference to the internal protocol
468 /// description, creating an empty one if it has not been
469 /// defined. The return value has type ProtocolPtrTy.
470 llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +0000471
472 /// GetIvarBaseOffset - returns ivars byte offset.
473 uint64_t GetIvarBaseOffset(const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +0000474 const FieldDecl *Field);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000475
Chris Lattnercd0ee142009-03-31 08:33:16 +0000476 /// GetFieldBaseOffset - return's field byte offset.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000477 uint64_t GetFieldBaseOffset(const ObjCInterfaceDecl *OI,
478 const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +0000479 const FieldDecl *Field);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000480
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000481 /// CreateMetadataVar - Create a global variable with internal
482 /// linkage for use by the Objective-C runtime.
483 ///
484 /// This is a convenience wrapper which not only creates the
485 /// variable, but also sets the section and alignment and adds the
486 /// global to the UsedGlobals list.
Daniel Dunbar35bd7632009-03-09 20:50:13 +0000487 ///
488 /// \param Name - The variable name.
489 /// \param Init - The variable initializer; this is also used to
490 /// define the type of the variable.
491 /// \param Section - The section the variable should go into, or 0.
492 /// \param Align - The alignment for the variable, or 0.
493 /// \param AddToUsed - Whether the variable should be added to
494 /// llvm.
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000495 llvm::GlobalVariable *CreateMetadataVar(const std::string &Name,
496 llvm::Constant *Init,
497 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +0000498 unsigned Align,
499 bool AddToUsed);
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000500
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000501public:
502 CGObjCCommonMac(CodeGen::CodeGenModule &cgm) : CGM(cgm)
503 { }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000504
Steve Naroff33fdb732009-03-31 16:53:37 +0000505 virtual llvm::Constant *GenerateConstantString(const ObjCStringLiteral *SL);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000506
507 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
508 const ObjCContainerDecl *CD=0);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000509
510 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
511
512 /// GetOrEmitProtocol - Get the protocol object for the given
513 /// declaration, emitting it if necessary. The return value has type
514 /// ProtocolPtrTy.
515 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD)=0;
516
517 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
518 /// object for the given declaration, emitting it if needed. These
519 /// forward references will be filled in with empty bodies if no
520 /// definition is seen. The return value has type ProtocolPtrTy.
521 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD)=0;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000522};
523
524class CGObjCMac : public CGObjCCommonMac {
525private:
526 ObjCTypesHelper ObjCTypes;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000527 /// EmitImageInfo - Emit the image info marker used to encode some module
528 /// level information.
529 void EmitImageInfo();
530
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000531 /// EmitModuleInfo - Another marker encoding module level
532 /// information.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000533 void EmitModuleInfo();
534
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000535 /// EmitModuleSymols - Emit module symbols, the list of defined
536 /// classes and categories. The result has type SymtabPtrTy.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000537 llvm::Constant *EmitModuleSymbols();
538
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000539 /// FinishModule - Write out global data structures at the end of
540 /// processing a translation unit.
541 void FinishModule();
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000542
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000543 /// EmitClassExtension - Generate the class extension structure used
544 /// to store the weak ivar layout and properties. The return value
545 /// has type ClassExtensionPtrTy.
546 llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID);
547
548 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
549 /// for the given class.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000550 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000551 const ObjCInterfaceDecl *ID);
552
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000553 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000554 QualType ResultType,
555 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000556 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000557 QualType Arg0Ty,
558 bool IsSuper,
559 const CallArgList &CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000560
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000561 /// EmitIvarList - Emit the ivar list for the given
562 /// implementation. If ForClass is true the list of class ivars
563 /// (i.e. metaclass ivars) is emitted, otherwise the list of
564 /// interface ivars will be emitted. The return value has type
565 /// IvarListPtrTy.
566 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +0000567 bool ForClass);
568
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000569 /// EmitMetaClass - Emit a forward reference to the class structure
570 /// for the metaclass of the given interface. The return value has
571 /// type ClassPtrTy.
572 llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
573
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000574 /// EmitMetaClass - Emit a class structure for the metaclass of the
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000575 /// given implementation. The return value has type ClassPtrTy.
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000576 llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
577 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000578 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000579 const ConstantVector &Methods);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000580
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000581 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000582
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000583 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000584
585 /// EmitMethodList - Emit the method list for the given
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000586 /// implementation. The return value has type MethodListPtrTy.
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000587 llvm::Constant *EmitMethodList(const std::string &Name,
588 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000589 const ConstantVector &Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000590
591 /// EmitMethodDescList - Emit a method description list for a list of
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000592 /// method declarations.
593 /// - TypeName: The name for the type containing the methods.
594 /// - IsProtocol: True iff these methods are for a protocol.
595 /// - ClassMethds: True iff these are class methods.
596 /// - Required: When true, only "required" methods are
597 /// listed. Similarly, when false only "optional" methods are
598 /// listed. For classes this should always be true.
599 /// - begin, end: The method list to output.
600 ///
601 /// The return value has type MethodDescriptionListPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000602 llvm::Constant *EmitMethodDescList(const std::string &Name,
603 const char *Section,
604 const ConstantVector &Methods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000605
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000606 /// GetOrEmitProtocol - Get the protocol object for the given
607 /// declaration, emitting it if necessary. The return value has type
608 /// ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +0000609 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000610
611 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
612 /// object for the given declaration, emitting it if needed. These
613 /// forward references will be filled in with empty bodies if no
614 /// definition is seen. The return value has type ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +0000615 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000616
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000617 /// EmitProtocolExtension - Generate the protocol extension
618 /// structure used to store optional instance and class methods, and
619 /// protocol properties. The return value has type
620 /// ProtocolExtensionPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000621 llvm::Constant *
622 EmitProtocolExtension(const ObjCProtocolDecl *PD,
623 const ConstantVector &OptInstanceMethods,
624 const ConstantVector &OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000625
626 /// EmitProtocolList - Generate the list of referenced
627 /// protocols. The return value has type ProtocolListPtrTy.
Daniel Dunbardbc933702008-08-21 21:57:41 +0000628 llvm::Constant *EmitProtocolList(const std::string &Name,
629 ObjCProtocolDecl::protocol_iterator begin,
630 ObjCProtocolDecl::protocol_iterator end);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000631
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000632 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
633 /// for the given selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000634 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000635
Fariborz Jahanianda320092009-01-29 19:24:30 +0000636 public:
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000637 CGObjCMac(CodeGen::CodeGenModule &cgm);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000638
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000639 virtual llvm::Function *ModuleInitFunction();
640
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000641 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000642 QualType ResultType,
643 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000644 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000645 bool IsClassMessage,
646 const CallArgList &CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000647
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000648 virtual CodeGen::RValue
649 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000650 QualType ResultType,
651 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000652 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000653 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000654 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000655 bool IsClassMessage,
656 const CallArgList &CallArgs);
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000657
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000658 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000659 const ObjCInterfaceDecl *ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000660
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000661 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000662
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000663 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000664
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000665 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000666
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000667 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000668 const ObjCProtocolDecl *PD);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000669
Chris Lattner74391b42009-03-22 21:03:39 +0000670 virtual llvm::Constant *GetPropertyGetFunction();
671 virtual llvm::Constant *GetPropertySetFunction();
672 virtual llvm::Constant *EnumerationMutationFunction();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000673
Fariborz Jahanianbd71be42008-11-21 00:49:24 +0000674 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
675 const Stmt &S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000676 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
677 const ObjCAtThrowStmt &S);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000678 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +0000679 llvm::Value *AddrWeakObj);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000680 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
681 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000682 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
683 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian7eda8362008-11-20 19:23:36 +0000684 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
685 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000686 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
687 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian0bb20362009-02-02 20:02:29 +0000688
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000689 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
690 QualType ObjectTy,
691 llvm::Value *BaseValue,
692 const ObjCIvarDecl *Ivar,
693 const FieldDecl *Field,
694 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000695 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
696 ObjCInterfaceDecl *Interface,
697 const ObjCIvarDecl *Ivar);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000698};
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000699
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000700class CGObjCNonFragileABIMac : public CGObjCCommonMac {
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000701private:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000702 ObjCNonFragileABITypesHelper ObjCTypes;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000703 llvm::GlobalVariable* ObjCEmptyCacheVar;
704 llvm::GlobalVariable* ObjCEmptyVtableVar;
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000705
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000706 /// MetaClassReferences - uniqued meta class references.
707 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> MetaClassReferences;
Daniel Dunbare588b992009-03-01 04:46:24 +0000708
709 /// EHTypeReferences - uniqued class ehtype references.
710 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> EHTypeReferences;
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000711
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000712 /// FinishNonFragileABIModule - Write out global data structures at the end of
713 /// processing a translation unit.
714 void FinishNonFragileABIModule();
Daniel Dunbar8158a2f2009-04-08 04:21:03 +0000715
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000716 llvm::GlobalVariable * BuildClassRoTInitializer(unsigned flags,
717 unsigned InstanceStart,
718 unsigned InstanceSize,
719 const ObjCImplementationDecl *ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +0000720 llvm::GlobalVariable * BuildClassMetaData(std::string &ClassName,
721 llvm::Constant *IsAGV,
722 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +0000723 llvm::Constant *ClassRoGV,
724 bool HiddenVisibility);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000725
726 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
727
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +0000728 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
729
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000730 /// EmitMethodList - Emit the method list for the given
731 /// implementation. The return value has type MethodListnfABITy.
732 llvm::Constant *EmitMethodList(const std::string &Name,
733 const char *Section,
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +0000734 const ConstantVector &Methods);
735 /// EmitIvarList - Emit the ivar list for the given
736 /// implementation. If ForClass is true the list of class ivars
737 /// (i.e. metaclass ivars) is emitted, otherwise the list of
738 /// interface ivars will be emitted. The return value has type
739 /// IvarListnfABIPtrTy.
740 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000741
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000742 llvm::Constant *EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +0000743 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +0000744 unsigned long int offset);
745
Fariborz Jahanianda320092009-01-29 19:24:30 +0000746 /// GetOrEmitProtocol - Get the protocol object for the given
747 /// declaration, emitting it if necessary. The return value has type
748 /// ProtocolPtrTy.
749 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
750
751 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
752 /// object for the given declaration, emitting it if needed. These
753 /// forward references will be filled in with empty bodies if no
754 /// definition is seen. The return value has type ProtocolPtrTy.
755 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
756
757 /// EmitProtocolList - Generate the list of referenced
758 /// protocols. The return value has type ProtocolListPtrTy.
759 llvm::Constant *EmitProtocolList(const std::string &Name,
760 ObjCProtocolDecl::protocol_iterator begin,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000761 ObjCProtocolDecl::protocol_iterator end);
762
763 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
764 QualType ResultType,
765 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000766 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000767 QualType Arg0Ty,
768 bool IsSuper,
769 const CallArgList &CallArgs);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +0000770
771 /// GetClassGlobal - Return the global variable for the Objective-C
772 /// class of the given name.
Daniel Dunbar6ab187a2009-04-07 05:48:37 +0000773 llvm::GlobalVariable *GetClassGlobal(const std::string &Name,
774 bool AddToUsed = true);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000775
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000776 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
777 /// for the given class.
778 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000779 const ObjCInterfaceDecl *ID,
780 bool IsSuper = false);
781
782 /// EmitMetaClassRef - Return a Value * of the address of _class_t
783 /// meta-data
784 llvm::Value *EmitMetaClassRef(CGBuilderTy &Builder,
785 const ObjCInterfaceDecl *ID);
786
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000787 /// ObjCIvarOffsetVariable - Returns the ivar offset variable for
788 /// the given ivar.
789 ///
790 llvm::GlobalVariable * ObjCIvarOffsetVariable(std::string &Name,
Fariborz Jahanian01a0c362009-02-12 18:51:23 +0000791 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000792 const ObjCIvarDecl *Ivar);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000793
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +0000794 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
795 /// for the given selector.
796 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbare588b992009-03-01 04:46:24 +0000797
Daniel Dunbar8158a2f2009-04-08 04:21:03 +0000798 /// GetInterfaceEHType - Get the cached ehtype for the given Objective-C
Daniel Dunbare588b992009-03-01 04:46:24 +0000799 /// interface. The return value has type EHTypePtrTy.
Daniel Dunbar8158a2f2009-04-08 04:21:03 +0000800 llvm::Value *GetInterfaceEHType(const ObjCInterfaceDecl *ID,
801 bool ForDefinition);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +0000802
803 const char *getMetaclassSymbolPrefix() const {
804 return "OBJC_METACLASS_$_";
805 }
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000806
Daniel Dunbar6ab187a2009-04-07 05:48:37 +0000807 const char *getClassSymbolPrefix() const {
808 return "OBJC_CLASS_$_";
809 }
810
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000811public:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000812 CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000813 // FIXME. All stubs for now!
814 virtual llvm::Function *ModuleInitFunction();
815
816 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
817 QualType ResultType,
818 Selector Sel,
819 llvm::Value *Receiver,
820 bool IsClassMessage,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000821 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000822
823 virtual CodeGen::RValue
824 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
825 QualType ResultType,
826 Selector Sel,
827 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000828 bool isCategoryImpl,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000829 llvm::Value *Receiver,
830 bool IsClassMessage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000831 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000832
833 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000834 const ObjCInterfaceDecl *ID);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000835
836 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel)
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +0000837 { return EmitSelector(Builder, Sel); }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000838
Fariborz Jahanianeb062d92009-01-26 18:32:24 +0000839 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000840
841 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000842 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +0000843 const ObjCProtocolDecl *PD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000844
Chris Lattner74391b42009-03-22 21:03:39 +0000845 virtual llvm::Constant *GetPropertyGetFunction() {
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000846 return ObjCTypes.GetPropertyFn;
847 }
Chris Lattner74391b42009-03-22 21:03:39 +0000848 virtual llvm::Constant *GetPropertySetFunction() {
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000849 return ObjCTypes.SetPropertyFn;
850 }
Chris Lattner74391b42009-03-22 21:03:39 +0000851 virtual llvm::Constant *EnumerationMutationFunction() {
Daniel Dunbar28ed0842009-02-16 18:48:45 +0000852 return ObjCTypes.EnumerationMutationFn;
853 }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000854
855 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000856 const Stmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000857 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000858 const ObjCAtThrowStmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000859 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000860 llvm::Value *AddrWeakObj);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000861 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000862 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000863 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000864 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000865 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000866 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000867 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000868 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000869 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
870 QualType ObjectTy,
871 llvm::Value *BaseValue,
872 const ObjCIvarDecl *Ivar,
873 const FieldDecl *Field,
874 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000875 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
876 ObjCInterfaceDecl *Interface,
877 const ObjCIvarDecl *Ivar);
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000878};
879
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000880} // end anonymous namespace
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000881
882/* *** Helper Functions *** */
883
884/// getConstantGEP() - Help routine to construct simple GEPs.
885static llvm::Constant *getConstantGEP(llvm::Constant *C,
886 unsigned idx0,
887 unsigned idx1) {
888 llvm::Value *Idxs[] = {
889 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx0),
890 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx1)
891 };
892 return llvm::ConstantExpr::getGetElementPtr(C, Idxs, 2);
893}
894
Daniel Dunbar8158a2f2009-04-08 04:21:03 +0000895/// hasObjCExceptionAttribute - Return true if this class or any super
896/// class has the __objc_exception__ attribute.
897static bool hasObjCExceptionAttribute(const ObjCInterfaceDecl *OID) {
898 if (OID->getAttr<ObjCExceptionAttr>())
899 return true;
900 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
901 return hasObjCExceptionAttribute(Super);
902 return false;
903}
904
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000905/* *** CGObjCMac Public Interface *** */
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000906
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000907CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm),
908 ObjCTypes(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000909{
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000910 ObjCABI = 1;
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000911 EmitImageInfo();
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000912}
913
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000914/// GetClass - Return a reference to the class for the given interface
915/// decl.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000916llvm::Value *CGObjCMac::GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000917 const ObjCInterfaceDecl *ID) {
918 return EmitClassRef(Builder, ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000919}
920
921/// GetSelector - Return the pointer to the unique'd string for this selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000922llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000923 return EmitSelector(Builder, Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000924}
925
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000926/// Generate a constant CFString object.
927/*
928 struct __builtin_CFString {
929 const int *isa; // point to __CFConstantStringClassReference
930 int flags;
931 const char *str;
932 long length;
933 };
934*/
935
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000936llvm::Constant *CGObjCCommonMac::GenerateConstantString(
Steve Naroff33fdb732009-03-31 16:53:37 +0000937 const ObjCStringLiteral *SL) {
Steve Naroff8d4141f2009-04-01 13:55:36 +0000938 return CGM.GetAddrOfConstantCFString(SL->getString());
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000939}
940
941/// Generates a message send where the super is the receiver. This is
942/// a message send to self with special delivery semantics indicating
943/// which class's method should be called.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000944CodeGen::RValue
945CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000946 QualType ResultType,
947 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000948 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000949 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000950 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000951 bool IsClassMessage,
Daniel Dunbar46f45b92008-09-09 01:06:48 +0000952 const CodeGen::CallArgList &CallArgs) {
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000953 // Create and init a super structure; this is a (receiver, class)
954 // pair we will pass to objc_msgSendSuper.
955 llvm::Value *ObjCSuper =
956 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
957 llvm::Value *ReceiverAsObject =
958 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
959 CGF.Builder.CreateStore(ReceiverAsObject,
960 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000961
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000962 // If this is a class message the metaclass is passed as the target.
963 llvm::Value *Target;
964 if (IsClassMessage) {
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000965 if (isCategoryImpl) {
966 // Message sent to 'super' in a class method defined in a category
967 // implementation requires an odd treatment.
968 // If we are in a class method, we must retrieve the
969 // _metaclass_ for the current class, pointed at by
970 // the class's "isa" pointer. The following assumes that
971 // isa" is the first ivar in a class (which it must be).
972 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
973 Target = CGF.Builder.CreateStructGEP(Target, 0);
974 Target = CGF.Builder.CreateLoad(Target);
975 }
976 else {
977 llvm::Value *MetaClassPtr = EmitMetaClassRef(Class);
978 llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1);
979 llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr);
980 Target = Super;
981 }
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000982 } else {
983 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
984 }
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000985 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
986 // and ObjCTypes types.
987 const llvm::Type *ClassTy =
988 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000989 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000990 CGF.Builder.CreateStore(Target,
991 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
992
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000993 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000994 ObjCSuper, ObjCTypes.SuperPtrCTy,
995 true, CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000996}
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000997
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000998/// Generate code for a message send expression.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000999CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001000 QualType ResultType,
1001 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001002 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001003 bool IsClassMessage,
1004 const CallArgList &CallArgs) {
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001005 llvm::Value *Arg0 =
1006 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy, "tmp");
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001007 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001008 Arg0, CGF.getContext().getObjCIdType(),
1009 false, CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001010}
1011
1012CodeGen::RValue CGObjCMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001013 QualType ResultType,
1014 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001015 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001016 QualType Arg0Ty,
1017 bool IsSuper,
1018 const CallArgList &CallArgs) {
1019 CallArgList ActualArgs;
Daniel Dunbar46f45b92008-09-09 01:06:48 +00001020 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
1021 ActualArgs.push_back(std::make_pair(RValue::get(EmitSelector(CGF.Builder,
1022 Sel)),
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001023 CGF.getContext().getObjCSelType()));
1024 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001025
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001026 CodeGenTypes &Types = CGM.getTypes();
1027 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs);
1028 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo, false);
Daniel Dunbar5669e572008-10-17 03:24:53 +00001029
1030 llvm::Constant *Fn;
Daniel Dunbar88b53962009-02-02 22:03:45 +00001031 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Daniel Dunbar5669e572008-10-17 03:24:53 +00001032 Fn = ObjCTypes.getSendStretFn(IsSuper);
1033 } else if (ResultType->isFloatingType()) {
1034 // FIXME: Sadly, this is wrong. This actually depends on the
1035 // architecture. This happens to be right for x86-32 though.
1036 Fn = ObjCTypes.getSendFpretFn(IsSuper);
1037 } else {
1038 Fn = ObjCTypes.getSendFn(IsSuper);
1039 }
Daniel Dunbar62d5c1b2008-09-10 07:00:50 +00001040 Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy));
Daniel Dunbar88b53962009-02-02 22:03:45 +00001041 return CGF.EmitCall(FnInfo, Fn, ActualArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001042}
1043
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001044llvm::Value *CGObjCMac::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001045 const ObjCProtocolDecl *PD) {
Daniel Dunbarc67876d2008-09-04 04:33:15 +00001046 // FIXME: I don't understand why gcc generates this, or where it is
1047 // resolved. Investigate. Its also wasteful to look this up over and
1048 // over.
1049 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1050
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001051 return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
1052 ObjCTypes.ExternalProtocolPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001053}
1054
Fariborz Jahanianda320092009-01-29 19:24:30 +00001055void CGObjCCommonMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001056 // FIXME: We shouldn't need this, the protocol decl should contain
1057 // enough information to tell us whether this was a declaration or a
1058 // definition.
1059 DefinedProtocols.insert(PD->getIdentifier());
1060
1061 // If we have generated a forward reference to this protocol, emit
1062 // it now. Otherwise do nothing, the protocol objects are lazily
1063 // emitted.
1064 if (Protocols.count(PD->getIdentifier()))
1065 GetOrEmitProtocol(PD);
1066}
1067
Fariborz Jahanianda320092009-01-29 19:24:30 +00001068llvm::Constant *CGObjCCommonMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001069 if (DefinedProtocols.count(PD->getIdentifier()))
1070 return GetOrEmitProtocol(PD);
1071 return GetOrEmitProtocolRef(PD);
1072}
1073
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001074/*
1075 // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions
1076 struct _objc_protocol {
1077 struct _objc_protocol_extension *isa;
1078 char *protocol_name;
1079 struct _objc_protocol_list *protocol_list;
1080 struct _objc__method_prototype_list *instance_methods;
1081 struct _objc__method_prototype_list *class_methods
1082 };
1083
1084 See EmitProtocolExtension().
1085*/
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001086llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
1087 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1088
1089 // Early exit if a defining object has already been generated.
1090 if (Entry && Entry->hasInitializer())
1091 return Entry;
1092
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001093 // FIXME: I don't understand why gcc generates this, or where it is
1094 // resolved. Investigate. Its also wasteful to look this up over and
1095 // over.
1096 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1097
Chris Lattner8ec03f52008-11-24 03:54:41 +00001098 const char *ProtocolName = PD->getNameAsCString();
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001099
1100 // Construct method lists.
1101 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1102 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregor6ab35242009-04-09 21:40:53 +00001103 for (ObjCProtocolDecl::instmeth_iterator
1104 i = PD->instmeth_begin(CGM.getContext()),
1105 e = PD->instmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001106 ObjCMethodDecl *MD = *i;
1107 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1108 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1109 OptInstanceMethods.push_back(C);
1110 } else {
1111 InstanceMethods.push_back(C);
1112 }
1113 }
1114
Douglas Gregor6ab35242009-04-09 21:40:53 +00001115 for (ObjCProtocolDecl::classmeth_iterator
1116 i = PD->classmeth_begin(CGM.getContext()),
1117 e = PD->classmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001118 ObjCMethodDecl *MD = *i;
1119 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1120 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1121 OptClassMethods.push_back(C);
1122 } else {
1123 ClassMethods.push_back(C);
1124 }
1125 }
1126
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001127 std::vector<llvm::Constant*> Values(5);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001128 Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001129 Values[1] = GetClassName(PD->getIdentifier());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001130 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001131 EmitProtocolList("\01L_OBJC_PROTOCOL_REFS_" + PD->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001132 PD->protocol_begin(),
1133 PD->protocol_end());
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001134 Values[3] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001135 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_"
1136 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001137 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1138 InstanceMethods);
1139 Values[4] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001140 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_"
1141 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001142 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1143 ClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001144 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
1145 Values);
1146
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001147 if (Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001148 // Already created, fix the linkage and update the initializer.
1149 Entry->setLinkage(llvm::GlobalValue::InternalLinkage);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001150 Entry->setInitializer(Init);
1151 } else {
1152 Entry =
1153 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
1154 llvm::GlobalValue::InternalLinkage,
1155 Init,
1156 std::string("\01L_OBJC_PROTOCOL_")+ProtocolName,
1157 &CGM.getModule());
1158 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001159 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001160 UsedGlobals.push_back(Entry);
1161 // FIXME: Is this necessary? Why only for protocol?
1162 Entry->setAlignment(4);
1163 }
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001164
1165 return Entry;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001166}
1167
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001168llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001169 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1170
1171 if (!Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001172 // We use the initializer as a marker of whether this is a forward
1173 // reference or not. At module finalization we add the empty
1174 // contents for protocols which were referenced but never defined.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001175 Entry =
1176 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001177 llvm::GlobalValue::ExternalLinkage,
1178 0,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001179 "\01L_OBJC_PROTOCOL_" + PD->getNameAsString(),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001180 &CGM.getModule());
1181 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001182 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001183 UsedGlobals.push_back(Entry);
1184 // FIXME: Is this necessary? Why only for protocol?
1185 Entry->setAlignment(4);
1186 }
1187
1188 return Entry;
1189}
1190
1191/*
1192 struct _objc_protocol_extension {
1193 uint32_t size;
1194 struct objc_method_description_list *optional_instance_methods;
1195 struct objc_method_description_list *optional_class_methods;
1196 struct objc_property_list *instance_properties;
1197 };
1198*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001199llvm::Constant *
1200CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
1201 const ConstantVector &OptInstanceMethods,
1202 const ConstantVector &OptClassMethods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001203 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001204 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolExtensionTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001205 std::vector<llvm::Constant*> Values(4);
1206 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001207 Values[1] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001208 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_"
1209 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001210 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1211 OptInstanceMethods);
1212 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001213 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_"
1214 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001215 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1216 OptClassMethods);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001217 Values[3] = EmitPropertyList("\01L_OBJC_$_PROP_PROTO_LIST_" +
1218 PD->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001219 0, PD, ObjCTypes);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001220
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001221 // Return null if no extension bits are used.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001222 if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
1223 Values[3]->isNullValue())
1224 return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
1225
1226 llvm::Constant *Init =
1227 llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001228
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001229 // No special section, but goes in llvm.used
1230 return CreateMetadataVar("\01L_OBJC_PROTOCOLEXT_" + PD->getNameAsString(),
1231 Init,
1232 0, 0, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001233}
1234
1235/*
1236 struct objc_protocol_list {
1237 struct objc_protocol_list *next;
1238 long count;
1239 Protocol *list[];
1240 };
1241*/
Daniel Dunbardbc933702008-08-21 21:57:41 +00001242llvm::Constant *
1243CGObjCMac::EmitProtocolList(const std::string &Name,
1244 ObjCProtocolDecl::protocol_iterator begin,
1245 ObjCProtocolDecl::protocol_iterator end) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001246 std::vector<llvm::Constant*> ProtocolRefs;
1247
Daniel Dunbardbc933702008-08-21 21:57:41 +00001248 for (; begin != end; ++begin)
1249 ProtocolRefs.push_back(GetProtocolRef(*begin));
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001250
1251 // Just return null for empty protocol lists
1252 if (ProtocolRefs.empty())
1253 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1254
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001255 // This list is null terminated.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001256 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
1257
1258 std::vector<llvm::Constant*> Values(3);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001259 // This field is only used by the runtime.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001260 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1261 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
1262 Values[2] =
1263 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
1264 ProtocolRefs.size()),
1265 ProtocolRefs);
1266
1267 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1268 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001269 CreateMetadataVar(Name, Init, "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001270 4, false);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001271 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
1272}
1273
1274/*
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001275 struct _objc_property {
1276 const char * const name;
1277 const char * const attributes;
1278 };
1279
1280 struct _objc_property_list {
1281 uint32_t entsize; // sizeof (struct _objc_property)
1282 uint32_t prop_count;
1283 struct _objc_property[prop_count];
1284 };
1285*/
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001286llvm::Constant *CGObjCCommonMac::EmitPropertyList(const std::string &Name,
1287 const Decl *Container,
1288 const ObjCContainerDecl *OCD,
1289 const ObjCCommonTypesHelper &ObjCTypes) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001290 std::vector<llvm::Constant*> Properties, Prop(2);
Douglas Gregor6ab35242009-04-09 21:40:53 +00001291 for (ObjCContainerDecl::prop_iterator I = OCD->prop_begin(CGM.getContext()),
1292 E = OCD->prop_end(CGM.getContext()); I != E; ++I) {
Steve Naroff93983f82009-01-11 12:47:58 +00001293 const ObjCPropertyDecl *PD = *I;
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001294 Prop[0] = GetPropertyName(PD->getIdentifier());
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00001295 Prop[1] = GetPropertyTypeString(PD, Container);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001296 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
1297 Prop));
1298 }
1299
1300 // Return null for empty list.
1301 if (Properties.empty())
1302 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1303
1304 unsigned PropertySize =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001305 CGM.getTargetData().getTypePaddedSize(ObjCTypes.PropertyTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001306 std::vector<llvm::Constant*> Values(3);
1307 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
1308 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
1309 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
1310 Properties.size());
1311 Values[2] = llvm::ConstantArray::get(AT, Properties);
1312 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1313
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001314 // No special section on property lists?
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001315 llvm::GlobalVariable *GV =
1316 CreateMetadataVar(Name, Init, (ObjCABI == 2) ? "__DATA, __objc_const" : 0,
1317 0, true);
1318 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.PropertyListPtrTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001319}
1320
1321/*
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001322 struct objc_method_description_list {
1323 int count;
1324 struct objc_method_description list[];
1325 };
1326*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001327llvm::Constant *
1328CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
1329 std::vector<llvm::Constant*> Desc(2);
1330 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1331 ObjCTypes.SelectorPtrTy);
1332 Desc[1] = GetMethodVarType(MD);
1333 return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
1334 Desc);
1335}
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001336
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001337llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name,
1338 const char *Section,
1339 const ConstantVector &Methods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001340 // Return null for empty list.
1341 if (Methods.empty())
1342 return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
1343
1344 std::vector<llvm::Constant*> Values(2);
1345 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1346 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
1347 Methods.size());
1348 Values[1] = llvm::ConstantArray::get(AT, Methods);
1349 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1350
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001351 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 0, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001352 return llvm::ConstantExpr::getBitCast(GV,
1353 ObjCTypes.MethodDescriptionListPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001354}
1355
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001356/*
1357 struct _objc_category {
1358 char *category_name;
1359 char *class_name;
1360 struct _objc_method_list *instance_methods;
1361 struct _objc_method_list *class_methods;
1362 struct _objc_protocol_list *protocols;
1363 uint32_t size; // <rdar://4585769>
1364 struct _objc_property_list *instance_properties;
1365 };
1366 */
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001367void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001368 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.CategoryTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001369
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001370 // FIXME: This is poor design, the OCD should have a pointer to the
1371 // category decl. Additionally, note that Category can be null for
1372 // the @implementation w/o an @interface case. Sema should just
1373 // create one for us as it does for @implementation so everyone else
1374 // can live life under a clear blue sky.
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001375 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001376 const ObjCCategoryDecl *Category =
1377 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001378 std::string ExtName(Interface->getNameAsString() + "_" +
1379 OCD->getNameAsString());
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001380
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001381 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1382 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
1383 e = OCD->instmeth_end(); i != e; ++i) {
1384 // Instance methods should always be defined.
1385 InstanceMethods.push_back(GetMethodConstant(*i));
1386 }
1387 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
1388 e = OCD->classmeth_end(); i != e; ++i) {
1389 // Class methods should always be defined.
1390 ClassMethods.push_back(GetMethodConstant(*i));
1391 }
1392
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001393 std::vector<llvm::Constant*> Values(7);
1394 Values[0] = GetClassName(OCD->getIdentifier());
1395 Values[1] = GetClassName(Interface->getIdentifier());
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001396 Values[2] =
1397 EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") +
1398 ExtName,
1399 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001400 InstanceMethods);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001401 Values[3] =
1402 EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName,
1403 "__OBJC,__cat_class_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001404 ClassMethods);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001405 if (Category) {
1406 Values[4] =
1407 EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName,
1408 Category->protocol_begin(),
1409 Category->protocol_end());
1410 } else {
1411 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1412 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001413 Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001414
1415 // If there is no category @interface then there can be no properties.
1416 if (Category) {
1417 Values[6] = EmitPropertyList(std::string("\01L_OBJC_$_PROP_LIST_") + ExtName,
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001418 OCD, Category, ObjCTypes);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001419 } else {
1420 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1421 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001422
1423 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
1424 Values);
1425
1426 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001427 CreateMetadataVar(std::string("\01L_OBJC_CATEGORY_")+ExtName, Init,
1428 "__OBJC,__category,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001429 4, true);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001430 DefinedCategories.push_back(GV);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001431}
1432
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001433// FIXME: Get from somewhere?
1434enum ClassFlags {
1435 eClassFlags_Factory = 0x00001,
1436 eClassFlags_Meta = 0x00002,
1437 // <rdr://5142207>
1438 eClassFlags_HasCXXStructors = 0x02000,
1439 eClassFlags_Hidden = 0x20000,
1440 eClassFlags_ABI2_Hidden = 0x00010,
1441 eClassFlags_ABI2_HasCXXStructors = 0x00004 // <rdr://4923634>
1442};
1443
Fariborz Jahaniancf71dd42009-04-07 20:26:30 +00001444bool CGObjCCommonMac::IsClassHidden(const ObjCInterfaceDecl *ID) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001445 if (const VisibilityAttr *attr = ID->getAttr<VisibilityAttr>()) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001446 switch (attr->getVisibility()) {
1447 default:
1448 assert(0 && "Unknown visibility");
1449 return false;
1450 case VisibilityAttr::DefaultVisibility:
1451 case VisibilityAttr::ProtectedVisibility: // FIXME: What do we do here?
1452 return false;
1453 case VisibilityAttr::HiddenVisibility:
1454 return true;
1455 }
Fariborz Jahaniancf71dd42009-04-07 20:26:30 +00001456 } else
1457 return (CGM.getLangOptions().getVisibilityMode() ==
1458 LangOptions::HiddenVisibility);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001459}
1460
1461/*
1462 struct _objc_class {
1463 Class isa;
1464 Class super_class;
1465 const char *name;
1466 long version;
1467 long info;
1468 long instance_size;
1469 struct _objc_ivar_list *ivars;
1470 struct _objc_method_list *methods;
1471 struct _objc_cache *cache;
1472 struct _objc_protocol_list *protocols;
1473 // Objective-C 1.0 extensions (<rdr://4585769>)
1474 const char *ivar_layout;
1475 struct _objc_class_ext *ext;
1476 };
1477
1478 See EmitClassExtension();
1479 */
1480void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001481 DefinedSymbols.insert(ID->getIdentifier());
1482
Chris Lattner8ec03f52008-11-24 03:54:41 +00001483 std::string ClassName = ID->getNameAsString();
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001484 // FIXME: Gross
1485 ObjCInterfaceDecl *Interface =
1486 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001487 llvm::Constant *Protocols =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001488 EmitProtocolList("\01L_OBJC_CLASS_PROTOCOLS_" + ID->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001489 Interface->protocol_begin(),
1490 Interface->protocol_end());
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001491 const llvm::Type *InterfaceTy =
Chris Lattner03d9f342009-04-01 06:23:52 +00001492 CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(Interface));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001493 unsigned Flags = eClassFlags_Factory;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001494 unsigned Size = CGM.getTargetData().getTypePaddedSize(InterfaceTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001495
1496 // FIXME: Set CXX-structors flag.
1497 if (IsClassHidden(ID->getClassInterface()))
1498 Flags |= eClassFlags_Hidden;
1499
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001500 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1501 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
1502 e = ID->instmeth_end(); i != e; ++i) {
1503 // Instance methods should always be defined.
1504 InstanceMethods.push_back(GetMethodConstant(*i));
1505 }
1506 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
1507 e = ID->classmeth_end(); i != e; ++i) {
1508 // Class methods should always be defined.
1509 ClassMethods.push_back(GetMethodConstant(*i));
1510 }
1511
1512 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
1513 e = ID->propimpl_end(); i != e; ++i) {
1514 ObjCPropertyImplDecl *PID = *i;
1515
1516 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1517 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1518
1519 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
1520 if (llvm::Constant *C = GetMethodConstant(MD))
1521 InstanceMethods.push_back(C);
1522 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
1523 if (llvm::Constant *C = GetMethodConstant(MD))
1524 InstanceMethods.push_back(C);
1525 }
1526 }
1527
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001528 std::vector<llvm::Constant*> Values(12);
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001529 Values[ 0] = EmitMetaClass(ID, Protocols, InterfaceTy, ClassMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001530 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001531 // Record a reference to the super class.
1532 LazySymbols.insert(Super->getIdentifier());
1533
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001534 Values[ 1] =
1535 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1536 ObjCTypes.ClassPtrTy);
1537 } else {
1538 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1539 }
1540 Values[ 2] = GetClassName(ID->getIdentifier());
1541 // Version is always 0.
1542 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1543 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1544 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001545 Values[ 6] = EmitIvarList(ID, false);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001546 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001547 EmitMethodList("\01L_OBJC_INSTANCE_METHODS_" + ID->getNameAsString(),
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001548 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001549 InstanceMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001550 // cache is always NULL.
1551 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1552 Values[ 9] = Protocols;
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001553 // FIXME: Set ivar_layout
Fariborz Jahanian667423a2009-03-25 22:36:49 +00001554 // Values[10] = BuildIvarLayout(ID, true);
1555 Values[10] = GetIvarLayoutName(0, ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001556 Values[11] = EmitClassExtension(ID);
1557 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1558 Values);
1559
1560 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001561 CreateMetadataVar(std::string("\01L_OBJC_CLASS_")+ClassName, Init,
1562 "__OBJC,__class,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001563 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001564 DefinedClasses.push_back(GV);
1565}
1566
1567llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
1568 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001569 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001570 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001571 unsigned Flags = eClassFlags_Meta;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001572 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001573
1574 if (IsClassHidden(ID->getClassInterface()))
1575 Flags |= eClassFlags_Hidden;
1576
1577 std::vector<llvm::Constant*> Values(12);
1578 // The isa for the metaclass is the root of the hierarchy.
1579 const ObjCInterfaceDecl *Root = ID->getClassInterface();
1580 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
1581 Root = Super;
1582 Values[ 0] =
1583 llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
1584 ObjCTypes.ClassPtrTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001585 // The super class for the metaclass is emitted as the name of the
1586 // super class. The runtime fixes this up to point to the
1587 // *metaclass* for the super class.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001588 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
1589 Values[ 1] =
1590 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1591 ObjCTypes.ClassPtrTy);
1592 } else {
1593 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1594 }
1595 Values[ 2] = GetClassName(ID->getIdentifier());
1596 // Version is always 0.
1597 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1598 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1599 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001600 Values[ 6] = EmitIvarList(ID, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001601 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001602 EmitMethodList("\01L_OBJC_CLASS_METHODS_" + ID->getNameAsString(),
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001603 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001604 Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001605 // cache is always NULL.
1606 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1607 Values[ 9] = Protocols;
1608 // ivar_layout for metaclass is always NULL.
1609 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1610 // The class extension is always unused for metaclasses.
1611 Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1612 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1613 Values);
1614
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001615 std::string Name("\01L_OBJC_METACLASS_");
Chris Lattner8ec03f52008-11-24 03:54:41 +00001616 Name += ID->getNameAsCString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001617
1618 // Check for a forward reference.
1619 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
1620 if (GV) {
1621 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1622 "Forward metaclass reference has incorrect type.");
1623 GV->setLinkage(llvm::GlobalValue::InternalLinkage);
1624 GV->setInitializer(Init);
1625 } else {
1626 GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1627 llvm::GlobalValue::InternalLinkage,
1628 Init, Name,
1629 &CGM.getModule());
1630 }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001631 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001632 GV->setAlignment(4);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001633 UsedGlobals.push_back(GV);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001634
1635 return GV;
1636}
1637
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001638llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001639 std::string Name = "\01L_OBJC_METACLASS_" + ID->getNameAsString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001640
1641 // FIXME: Should we look these up somewhere other than the
1642 // module. Its a bit silly since we only generate these while
1643 // processing an implementation, so exactly one pointer would work
1644 // if know when we entered/exitted an implementation block.
1645
1646 // Check for an existing forward reference.
Fariborz Jahanianb0d27942009-01-07 20:11:22 +00001647 // Previously, metaclass with internal linkage may have been defined.
1648 // pass 'true' as 2nd argument so it is returned.
1649 if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true)) {
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001650 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1651 "Forward metaclass reference has incorrect type.");
1652 return GV;
1653 } else {
1654 // Generate as an external reference to keep a consistent
1655 // module. This will be patched up when we emit the metaclass.
1656 return new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1657 llvm::GlobalValue::ExternalLinkage,
1658 0,
1659 Name,
1660 &CGM.getModule());
1661 }
1662}
1663
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001664/*
1665 struct objc_class_ext {
1666 uint32_t size;
1667 const char *weak_ivar_layout;
1668 struct _objc_property_list *properties;
1669 };
1670*/
1671llvm::Constant *
1672CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
1673 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001674 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassExtensionTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001675
1676 std::vector<llvm::Constant*> Values(3);
1677 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001678 // FIXME: Output weak_ivar_layout string.
Fariborz Jahanian667423a2009-03-25 22:36:49 +00001679 // Values[1] = BuildIvarLayout(ID, false);
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00001680 Values[1] = GetIvarLayoutName(0, ObjCTypes);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001681 Values[2] = EmitPropertyList("\01L_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001682 ID, ID->getClassInterface(), ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001683
1684 // Return null if no extension bits are used.
1685 if (Values[1]->isNullValue() && Values[2]->isNullValue())
1686 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1687
1688 llvm::Constant *Init =
1689 llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001690 return CreateMetadataVar("\01L_OBJC_CLASSEXT_" + ID->getNameAsString(),
1691 Init, 0, 0, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001692}
1693
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001694/// countInheritedIvars - count number of ivars in class and its super class(s)
1695///
Douglas Gregor6ab35242009-04-09 21:40:53 +00001696static int countInheritedIvars(const ObjCInterfaceDecl *OI,
1697 ASTContext &Context) {
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001698 int count = 0;
1699 if (!OI)
1700 return 0;
1701 const ObjCInterfaceDecl *SuperClass = OI->getSuperClass();
1702 if (SuperClass)
Douglas Gregor6ab35242009-04-09 21:40:53 +00001703 count += countInheritedIvars(SuperClass, Context);
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001704 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1705 E = OI->ivar_end(); I != E; ++I)
1706 ++count;
Fariborz Jahanian18191882009-03-31 18:11:23 +00001707 // look into properties.
Douglas Gregor6ab35242009-04-09 21:40:53 +00001708 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(Context),
1709 E = OI->prop_end(Context); I != E; ++I) {
Fariborz Jahanian18191882009-03-31 18:11:23 +00001710 if ((*I)->getPropertyIvarDecl())
1711 ++count;
1712 }
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001713 return count;
1714}
1715
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001716/// getInterfaceDeclForIvar - Get the interface declaration node where
1717/// this ivar is declared in.
1718/// FIXME. Ideally, this info should be in the ivar node. But currently
1719/// it is not and prevailing wisdom is that ASTs should not have more
1720/// info than is absolutely needed, even though this info reflects the
1721/// source language.
1722///
1723static const ObjCInterfaceDecl *getInterfaceDeclForIvar(
1724 const ObjCInterfaceDecl *OI,
Douglas Gregor6ab35242009-04-09 21:40:53 +00001725 const ObjCIvarDecl *IVD,
1726 ASTContext &Context) {
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001727 if (!OI)
1728 return 0;
1729 assert(isa<ObjCInterfaceDecl>(OI) && "OI is not an interface");
1730 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1731 E = OI->ivar_end(); I != E; ++I)
1732 if ((*I)->getIdentifier() == IVD->getIdentifier())
1733 return OI;
Fariborz Jahanian5a4b4532009-03-31 17:00:52 +00001734 // look into properties.
Douglas Gregor6ab35242009-04-09 21:40:53 +00001735 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(Context),
1736 E = OI->prop_end(Context); I != E; ++I) {
Fariborz Jahanian5a4b4532009-03-31 17:00:52 +00001737 ObjCPropertyDecl *PDecl = (*I);
1738 if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl())
1739 if (IV->getIdentifier() == IVD->getIdentifier())
1740 return OI;
1741 }
Douglas Gregor6ab35242009-04-09 21:40:53 +00001742 return getInterfaceDeclForIvar(OI->getSuperClass(), IVD, Context);
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001743}
1744
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001745/*
1746 struct objc_ivar {
1747 char *ivar_name;
1748 char *ivar_type;
1749 int ivar_offset;
1750 };
1751
1752 struct objc_ivar_list {
1753 int ivar_count;
1754 struct objc_ivar list[count];
1755 };
1756 */
1757llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001758 bool ForClass) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001759 std::vector<llvm::Constant*> Ivars, Ivar(3);
1760
1761 // When emitting the root class GCC emits ivar entries for the
1762 // actual class structure. It is not clear if we need to follow this
1763 // behavior; for now lets try and get away with not doing it. If so,
1764 // the cleanest solution would be to make up an ObjCInterfaceDecl
1765 // for the class.
1766 if (ForClass)
1767 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001768
1769 ObjCInterfaceDecl *OID =
1770 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00001771 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001772
1773 RecordDecl::field_iterator ifield, pfield;
1774 const RecordDecl *RD = GetFirstIvarInRecord(OID, ifield, pfield);
Douglas Gregor6ab35242009-04-09 21:40:53 +00001775 for (RecordDecl::field_iterator e = RD->field_end(CGM.getContext());
1776 ifield != e; ++ifield) {
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001777 FieldDecl *Field = *ifield;
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00001778 uint64_t Offset = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001779 if (Field->getIdentifier())
1780 Ivar[0] = GetMethodVarName(Field->getIdentifier());
1781 else
1782 Ivar[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Devang Patel7794bb82009-03-04 18:21:39 +00001783 Ivar[1] = GetMethodVarType(Field);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001784 Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy, Offset);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001785 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001786 }
1787
1788 // Return null for empty list.
1789 if (Ivars.empty())
1790 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
1791
1792 std::vector<llvm::Constant*> Values(2);
1793 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
1794 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
1795 Ivars.size());
1796 Values[1] = llvm::ConstantArray::get(AT, Ivars);
1797 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1798
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001799 llvm::GlobalVariable *GV;
1800 if (ForClass)
1801 GV = CreateMetadataVar("\01L_OBJC_CLASS_VARIABLES_" + ID->getNameAsString(),
Daniel Dunbar58a29122009-03-09 22:18:41 +00001802 Init, "__OBJC,__class_vars,regular,no_dead_strip",
1803 4, true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001804 else
1805 GV = CreateMetadataVar("\01L_OBJC_INSTANCE_VARIABLES_"
1806 + ID->getNameAsString(),
1807 Init, "__OBJC,__instance_vars,regular,no_dead_strip",
1808 0, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001809 return llvm::ConstantExpr::getBitCast(GV,
1810 ObjCTypes.IvarListPtrTy);
1811}
1812
1813/*
1814 struct objc_method {
1815 SEL method_name;
1816 char *method_types;
1817 void *method;
1818 };
1819
1820 struct objc_method_list {
1821 struct objc_method_list *obsolete;
1822 int count;
1823 struct objc_method methods_list[count];
1824 };
1825*/
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001826
1827/// GetMethodConstant - Return a struct objc_method constant for the
1828/// given method if it has been defined. The result is null if the
1829/// method has not been defined. The return value has type MethodPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001830llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001831 // FIXME: Use DenseMap::lookup
1832 llvm::Function *Fn = MethodDefinitions[MD];
1833 if (!Fn)
1834 return 0;
1835
1836 std::vector<llvm::Constant*> Method(3);
1837 Method[0] =
1838 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1839 ObjCTypes.SelectorPtrTy);
1840 Method[1] = GetMethodVarType(MD);
1841 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
1842 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
1843}
1844
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001845llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name,
1846 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001847 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001848 // Return null for empty list.
1849 if (Methods.empty())
1850 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
1851
1852 std::vector<llvm::Constant*> Values(3);
1853 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1854 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1855 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
1856 Methods.size());
1857 Values[2] = llvm::ConstantArray::get(AT, Methods);
1858 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1859
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001860 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 0, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001861 return llvm::ConstantExpr::getBitCast(GV,
1862 ObjCTypes.MethodListPtrTy);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001863}
1864
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001865llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD,
Daniel Dunbarbb36d332009-02-02 21:43:58 +00001866 const ObjCContainerDecl *CD) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001867 std::string Name;
Fariborz Jahanian679a5022009-01-10 21:06:09 +00001868 GetNameForMethod(OMD, CD, Name);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001869
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001870 CodeGenTypes &Types = CGM.getTypes();
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001871 const llvm::FunctionType *MethodTy =
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001872 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001873 llvm::Function *Method =
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001874 llvm::Function::Create(MethodTy,
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001875 llvm::GlobalValue::InternalLinkage,
1876 Name,
1877 &CGM.getModule());
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001878 MethodDefinitions.insert(std::make_pair(OMD, Method));
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001879
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001880 return Method;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001881}
1882
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00001883uint64_t CGObjCCommonMac::GetIvarBaseOffset(const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +00001884 const FieldDecl *Field) {
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00001885 if (!Field->isBitField())
1886 return Layout->getElementOffset(
1887 CGM.getTypes().getLLVMFieldNo(Field));
1888 // FIXME. Must be a better way of getting a bitfield base offset.
1889 uint64_t offset = CGM.getTypes().getLLVMFieldNo(Field);
1890 const llvm::Type *Ty = CGM.getTypes().ConvertTypeForMemRecursive(Field->getType());
1891 uint64_t size = CGM.getTypes().getTargetData().getTypePaddedSizeInBits(Ty);
1892 offset = (offset*size)/8;
1893 return offset;
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00001894}
1895
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00001896/// GetFieldBaseOffset - return's field byt offset.
1897uint64_t CGObjCCommonMac::GetFieldBaseOffset(const ObjCInterfaceDecl *OI,
1898 const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +00001899 const FieldDecl *Field) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00001900 const ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
Chris Lattnercd0ee142009-03-31 08:33:16 +00001901 const FieldDecl *FD = OI->lookupFieldDeclForIvar(CGM.getContext(), Ivar);
1902 return GetIvarBaseOffset(Layout, FD);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00001903}
1904
Daniel Dunbarfd65d372009-03-09 20:09:19 +00001905llvm::GlobalVariable *
1906CGObjCCommonMac::CreateMetadataVar(const std::string &Name,
1907 llvm::Constant *Init,
1908 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +00001909 unsigned Align,
1910 bool AddToUsed) {
Daniel Dunbarfd65d372009-03-09 20:09:19 +00001911 const llvm::Type *Ty = Init->getType();
1912 llvm::GlobalVariable *GV =
1913 new llvm::GlobalVariable(Ty, false,
1914 llvm::GlobalValue::InternalLinkage,
1915 Init,
1916 Name,
1917 &CGM.getModule());
1918 if (Section)
1919 GV->setSection(Section);
Daniel Dunbar35bd7632009-03-09 20:50:13 +00001920 if (Align)
1921 GV->setAlignment(Align);
1922 if (AddToUsed)
Daniel Dunbarfd65d372009-03-09 20:09:19 +00001923 UsedGlobals.push_back(GV);
1924 return GV;
1925}
1926
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001927llvm::Function *CGObjCMac::ModuleInitFunction() {
Daniel Dunbarf77ac862008-08-11 21:35:06 +00001928 // Abuse this interface function as a place to finalize.
1929 FinishModule();
1930
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001931 return NULL;
1932}
1933
Chris Lattner74391b42009-03-22 21:03:39 +00001934llvm::Constant *CGObjCMac::GetPropertyGetFunction() {
Daniel Dunbar49f66022008-09-24 03:38:44 +00001935 return ObjCTypes.GetPropertyFn;
1936}
1937
Chris Lattner74391b42009-03-22 21:03:39 +00001938llvm::Constant *CGObjCMac::GetPropertySetFunction() {
Daniel Dunbar49f66022008-09-24 03:38:44 +00001939 return ObjCTypes.SetPropertyFn;
1940}
1941
Chris Lattner74391b42009-03-22 21:03:39 +00001942llvm::Constant *CGObjCMac::EnumerationMutationFunction() {
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001943 return ObjCTypes.EnumerationMutationFn;
1944}
1945
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001946/*
1947
1948Objective-C setjmp-longjmp (sjlj) Exception Handling
1949--
1950
1951The basic framework for a @try-catch-finally is as follows:
1952{
1953 objc_exception_data d;
1954 id _rethrow = null;
Anders Carlsson190d00e2009-02-07 21:26:04 +00001955 bool _call_try_exit = true;
1956
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001957 objc_exception_try_enter(&d);
1958 if (!setjmp(d.jmp_buf)) {
1959 ... try body ...
1960 } else {
1961 // exception path
1962 id _caught = objc_exception_extract(&d);
1963
1964 // enter new try scope for handlers
1965 if (!setjmp(d.jmp_buf)) {
1966 ... match exception and execute catch blocks ...
1967
1968 // fell off end, rethrow.
1969 _rethrow = _caught;
Daniel Dunbar898d5082008-09-30 01:06:03 +00001970 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001971 } else {
1972 // exception in catch block
1973 _rethrow = objc_exception_extract(&d);
Anders Carlsson190d00e2009-02-07 21:26:04 +00001974 _call_try_exit = false;
1975 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001976 }
1977 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00001978 ... jump-through-finally to finally_end ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001979
1980finally:
Anders Carlsson190d00e2009-02-07 21:26:04 +00001981 if (_call_try_exit)
1982 objc_exception_try_exit(&d);
1983
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001984 ... finally block ....
Daniel Dunbar898d5082008-09-30 01:06:03 +00001985 ... dispatch to finally destination ...
1986
1987finally_rethrow:
1988 objc_exception_throw(_rethrow);
1989
1990finally_end:
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001991}
1992
1993This framework differs slightly from the one gcc uses, in that gcc
Daniel Dunbar898d5082008-09-30 01:06:03 +00001994uses _rethrow to determine if objc_exception_try_exit should be called
1995and if the object should be rethrown. This breaks in the face of
1996throwing nil and introduces unnecessary branches.
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001997
1998We specialize this framework for a few particular circumstances:
1999
2000 - If there are no catch blocks, then we avoid emitting the second
2001 exception handling context.
2002
2003 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
2004 e)) we avoid emitting the code to rethrow an uncaught exception.
2005
2006 - FIXME: If there is no @finally block we can do a few more
2007 simplifications.
2008
2009Rethrows and Jumps-Through-Finally
2010--
2011
2012Support for implicit rethrows and jumping through the finally block is
2013handled by storing the current exception-handling context in
2014ObjCEHStack.
2015
Daniel Dunbar898d5082008-09-30 01:06:03 +00002016In order to implement proper @finally semantics, we support one basic
2017mechanism for jumping through the finally block to an arbitrary
2018destination. Constructs which generate exits from a @try or @catch
2019block use this mechanism to implement the proper semantics by chaining
2020jumps, as necessary.
2021
2022This mechanism works like the one used for indirect goto: we
2023arbitrarily assign an ID to each destination and store the ID for the
2024destination in a variable prior to entering the finally block. At the
2025end of the finally block we simply create a switch to the proper
2026destination.
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002027
2028Code gen for @synchronized(expr) stmt;
2029Effectively generating code for:
2030objc_sync_enter(expr);
2031@try stmt @finally { objc_sync_exit(expr); }
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002032*/
2033
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002034void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
2035 const Stmt &S) {
2036 bool isTry = isa<ObjCAtTryStmt>(S);
Daniel Dunbar898d5082008-09-30 01:06:03 +00002037 // Create various blocks we refer to for handling @finally.
Daniel Dunbar55e87422008-11-11 02:29:29 +00002038 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002039 llvm::BasicBlock *FinallyExit = CGF.createBasicBlock("finally.exit");
Daniel Dunbar55e87422008-11-11 02:29:29 +00002040 llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
2041 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
2042 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
Daniel Dunbar1c566672009-02-24 01:43:46 +00002043
2044 // For @synchronized, call objc_sync_enter(sync.expr). The
2045 // evaluation of the expression must occur before we enter the
2046 // @synchronized. We can safely avoid a temp here because jumps into
2047 // @synchronized are illegal & this will dominate uses.
2048 llvm::Value *SyncArg = 0;
2049 if (!isTry) {
2050 SyncArg =
2051 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
2052 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00002053 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar1c566672009-02-24 01:43:46 +00002054 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00002055
2056 // Push an EH context entry, used for handling rethrows and jumps
2057 // through finally.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002058 CGF.PushCleanupBlock(FinallyBlock);
2059
Anders Carlsson273558f2009-02-07 21:37:21 +00002060 CGF.ObjCEHValueStack.push_back(0);
2061
Daniel Dunbar898d5082008-09-30 01:06:03 +00002062 // Allocate memory for the exception data and rethrow pointer.
Anders Carlsson80f25672008-09-09 17:59:25 +00002063 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
2064 "exceptiondata.ptr");
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002065 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
2066 "_rethrow");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002067 llvm::Value *CallTryExitPtr = CGF.CreateTempAlloca(llvm::Type::Int1Ty,
2068 "_call_try_exit");
2069 CGF.Builder.CreateStore(llvm::ConstantInt::getTrue(), CallTryExitPtr);
2070
Anders Carlsson80f25672008-09-09 17:59:25 +00002071 // Enter a new try block and call setjmp.
2072 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
2073 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
2074 "jmpbufarray");
2075 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
2076 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
2077 JmpBufPtr, "result");
Daniel Dunbar898d5082008-09-30 01:06:03 +00002078
Daniel Dunbar55e87422008-11-11 02:29:29 +00002079 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
2080 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002081 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002082 TryHandler, TryBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002083
2084 // Emit the @try block.
2085 CGF.EmitBlock(TryBlock);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002086 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
2087 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002088 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002089
2090 // Emit the "exception in @try" block.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002091 CGF.EmitBlock(TryHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002092
2093 // Retrieve the exception object. We may emit multiple blocks but
2094 // nothing can cross this so the value is already in SSA form.
2095 llvm::Value *Caught = CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
2096 ExceptionData,
2097 "caught");
Anders Carlsson273558f2009-02-07 21:37:21 +00002098 CGF.ObjCEHValueStack.back() = Caught;
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002099 if (!isTry)
2100 {
2101 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002102 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002103 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002104 }
2105 else if (const ObjCAtCatchStmt* CatchStmt =
2106 cast<ObjCAtTryStmt>(S).getCatchStmts())
2107 {
Daniel Dunbar55e40722008-09-27 07:03:52 +00002108 // Enter a new exception try block (in case a @catch block throws
2109 // an exception).
Anders Carlsson80f25672008-09-09 17:59:25 +00002110 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002111
Anders Carlsson80f25672008-09-09 17:59:25 +00002112 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
2113 JmpBufPtr, "result");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002114 llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw");
Anders Carlsson80f25672008-09-09 17:59:25 +00002115
Daniel Dunbar55e87422008-11-11 02:29:29 +00002116 llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch");
2117 llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler");
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002118 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002119
2120 CGF.EmitBlock(CatchBlock);
2121
Daniel Dunbar55e40722008-09-27 07:03:52 +00002122 // Handle catch list. As a special case we check if everything is
2123 // matched and avoid generating code for falling off the end if
2124 // so.
2125 bool AllMatched = false;
Anders Carlsson80f25672008-09-09 17:59:25 +00002126 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbar55e87422008-11-11 02:29:29 +00002127 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch");
Anders Carlsson80f25672008-09-09 17:59:25 +00002128
Steve Naroff7ba138a2009-03-03 19:52:17 +00002129 const ParmVarDecl *CatchParam = CatchStmt->getCatchParamDecl();
Daniel Dunbar129271a2008-09-27 07:36:24 +00002130 const PointerType *PT = 0;
2131
Anders Carlsson80f25672008-09-09 17:59:25 +00002132 // catch(...) always matches.
Daniel Dunbar55e40722008-09-27 07:03:52 +00002133 if (!CatchParam) {
2134 AllMatched = true;
2135 } else {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002136 PT = CatchParam->getType()->getAsPointerType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002137
Daniel Dunbar97f61d12008-09-27 22:21:14 +00002138 // catch(id e) always matches.
2139 // FIXME: For the time being we also match id<X>; this should
2140 // be rejected by Sema instead.
Steve Naroff389bf462009-02-12 17:52:19 +00002141 if ((PT && CGF.getContext().isObjCIdStructType(PT->getPointeeType())) ||
Steve Naroff7ba138a2009-03-03 19:52:17 +00002142 CatchParam->getType()->isObjCQualifiedIdType())
Daniel Dunbar55e40722008-09-27 07:03:52 +00002143 AllMatched = true;
Anders Carlsson80f25672008-09-09 17:59:25 +00002144 }
2145
Daniel Dunbar55e40722008-09-27 07:03:52 +00002146 if (AllMatched) {
Anders Carlssondde0a942008-09-11 09:15:33 +00002147 if (CatchParam) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002148 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002149 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002150 CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002151 }
Anders Carlsson1452f552008-09-11 08:21:54 +00002152
Anders Carlssondde0a942008-09-11 09:15:33 +00002153 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002154 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002155 break;
2156 }
2157
Daniel Dunbar129271a2008-09-27 07:36:24 +00002158 assert(PT && "Unexpected non-pointer type in @catch");
2159 QualType T = PT->getPointeeType();
Anders Carlsson4b7ff6e2008-09-11 06:35:14 +00002160 const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002161 assert(ObjCType && "Catch parameter must have Objective-C type!");
2162
2163 // Check if the @catch block matches the exception object.
2164 llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl());
2165
Anders Carlsson80f25672008-09-09 17:59:25 +00002166 llvm::Value *Match = CGF.Builder.CreateCall2(ObjCTypes.ExceptionMatchFn,
2167 Class, Caught, "match");
Anders Carlsson80f25672008-09-09 17:59:25 +00002168
Daniel Dunbar55e87422008-11-11 02:29:29 +00002169 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched");
Anders Carlsson80f25672008-09-09 17:59:25 +00002170
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002171 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002172 MatchedBlock, NextCatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002173
2174 // Emit the @catch block.
2175 CGF.EmitBlock(MatchedBlock);
Steve Naroff7ba138a2009-03-03 19:52:17 +00002176 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002177 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002178
2179 llvm::Value *Tmp =
Steve Naroff7ba138a2009-03-03 19:52:17 +00002180 CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(CatchParam->getType()),
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002181 "tmp");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002182 CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002183
2184 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002185 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002186
2187 CGF.EmitBlock(NextCatchBlock);
2188 }
2189
Daniel Dunbar55e40722008-09-27 07:03:52 +00002190 if (!AllMatched) {
2191 // None of the handlers caught the exception, so store it to be
2192 // rethrown at the end of the @finally block.
2193 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002194 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002195 }
2196
2197 // Emit the exception handler for the @catch blocks.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002198 CGF.EmitBlock(CatchHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002199 CGF.Builder.CreateStore(CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
2200 ExceptionData),
2201 RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002202 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002203 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002204 } else {
Anders Carlsson80f25672008-09-09 17:59:25 +00002205 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002206 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002207 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Anders Carlsson80f25672008-09-09 17:59:25 +00002208 }
2209
Daniel Dunbar898d5082008-09-30 01:06:03 +00002210 // Pop the exception-handling stack entry. It is important to do
2211 // this now, because the code in the @finally block is not in this
2212 // context.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002213 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
2214
Anders Carlsson273558f2009-02-07 21:37:21 +00002215 CGF.ObjCEHValueStack.pop_back();
2216
Anders Carlsson80f25672008-09-09 17:59:25 +00002217 // Emit the @finally block.
2218 CGF.EmitBlock(FinallyBlock);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002219 llvm::Value* CallTryExit = CGF.Builder.CreateLoad(CallTryExitPtr, "tmp");
2220
2221 CGF.Builder.CreateCondBr(CallTryExit, FinallyExit, FinallyNoExit);
2222
2223 CGF.EmitBlock(FinallyExit);
Anders Carlsson80f25672008-09-09 17:59:25 +00002224 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryExitFn, ExceptionData);
Daniel Dunbar129271a2008-09-27 07:36:24 +00002225
2226 CGF.EmitBlock(FinallyNoExit);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002227 if (isTry) {
2228 if (const ObjCAtFinallyStmt* FinallyStmt =
2229 cast<ObjCAtTryStmt>(S).getFinallyStmt())
2230 CGF.EmitStmt(FinallyStmt->getFinallyBody());
Daniel Dunbar1c566672009-02-24 01:43:46 +00002231 } else {
2232 // Emit objc_sync_exit(expr); as finally's sole statement for
2233 // @synchronized.
2234 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, SyncArg);
Fariborz Jahanianf2878e52008-11-21 19:21:53 +00002235 }
Anders Carlsson80f25672008-09-09 17:59:25 +00002236
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002237 // Emit the switch block
2238 if (Info.SwitchBlock)
2239 CGF.EmitBlock(Info.SwitchBlock);
2240 if (Info.EndBlock)
2241 CGF.EmitBlock(Info.EndBlock);
2242
Daniel Dunbar898d5082008-09-30 01:06:03 +00002243 CGF.EmitBlock(FinallyRethrow);
2244 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn,
2245 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002246 CGF.Builder.CreateUnreachable();
Daniel Dunbar898d5082008-09-30 01:06:03 +00002247
2248 CGF.EmitBlock(FinallyEnd);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002249}
2250
2251void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar898d5082008-09-30 01:06:03 +00002252 const ObjCAtThrowStmt &S) {
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002253 llvm::Value *ExceptionAsObject;
2254
2255 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2256 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
2257 ExceptionAsObject =
2258 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
2259 } else {
Anders Carlsson273558f2009-02-07 21:37:21 +00002260 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002261 "Unexpected rethrow outside @catch block.");
Anders Carlsson273558f2009-02-07 21:37:21 +00002262 ExceptionAsObject = CGF.ObjCEHValueStack.back();
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002263 }
2264
2265 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
Anders Carlsson80f25672008-09-09 17:59:25 +00002266 CGF.Builder.CreateUnreachable();
Daniel Dunbara448fb22008-11-11 23:11:34 +00002267
2268 // Clear the insertion point to indicate we are in unreachable code.
2269 CGF.Builder.ClearInsertionPoint();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002270}
2271
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002272/// EmitObjCWeakRead - Code gen for loading value of a __weak
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002273/// object: objc_read_weak (id *src)
2274///
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002275llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002276 llvm::Value *AddrWeakObj)
2277{
Eli Friedman8339b352009-03-07 03:57:15 +00002278 const llvm::Type* DestTy =
2279 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002280 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002281 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002282 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00002283 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002284 return read_weak;
2285}
2286
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002287/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
2288/// objc_assign_weak (id src, id *dst)
2289///
2290void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
2291 llvm::Value *src, llvm::Value *dst)
2292{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002293 const llvm::Type * SrcTy = src->getType();
2294 if (!isa<llvm::PointerType>(SrcTy)) {
2295 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2296 assert(Size <= 8 && "does not support size > 8");
2297 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2298 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002299 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2300 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002301 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2302 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002303 CGF.Builder.CreateCall2(ObjCTypes.GcAssignWeakFn,
2304 src, dst, "weakassign");
2305 return;
2306}
2307
Fariborz Jahanian58626502008-11-19 00:59:10 +00002308/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
2309/// objc_assign_global (id src, id *dst)
2310///
2311void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
2312 llvm::Value *src, llvm::Value *dst)
2313{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002314 const llvm::Type * SrcTy = src->getType();
2315 if (!isa<llvm::PointerType>(SrcTy)) {
2316 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2317 assert(Size <= 8 && "does not support size > 8");
2318 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2319 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002320 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2321 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002322 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2323 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian58626502008-11-19 00:59:10 +00002324 CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn,
2325 src, dst, "globalassign");
2326 return;
2327}
2328
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002329/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
2330/// objc_assign_ivar (id src, id *dst)
2331///
2332void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
2333 llvm::Value *src, llvm::Value *dst)
2334{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002335 const llvm::Type * SrcTy = src->getType();
2336 if (!isa<llvm::PointerType>(SrcTy)) {
2337 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2338 assert(Size <= 8 && "does not support size > 8");
2339 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2340 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002341 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2342 }
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002343 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2344 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
2345 CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn,
2346 src, dst, "assignivar");
2347 return;
2348}
2349
Fariborz Jahanian58626502008-11-19 00:59:10 +00002350/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
2351/// objc_assign_strongCast (id src, id *dst)
2352///
2353void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
2354 llvm::Value *src, llvm::Value *dst)
2355{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002356 const llvm::Type * SrcTy = src->getType();
2357 if (!isa<llvm::PointerType>(SrcTy)) {
2358 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2359 assert(Size <= 8 && "does not support size > 8");
2360 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2361 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002362 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2363 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002364 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2365 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian58626502008-11-19 00:59:10 +00002366 CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn,
2367 src, dst, "weakassign");
2368 return;
2369}
2370
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002371/// EmitObjCValueForIvar - Code Gen for ivar reference.
2372///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002373LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
2374 QualType ObjectTy,
2375 llvm::Value *BaseValue,
2376 const ObjCIvarDecl *Ivar,
2377 const FieldDecl *Field,
2378 unsigned CVRQualifiers) {
2379 if (Ivar->isBitField())
2380 return CGF.EmitLValueForBitfield(BaseValue, const_cast<FieldDecl *>(Field),
2381 CVRQualifiers);
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002382 // TODO: Add a special case for isa (index 0)
2383 unsigned Index = CGM.getTypes().getLLVMFieldNo(Field);
2384 llvm::Value *V = CGF.Builder.CreateStructGEP(BaseValue, Index, "tmp");
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002385 LValue LV = LValue::MakeAddr(V,
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00002386 Ivar->getType().getCVRQualifiers()|CVRQualifiers,
2387 CGM.getContext().getObjCGCAttrKind(Ivar->getType()));
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002388 LValue::SetObjCIvar(LV, true);
2389 return LV;
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002390}
2391
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002392llvm::Value *CGObjCMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
2393 ObjCInterfaceDecl *Interface,
2394 const ObjCIvarDecl *Ivar) {
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002395 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(Interface);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002396 FieldDecl *Field = Interface->lookupFieldDeclForIvar(CGM.getContext(), Ivar);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00002397 uint64_t Offset = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002398 return llvm::ConstantInt::get(
2399 CGM.getTypes().ConvertType(CGM.getContext().LongTy),
2400 Offset);
2401}
2402
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002403/* *** Private Interface *** */
2404
2405/// EmitImageInfo - Emit the image info marker used to encode some module
2406/// level information.
2407///
2408/// See: <rdr://4810609&4810587&4810587>
2409/// struct IMAGE_INFO {
2410/// unsigned version;
2411/// unsigned flags;
2412/// };
2413enum ImageInfoFlags {
2414 eImageInfo_FixAndContinue = (1 << 0), // FIXME: Not sure what this implies
2415 eImageInfo_GarbageCollected = (1 << 1),
2416 eImageInfo_GCOnly = (1 << 2)
2417};
2418
2419void CGObjCMac::EmitImageInfo() {
2420 unsigned version = 0; // Version is unused?
2421 unsigned flags = 0;
2422
2423 // FIXME: Fix and continue?
2424 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
2425 flags |= eImageInfo_GarbageCollected;
2426 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
2427 flags |= eImageInfo_GCOnly;
2428
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002429 // Emitted as int[2];
2430 llvm::Constant *values[2] = {
2431 llvm::ConstantInt::get(llvm::Type::Int32Ty, version),
2432 llvm::ConstantInt::get(llvm::Type::Int32Ty, flags)
2433 };
2434 llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002435
2436 const char *Section;
2437 if (ObjCABI == 1)
2438 Section = "__OBJC, __image_info,regular";
2439 else
2440 Section = "__DATA, __objc_imageinfo, regular, no_dead_strip";
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002441 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002442 CreateMetadataVar("\01L_OBJC_IMAGE_INFO",
2443 llvm::ConstantArray::get(AT, values, 2),
2444 Section,
2445 0,
2446 true);
2447 GV->setConstant(true);
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002448}
2449
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002450
2451// struct objc_module {
2452// unsigned long version;
2453// unsigned long size;
2454// const char *name;
2455// Symtab symtab;
2456// };
2457
2458// FIXME: Get from somewhere
2459static const int ModuleVersion = 7;
2460
2461void CGObjCMac::EmitModuleInfo() {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00002462 uint64_t Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ModuleTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002463
2464 std::vector<llvm::Constant*> Values(4);
2465 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
2466 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002467 // This used to be the filename, now it is unused. <rdr://4327263>
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002468 Values[2] = GetClassName(&CGM.getContext().Idents.get(""));
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002469 Values[3] = EmitModuleSymbols();
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002470 CreateMetadataVar("\01L_OBJC_MODULES",
2471 llvm::ConstantStruct::get(ObjCTypes.ModuleTy, Values),
2472 "__OBJC,__module_info,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00002473 4, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002474}
2475
2476llvm::Constant *CGObjCMac::EmitModuleSymbols() {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002477 unsigned NumClasses = DefinedClasses.size();
2478 unsigned NumCategories = DefinedCategories.size();
2479
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002480 // Return null if no symbols were defined.
2481 if (!NumClasses && !NumCategories)
2482 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
2483
2484 std::vector<llvm::Constant*> Values(5);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002485 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2486 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
2487 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
2488 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
2489
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002490 // The runtime expects exactly the list of defined classes followed
2491 // by the list of defined categories, in a single array.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002492 std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002493 for (unsigned i=0; i<NumClasses; i++)
2494 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
2495 ObjCTypes.Int8PtrTy);
2496 for (unsigned i=0; i<NumCategories; i++)
2497 Symbols[NumClasses + i] =
2498 llvm::ConstantExpr::getBitCast(DefinedCategories[i],
2499 ObjCTypes.Int8PtrTy);
2500
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002501 Values[4] =
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002502 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002503 NumClasses + NumCategories),
2504 Symbols);
2505
2506 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2507
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002508 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002509 CreateMetadataVar("\01L_OBJC_SYMBOLS", Init,
2510 "__OBJC,__symbols,regular,no_dead_strip",
2511 0, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002512 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
2513}
2514
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002515llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002516 const ObjCInterfaceDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002517 LazySymbols.insert(ID->getIdentifier());
2518
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002519 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
2520
2521 if (!Entry) {
2522 llvm::Constant *Casted =
2523 llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()),
2524 ObjCTypes.ClassPtrTy);
2525 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002526 CreateMetadataVar("\01L_OBJC_CLASS_REFERENCES_", Casted,
2527 "__OBJC,__cls_refs,literal_pointers,no_dead_strip",
2528 0, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002529 }
2530
2531 return Builder.CreateLoad(Entry, false, "tmp");
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002532}
2533
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002534llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002535 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
2536
2537 if (!Entry) {
2538 llvm::Constant *Casted =
2539 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
2540 ObjCTypes.SelectorPtrTy);
2541 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002542 CreateMetadataVar("\01L_OBJC_SELECTOR_REFERENCES_", Casted,
2543 "__OBJC,__message_refs,literal_pointers,no_dead_strip",
2544 0, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002545 }
2546
2547 return Builder.CreateLoad(Entry, false, "tmp");
2548}
2549
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00002550llvm::Constant *CGObjCCommonMac::GetClassName(IdentifierInfo *Ident) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002551 llvm::GlobalVariable *&Entry = ClassNames[Ident];
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002552
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002553 if (!Entry)
2554 Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
2555 llvm::ConstantArray::get(Ident->getName()),
2556 "__TEXT,__cstring,cstring_literals",
2557 0, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002558
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002559 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002560}
2561
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002562/// GetInterfaceDeclStructLayout - Get layout for ivars of given
2563/// interface declaration.
2564const llvm::StructLayout *CGObjCCommonMac::GetInterfaceDeclStructLayout(
2565 const ObjCInterfaceDecl *OID) const {
2566 const llvm::Type *InterfaceTy =
2567 CGM.getTypes().ConvertType(
2568 CGM.getContext().getObjCInterfaceType(
2569 const_cast<ObjCInterfaceDecl*>(OID)));
2570 const llvm::StructLayout *Layout =
2571 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceTy));
2572 return Layout;
2573}
2574
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00002575/// GetIvarLayoutName - Returns a unique constant for the given
2576/// ivar layout bitmap.
2577llvm::Constant *CGObjCCommonMac::GetIvarLayoutName(IdentifierInfo *Ident,
2578 const ObjCCommonTypesHelper &ObjCTypes) {
2579 return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2580}
2581
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002582void CGObjCCommonMac::BuildAggrIvarLayout(const ObjCInterfaceDecl *OI,
2583 const llvm::StructLayout *Layout,
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002584 const RecordDecl *RD,
Chris Lattnerf1690852009-03-31 08:48:01 +00002585 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002586 unsigned int BytePos, bool ForStrongLayout,
2587 int &Index, int &SkIndex, bool &HasUnion) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002588 bool IsUnion = (RD && RD->isUnion());
2589 uint64_t MaxUnionIvarSize = 0;
2590 uint64_t MaxSkippedUnionIvarSize = 0;
2591 FieldDecl *MaxField = 0;
2592 FieldDecl *MaxSkippedField = 0;
Chris Lattnerf1690852009-03-31 08:48:01 +00002593 unsigned base = 0;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002594 if (RecFields.empty())
2595 return;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002596 if (IsUnion)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002597 base = BytePos + GetFieldBaseOffset(OI, Layout, RecFields[0]);
Chris Lattnerf1690852009-03-31 08:48:01 +00002598 unsigned WordSizeInBits = CGM.getContext().Target.getPointerWidth(0);
2599 unsigned ByteSizeInBits = CGM.getContext().Target.getCharWidth();
2600
2601 llvm::SmallVector<FieldDecl*, 16> TmpRecFields;
2602
2603 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002604 FieldDecl *Field = RecFields[i];
2605 // Skip over unnamed or bitfields
2606 if (!Field->getIdentifier() || Field->isBitField())
2607 continue;
2608 QualType FQT = Field->getType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002609 if (FQT->isRecordType() || FQT->isUnionType()) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002610 if (FQT->isUnionType())
2611 HasUnion = true;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002612 else
2613 assert(FQT->isRecordType() &&
2614 "only union/record is supported for ivar layout bitmap");
2615
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002616 const RecordType *RT = FQT->getAsRecordType();
2617 const RecordDecl *RD = RT->getDecl();
2618 // FIXME - Find a more efficiant way of passing records down.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002619 TmpRecFields.append(RD->field_begin(CGM.getContext()),
2620 RD->field_end(CGM.getContext()));
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002621 // FIXME - Is Layout correct?
Chris Lattnerf1690852009-03-31 08:48:01 +00002622 BuildAggrIvarLayout(OI, Layout, RD, TmpRecFields,
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002623 BytePos + GetFieldBaseOffset(OI, Layout, Field),
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002624 ForStrongLayout, Index, SkIndex,
2625 HasUnion);
Chris Lattnerf1690852009-03-31 08:48:01 +00002626 TmpRecFields.clear();
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002627 continue;
2628 }
Chris Lattnerf1690852009-03-31 08:48:01 +00002629
2630 if (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002631 const ConstantArrayType *CArray =
2632 dyn_cast_or_null<ConstantArrayType>(Array);
2633 assert(CArray && "only array with know element size is supported");
2634 FQT = CArray->getElementType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002635 while (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
2636 const ConstantArrayType *CArray =
2637 dyn_cast_or_null<ConstantArrayType>(Array);
2638 FQT = CArray->getElementType();
2639 }
2640
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002641 assert(!FQT->isUnionType() &&
2642 "layout for array of unions not supported");
2643 if (FQT->isRecordType()) {
2644 uint64_t ElCount = CArray->getSize().getZExtValue();
2645 int OldIndex = Index;
2646 int OldSkIndex = SkIndex;
2647
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002648 // FIXME - Use a common routine with the above!
2649 const RecordType *RT = FQT->getAsRecordType();
2650 const RecordDecl *RD = RT->getDecl();
2651 // FIXME - Find a more efficiant way of passing records down.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002652 TmpRecFields.append(RD->field_begin(CGM.getContext()),
2653 RD->field_end(CGM.getContext()));
Chris Lattnerf1690852009-03-31 08:48:01 +00002654
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002655 BuildAggrIvarLayout(OI, Layout, RD,
Chris Lattnerf1690852009-03-31 08:48:01 +00002656 TmpRecFields,
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002657 BytePos + GetFieldBaseOffset(OI, Layout, Field),
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002658 ForStrongLayout, Index, SkIndex,
2659 HasUnion);
Chris Lattnerf1690852009-03-31 08:48:01 +00002660 TmpRecFields.clear();
2661
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002662 // Replicate layout information for each array element. Note that
2663 // one element is already done.
2664 uint64_t ElIx = 1;
2665 for (int FirstIndex = Index, FirstSkIndex = SkIndex;
2666 ElIx < ElCount; ElIx++) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002667 uint64_t Size = CGM.getContext().getTypeSize(RT)/ByteSizeInBits;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002668 for (int i = OldIndex+1; i <= FirstIndex; ++i)
2669 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002670 GC_IVAR gcivar;
2671 gcivar.ivar_bytepos = IvarsInfo[i].ivar_bytepos + Size*ElIx;
2672 gcivar.ivar_size = IvarsInfo[i].ivar_size;
2673 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002674 }
2675
Chris Lattnerf1690852009-03-31 08:48:01 +00002676 for (int i = OldSkIndex+1; i <= FirstSkIndex; ++i) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002677 GC_IVAR skivar;
2678 skivar.ivar_bytepos = SkipIvars[i].ivar_bytepos + Size*ElIx;
2679 skivar.ivar_size = SkipIvars[i].ivar_size;
2680 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002681 }
2682 }
2683 continue;
2684 }
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002685 }
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002686 // At this point, we are done with Record/Union and array there of.
2687 // For other arrays we are down to its element type.
2688 QualType::GCAttrTypes GCAttr = QualType::GCNone;
2689 do {
2690 if (FQT.isObjCGCStrong() || FQT.isObjCGCWeak()) {
2691 GCAttr = FQT.isObjCGCStrong() ? QualType::Strong : QualType::Weak;
2692 break;
2693 }
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002694 else if (CGM.getContext().isObjCObjectPointerType(FQT)) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002695 GCAttr = QualType::Strong;
2696 break;
2697 }
2698 else if (const PointerType *PT = FQT->getAsPointerType()) {
2699 FQT = PT->getPointeeType();
2700 }
2701 else {
2702 break;
2703 }
2704 } while (true);
Chris Lattnerf1690852009-03-31 08:48:01 +00002705
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002706 if ((ForStrongLayout && GCAttr == QualType::Strong)
2707 || (!ForStrongLayout && GCAttr == QualType::Weak)) {
2708 if (IsUnion)
2709 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002710 uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType())
2711 / WordSizeInBits;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002712 if (UnionIvarSize > MaxUnionIvarSize)
2713 {
2714 MaxUnionIvarSize = UnionIvarSize;
2715 MaxField = Field;
2716 }
2717 }
2718 else
2719 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002720 GC_IVAR gcivar;
2721 gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field);
2722 gcivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) /
2723 WordSizeInBits;
2724 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002725 }
2726 }
2727 else if ((ForStrongLayout &&
2728 (GCAttr == QualType::GCNone || GCAttr == QualType::Weak))
2729 || (!ForStrongLayout && GCAttr != QualType::Weak)) {
2730 if (IsUnion)
2731 {
2732 uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType());
2733 if (UnionIvarSize > MaxSkippedUnionIvarSize)
2734 {
2735 MaxSkippedUnionIvarSize = UnionIvarSize;
2736 MaxSkippedField = Field;
2737 }
2738 }
2739 else
2740 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002741 GC_IVAR skivar;
2742 skivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field);
2743 skivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) /
2744 WordSizeInBits;
2745 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002746 }
2747 }
2748 }
Chris Lattnerf1690852009-03-31 08:48:01 +00002749 if (MaxField) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002750 GC_IVAR gcivar;
2751 gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, MaxField);
2752 gcivar.ivar_size = MaxUnionIvarSize;
2753 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002754 }
Chris Lattnerf1690852009-03-31 08:48:01 +00002755
2756 if (MaxSkippedField) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002757 GC_IVAR skivar;
2758 skivar.ivar_bytepos = BytePos +
2759 GetFieldBaseOffset(OI, Layout, MaxSkippedField);
2760 skivar.ivar_size = MaxSkippedUnionIvarSize;
2761 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002762 }
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002763}
2764
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002765static int
Chris Lattnerf1690852009-03-31 08:48:01 +00002766IvarBytePosCompare(const void *a, const void *b)
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002767{
2768 unsigned int sa = ((CGObjCCommonMac::GC_IVAR *)a)->ivar_bytepos;
2769 unsigned int sb = ((CGObjCCommonMac::GC_IVAR *)b)->ivar_bytepos;
2770
2771 if (sa < sb)
2772 return -1;
2773 if (sa > sb)
2774 return 1;
2775 return 0;
2776}
2777
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002778/// BuildIvarLayout - Builds ivar layout bitmap for the class
2779/// implementation for the __strong or __weak case.
2780/// The layout map displays which words in ivar list must be skipped
2781/// and which must be scanned by GC (see below). String is built of bytes.
2782/// Each byte is divided up in two nibbles (4-bit each). Left nibble is count
2783/// of words to skip and right nibble is count of words to scan. So, each
2784/// nibble represents up to 15 workds to skip or scan. Skipping the rest is
2785/// represented by a 0x00 byte which also ends the string.
2786/// 1. when ForStrongLayout is true, following ivars are scanned:
2787/// - id, Class
2788/// - object *
2789/// - __strong anything
2790///
2791/// 2. When ForStrongLayout is false, following ivars are scanned:
2792/// - __weak anything
2793///
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002794llvm::Constant *CGObjCCommonMac::BuildIvarLayout(
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002795 const ObjCImplementationDecl *OMD,
2796 bool ForStrongLayout) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002797 int Index = -1;
2798 int SkIndex = -1;
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002799 bool hasUnion = false;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002800 int SkipScan;
2801 unsigned int WordsToScan, WordsToSkip;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002802 const llvm::Type *PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
2803 if (CGM.getLangOptions().getGCMode() == LangOptions::NonGC)
2804 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002805
Chris Lattnerf1690852009-03-31 08:48:01 +00002806 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002807 const ObjCInterfaceDecl *OI = OMD->getClassInterface();
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002808 CGM.getContext().CollectObjCIvars(OI, RecFields);
2809 if (RecFields.empty())
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002810 return llvm::Constant::getNullValue(PtrTy);
Chris Lattnerf1690852009-03-31 08:48:01 +00002811
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002812 SkipIvars.clear();
2813 IvarsInfo.clear();
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002814
2815 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OI);
Chris Lattnerf1690852009-03-31 08:48:01 +00002816 BuildAggrIvarLayout(OI, Layout, 0, RecFields, 0, ForStrongLayout,
2817 Index, SkIndex, hasUnion);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002818 if (Index == -1)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002819 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002820
2821 // Sort on byte position in case we encounterred a union nested in
2822 // the ivar list.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002823 if (hasUnion && !IvarsInfo.empty())
2824 qsort(&IvarsInfo[0], Index+1, sizeof(GC_IVAR), IvarBytePosCompare);
2825 if (hasUnion && !SkipIvars.empty())
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002826 qsort(&SkipIvars[0], Index+1, sizeof(GC_IVAR), IvarBytePosCompare);
2827
2828 // Build the string of skip/scan nibbles
2829 SkipScan = -1;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002830 SkipScanIvars.clear();
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002831 unsigned int WordSize =
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002832 CGM.getTypes().getTargetData().getTypePaddedSize(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002833 if (IvarsInfo[0].ivar_bytepos == 0) {
2834 WordsToSkip = 0;
2835 WordsToScan = IvarsInfo[0].ivar_size;
2836 }
2837 else {
2838 WordsToSkip = IvarsInfo[0].ivar_bytepos/WordSize;
2839 WordsToScan = IvarsInfo[0].ivar_size;
2840 }
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002841 for (unsigned int i=1, Last=IvarsInfo.size(); i != Last; i++)
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002842 {
2843 unsigned int TailPrevGCObjC =
2844 IvarsInfo[i-1].ivar_bytepos + IvarsInfo[i-1].ivar_size * WordSize;
2845 if (IvarsInfo[i].ivar_bytepos == TailPrevGCObjC)
2846 {
2847 // consecutive 'scanned' object pointers.
2848 WordsToScan += IvarsInfo[i].ivar_size;
2849 }
2850 else
2851 {
2852 // Skip over 'gc'able object pointer which lay over each other.
2853 if (TailPrevGCObjC > IvarsInfo[i].ivar_bytepos)
2854 continue;
2855 // Must skip over 1 or more words. We save current skip/scan values
2856 // and start a new pair.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002857 SKIP_SCAN SkScan;
2858 SkScan.skip = WordsToSkip;
2859 SkScan.scan = WordsToScan;
2860 SkipScanIvars.push_back(SkScan); ++SkipScan;
2861
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002862 // Skip the hole.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002863 SkScan.skip = (IvarsInfo[i].ivar_bytepos - TailPrevGCObjC) / WordSize;
2864 SkScan.scan = 0;
2865 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002866 WordsToSkip = 0;
2867 WordsToScan = IvarsInfo[i].ivar_size;
2868 }
2869 }
2870 if (WordsToScan > 0)
2871 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002872 SKIP_SCAN SkScan;
2873 SkScan.skip = WordsToSkip;
2874 SkScan.scan = WordsToScan;
2875 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002876 }
2877
2878 bool BytesSkipped = false;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002879 if (!SkipIvars.empty())
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002880 {
2881 int LastByteSkipped =
2882 SkipIvars[SkIndex].ivar_bytepos + SkipIvars[SkIndex].ivar_size;
2883 int LastByteScanned =
2884 IvarsInfo[Index].ivar_bytepos + IvarsInfo[Index].ivar_size * WordSize;
2885 BytesSkipped = (LastByteSkipped > LastByteScanned);
2886 // Compute number of bytes to skip at the tail end of the last ivar scanned.
2887 if (BytesSkipped)
2888 {
2889 unsigned int TotalWords = (LastByteSkipped + (WordSize -1)) / WordSize;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002890 SKIP_SCAN SkScan;
2891 SkScan.skip = TotalWords - (LastByteScanned/WordSize);
2892 SkScan.scan = 0;
2893 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002894 }
2895 }
2896 // Mini optimization of nibbles such that an 0xM0 followed by 0x0N is produced
2897 // as 0xMN.
2898 for (int i = 0; i <= SkipScan; i++)
2899 {
2900 if ((i < SkipScan) && SkipScanIvars[i].skip && SkipScanIvars[i].scan == 0
2901 && SkipScanIvars[i+1].skip == 0 && SkipScanIvars[i+1].scan) {
2902 // 0xM0 followed by 0x0N detected.
2903 SkipScanIvars[i].scan = SkipScanIvars[i+1].scan;
2904 for (int j = i+1; j < SkipScan; j++)
2905 SkipScanIvars[j] = SkipScanIvars[j+1];
2906 --SkipScan;
2907 }
2908 }
2909
2910 // Generate the string.
2911 std::string BitMap;
2912 for (int i = 0; i <= SkipScan; i++)
2913 {
2914 unsigned char byte;
2915 unsigned int skip_small = SkipScanIvars[i].skip % 0xf;
2916 unsigned int scan_small = SkipScanIvars[i].scan % 0xf;
2917 unsigned int skip_big = SkipScanIvars[i].skip / 0xf;
2918 unsigned int scan_big = SkipScanIvars[i].scan / 0xf;
2919
2920 if (skip_small > 0 || skip_big > 0)
2921 BytesSkipped = true;
2922 // first skip big.
2923 for (unsigned int ix = 0; ix < skip_big; ix++)
2924 BitMap += (unsigned char)(0xf0);
2925
2926 // next (skip small, scan)
2927 if (skip_small)
2928 {
2929 byte = skip_small << 4;
2930 if (scan_big > 0)
2931 {
2932 byte |= 0xf;
2933 --scan_big;
2934 }
2935 else if (scan_small)
2936 {
2937 byte |= scan_small;
2938 scan_small = 0;
2939 }
2940 BitMap += byte;
2941 }
2942 // next scan big
2943 for (unsigned int ix = 0; ix < scan_big; ix++)
2944 BitMap += (unsigned char)(0x0f);
2945 // last scan small
2946 if (scan_small)
2947 {
2948 byte = scan_small;
2949 BitMap += byte;
2950 }
2951 }
2952 // null terminate string.
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002953 unsigned char zero = 0;
2954 BitMap += zero;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002955 // if ivar_layout bitmap is all 1 bits (nothing skipped) then use NULL as
2956 // final layout.
2957 if (ForStrongLayout && !BytesSkipped)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002958 return llvm::Constant::getNullValue(PtrTy);
2959 llvm::GlobalVariable * Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
2960 llvm::ConstantArray::get(BitMap.c_str()),
2961 "__TEXT,__cstring,cstring_literals",
2962 0, true);
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002963 // FIXME. Need a commomand-line option for this eventually.
2964 if (ForStrongLayout)
2965 printf("\nstrong ivar layout: ");
2966 else
2967 printf("\nweak ivar layout: ");
2968 const unsigned char *s = (unsigned char*)BitMap.c_str();
2969 for (unsigned i = 0; i < BitMap.size(); i++)
Fariborz Jahaniandbf15cb2009-03-26 19:10:36 +00002970 if (!(s[i] & 0xf0))
2971 printf("0x0%x%s", s[i], s[i] != 0 ? ", " : "");
2972 else
2973 printf("0x%x%s", s[i], s[i] != 0 ? ", " : "");
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002974 printf("\n");
2975
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002976 return getConstantGEP(Entry, 0, 0);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002977}
2978
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002979llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002980 llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
2981
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002982 // FIXME: Avoid std::string copying.
2983 if (!Entry)
2984 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_NAME_",
2985 llvm::ConstantArray::get(Sel.getAsString()),
2986 "__TEXT,__cstring,cstring_literals",
2987 0, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002988
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002989 return getConstantGEP(Entry, 0, 0);
2990}
2991
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002992// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002993llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002994 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
2995}
2996
2997// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002998llvm::Constant *CGObjCCommonMac::GetMethodVarName(const std::string &Name) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002999 return GetMethodVarName(&CGM.getContext().Idents.get(Name));
3000}
3001
Devang Patel7794bb82009-03-04 18:21:39 +00003002llvm::Constant *CGObjCCommonMac::GetMethodVarType(FieldDecl *Field) {
3003 std::string TypeStr;
3004 CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
3005
3006 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003007
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003008 if (!Entry)
3009 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3010 llvm::ConstantArray::get(TypeStr),
3011 "__TEXT,__cstring,cstring_literals",
3012 0, true);
3013
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003014 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003015}
3016
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003017llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003018 std::string TypeStr;
Daniel Dunbarc45ef602008-08-26 21:51:14 +00003019 CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D),
3020 TypeStr);
Devang Patel7794bb82009-03-04 18:21:39 +00003021
3022 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
3023
3024 if (!Entry) {
3025 llvm::Constant *C = llvm::ConstantArray::get(TypeStr);
3026 Entry =
3027 new llvm::GlobalVariable(C->getType(), false,
3028 llvm::GlobalValue::InternalLinkage,
3029 C, "\01L_OBJC_METH_VAR_TYPE_",
3030 &CGM.getModule());
3031 Entry->setSection("__TEXT,__cstring,cstring_literals");
3032 UsedGlobals.push_back(Entry);
3033 }
3034
3035 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003036}
3037
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003038// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003039llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003040 llvm::GlobalVariable *&Entry = PropertyNames[Ident];
3041
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003042 if (!Entry)
3043 Entry = CreateMetadataVar("\01L_OBJC_PROP_NAME_ATTR_",
3044 llvm::ConstantArray::get(Ident->getName()),
3045 "__TEXT,__cstring,cstring_literals",
3046 0, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003047
3048 return getConstantGEP(Entry, 0, 0);
3049}
3050
3051// FIXME: Merge into a single cstring creation function.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003052// FIXME: This Decl should be more precise.
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003053llvm::Constant *
3054 CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
3055 const Decl *Container) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003056 std::string TypeStr;
3057 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003058 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
3059}
3060
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003061void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D,
3062 const ObjCContainerDecl *CD,
3063 std::string &NameOut) {
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00003064 NameOut = '\01';
3065 NameOut += (D->isInstanceMethod() ? '-' : '+');
Chris Lattner077bf5e2008-11-24 03:33:13 +00003066 NameOut += '[';
Fariborz Jahanian679a5022009-01-10 21:06:09 +00003067 assert (CD && "Missing container decl in GetNameForMethod");
3068 NameOut += CD->getNameAsString();
Fariborz Jahanian52847332009-01-26 23:49:05 +00003069 // FIXME. For a method in a category, (CAT_NAME) is inserted here.
3070 // Right now! there is not enough info. to do this.
Chris Lattner077bf5e2008-11-24 03:33:13 +00003071 NameOut += ' ';
3072 NameOut += D->getSelector().getAsString();
3073 NameOut += ']';
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00003074}
3075
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00003076/// GetFirstIvarInRecord - This routine returns the record for the
3077/// implementation of the fiven class OID. It also returns field
3078/// corresponding to the first ivar in the class in FIV. It also
3079/// returns the one before the first ivar.
3080///
3081const RecordDecl *CGObjCCommonMac::GetFirstIvarInRecord(
3082 const ObjCInterfaceDecl *OID,
3083 RecordDecl::field_iterator &FIV,
3084 RecordDecl::field_iterator &PIV) {
Douglas Gregor6ab35242009-04-09 21:40:53 +00003085 int countSuperClassIvars = countInheritedIvars(OID->getSuperClass(),
3086 CGM.getContext());
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00003087 const RecordDecl *RD = CGM.getContext().addRecordToClass(OID);
Douglas Gregor6ab35242009-04-09 21:40:53 +00003088 RecordDecl::field_iterator ifield = RD->field_begin(CGM.getContext());
3089 RecordDecl::field_iterator pfield = RD->field_end(CGM.getContext());
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00003090 while (countSuperClassIvars-- > 0) {
3091 pfield = ifield;
3092 ++ifield;
3093 }
3094 FIV = ifield;
3095 PIV = pfield;
3096 return RD;
3097}
3098
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003099void CGObjCMac::FinishModule() {
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003100 EmitModuleInfo();
3101
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003102 // Emit the dummy bodies for any protocols which were referenced but
3103 // never defined.
3104 for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
3105 i = Protocols.begin(), e = Protocols.end(); i != e; ++i) {
3106 if (i->second->hasInitializer())
3107 continue;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003108
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003109 std::vector<llvm::Constant*> Values(5);
3110 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
3111 Values[1] = GetClassName(i->first);
3112 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
3113 Values[3] = Values[4] =
3114 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
3115 i->second->setLinkage(llvm::GlobalValue::InternalLinkage);
3116 i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
3117 Values));
3118 }
3119
3120 std::vector<llvm::Constant*> Used;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003121 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003122 e = UsedGlobals.end(); i != e; ++i) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003123 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003124 }
3125
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003126 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003127 llvm::GlobalValue *GV =
3128 new llvm::GlobalVariable(AT, false,
3129 llvm::GlobalValue::AppendingLinkage,
3130 llvm::ConstantArray::get(AT, Used),
3131 "llvm.used",
3132 &CGM.getModule());
3133
3134 GV->setSection("llvm.metadata");
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003135
3136 // Add assembler directives to add lazy undefined symbol references
3137 // for classes which are referenced but not defined. This is
3138 // important for correct linker interaction.
3139
3140 // FIXME: Uh, this isn't particularly portable.
3141 std::stringstream s;
Anders Carlsson565c99f2008-12-10 02:21:04 +00003142
3143 if (!CGM.getModule().getModuleInlineAsm().empty())
3144 s << "\n";
3145
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003146 for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(),
3147 e = LazySymbols.end(); i != e; ++i) {
3148 s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n";
3149 }
3150 for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(),
3151 e = DefinedSymbols.end(); i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003152 s << "\t.objc_class_name_" << (*i)->getName() << "=0\n"
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003153 << "\t.globl .objc_class_name_" << (*i)->getName() << "\n";
3154 }
Anders Carlsson565c99f2008-12-10 02:21:04 +00003155
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003156 CGM.getModule().appendModuleInlineAsm(s.str());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003157}
3158
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003159CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003160 : CGObjCCommonMac(cgm),
3161 ObjCTypes(cgm)
3162{
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003163 ObjCEmptyCacheVar = ObjCEmptyVtableVar = NULL;
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003164 ObjCABI = 2;
3165}
3166
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003167/* *** */
3168
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003169ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm)
3170: CGM(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003171{
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003172 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3173 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003174
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003175 ShortTy = Types.ConvertType(Ctx.ShortTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003176 IntTy = Types.ConvertType(Ctx.IntTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003177 LongTy = Types.ConvertType(Ctx.LongTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00003178 LongLongTy = Types.ConvertType(Ctx.LongLongTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003179 Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3180
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003181 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00003182 PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003183 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003184
3185 // FIXME: It would be nice to unify this with the opaque type, so
3186 // that the IR comes out a bit cleaner.
3187 const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
3188 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003189
3190 // I'm not sure I like this. The implicit coordination is a bit
3191 // gross. We should solve this in a reasonable fashion because this
3192 // is a pretty common task (match some runtime data structure with
3193 // an LLVM data structure).
3194
3195 // FIXME: This is leaked.
3196 // FIXME: Merge with rewriter code?
3197
3198 // struct _objc_super {
3199 // id self;
3200 // Class cls;
3201 // }
3202 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3203 SourceLocation(),
3204 &Ctx.Idents.get("_objc_super"));
Douglas Gregor6ab35242009-04-09 21:40:53 +00003205 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3206 Ctx.getObjCIdType(), 0, false));
3207 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3208 Ctx.getObjCClassType(), 0, false));
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003209 RD->completeDefinition(Ctx);
3210
3211 SuperCTy = Ctx.getTagDeclType(RD);
3212 SuperPtrCTy = Ctx.getPointerType(SuperCTy);
3213
3214 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003215 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
3216
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003217 // struct _prop_t {
3218 // char *name;
3219 // char *attributes;
3220 // }
3221 PropertyTy = llvm::StructType::get(Int8PtrTy,
3222 Int8PtrTy,
3223 NULL);
3224 CGM.getModule().addTypeName("struct._prop_t",
3225 PropertyTy);
3226
3227 // struct _prop_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003228 // uint32_t entsize; // sizeof(struct _prop_t)
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003229 // uint32_t count_of_properties;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003230 // struct _prop_t prop_list[count_of_properties];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003231 // }
3232 PropertyListTy = llvm::StructType::get(IntTy,
3233 IntTy,
3234 llvm::ArrayType::get(PropertyTy, 0),
3235 NULL);
3236 CGM.getModule().addTypeName("struct._prop_list_t",
3237 PropertyListTy);
3238 // struct _prop_list_t *
3239 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
3240
3241 // struct _objc_method {
3242 // SEL _cmd;
3243 // char *method_type;
3244 // char *_imp;
3245 // }
3246 MethodTy = llvm::StructType::get(SelectorPtrTy,
3247 Int8PtrTy,
3248 Int8PtrTy,
3249 NULL);
3250 CGM.getModule().addTypeName("struct._objc_method", MethodTy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003251
3252 // struct _objc_cache *
3253 CacheTy = llvm::OpaqueType::get();
3254 CGM.getModule().addTypeName("struct._objc_cache", CacheTy);
3255 CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003256
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003257 // Property manipulation functions.
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003258
3259 QualType IdType = Ctx.getObjCIdType();
3260 QualType SelType = Ctx.getObjCSelType();
3261 llvm::SmallVector<QualType,16> Params;
3262 const llvm::FunctionType *FTy;
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003263
3264 // id objc_getProperty (id, SEL, ptrdiff_t, bool)
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003265 Params.push_back(IdType);
3266 Params.push_back(SelType);
3267 Params.push_back(Ctx.LongTy);
3268 Params.push_back(Ctx.BoolTy);
3269 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params),
3270 false);
3271 GetPropertyFn = CGM.CreateRuntimeFunction(FTy, "objc_getProperty");
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003272
3273 // void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool)
3274 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003275 Params.push_back(IdType);
3276 Params.push_back(SelType);
3277 Params.push_back(Ctx.LongTy);
3278 Params.push_back(IdType);
3279 Params.push_back(Ctx.BoolTy);
3280 Params.push_back(Ctx.BoolTy);
3281 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
3282 SetPropertyFn = CGM.CreateRuntimeFunction(FTy, "objc_setProperty");
3283
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003284 // Enumeration mutation.
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003285
3286 // void objc_enumerationMutation (id)
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003287 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003288 Params.push_back(IdType);
3289 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
3290 EnumerationMutationFn = CGM.CreateRuntimeFunction(FTy,
3291 "objc_enumerationMutation");
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003292
3293 // gc's API
3294 // id objc_read_weak (id *)
3295 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003296 Params.push_back(Ctx.getPointerType(IdType));
3297 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
3298 GcReadWeakFn = CGM.CreateRuntimeFunction(FTy, "objc_read_weak");
3299
3300 // id objc_assign_weak (id, id *)
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003301 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003302 Params.push_back(IdType);
3303 Params.push_back(Ctx.getPointerType(IdType));
3304
3305 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
3306 GcAssignWeakFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_weak");
3307 GcAssignGlobalFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_global");
3308 GcAssignIvarFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_ivar");
3309 GcAssignStrongCastFn =
3310 CGM.CreateRuntimeFunction(FTy, "objc_assign_strongCast");
Anders Carlssonf57c5b22009-02-16 22:59:18 +00003311
3312 // void objc_exception_throw(id)
3313 Params.clear();
3314 Params.push_back(IdType);
3315
3316 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00003317 ExceptionThrowFn =
3318 CGM.CreateRuntimeFunction(FTy, "objc_exception_throw");
Daniel Dunbar1c566672009-02-24 01:43:46 +00003319
3320 // synchronized APIs
Daniel Dunbar1c566672009-02-24 01:43:46 +00003321 // void objc_sync_exit (id)
3322 Params.clear();
3323 Params.push_back(IdType);
3324
3325 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
Daniel Dunbar1c566672009-02-24 01:43:46 +00003326 SyncExitFn = CGM.CreateRuntimeFunction(FTy, "objc_sync_exit");
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003327}
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003328
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003329ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
3330 : ObjCCommonTypesHelper(cgm)
3331{
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003332 // struct _objc_method_description {
3333 // SEL name;
3334 // char *types;
3335 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003336 MethodDescriptionTy =
3337 llvm::StructType::get(SelectorPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003338 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003339 NULL);
3340 CGM.getModule().addTypeName("struct._objc_method_description",
3341 MethodDescriptionTy);
3342
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003343 // struct _objc_method_description_list {
3344 // int count;
3345 // struct _objc_method_description[1];
3346 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003347 MethodDescriptionListTy =
3348 llvm::StructType::get(IntTy,
3349 llvm::ArrayType::get(MethodDescriptionTy, 0),
3350 NULL);
3351 CGM.getModule().addTypeName("struct._objc_method_description_list",
3352 MethodDescriptionListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003353
3354 // struct _objc_method_description_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003355 MethodDescriptionListPtrTy =
3356 llvm::PointerType::getUnqual(MethodDescriptionListTy);
3357
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003358 // Protocol description structures
3359
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003360 // struct _objc_protocol_extension {
3361 // uint32_t size; // sizeof(struct _objc_protocol_extension)
3362 // struct _objc_method_description_list *optional_instance_methods;
3363 // struct _objc_method_description_list *optional_class_methods;
3364 // struct _objc_property_list *instance_properties;
3365 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003366 ProtocolExtensionTy =
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003367 llvm::StructType::get(IntTy,
3368 MethodDescriptionListPtrTy,
3369 MethodDescriptionListPtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003370 PropertyListPtrTy,
3371 NULL);
3372 CGM.getModule().addTypeName("struct._objc_protocol_extension",
3373 ProtocolExtensionTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003374
3375 // struct _objc_protocol_extension *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003376 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
3377
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003378 // Handle recursive construction of Protocol and ProtocolList types
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003379
3380 llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get();
3381 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3382
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003383 const llvm::Type *T =
3384 llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder),
3385 LongTy,
3386 llvm::ArrayType::get(ProtocolTyHolder, 0),
3387 NULL);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003388 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T);
3389
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003390 // struct _objc_protocol {
3391 // struct _objc_protocol_extension *isa;
3392 // char *protocol_name;
3393 // struct _objc_protocol **_objc_protocol_list;
3394 // struct _objc_method_description_list *instance_methods;
3395 // struct _objc_method_description_list *class_methods;
3396 // }
3397 T = llvm::StructType::get(ProtocolExtensionPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003398 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003399 llvm::PointerType::getUnqual(ProtocolListTyHolder),
3400 MethodDescriptionListPtrTy,
3401 MethodDescriptionListPtrTy,
3402 NULL);
3403 cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T);
3404
3405 ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get());
3406 CGM.getModule().addTypeName("struct._objc_protocol_list",
3407 ProtocolListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003408 // struct _objc_protocol_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003409 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
3410
3411 ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get());
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003412 CGM.getModule().addTypeName("struct._objc_protocol", ProtocolTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003413 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003414
3415 // Class description structures
3416
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003417 // struct _objc_ivar {
3418 // char *ivar_name;
3419 // char *ivar_type;
3420 // int ivar_offset;
3421 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003422 IvarTy = llvm::StructType::get(Int8PtrTy,
3423 Int8PtrTy,
3424 IntTy,
3425 NULL);
3426 CGM.getModule().addTypeName("struct._objc_ivar", IvarTy);
3427
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003428 // struct _objc_ivar_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003429 IvarListTy = llvm::OpaqueType::get();
3430 CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy);
3431 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
3432
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003433 // struct _objc_method_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003434 MethodListTy = llvm::OpaqueType::get();
3435 CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy);
3436 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
3437
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003438 // struct _objc_class_extension *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003439 ClassExtensionTy =
3440 llvm::StructType::get(IntTy,
3441 Int8PtrTy,
3442 PropertyListPtrTy,
3443 NULL);
3444 CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy);
3445 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
3446
3447 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3448
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003449 // struct _objc_class {
3450 // Class isa;
3451 // Class super_class;
3452 // char *name;
3453 // long version;
3454 // long info;
3455 // long instance_size;
3456 // struct _objc_ivar_list *ivars;
3457 // struct _objc_method_list *methods;
3458 // struct _objc_cache *cache;
3459 // struct _objc_protocol_list *protocols;
3460 // char *ivar_layout;
3461 // struct _objc_class_ext *ext;
3462 // };
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003463 T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3464 llvm::PointerType::getUnqual(ClassTyHolder),
3465 Int8PtrTy,
3466 LongTy,
3467 LongTy,
3468 LongTy,
3469 IvarListPtrTy,
3470 MethodListPtrTy,
3471 CachePtrTy,
3472 ProtocolListPtrTy,
3473 Int8PtrTy,
3474 ClassExtensionPtrTy,
3475 NULL);
3476 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T);
3477
3478 ClassTy = cast<llvm::StructType>(ClassTyHolder.get());
3479 CGM.getModule().addTypeName("struct._objc_class", ClassTy);
3480 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
3481
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003482 // struct _objc_category {
3483 // char *category_name;
3484 // char *class_name;
3485 // struct _objc_method_list *instance_method;
3486 // struct _objc_method_list *class_method;
3487 // uint32_t size; // sizeof(struct _objc_category)
3488 // struct _objc_property_list *instance_properties;// category's @property
3489 // }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003490 CategoryTy = llvm::StructType::get(Int8PtrTy,
3491 Int8PtrTy,
3492 MethodListPtrTy,
3493 MethodListPtrTy,
3494 ProtocolListPtrTy,
3495 IntTy,
3496 PropertyListPtrTy,
3497 NULL);
3498 CGM.getModule().addTypeName("struct._objc_category", CategoryTy);
3499
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003500 // Global metadata structures
3501
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003502 // struct _objc_symtab {
3503 // long sel_ref_cnt;
3504 // SEL *refs;
3505 // short cls_def_cnt;
3506 // short cat_def_cnt;
3507 // char *defs[cls_def_cnt + cat_def_cnt];
3508 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003509 SymtabTy = llvm::StructType::get(LongTy,
3510 SelectorPtrTy,
3511 ShortTy,
3512 ShortTy,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003513 llvm::ArrayType::get(Int8PtrTy, 0),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003514 NULL);
3515 CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy);
3516 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
3517
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003518 // struct _objc_module {
3519 // long version;
3520 // long size; // sizeof(struct _objc_module)
3521 // char *name;
3522 // struct _objc_symtab* symtab;
3523 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003524 ModuleTy =
3525 llvm::StructType::get(LongTy,
3526 LongTy,
3527 Int8PtrTy,
3528 SymtabPtrTy,
3529 NULL);
3530 CGM.getModule().addTypeName("struct._objc_module", ModuleTy);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003531
Daniel Dunbar49f66022008-09-24 03:38:44 +00003532 // Message send functions.
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003533
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003534 // id objc_msgSend (id, SEL, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003535 std::vector<const llvm::Type*> Params;
3536 Params.push_back(ObjectPtrTy);
3537 Params.push_back(SelectorPtrTy);
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003538 MessageSendFn =
3539 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3540 Params,
3541 true),
3542 "objc_msgSend");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003543
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003544 // id objc_msgSend_stret (id, SEL, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003545 Params.clear();
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003546 Params.push_back(ObjectPtrTy);
3547 Params.push_back(SelectorPtrTy);
3548 MessageSendStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003549 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3550 Params,
3551 true),
3552 "objc_msgSend_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00003553
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003554 //
Daniel Dunbar5669e572008-10-17 03:24:53 +00003555 Params.clear();
3556 Params.push_back(ObjectPtrTy);
3557 Params.push_back(SelectorPtrTy);
3558 // FIXME: This should be long double on x86_64?
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003559 // [double | long double] objc_msgSend_fpret(id self, SEL op, ...)
Daniel Dunbar5669e572008-10-17 03:24:53 +00003560 MessageSendFpretFn =
3561 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::DoubleTy,
3562 Params,
3563 true),
3564 "objc_msgSend_fpret");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003565
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003566 // id objc_msgSendSuper(struct objc_super *super, SEL op, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003567 Params.clear();
3568 Params.push_back(SuperPtrTy);
3569 Params.push_back(SelectorPtrTy);
3570 MessageSendSuperFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003571 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3572 Params,
3573 true),
3574 "objc_msgSendSuper");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003575
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003576 // void objc_msgSendSuper_stret(void * stretAddr, struct objc_super *super,
3577 // SEL op, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003578 Params.clear();
3579 Params.push_back(Int8PtrTy);
3580 Params.push_back(SuperPtrTy);
3581 Params.push_back(SelectorPtrTy);
3582 MessageSendSuperStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003583 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3584 Params,
3585 true),
3586 "objc_msgSendSuper_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00003587
3588 // There is no objc_msgSendSuper_fpret? How can that work?
3589 MessageSendSuperFpretFn = MessageSendSuperFn;
Anders Carlsson2abd89c2008-08-31 04:05:03 +00003590
Anders Carlsson124526b2008-09-09 10:10:21 +00003591 // FIXME: This is the size of the setjmp buffer and should be
3592 // target specific. 18 is what's used on 32-bit X86.
3593 uint64_t SetJmpBufferSize = 18;
3594
3595 // Exceptions
3596 const llvm::Type *StackPtrTy =
Daniel Dunbar10004912008-09-27 06:32:25 +00003597 llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4);
Anders Carlsson124526b2008-09-09 10:10:21 +00003598
3599 ExceptionDataTy =
3600 llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty,
3601 SetJmpBufferSize),
3602 StackPtrTy, NULL);
3603 CGM.getModule().addTypeName("struct._objc_exception_data",
3604 ExceptionDataTy);
3605
3606 Params.clear();
Anders Carlsson124526b2008-09-09 10:10:21 +00003607 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
3608 ExceptionTryEnterFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003609 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3610 Params,
3611 false),
3612 "objc_exception_try_enter");
Anders Carlsson124526b2008-09-09 10:10:21 +00003613 ExceptionTryExitFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003614 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3615 Params,
3616 false),
3617 "objc_exception_try_exit");
Anders Carlsson124526b2008-09-09 10:10:21 +00003618 ExceptionExtractFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003619 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3620 Params,
3621 false),
3622 "objc_exception_extract");
Anders Carlsson124526b2008-09-09 10:10:21 +00003623
3624 Params.clear();
3625 Params.push_back(ClassPtrTy);
3626 Params.push_back(ObjectPtrTy);
3627 ExceptionMatchFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003628 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
3629 Params,
3630 false),
3631 "objc_exception_match");
Chris Lattner10cac6f2008-11-15 21:26:17 +00003632
Anders Carlsson124526b2008-09-09 10:10:21 +00003633 Params.clear();
3634 Params.push_back(llvm::PointerType::getUnqual(llvm::Type::Int32Ty));
3635 SetJmpFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003636 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
3637 Params,
3638 false),
3639 "_setjmp");
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00003640
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003641}
3642
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003643ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003644: ObjCCommonTypesHelper(cgm)
3645{
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003646 // struct _method_list_t {
3647 // uint32_t entsize; // sizeof(struct _objc_method)
3648 // uint32_t method_count;
3649 // struct _objc_method method_list[method_count];
3650 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003651 MethodListnfABITy = llvm::StructType::get(IntTy,
3652 IntTy,
3653 llvm::ArrayType::get(MethodTy, 0),
3654 NULL);
3655 CGM.getModule().addTypeName("struct.__method_list_t",
3656 MethodListnfABITy);
3657 // struct method_list_t *
3658 MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003659
3660 // struct _protocol_t {
3661 // id isa; // NULL
3662 // const char * const protocol_name;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003663 // const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003664 // const struct method_list_t * const instance_methods;
3665 // const struct method_list_t * const class_methods;
3666 // const struct method_list_t *optionalInstanceMethods;
3667 // const struct method_list_t *optionalClassMethods;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003668 // const struct _prop_list_t * properties;
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003669 // const uint32_t size; // sizeof(struct _protocol_t)
3670 // const uint32_t flags; // = 0
3671 // }
3672
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003673 // Holder for struct _protocol_list_t *
3674 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3675
3676 ProtocolnfABITy = llvm::StructType::get(ObjectPtrTy,
3677 Int8PtrTy,
3678 llvm::PointerType::getUnqual(
3679 ProtocolListTyHolder),
3680 MethodListnfABIPtrTy,
3681 MethodListnfABIPtrTy,
3682 MethodListnfABIPtrTy,
3683 MethodListnfABIPtrTy,
3684 PropertyListPtrTy,
3685 IntTy,
3686 IntTy,
3687 NULL);
3688 CGM.getModule().addTypeName("struct._protocol_t",
3689 ProtocolnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003690
3691 // struct _protocol_t*
3692 ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003693
Fariborz Jahanianda320092009-01-29 19:24:30 +00003694 // struct _protocol_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003695 // long protocol_count; // Note, this is 32/64 bit
Daniel Dunbar948e2582009-02-15 07:36:20 +00003696 // struct _protocol_t *[protocol_count];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003697 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003698 ProtocolListnfABITy = llvm::StructType::get(LongTy,
3699 llvm::ArrayType::get(
Daniel Dunbar948e2582009-02-15 07:36:20 +00003700 ProtocolnfABIPtrTy, 0),
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003701 NULL);
3702 CGM.getModule().addTypeName("struct._objc_protocol_list",
3703 ProtocolListnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003704 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(
3705 ProtocolListnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003706
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003707 // struct _objc_protocol_list*
3708 ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003709
3710 // struct _ivar_t {
3711 // unsigned long int *offset; // pointer to ivar offset location
3712 // char *name;
3713 // char *type;
3714 // uint32_t alignment;
3715 // uint32_t size;
3716 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003717 IvarnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(LongTy),
3718 Int8PtrTy,
3719 Int8PtrTy,
3720 IntTy,
3721 IntTy,
3722 NULL);
3723 CGM.getModule().addTypeName("struct._ivar_t", IvarnfABITy);
3724
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003725 // struct _ivar_list_t {
3726 // uint32 entsize; // sizeof(struct _ivar_t)
3727 // uint32 count;
3728 // struct _iver_t list[count];
3729 // }
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003730 IvarListnfABITy = llvm::StructType::get(IntTy,
3731 IntTy,
3732 llvm::ArrayType::get(
3733 IvarnfABITy, 0),
3734 NULL);
3735 CGM.getModule().addTypeName("struct._ivar_list_t", IvarListnfABITy);
3736
3737 IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003738
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003739 // struct _class_ro_t {
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003740 // uint32_t const flags;
3741 // uint32_t const instanceStart;
3742 // uint32_t const instanceSize;
3743 // uint32_t const reserved; // only when building for 64bit targets
3744 // const uint8_t * const ivarLayout;
3745 // const char *const name;
3746 // const struct _method_list_t * const baseMethods;
3747 // const struct _objc_protocol_list *const baseProtocols;
3748 // const struct _ivar_list_t *const ivars;
3749 // const uint8_t * const weakIvarLayout;
3750 // const struct _prop_list_t * const properties;
3751 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003752
3753 // FIXME. Add 'reserved' field in 64bit abi mode!
3754 ClassRonfABITy = llvm::StructType::get(IntTy,
3755 IntTy,
3756 IntTy,
3757 Int8PtrTy,
3758 Int8PtrTy,
3759 MethodListnfABIPtrTy,
3760 ProtocolListnfABIPtrTy,
3761 IvarListnfABIPtrTy,
3762 Int8PtrTy,
3763 PropertyListPtrTy,
3764 NULL);
3765 CGM.getModule().addTypeName("struct._class_ro_t",
3766 ClassRonfABITy);
3767
3768 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
3769 std::vector<const llvm::Type*> Params;
3770 Params.push_back(ObjectPtrTy);
3771 Params.push_back(SelectorPtrTy);
3772 ImpnfABITy = llvm::PointerType::getUnqual(
3773 llvm::FunctionType::get(ObjectPtrTy, Params, false));
3774
3775 // struct _class_t {
3776 // struct _class_t *isa;
3777 // struct _class_t * const superclass;
3778 // void *cache;
3779 // IMP *vtable;
3780 // struct class_ro_t *ro;
3781 // }
3782
3783 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3784 ClassnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3785 llvm::PointerType::getUnqual(ClassTyHolder),
3786 CachePtrTy,
3787 llvm::PointerType::getUnqual(ImpnfABITy),
3788 llvm::PointerType::getUnqual(
3789 ClassRonfABITy),
3790 NULL);
3791 CGM.getModule().addTypeName("struct._class_t", ClassnfABITy);
3792
3793 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(
3794 ClassnfABITy);
3795
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003796 // LLVM for struct _class_t *
3797 ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy);
3798
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003799 // struct _category_t {
3800 // const char * const name;
3801 // struct _class_t *const cls;
3802 // const struct _method_list_t * const instance_methods;
3803 // const struct _method_list_t * const class_methods;
3804 // const struct _protocol_list_t * const protocols;
3805 // const struct _prop_list_t * const properties;
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003806 // }
3807 CategorynfABITy = llvm::StructType::get(Int8PtrTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003808 ClassnfABIPtrTy,
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003809 MethodListnfABIPtrTy,
3810 MethodListnfABIPtrTy,
3811 ProtocolListnfABIPtrTy,
3812 PropertyListPtrTy,
3813 NULL);
3814 CGM.getModule().addTypeName("struct._category_t", CategorynfABITy);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003815
3816 // New types for nonfragile abi messaging.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003817 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3818 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003819
3820 // MessageRefTy - LLVM for:
3821 // struct _message_ref_t {
3822 // IMP messenger;
3823 // SEL name;
3824 // };
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003825
3826 // First the clang type for struct _message_ref_t
3827 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3828 SourceLocation(),
3829 &Ctx.Idents.get("_message_ref_t"));
Douglas Gregor6ab35242009-04-09 21:40:53 +00003830 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3831 Ctx.VoidPtrTy, 0, false));
3832 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3833 Ctx.getObjCSelType(), 0, false));
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003834 RD->completeDefinition(Ctx);
3835
3836 MessageRefCTy = Ctx.getTagDeclType(RD);
3837 MessageRefCPtrTy = Ctx.getPointerType(MessageRefCTy);
3838 MessageRefTy = cast<llvm::StructType>(Types.ConvertType(MessageRefCTy));
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003839
3840 // MessageRefPtrTy - LLVM for struct _message_ref_t*
3841 MessageRefPtrTy = llvm::PointerType::getUnqual(MessageRefTy);
3842
3843 // SuperMessageRefTy - LLVM for:
3844 // struct _super_message_ref_t {
3845 // SUPER_IMP messenger;
3846 // SEL name;
3847 // };
3848 SuperMessageRefTy = llvm::StructType::get(ImpnfABITy,
3849 SelectorPtrTy,
3850 NULL);
3851 CGM.getModule().addTypeName("struct._super_message_ref_t", SuperMessageRefTy);
3852
3853 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
3854 SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy);
3855
3856 // id objc_msgSend_fixup (id, struct message_ref_t*, ...)
3857 Params.clear();
3858 Params.push_back(ObjectPtrTy);
3859 Params.push_back(MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00003860 MessengerTy = llvm::FunctionType::get(ObjectPtrTy,
3861 Params,
3862 true);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003863 MessageSendFixupFn =
Fariborz Jahanianef163782009-02-05 01:13:09 +00003864 CGM.CreateRuntimeFunction(MessengerTy,
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003865 "objc_msgSend_fixup");
3866
3867 // id objc_msgSend_fpret_fixup (id, struct message_ref_t*, ...)
3868 MessageSendFpretFixupFn =
3869 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3870 Params,
3871 true),
3872 "objc_msgSend_fpret_fixup");
3873
3874 // id objc_msgSend_stret_fixup (id, struct message_ref_t*, ...)
3875 MessageSendStretFixupFn =
3876 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3877 Params,
3878 true),
3879 "objc_msgSend_stret_fixup");
3880
3881 // id objc_msgSendId_fixup (id, struct message_ref_t*, ...)
3882 MessageSendIdFixupFn =
3883 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3884 Params,
3885 true),
3886 "objc_msgSendId_fixup");
3887
3888
3889 // id objc_msgSendId_stret_fixup (id, struct message_ref_t*, ...)
3890 MessageSendIdStretFixupFn =
3891 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3892 Params,
3893 true),
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003894 "objc_msgSendId_stret_fixup");
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003895
3896 // id objc_msgSendSuper2_fixup (struct objc_super *,
3897 // struct _super_message_ref_t*, ...)
3898 Params.clear();
3899 Params.push_back(SuperPtrTy);
3900 Params.push_back(SuperMessageRefPtrTy);
3901 MessageSendSuper2FixupFn =
3902 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3903 Params,
3904 true),
3905 "objc_msgSendSuper2_fixup");
3906
3907
3908 // id objc_msgSendSuper2_stret_fixup (struct objc_super *,
3909 // struct _super_message_ref_t*, ...)
3910 MessageSendSuper2StretFixupFn =
3911 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3912 Params,
3913 true),
3914 "objc_msgSendSuper2_stret_fixup");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00003915
3916 Params.clear();
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00003917 Params.push_back(Int8PtrTy);
3918 UnwindResumeOrRethrowFn =
3919 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3920 Params,
3921 false),
3922 "_Unwind_Resume_or_Rethrow");
Daniel Dunbare588b992009-03-01 04:46:24 +00003923 ObjCBeginCatchFn =
3924 CGM.CreateRuntimeFunction(llvm::FunctionType::get(Int8PtrTy,
3925 Params,
3926 false),
3927 "objc_begin_catch");
3928
3929 Params.clear();
3930 ObjCEndCatchFn =
3931 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3932 Params,
3933 false),
3934 "objc_end_catch");
3935
3936 // struct objc_typeinfo {
3937 // const void** vtable; // objc_ehtype_vtable + 2
3938 // const char* name; // c++ typeinfo string
3939 // Class cls;
3940 // };
3941 EHTypeTy = llvm::StructType::get(llvm::PointerType::getUnqual(Int8PtrTy),
3942 Int8PtrTy,
3943 ClassnfABIPtrTy,
3944 NULL);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00003945 CGM.getModule().addTypeName("struct._objc_typeinfo", EHTypeTy);
Daniel Dunbare588b992009-03-01 04:46:24 +00003946 EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy);
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003947}
3948
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003949llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() {
3950 FinishNonFragileABIModule();
3951
3952 return NULL;
3953}
3954
3955void CGObjCNonFragileABIMac::FinishNonFragileABIModule() {
3956 // nonfragile abi has no module definition.
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003957
3958 // Build list of all implemented classe addresses in array
3959 // L_OBJC_LABEL_CLASS_$.
3960 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CLASS_$
3961 // list of 'nonlazy' implementations (defined as those with a +load{}
3962 // method!!).
3963 unsigned NumClasses = DefinedClasses.size();
3964 if (NumClasses) {
3965 std::vector<llvm::Constant*> Symbols(NumClasses);
3966 for (unsigned i=0; i<NumClasses; i++)
3967 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
3968 ObjCTypes.Int8PtrTy);
3969 llvm::Constant* Init =
3970 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
3971 NumClasses),
3972 Symbols);
3973
3974 llvm::GlobalVariable *GV =
3975 new llvm::GlobalVariable(Init->getType(), false,
3976 llvm::GlobalValue::InternalLinkage,
3977 Init,
3978 "\01L_OBJC_LABEL_CLASS_$",
3979 &CGM.getModule());
Daniel Dunbar58a29122009-03-09 22:18:41 +00003980 GV->setAlignment(8);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003981 GV->setSection("__DATA, __objc_classlist, regular, no_dead_strip");
3982 UsedGlobals.push_back(GV);
3983 }
3984
3985 // Build list of all implemented category addresses in array
3986 // L_OBJC_LABEL_CATEGORY_$.
3987 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CATEGORY_$
3988 // list of 'nonlazy' category implementations (defined as those with a +load{}
3989 // method!!).
3990 unsigned NumCategory = DefinedCategories.size();
3991 if (NumCategory) {
3992 std::vector<llvm::Constant*> Symbols(NumCategory);
3993 for (unsigned i=0; i<NumCategory; i++)
3994 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedCategories[i],
3995 ObjCTypes.Int8PtrTy);
3996 llvm::Constant* Init =
3997 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
3998 NumCategory),
3999 Symbols);
4000
4001 llvm::GlobalVariable *GV =
4002 new llvm::GlobalVariable(Init->getType(), false,
4003 llvm::GlobalValue::InternalLinkage,
4004 Init,
4005 "\01L_OBJC_LABEL_CATEGORY_$",
4006 &CGM.getModule());
Daniel Dunbar58a29122009-03-09 22:18:41 +00004007 GV->setAlignment(8);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004008 GV->setSection("__DATA, __objc_catlist, regular, no_dead_strip");
4009 UsedGlobals.push_back(GV);
4010 }
4011
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004012 // static int L_OBJC_IMAGE_INFO[2] = { 0, flags };
4013 // FIXME. flags can be 0 | 1 | 2 | 6. For now just use 0
4014 std::vector<llvm::Constant*> Values(2);
4015 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, 0);
Fariborz Jahanian067986e2009-02-24 21:08:09 +00004016 unsigned int flags = 0;
Fariborz Jahanian66a5c2c2009-02-24 23:34:44 +00004017 // FIXME: Fix and continue?
4018 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
4019 flags |= eImageInfo_GarbageCollected;
4020 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
4021 flags |= eImageInfo_GCOnly;
Fariborz Jahanian067986e2009-02-24 21:08:09 +00004022 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004023 llvm::Constant* Init = llvm::ConstantArray::get(
4024 llvm::ArrayType::get(ObjCTypes.IntTy, 2),
4025 Values);
4026 llvm::GlobalVariable *IMGV =
4027 new llvm::GlobalVariable(Init->getType(), false,
4028 llvm::GlobalValue::InternalLinkage,
4029 Init,
4030 "\01L_OBJC_IMAGE_INFO",
4031 &CGM.getModule());
4032 IMGV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
4033 UsedGlobals.push_back(IMGV);
4034
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004035 std::vector<llvm::Constant*> Used;
4036 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
4037 e = UsedGlobals.end(); i != e; ++i) {
4038 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
4039 }
4040
4041 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
4042 llvm::GlobalValue *GV =
4043 new llvm::GlobalVariable(AT, false,
4044 llvm::GlobalValue::AppendingLinkage,
4045 llvm::ConstantArray::get(AT, Used),
4046 "llvm.used",
4047 &CGM.getModule());
4048
4049 GV->setSection("llvm.metadata");
4050
4051}
4052
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004053// Metadata flags
4054enum MetaDataDlags {
4055 CLS = 0x0,
4056 CLS_META = 0x1,
4057 CLS_ROOT = 0x2,
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004058 OBJC2_CLS_HIDDEN = 0x10,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004059 CLS_EXCEPTION = 0x20
4060};
4061/// BuildClassRoTInitializer - generate meta-data for:
4062/// struct _class_ro_t {
4063/// uint32_t const flags;
4064/// uint32_t const instanceStart;
4065/// uint32_t const instanceSize;
4066/// uint32_t const reserved; // only when building for 64bit targets
4067/// const uint8_t * const ivarLayout;
4068/// const char *const name;
4069/// const struct _method_list_t * const baseMethods;
Fariborz Jahanianda320092009-01-29 19:24:30 +00004070/// const struct _protocol_list_t *const baseProtocols;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004071/// const struct _ivar_list_t *const ivars;
4072/// const uint8_t * const weakIvarLayout;
4073/// const struct _prop_list_t * const properties;
4074/// }
4075///
4076llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer(
4077 unsigned flags,
4078 unsigned InstanceStart,
4079 unsigned InstanceSize,
4080 const ObjCImplementationDecl *ID) {
4081 std::string ClassName = ID->getNameAsString();
4082 std::vector<llvm::Constant*> Values(10); // 11 for 64bit targets!
4083 Values[ 0] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
4084 Values[ 1] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceStart);
4085 Values[ 2] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceSize);
4086 // FIXME. For 64bit targets add 0 here.
Fariborz Jahanianda320092009-01-29 19:24:30 +00004087 // FIXME. ivarLayout is currently null!
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00004088 Values[ 3] = GetIvarLayoutName(0, ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004089 Values[ 4] = GetClassName(ID->getIdentifier());
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004090 // const struct _method_list_t * const baseMethods;
4091 std::vector<llvm::Constant*> Methods;
4092 std::string MethodListName("\01l_OBJC_$_");
4093 if (flags & CLS_META) {
4094 MethodListName += "CLASS_METHODS_" + ID->getNameAsString();
4095 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
4096 e = ID->classmeth_end(); i != e; ++i) {
4097 // Class methods should always be defined.
4098 Methods.push_back(GetMethodConstant(*i));
4099 }
4100 } else {
4101 MethodListName += "INSTANCE_METHODS_" + ID->getNameAsString();
4102 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
4103 e = ID->instmeth_end(); i != e; ++i) {
4104 // Instance methods should always be defined.
4105 Methods.push_back(GetMethodConstant(*i));
4106 }
Fariborz Jahanian939abce2009-01-28 22:46:49 +00004107 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
4108 e = ID->propimpl_end(); i != e; ++i) {
4109 ObjCPropertyImplDecl *PID = *i;
4110
4111 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize){
4112 ObjCPropertyDecl *PD = PID->getPropertyDecl();
4113
4114 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
4115 if (llvm::Constant *C = GetMethodConstant(MD))
4116 Methods.push_back(C);
4117 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
4118 if (llvm::Constant *C = GetMethodConstant(MD))
4119 Methods.push_back(C);
4120 }
4121 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004122 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004123 Values[ 5] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004124 "__DATA, __objc_const", Methods);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004125
4126 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4127 assert(OID && "CGObjCNonFragileABIMac::BuildClassRoTInitializer");
4128 Values[ 6] = EmitProtocolList("\01l_OBJC_CLASS_PROTOCOLS_$_"
4129 + OID->getNameAsString(),
4130 OID->protocol_begin(),
4131 OID->protocol_end());
4132
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004133 if (flags & CLS_META)
4134 Values[ 7] = llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4135 else
4136 Values[ 7] = EmitIvarList(ID);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004137 // FIXME. weakIvarLayout is currently null.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00004138 Values[ 8] = GetIvarLayoutName(0, ObjCTypes);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004139 if (flags & CLS_META)
4140 Values[ 9] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4141 else
4142 Values[ 9] =
4143 EmitPropertyList(
4144 "\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
4145 ID, ID->getClassInterface(), ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004146 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassRonfABITy,
4147 Values);
4148 llvm::GlobalVariable *CLASS_RO_GV =
4149 new llvm::GlobalVariable(ObjCTypes.ClassRonfABITy, false,
4150 llvm::GlobalValue::InternalLinkage,
4151 Init,
4152 (flags & CLS_META) ?
4153 std::string("\01l_OBJC_METACLASS_RO_$_")+ClassName :
4154 std::string("\01l_OBJC_CLASS_RO_$_")+ClassName,
4155 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004156 CLASS_RO_GV->setAlignment(
4157 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassRonfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004158 CLASS_RO_GV->setSection("__DATA, __objc_const");
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004159 return CLASS_RO_GV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004160
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004161}
4162
4163/// BuildClassMetaData - This routine defines that to-level meta-data
4164/// for the given ClassName for:
4165/// struct _class_t {
4166/// struct _class_t *isa;
4167/// struct _class_t * const superclass;
4168/// void *cache;
4169/// IMP *vtable;
4170/// struct class_ro_t *ro;
4171/// }
4172///
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004173llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassMetaData(
4174 std::string &ClassName,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004175 llvm::Constant *IsAGV,
4176 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004177 llvm::Constant *ClassRoGV,
4178 bool HiddenVisibility) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004179 std::vector<llvm::Constant*> Values(5);
4180 Values[0] = IsAGV;
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004181 Values[1] = SuperClassGV
4182 ? SuperClassGV
4183 : llvm::Constant::getNullValue(ObjCTypes.ClassnfABIPtrTy);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004184 Values[2] = ObjCEmptyCacheVar; // &ObjCEmptyCacheVar
4185 Values[3] = ObjCEmptyVtableVar; // &ObjCEmptyVtableVar
4186 Values[4] = ClassRoGV; // &CLASS_RO_GV
4187 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassnfABITy,
4188 Values);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004189 llvm::GlobalVariable *GV = GetClassGlobal(ClassName);
4190 GV->setInitializer(Init);
Fariborz Jahaniandd0db2a2009-01-31 01:07:39 +00004191 GV->setSection("__DATA, __objc_data");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004192 GV->setAlignment(
4193 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassnfABITy));
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004194 if (HiddenVisibility)
4195 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004196 return GV;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004197}
4198
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004199void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) {
4200 std::string ClassName = ID->getNameAsString();
4201 if (!ObjCEmptyCacheVar) {
4202 ObjCEmptyCacheVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004203 ObjCTypes.CacheTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004204 false,
4205 llvm::GlobalValue::ExternalLinkage,
4206 0,
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004207 "_objc_empty_cache",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004208 &CGM.getModule());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004209
4210 ObjCEmptyVtableVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004211 ObjCTypes.ImpnfABITy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004212 false,
4213 llvm::GlobalValue::ExternalLinkage,
4214 0,
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004215 "_objc_empty_vtable",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004216 &CGM.getModule());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004217 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004218 assert(ID->getClassInterface() &&
4219 "CGObjCNonFragileABIMac::GenerateClass - class is 0");
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004220 uint32_t InstanceStart =
4221 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassnfABITy);
4222 uint32_t InstanceSize = InstanceStart;
4223 uint32_t flags = CLS_META;
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004224 std::string ObjCMetaClassName(getMetaclassSymbolPrefix());
4225 std::string ObjCClassName(getClassSymbolPrefix());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004226
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004227 llvm::GlobalVariable *SuperClassGV, *IsAGV;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004228
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004229 bool classIsHidden = IsClassHidden(ID->getClassInterface());
4230 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004231 flags |= OBJC2_CLS_HIDDEN;
4232 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004233 // class is root
4234 flags |= CLS_ROOT;
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004235 SuperClassGV = GetClassGlobal(ObjCClassName + ClassName);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004236 IsAGV = GetClassGlobal(ObjCMetaClassName + ClassName, false);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004237 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004238 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004239 const ObjCInterfaceDecl *Root = ID->getClassInterface();
4240 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
4241 Root = Super;
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004242 IsAGV = GetClassGlobal(ObjCMetaClassName + Root->getNameAsString(), false);
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004243 // work on super class metadata symbol.
4244 std::string SuperClassName =
4245 ObjCMetaClassName + ID->getClassInterface()->getSuperClass()->getNameAsString();
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004246 SuperClassGV = GetClassGlobal(SuperClassName, false);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004247 }
4248 llvm::GlobalVariable *CLASS_RO_GV = BuildClassRoTInitializer(flags,
4249 InstanceStart,
4250 InstanceSize,ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004251 std::string TClassName = ObjCMetaClassName + ClassName;
4252 llvm::GlobalVariable *MetaTClass =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004253 BuildClassMetaData(TClassName, IsAGV, SuperClassGV, CLASS_RO_GV,
4254 classIsHidden);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004255
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004256 // Metadata for the class
4257 flags = CLS;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004258 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004259 flags |= OBJC2_CLS_HIDDEN;
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004260
4261 if (hasObjCExceptionAttribute(ID->getClassInterface()))
4262 flags |= CLS_EXCEPTION;
4263
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004264 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004265 flags |= CLS_ROOT;
4266 SuperClassGV = 0;
4267 }
4268 else {
4269 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004270 std::string RootClassName =
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004271 ID->getClassInterface()->getSuperClass()->getNameAsString();
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004272 SuperClassGV = GetClassGlobal(ObjCClassName + RootClassName);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004273 }
Fariborz Jahanianebf9ed32009-03-20 20:48:19 +00004274 // FIXME: Gross
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004275 InstanceStart = InstanceSize = 0;
4276 if (ObjCInterfaceDecl *OID =
4277 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface())) {
4278 // FIXME. Share this with the one in EmitIvarList.
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00004279 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID);
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004280
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00004281 RecordDecl::field_iterator firstField, lastField;
4282 const RecordDecl *RD = GetFirstIvarInRecord(OID, firstField, lastField);
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004283
Douglas Gregor6ab35242009-04-09 21:40:53 +00004284 for (RecordDecl::field_iterator e = RD->field_end(CGM.getContext()),
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004285 ifield = firstField; ifield != e; ++ifield)
4286 lastField = ifield;
4287
Douglas Gregor6ab35242009-04-09 21:40:53 +00004288 if (lastField != RD->field_end(CGM.getContext())) {
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004289 FieldDecl *Field = *lastField;
4290 const llvm::Type *FieldTy =
4291 CGM.getTypes().ConvertTypeForMem(Field->getType());
4292 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00004293 InstanceSize = GetIvarBaseOffset(Layout, Field) + Size;
Douglas Gregor6ab35242009-04-09 21:40:53 +00004294 if (firstField == RD->field_end(CGM.getContext()))
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004295 InstanceStart = InstanceSize;
Fariborz Jahanian11894a42009-03-07 19:43:20 +00004296 else {
4297 Field = *firstField;
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00004298 InstanceStart = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanian11894a42009-03-07 19:43:20 +00004299 }
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004300 }
4301 }
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004302 CLASS_RO_GV = BuildClassRoTInitializer(flags,
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004303 InstanceStart,
4304 InstanceSize,
4305 ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004306
4307 TClassName = ObjCClassName + ClassName;
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004308 llvm::GlobalVariable *ClassMD =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004309 BuildClassMetaData(TClassName, MetaTClass, SuperClassGV, CLASS_RO_GV,
4310 classIsHidden);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004311 UsedGlobals.push_back(ClassMD);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004312 DefinedClasses.push_back(ClassMD);
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004313
4314 // Force the definition of the EHType if necessary.
4315 if (flags & CLS_EXCEPTION)
4316 GetInterfaceEHType(ID->getClassInterface(), true);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004317}
4318
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004319/// GenerateProtocolRef - This routine is called to generate code for
4320/// a protocol reference expression; as in:
4321/// @code
4322/// @protocol(Proto1);
4323/// @endcode
4324/// It generates a weak reference to l_OBJC_PROTOCOL_REFERENCE_$_Proto1
4325/// which will hold address of the protocol meta-data.
4326///
4327llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CGBuilderTy &Builder,
4328 const ObjCProtocolDecl *PD) {
4329
4330 llvm::Constant *Init = llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
4331 ObjCTypes.ExternalProtocolPtrTy);
4332
4333 std::string ProtocolName("\01l_OBJC_PROTOCOL_REFERENCE_$_");
4334 ProtocolName += PD->getNameAsCString();
4335
4336 llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName);
4337 if (PTGV)
4338 return Builder.CreateLoad(PTGV, false, "tmp");
4339 PTGV = new llvm::GlobalVariable(
4340 Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00004341 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004342 Init,
4343 ProtocolName,
4344 &CGM.getModule());
4345 PTGV->setSection("__DATA, __objc_protorefs, coalesced, no_dead_strip");
4346 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4347 UsedGlobals.push_back(PTGV);
4348 return Builder.CreateLoad(PTGV, false, "tmp");
4349}
4350
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004351/// GenerateCategory - Build metadata for a category implementation.
4352/// struct _category_t {
4353/// const char * const name;
4354/// struct _class_t *const cls;
4355/// const struct _method_list_t * const instance_methods;
4356/// const struct _method_list_t * const class_methods;
4357/// const struct _protocol_list_t * const protocols;
4358/// const struct _prop_list_t * const properties;
4359/// }
4360///
4361void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD)
4362{
4363 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004364 const char *Prefix = "\01l_OBJC_$_CATEGORY_";
4365 std::string ExtCatName(Prefix + Interface->getNameAsString()+
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004366 "_$_" + OCD->getNameAsString());
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004367 std::string ExtClassName(getClassSymbolPrefix() +
4368 Interface->getNameAsString());
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004369
4370 std::vector<llvm::Constant*> Values(6);
4371 Values[0] = GetClassName(OCD->getIdentifier());
4372 // meta-class entry symbol
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004373 llvm::GlobalVariable *ClassGV = GetClassGlobal(ExtClassName);
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004374 Values[1] = ClassGV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004375 std::vector<llvm::Constant*> Methods;
4376 std::string MethodListName(Prefix);
4377 MethodListName += "INSTANCE_METHODS_" + Interface->getNameAsString() +
4378 "_$_" + OCD->getNameAsString();
4379
4380 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
4381 e = OCD->instmeth_end(); i != e; ++i) {
4382 // Instance methods should always be defined.
4383 Methods.push_back(GetMethodConstant(*i));
4384 }
4385
4386 Values[2] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004387 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004388 Methods);
4389
4390 MethodListName = Prefix;
4391 MethodListName += "CLASS_METHODS_" + Interface->getNameAsString() + "_$_" +
4392 OCD->getNameAsString();
4393 Methods.clear();
4394 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
4395 e = OCD->classmeth_end(); i != e; ++i) {
4396 // Class methods should always be defined.
4397 Methods.push_back(GetMethodConstant(*i));
4398 }
4399
4400 Values[3] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004401 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004402 Methods);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004403 const ObjCCategoryDecl *Category =
4404 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Fariborz Jahanian943ed6f2009-02-13 17:52:22 +00004405 if (Category) {
4406 std::string ExtName(Interface->getNameAsString() + "_$_" +
4407 OCD->getNameAsString());
4408 Values[4] = EmitProtocolList("\01l_OBJC_CATEGORY_PROTOCOLS_$_"
4409 + Interface->getNameAsString() + "_$_"
4410 + Category->getNameAsString(),
4411 Category->protocol_begin(),
4412 Category->protocol_end());
4413 Values[5] =
4414 EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
4415 OCD, Category, ObjCTypes);
4416 }
4417 else {
4418 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4419 Values[5] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4420 }
4421
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004422 llvm::Constant *Init =
4423 llvm::ConstantStruct::get(ObjCTypes.CategorynfABITy,
4424 Values);
4425 llvm::GlobalVariable *GCATV
4426 = new llvm::GlobalVariable(ObjCTypes.CategorynfABITy,
4427 false,
4428 llvm::GlobalValue::InternalLinkage,
4429 Init,
4430 ExtCatName,
4431 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004432 GCATV->setAlignment(
4433 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.CategorynfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004434 GCATV->setSection("__DATA, __objc_const");
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004435 UsedGlobals.push_back(GCATV);
4436 DefinedCategories.push_back(GCATV);
4437}
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004438
4439/// GetMethodConstant - Return a struct objc_method constant for the
4440/// given method if it has been defined. The result is null if the
4441/// method has not been defined. The return value has type MethodPtrTy.
4442llvm::Constant *CGObjCNonFragileABIMac::GetMethodConstant(
4443 const ObjCMethodDecl *MD) {
4444 // FIXME: Use DenseMap::lookup
4445 llvm::Function *Fn = MethodDefinitions[MD];
4446 if (!Fn)
4447 return 0;
4448
4449 std::vector<llvm::Constant*> Method(3);
4450 Method[0] =
4451 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4452 ObjCTypes.SelectorPtrTy);
4453 Method[1] = GetMethodVarType(MD);
4454 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
4455 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
4456}
4457
4458/// EmitMethodList - Build meta-data for method declarations
4459/// struct _method_list_t {
4460/// uint32_t entsize; // sizeof(struct _objc_method)
4461/// uint32_t method_count;
4462/// struct _objc_method method_list[method_count];
4463/// }
4464///
4465llvm::Constant *CGObjCNonFragileABIMac::EmitMethodList(
4466 const std::string &Name,
4467 const char *Section,
4468 const ConstantVector &Methods) {
4469 // Return null for empty list.
4470 if (Methods.empty())
4471 return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy);
4472
4473 std::vector<llvm::Constant*> Values(3);
4474 // sizeof(struct _objc_method)
4475 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.MethodTy);
4476 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4477 // method_count
4478 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
4479 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
4480 Methods.size());
4481 Values[2] = llvm::ConstantArray::get(AT, Methods);
4482 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4483
4484 llvm::GlobalVariable *GV =
4485 new llvm::GlobalVariable(Init->getType(), false,
4486 llvm::GlobalValue::InternalLinkage,
4487 Init,
4488 Name,
4489 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004490 GV->setAlignment(
4491 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004492 GV->setSection(Section);
4493 UsedGlobals.push_back(GV);
4494 return llvm::ConstantExpr::getBitCast(GV,
4495 ObjCTypes.MethodListnfABIPtrTy);
4496}
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004497
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004498/// ObjCIvarOffsetVariable - Returns the ivar offset variable for
4499/// the given ivar.
4500///
4501llvm::GlobalVariable * CGObjCNonFragileABIMac::ObjCIvarOffsetVariable(
4502 std::string &Name,
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004503 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004504 const ObjCIvarDecl *Ivar) {
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004505 Name += "\01_OBJC_IVAR_$_" +
Douglas Gregor6ab35242009-04-09 21:40:53 +00004506 getInterfaceDeclForIvar(ID, Ivar, CGM.getContext())->getNameAsString() +
4507 '.' + Ivar->getNameAsString();
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004508 llvm::GlobalVariable *IvarOffsetGV =
4509 CGM.getModule().getGlobalVariable(Name);
4510 if (!IvarOffsetGV)
4511 IvarOffsetGV =
4512 new llvm::GlobalVariable(ObjCTypes.LongTy,
4513 false,
4514 llvm::GlobalValue::ExternalLinkage,
4515 0,
4516 Name,
4517 &CGM.getModule());
4518 return IvarOffsetGV;
4519}
4520
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004521llvm::Constant * CGObjCNonFragileABIMac::EmitIvarOffsetVar(
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004522 const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004523 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004524 unsigned long int Offset) {
4525
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004526 assert(ID && "EmitIvarOffsetVar - null interface decl.");
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004527 std::string ExternalName("\01_OBJC_IVAR_$_" + ID->getNameAsString() + '.'
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004528 + Ivar->getNameAsString());
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004529 llvm::Constant *Init = llvm::ConstantInt::get(ObjCTypes.LongTy, Offset);
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004530 llvm::GlobalVariable *IvarOffsetGV =
4531 CGM.getModule().getGlobalVariable(ExternalName);
Fariborz Jahanian77c9fd22009-04-06 18:30:00 +00004532 if (IvarOffsetGV)
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004533 // ivar offset symbol already built due to user code referencing it.
4534 IvarOffsetGV->setInitializer(Init);
Fariborz Jahanian77c9fd22009-04-06 18:30:00 +00004535 else
4536 IvarOffsetGV =
4537 new llvm::GlobalVariable(Init->getType(),
4538 false,
4539 llvm::GlobalValue::ExternalLinkage,
4540 Init,
4541 ExternalName,
4542 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004543 IvarOffsetGV->setAlignment(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004544 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.LongTy));
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004545 // @private and @package have hidden visibility.
4546 bool globalVisibility = (Ivar->getAccessControl() == ObjCIvarDecl::Public ||
Fariborz Jahanian77c9fd22009-04-06 18:30:00 +00004547 Ivar->getAccessControl() == ObjCIvarDecl::Protected);
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004548 if (!globalVisibility)
4549 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahanian77c9fd22009-04-06 18:30:00 +00004550 else if (IsClassHidden(ID))
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004551 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahanian77c9fd22009-04-06 18:30:00 +00004552 else if (CGM.getLangOptions().getVisibilityMode() ==
Fariborz Jahanian77c9fd22009-04-06 18:30:00 +00004553 LangOptions::DefaultVisibility)
4554 IvarOffsetGV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004555 IvarOffsetGV->setSection("__DATA, __objc_const");
4556 UsedGlobals.push_back(IvarOffsetGV);
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004557 return IvarOffsetGV;
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004558}
4559
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004560/// EmitIvarList - Emit the ivar list for the given
4561/// implementation. If ForClass is true the list of class ivars
4562/// (i.e. metaclass ivars) is emitted, otherwise the list of
4563/// interface ivars will be emitted. The return value has type
4564/// IvarListnfABIPtrTy.
4565/// struct _ivar_t {
4566/// unsigned long int *offset; // pointer to ivar offset location
4567/// char *name;
4568/// char *type;
4569/// uint32_t alignment;
4570/// uint32_t size;
4571/// }
4572/// struct _ivar_list_t {
4573/// uint32 entsize; // sizeof(struct _ivar_t)
4574/// uint32 count;
4575/// struct _iver_t list[count];
4576/// }
4577///
4578llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList(
4579 const ObjCImplementationDecl *ID) {
4580
4581 std::vector<llvm::Constant*> Ivars, Ivar(5);
4582
4583 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4584 assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface");
4585
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004586 // FIXME. Consolidate this with similar code in GenerateClass.
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00004587 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00004588
4589 RecordDecl::field_iterator i,p;
4590 const RecordDecl *RD = GetFirstIvarInRecord(OID, i,p);
Fariborz Jahanian18191882009-03-31 18:11:23 +00004591 // collect declared and synthesized ivars in a small vector.
4592 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
4593 for (ObjCInterfaceDecl::ivar_iterator I = OID->ivar_begin(),
4594 E = OID->ivar_end(); I != E; ++I)
4595 OIvars.push_back(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +00004596 for (ObjCInterfaceDecl::prop_iterator I = OID->prop_begin(CGM.getContext()),
4597 E = OID->prop_end(CGM.getContext()); I != E; ++I)
Fariborz Jahanian18191882009-03-31 18:11:23 +00004598 if (ObjCIvarDecl *IV = (*I)->getPropertyIvarDecl())
4599 OIvars.push_back(IV);
Fariborz Jahanian99eee362009-04-01 19:37:34 +00004600
Fariborz Jahanian18191882009-03-31 18:11:23 +00004601 unsigned iv = 0;
Douglas Gregor6ab35242009-04-09 21:40:53 +00004602 for (RecordDecl::field_iterator e = RD->field_end(CGM.getContext());
4603 i != e; ++i) {
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004604 FieldDecl *Field = *i;
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00004605 uint64_t offset = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanian18191882009-03-31 18:11:23 +00004606 Ivar[0] = EmitIvarOffsetVar(ID->getClassInterface(), OIvars[iv++], offset);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004607 if (Field->getIdentifier())
4608 Ivar[1] = GetMethodVarName(Field->getIdentifier());
4609 else
4610 Ivar[1] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Devang Patel7794bb82009-03-04 18:21:39 +00004611 Ivar[2] = GetMethodVarType(Field);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004612 const llvm::Type *FieldTy =
4613 CGM.getTypes().ConvertTypeForMem(Field->getType());
4614 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
4615 unsigned Align = CGM.getContext().getPreferredTypeAlign(
4616 Field->getType().getTypePtr()) >> 3;
4617 Align = llvm::Log2_32(Align);
4618 Ivar[3] = llvm::ConstantInt::get(ObjCTypes.IntTy, Align);
Fariborz Jahanian07236ba2009-01-27 22:27:56 +00004619 // NOTE. Size of a bitfield does not match gcc's, because of the way
4620 // bitfields are treated special in each. But I am told that 'size'
4621 // for bitfield ivars is ignored by the runtime so it does not matter.
4622 // (even if it matters, some day, there is enough info. to get the bitfield
4623 // right!
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004624 Ivar[4] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4625 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarnfABITy, Ivar));
4626 }
4627 // Return null for empty list.
4628 if (Ivars.empty())
4629 return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4630 std::vector<llvm::Constant*> Values(3);
4631 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.IvarnfABITy);
4632 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4633 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
4634 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarnfABITy,
4635 Ivars.size());
4636 Values[2] = llvm::ConstantArray::get(AT, Ivars);
4637 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4638 const char *Prefix = "\01l_OBJC_$_INSTANCE_VARIABLES_";
4639 llvm::GlobalVariable *GV =
4640 new llvm::GlobalVariable(Init->getType(), false,
4641 llvm::GlobalValue::InternalLinkage,
4642 Init,
4643 Prefix + OID->getNameAsString(),
4644 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004645 GV->setAlignment(
4646 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004647 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004648
4649 UsedGlobals.push_back(GV);
4650 return llvm::ConstantExpr::getBitCast(GV,
4651 ObjCTypes.IvarListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004652}
4653
4654llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef(
4655 const ObjCProtocolDecl *PD) {
4656 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4657
4658 if (!Entry) {
4659 // We use the initializer as a marker of whether this is a forward
4660 // reference or not. At module finalization we add the empty
4661 // contents for protocols which were referenced but never defined.
4662 Entry =
4663 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
4664 llvm::GlobalValue::ExternalLinkage,
4665 0,
4666 "\01l_OBJC_PROTOCOL_$_" + PD->getNameAsString(),
4667 &CGM.getModule());
4668 Entry->setSection("__DATA,__datacoal_nt,coalesced");
4669 UsedGlobals.push_back(Entry);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004670 }
4671
4672 return Entry;
4673}
4674
4675/// GetOrEmitProtocol - Generate the protocol meta-data:
4676/// @code
4677/// struct _protocol_t {
4678/// id isa; // NULL
4679/// const char * const protocol_name;
4680/// const struct _protocol_list_t * protocol_list; // super protocols
4681/// const struct method_list_t * const instance_methods;
4682/// const struct method_list_t * const class_methods;
4683/// const struct method_list_t *optionalInstanceMethods;
4684/// const struct method_list_t *optionalClassMethods;
4685/// const struct _prop_list_t * properties;
4686/// const uint32_t size; // sizeof(struct _protocol_t)
4687/// const uint32_t flags; // = 0
4688/// }
4689/// @endcode
4690///
4691
4692llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol(
4693 const ObjCProtocolDecl *PD) {
4694 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4695
4696 // Early exit if a defining object has already been generated.
4697 if (Entry && Entry->hasInitializer())
4698 return Entry;
4699
4700 const char *ProtocolName = PD->getNameAsCString();
4701
4702 // Construct method lists.
4703 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
4704 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregor6ab35242009-04-09 21:40:53 +00004705 for (ObjCProtocolDecl::instmeth_iterator
4706 i = PD->instmeth_begin(CGM.getContext()),
4707 e = PD->instmeth_end(CGM.getContext());
4708 i != e; ++i) {
Fariborz Jahanianda320092009-01-29 19:24:30 +00004709 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004710 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004711 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4712 OptInstanceMethods.push_back(C);
4713 } else {
4714 InstanceMethods.push_back(C);
4715 }
4716 }
4717
Douglas Gregor6ab35242009-04-09 21:40:53 +00004718 for (ObjCProtocolDecl::classmeth_iterator
4719 i = PD->classmeth_begin(CGM.getContext()),
4720 e = PD->classmeth_end(CGM.getContext());
4721 i != e; ++i) {
Fariborz Jahanianda320092009-01-29 19:24:30 +00004722 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004723 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004724 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4725 OptClassMethods.push_back(C);
4726 } else {
4727 ClassMethods.push_back(C);
4728 }
4729 }
4730
4731 std::vector<llvm::Constant*> Values(10);
4732 // isa is NULL
4733 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ObjectPtrTy);
4734 Values[1] = GetClassName(PD->getIdentifier());
4735 Values[2] = EmitProtocolList(
4736 "\01l_OBJC_$_PROTOCOL_REFS_" + PD->getNameAsString(),
4737 PD->protocol_begin(),
4738 PD->protocol_end());
4739
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004740 Values[3] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004741 + PD->getNameAsString(),
4742 "__DATA, __objc_const",
4743 InstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004744 Values[4] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004745 + PD->getNameAsString(),
4746 "__DATA, __objc_const",
4747 ClassMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004748 Values[5] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004749 + PD->getNameAsString(),
4750 "__DATA, __objc_const",
4751 OptInstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004752 Values[6] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004753 + PD->getNameAsString(),
4754 "__DATA, __objc_const",
4755 OptClassMethods);
4756 Values[7] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + PD->getNameAsString(),
4757 0, PD, ObjCTypes);
4758 uint32_t Size =
4759 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolnfABITy);
4760 Values[8] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4761 Values[9] = llvm::Constant::getNullValue(ObjCTypes.IntTy);
4762 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolnfABITy,
4763 Values);
4764
4765 if (Entry) {
4766 // Already created, fix the linkage and update the initializer.
Mike Stump286acbd2009-03-07 16:33:28 +00004767 Entry->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004768 Entry->setInitializer(Init);
4769 } else {
4770 Entry =
4771 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004772 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004773 Init,
4774 std::string("\01l_OBJC_PROTOCOL_$_")+ProtocolName,
4775 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004776 Entry->setAlignment(
4777 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABITy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004778 Entry->setSection("__DATA,__datacoal_nt,coalesced");
Fariborz Jahanianda320092009-01-29 19:24:30 +00004779 }
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004780 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
4781
4782 // Use this protocol meta-data to build protocol list table in section
4783 // __DATA, __objc_protolist
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004784 llvm::GlobalVariable *PTGV = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004785 ObjCTypes.ProtocolnfABIPtrTy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004786 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004787 Entry,
4788 std::string("\01l_OBJC_LABEL_PROTOCOL_$_")
4789 +ProtocolName,
4790 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004791 PTGV->setAlignment(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004792 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABIPtrTy));
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004793 PTGV->setSection("__DATA, __objc_protolist");
4794 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4795 UsedGlobals.push_back(PTGV);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004796 return Entry;
4797}
4798
4799/// EmitProtocolList - Generate protocol list meta-data:
4800/// @code
4801/// struct _protocol_list_t {
4802/// long protocol_count; // Note, this is 32/64 bit
4803/// struct _protocol_t[protocol_count];
4804/// }
4805/// @endcode
4806///
4807llvm::Constant *
4808CGObjCNonFragileABIMac::EmitProtocolList(const std::string &Name,
4809 ObjCProtocolDecl::protocol_iterator begin,
4810 ObjCProtocolDecl::protocol_iterator end) {
4811 std::vector<llvm::Constant*> ProtocolRefs;
4812
Fariborz Jahanianda320092009-01-29 19:24:30 +00004813 // Just return null for empty protocol lists
Daniel Dunbar948e2582009-02-15 07:36:20 +00004814 if (begin == end)
Fariborz Jahanianda320092009-01-29 19:24:30 +00004815 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4816
Daniel Dunbar948e2582009-02-15 07:36:20 +00004817 // FIXME: We shouldn't need to do this lookup here, should we?
Fariborz Jahanianda320092009-01-29 19:24:30 +00004818 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
4819 if (GV)
Daniel Dunbar948e2582009-02-15 07:36:20 +00004820 return llvm::ConstantExpr::getBitCast(GV,
4821 ObjCTypes.ProtocolListnfABIPtrTy);
4822
4823 for (; begin != end; ++begin)
4824 ProtocolRefs.push_back(GetProtocolRef(*begin)); // Implemented???
4825
Fariborz Jahanianda320092009-01-29 19:24:30 +00004826 // This list is null terminated.
4827 ProtocolRefs.push_back(llvm::Constant::getNullValue(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004828 ObjCTypes.ProtocolnfABIPtrTy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004829
4830 std::vector<llvm::Constant*> Values(2);
4831 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
4832 Values[1] =
Daniel Dunbar948e2582009-02-15 07:36:20 +00004833 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolnfABIPtrTy,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004834 ProtocolRefs.size()),
4835 ProtocolRefs);
4836
4837 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4838 GV = new llvm::GlobalVariable(Init->getType(), false,
4839 llvm::GlobalValue::InternalLinkage,
4840 Init,
4841 Name,
4842 &CGM.getModule());
4843 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004844 GV->setAlignment(
4845 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004846 UsedGlobals.push_back(GV);
Daniel Dunbar948e2582009-02-15 07:36:20 +00004847 return llvm::ConstantExpr::getBitCast(GV,
4848 ObjCTypes.ProtocolListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004849}
4850
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004851/// GetMethodDescriptionConstant - This routine build following meta-data:
4852/// struct _objc_method {
4853/// SEL _cmd;
4854/// char *method_type;
4855/// char *_imp;
4856/// }
4857
4858llvm::Constant *
4859CGObjCNonFragileABIMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
4860 std::vector<llvm::Constant*> Desc(3);
4861 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4862 ObjCTypes.SelectorPtrTy);
4863 Desc[1] = GetMethodVarType(MD);
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004864 // Protocol methods have no implementation. So, this entry is always NULL.
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004865 Desc[2] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
4866 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Desc);
4867}
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004868
4869/// EmitObjCValueForIvar - Code Gen for nonfragile ivar reference.
4870/// This code gen. amounts to generating code for:
4871/// @code
4872/// (type *)((char *)base + _OBJC_IVAR_$_.ivar;
4873/// @encode
4874///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004875LValue CGObjCNonFragileABIMac::EmitObjCValueForIvar(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004876 CodeGen::CodeGenFunction &CGF,
4877 QualType ObjectTy,
4878 llvm::Value *BaseValue,
4879 const ObjCIvarDecl *Ivar,
4880 const FieldDecl *Field,
4881 unsigned CVRQualifiers) {
4882 assert(ObjectTy->isObjCInterfaceType() &&
4883 "CGObjCNonFragileABIMac::EmitObjCValueForIvar");
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004884 ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004885 std::string ExternalName;
4886 llvm::GlobalVariable *IvarOffsetGV =
4887 ObjCIvarOffsetVariable(ExternalName, ID, Ivar);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004888
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004889 // (char *) BaseValue
4890 llvm::Value *V = CGF.Builder.CreateBitCast(BaseValue,
4891 ObjCTypes.Int8PtrTy);
4892 llvm::Value *Offset = CGF.Builder.CreateLoad(IvarOffsetGV);
4893 // (char*)BaseValue + Offset_symbol
4894 V = CGF.Builder.CreateGEP(V, Offset, "add.ptr");
4895 // (type *)((char*)BaseValue + Offset_symbol)
4896 const llvm::Type *IvarTy =
4897 CGM.getTypes().ConvertType(Ivar->getType());
4898 llvm::Type *ptrIvarTy = llvm::PointerType::getUnqual(IvarTy);
4899 V = CGF.Builder.CreateBitCast(V, ptrIvarTy);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004900
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00004901 if (Ivar->isBitField()) {
4902 CodeGenTypes::BitFieldInfo bitFieldInfo =
4903 CGM.getTypes().getBitFieldInfo(Field);
4904 return LValue::MakeBitfield(V, bitFieldInfo.Begin, bitFieldInfo.Size,
4905 Field->getType()->isSignedIntegerType(),
4906 Field->getType().getCVRQualifiers()|CVRQualifiers);
4907 }
4908
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004909 LValue LV = LValue::MakeAddr(V,
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004910 Ivar->getType().getCVRQualifiers()|CVRQualifiers,
4911 CGM.getContext().getObjCGCAttrKind(Ivar->getType()));
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004912 LValue::SetObjCIvar(LV, true);
4913 return LV;
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004914}
4915
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004916llvm::Value *CGObjCNonFragileABIMac::EmitIvarOffset(
4917 CodeGen::CodeGenFunction &CGF,
4918 ObjCInterfaceDecl *Interface,
4919 const ObjCIvarDecl *Ivar) {
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004920 std::string ExternalName;
4921 llvm::GlobalVariable *IvarOffsetGV =
4922 ObjCIvarOffsetVariable(ExternalName, Interface, Ivar);
4923
4924 return CGF.Builder.CreateLoad(IvarOffsetGV, false, "ivar");
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004925}
4926
Fariborz Jahanian46551122009-02-04 00:22:57 +00004927CodeGen::RValue CGObjCNonFragileABIMac::EmitMessageSend(
4928 CodeGen::CodeGenFunction &CGF,
4929 QualType ResultType,
4930 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004931 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +00004932 QualType Arg0Ty,
4933 bool IsSuper,
4934 const CallArgList &CallArgs) {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004935 // FIXME. Even though IsSuper is passes. This function doese not
4936 // handle calls to 'super' receivers.
4937 CodeGenTypes &Types = CGM.getTypes();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004938 llvm::Value *Arg0 = Receiver;
4939 if (!IsSuper)
4940 Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy, "tmp");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004941
4942 // Find the message function name.
Fariborz Jahanianef163782009-02-05 01:13:09 +00004943 // FIXME. This is too much work to get the ABI-specific result type
4944 // needed to find the message name.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004945 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType,
4946 llvm::SmallVector<QualType, 16>());
4947 llvm::Constant *Fn;
4948 std::string Name("\01l_");
4949 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004950#if 0
4951 // unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004952 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
4953 Fn = ObjCTypes.MessageSendIdStretFixupFn;
4954 // FIXME. Is there a better way of getting these names.
4955 // They are available in RuntimeFunctions vector pair.
4956 Name += "objc_msgSendId_stret_fixup";
4957 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004958 else
4959#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004960 if (IsSuper) {
4961 Fn = ObjCTypes.MessageSendSuper2StretFixupFn;
4962 Name += "objc_msgSendSuper2_stret_fixup";
4963 }
4964 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004965 {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004966 Fn = ObjCTypes.MessageSendStretFixupFn;
4967 Name += "objc_msgSend_stret_fixup";
4968 }
4969 }
Fariborz Jahanian1a6b3682009-02-05 19:35:43 +00004970 else if (ResultType->isFloatingType() &&
4971 // Selection of frret API only happens in 32bit nonfragile ABI.
4972 CGM.getTargetData().getTypePaddedSize(ObjCTypes.LongTy) == 4) {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004973 Fn = ObjCTypes.MessageSendFpretFixupFn;
4974 Name += "objc_msgSend_fpret_fixup";
4975 }
4976 else {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004977#if 0
4978// unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004979 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
4980 Fn = ObjCTypes.MessageSendIdFixupFn;
4981 Name += "objc_msgSendId_fixup";
4982 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004983 else
4984#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004985 if (IsSuper) {
4986 Fn = ObjCTypes.MessageSendSuper2FixupFn;
4987 Name += "objc_msgSendSuper2_fixup";
4988 }
4989 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004990 {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004991 Fn = ObjCTypes.MessageSendFixupFn;
4992 Name += "objc_msgSend_fixup";
4993 }
4994 }
4995 Name += '_';
4996 std::string SelName(Sel.getAsString());
4997 // Replace all ':' in selector name with '_' ouch!
4998 for(unsigned i = 0; i < SelName.size(); i++)
4999 if (SelName[i] == ':')
5000 SelName[i] = '_';
5001 Name += SelName;
5002 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5003 if (!GV) {
5004 // Build messafe ref table entry.
5005 std::vector<llvm::Constant*> Values(2);
5006 Values[0] = Fn;
5007 Values[1] = GetMethodVarName(Sel);
5008 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
5009 GV = new llvm::GlobalVariable(Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00005010 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005011 Init,
5012 Name,
5013 &CGM.getModule());
5014 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
5015 GV->setAlignment(
5016 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.MessageRefTy));
5017 GV->setSection("__DATA, __objc_msgrefs, coalesced");
5018 UsedGlobals.push_back(GV);
5019 }
5020 llvm::Value *Arg1 = CGF.Builder.CreateBitCast(GV, ObjCTypes.MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00005021
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005022 CallArgList ActualArgs;
5023 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
5024 ActualArgs.push_back(std::make_pair(RValue::get(Arg1),
5025 ObjCTypes.MessageRefCPtrTy));
5026 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Fariborz Jahanianef163782009-02-05 01:13:09 +00005027 const CGFunctionInfo &FnInfo1 = Types.getFunctionInfo(ResultType, ActualArgs);
5028 llvm::Value *Callee = CGF.Builder.CreateStructGEP(Arg1, 0);
5029 Callee = CGF.Builder.CreateLoad(Callee);
Fariborz Jahanian3ab75bd2009-02-14 21:25:36 +00005030 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo1, true);
Fariborz Jahanianef163782009-02-05 01:13:09 +00005031 Callee = CGF.Builder.CreateBitCast(Callee,
5032 llvm::PointerType::getUnqual(FTy));
5033 return CGF.EmitCall(FnInfo1, Callee, ActualArgs);
Fariborz Jahanian46551122009-02-04 00:22:57 +00005034}
5035
5036/// Generate code for a message send expression in the nonfragile abi.
5037CodeGen::RValue CGObjCNonFragileABIMac::GenerateMessageSend(
5038 CodeGen::CodeGenFunction &CGF,
5039 QualType ResultType,
5040 Selector Sel,
5041 llvm::Value *Receiver,
5042 bool IsClassMessage,
5043 const CallArgList &CallArgs) {
Fariborz Jahanian46551122009-02-04 00:22:57 +00005044 return EmitMessageSend(CGF, ResultType, Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005045 Receiver, CGF.getContext().getObjCIdType(),
Fariborz Jahanian46551122009-02-04 00:22:57 +00005046 false, CallArgs);
5047}
5048
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005049llvm::GlobalVariable *
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005050CGObjCNonFragileABIMac::GetClassGlobal(const std::string &Name,
5051 bool AddToUsed) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005052 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5053
Daniel Dunbardfff2302009-03-02 05:18:14 +00005054 if (!GV) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005055 GV = new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
5056 llvm::GlobalValue::ExternalLinkage,
5057 0, Name, &CGM.getModule());
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005058 if (AddToUsed)
5059 UsedGlobals.push_back(GV);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005060 }
5061
5062 return GV;
5063}
5064
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005065llvm::Value *CGObjCNonFragileABIMac::EmitClassRef(CGBuilderTy &Builder,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005066 const ObjCInterfaceDecl *ID,
5067 bool IsSuper) {
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005068
5069 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
5070
5071 if (!Entry) {
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005072 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005073 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005074 Entry =
5075 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5076 llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005077 ClassGV,
5078 IsSuper ? "\01L_OBJC_CLASSLIST_SUP_REFS_$_"
5079 : "\01L_OBJC_CLASSLIST_REFERENCES_$_",
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005080 &CGM.getModule());
5081 Entry->setAlignment(
5082 CGM.getTargetData().getPrefTypeAlignment(
5083 ObjCTypes.ClassnfABIPtrTy));
5084
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005085 if (IsSuper)
Fariborz Jahanian21228b72009-02-26 22:30:39 +00005086 Entry->setSection("__DATA,__objc_superrefs,regular,no_dead_strip");
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005087 else
Fariborz Jahanian21228b72009-02-26 22:30:39 +00005088 Entry->setSection("__DATA,__objc_classrefs,regular,no_dead_strip");
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005089 UsedGlobals.push_back(Entry);
5090 }
5091
5092 return Builder.CreateLoad(Entry, false, "tmp");
5093}
5094
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005095/// EmitMetaClassRef - Return a Value * of the address of _class_t
5096/// meta-data
5097///
5098llvm::Value *CGObjCNonFragileABIMac::EmitMetaClassRef(CGBuilderTy &Builder,
5099 const ObjCInterfaceDecl *ID) {
5100 llvm::GlobalVariable * &Entry = MetaClassReferences[ID->getIdentifier()];
5101 if (Entry)
5102 return Builder.CreateLoad(Entry, false, "tmp");
5103
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005104 std::string MetaClassName(getMetaclassSymbolPrefix() + ID->getNameAsString());
5105 llvm::GlobalVariable *MetaClassGV = GetClassGlobal(MetaClassName, false);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005106 Entry =
5107 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5108 llvm::GlobalValue::InternalLinkage,
5109 MetaClassGV,
5110 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5111 &CGM.getModule());
5112 Entry->setAlignment(
5113 CGM.getTargetData().getPrefTypeAlignment(
5114 ObjCTypes.ClassnfABIPtrTy));
5115
5116 Entry->setSection("__OBJC,__objc_superrefs,regular,no_dead_strip");
5117 UsedGlobals.push_back(Entry);
5118
5119 return Builder.CreateLoad(Entry, false, "tmp");
5120}
5121
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005122/// GetClass - Return a reference to the class for the given interface
5123/// decl.
5124llvm::Value *CGObjCNonFragileABIMac::GetClass(CGBuilderTy &Builder,
5125 const ObjCInterfaceDecl *ID) {
5126 return EmitClassRef(Builder, ID);
5127}
5128
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005129/// Generates a message send where the super is the receiver. This is
5130/// a message send to self with special delivery semantics indicating
5131/// which class's method should be called.
5132CodeGen::RValue
5133CGObjCNonFragileABIMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
5134 QualType ResultType,
5135 Selector Sel,
5136 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005137 bool isCategoryImpl,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005138 llvm::Value *Receiver,
5139 bool IsClassMessage,
5140 const CodeGen::CallArgList &CallArgs) {
5141 // ...
5142 // Create and init a super structure; this is a (receiver, class)
5143 // pair we will pass to objc_msgSendSuper.
5144 llvm::Value *ObjCSuper =
5145 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
5146
5147 llvm::Value *ReceiverAsObject =
5148 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
5149 CGF.Builder.CreateStore(ReceiverAsObject,
5150 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
5151
5152 // If this is a class message the metaclass is passed as the target.
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005153 llvm::Value *Target;
5154 if (IsClassMessage) {
5155 if (isCategoryImpl) {
5156 // Message sent to "super' in a class method defined in
5157 // a category implementation.
5158 Target = EmitClassRef(CGF.Builder, Class, false);
5159 Target = CGF.Builder.CreateStructGEP(Target, 0);
5160 Target = CGF.Builder.CreateLoad(Target);
5161 }
5162 else
5163 Target = EmitMetaClassRef(CGF.Builder, Class);
5164 }
5165 else
5166 Target = EmitClassRef(CGF.Builder, Class, true);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005167
5168 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
5169 // and ObjCTypes types.
5170 const llvm::Type *ClassTy =
5171 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
5172 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
5173 CGF.Builder.CreateStore(Target,
5174 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
5175
5176 return EmitMessageSend(CGF, ResultType, Sel,
5177 ObjCSuper, ObjCTypes.SuperPtrCTy,
5178 true, CallArgs);
5179}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005180
5181llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CGBuilderTy &Builder,
5182 Selector Sel) {
5183 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
5184
5185 if (!Entry) {
5186 llvm::Constant *Casted =
5187 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
5188 ObjCTypes.SelectorPtrTy);
5189 Entry =
5190 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
5191 llvm::GlobalValue::InternalLinkage,
5192 Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
5193 &CGM.getModule());
5194 Entry->setSection("__DATA,__objc_selrefs,literal_pointers,no_dead_strip");
5195 UsedGlobals.push_back(Entry);
5196 }
5197
5198 return Builder.CreateLoad(Entry, false, "tmp");
5199}
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005200/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
5201/// objc_assign_ivar (id src, id *dst)
5202///
5203void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
5204 llvm::Value *src, llvm::Value *dst)
5205{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005206 const llvm::Type * SrcTy = src->getType();
5207 if (!isa<llvm::PointerType>(SrcTy)) {
5208 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5209 assert(Size <= 8 && "does not support size > 8");
5210 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5211 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005212 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5213 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005214 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5215 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5216 CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn,
5217 src, dst, "assignivar");
5218 return;
5219}
5220
5221/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
5222/// objc_assign_strongCast (id src, id *dst)
5223///
5224void CGObjCNonFragileABIMac::EmitObjCStrongCastAssign(
5225 CodeGen::CodeGenFunction &CGF,
5226 llvm::Value *src, llvm::Value *dst)
5227{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005228 const llvm::Type * SrcTy = src->getType();
5229 if (!isa<llvm::PointerType>(SrcTy)) {
5230 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5231 assert(Size <= 8 && "does not support size > 8");
5232 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5233 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005234 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5235 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005236 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5237 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5238 CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn,
5239 src, dst, "weakassign");
5240 return;
5241}
5242
5243/// EmitObjCWeakRead - Code gen for loading value of a __weak
5244/// object: objc_read_weak (id *src)
5245///
5246llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead(
5247 CodeGen::CodeGenFunction &CGF,
5248 llvm::Value *AddrWeakObj)
5249{
Eli Friedman8339b352009-03-07 03:57:15 +00005250 const llvm::Type* DestTy =
5251 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005252 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
5253 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
5254 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00005255 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005256 return read_weak;
5257}
5258
5259/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
5260/// objc_assign_weak (id src, id *dst)
5261///
5262void CGObjCNonFragileABIMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
5263 llvm::Value *src, llvm::Value *dst)
5264{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005265 const llvm::Type * SrcTy = src->getType();
5266 if (!isa<llvm::PointerType>(SrcTy)) {
5267 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5268 assert(Size <= 8 && "does not support size > 8");
5269 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5270 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005271 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5272 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005273 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5274 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5275 CGF.Builder.CreateCall2(ObjCTypes.GcAssignWeakFn,
5276 src, dst, "weakassign");
5277 return;
5278}
5279
5280/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
5281/// objc_assign_global (id src, id *dst)
5282///
5283void CGObjCNonFragileABIMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
5284 llvm::Value *src, llvm::Value *dst)
5285{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005286 const llvm::Type * SrcTy = src->getType();
5287 if (!isa<llvm::PointerType>(SrcTy)) {
5288 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5289 assert(Size <= 8 && "does not support size > 8");
5290 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5291 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005292 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5293 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005294 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5295 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5296 CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn,
5297 src, dst, "globalassign");
5298 return;
5299}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005300
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005301void
5302CGObjCNonFragileABIMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
5303 const Stmt &S) {
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005304 bool isTry = isa<ObjCAtTryStmt>(S);
5305 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
5306 llvm::BasicBlock *PrevLandingPad = CGF.getInvokeDest();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005307 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005308 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005309 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005310 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
5311
5312 // For @synchronized, call objc_sync_enter(sync.expr). The
5313 // evaluation of the expression must occur before we enter the
5314 // @synchronized. We can safely avoid a temp here because jumps into
5315 // @synchronized are illegal & this will dominate uses.
5316 llvm::Value *SyncArg = 0;
5317 if (!isTry) {
5318 SyncArg =
5319 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
5320 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005321 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005322 }
5323
5324 // Push an EH context entry, used for handling rethrows and jumps
5325 // through finally.
5326 CGF.PushCleanupBlock(FinallyBlock);
5327
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005328 CGF.setInvokeDest(TryHandler);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005329
5330 CGF.EmitBlock(TryBlock);
5331 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
5332 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
5333 CGF.EmitBranchThroughCleanup(FinallyEnd);
5334
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005335 // Emit the exception handler.
5336
5337 CGF.EmitBlock(TryHandler);
5338
5339 llvm::Value *llvm_eh_exception =
5340 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_exception);
5341 llvm::Value *llvm_eh_selector_i64 =
5342 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector_i64);
5343 llvm::Value *llvm_eh_typeid_for_i64 =
5344 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for_i64);
5345 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5346 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(Exc->getType(), "_rethrow");
5347
5348 llvm::SmallVector<llvm::Value*, 8> SelectorArgs;
5349 SelectorArgs.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005350 SelectorArgs.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005351
5352 // Construct the lists of (type, catch body) to handle.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005353 llvm::SmallVector<std::pair<const ParmVarDecl*, const Stmt*>, 8> Handlers;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005354 bool HasCatchAll = false;
5355 if (isTry) {
5356 if (const ObjCAtCatchStmt* CatchStmt =
5357 cast<ObjCAtTryStmt>(S).getCatchStmts()) {
5358 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005359 const ParmVarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
Steve Naroff7ba138a2009-03-03 19:52:17 +00005360 Handlers.push_back(std::make_pair(CatchDecl, CatchStmt->getCatchBody()));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005361
5362 // catch(...) always matches.
Steve Naroff7ba138a2009-03-03 19:52:17 +00005363 if (!CatchDecl) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005364 // Use i8* null here to signal this is a catch all, not a cleanup.
5365 llvm::Value *Null = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
5366 SelectorArgs.push_back(Null);
5367 HasCatchAll = true;
5368 break;
5369 }
5370
Daniel Dunbarede8de92009-03-06 00:01:21 +00005371 if (CGF.getContext().isObjCIdType(CatchDecl->getType()) ||
5372 CatchDecl->getType()->isObjCQualifiedIdType()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005373 llvm::Value *IDEHType =
5374 CGM.getModule().getGlobalVariable("OBJC_EHTYPE_id");
5375 if (!IDEHType)
5376 IDEHType =
5377 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5378 llvm::GlobalValue::ExternalLinkage,
5379 0, "OBJC_EHTYPE_id", &CGM.getModule());
5380 SelectorArgs.push_back(IDEHType);
5381 HasCatchAll = true;
5382 break;
5383 }
5384
5385 // All other types should be Objective-C interface pointer types.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005386 const PointerType *PT = CatchDecl->getType()->getAsPointerType();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005387 assert(PT && "Invalid @catch type.");
5388 const ObjCInterfaceType *IT =
5389 PT->getPointeeType()->getAsObjCInterfaceType();
5390 assert(IT && "Invalid @catch type.");
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005391 llvm::Value *EHType = GetInterfaceEHType(IT->getDecl(), false);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005392 SelectorArgs.push_back(EHType);
5393 }
5394 }
5395 }
5396
5397 // We use a cleanup unless there was already a catch all.
5398 if (!HasCatchAll) {
5399 SelectorArgs.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
Daniel Dunbarede8de92009-03-06 00:01:21 +00005400 Handlers.push_back(std::make_pair((const ParmVarDecl*) 0, (const Stmt*) 0));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005401 }
5402
5403 llvm::Value *Selector =
5404 CGF.Builder.CreateCall(llvm_eh_selector_i64,
5405 SelectorArgs.begin(), SelectorArgs.end(),
5406 "selector");
5407 for (unsigned i = 0, e = Handlers.size(); i != e; ++i) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005408 const ParmVarDecl *CatchParam = Handlers[i].first;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005409 const Stmt *CatchBody = Handlers[i].second;
5410
5411 llvm::BasicBlock *Next = 0;
5412
5413 // The last handler always matches.
5414 if (i + 1 != e) {
5415 assert(CatchParam && "Only last handler can be a catch all.");
5416
5417 llvm::BasicBlock *Match = CGF.createBasicBlock("match");
5418 Next = CGF.createBasicBlock("catch.next");
5419 llvm::Value *Id =
5420 CGF.Builder.CreateCall(llvm_eh_typeid_for_i64,
5421 CGF.Builder.CreateBitCast(SelectorArgs[i+2],
5422 ObjCTypes.Int8PtrTy));
5423 CGF.Builder.CreateCondBr(CGF.Builder.CreateICmpEQ(Selector, Id),
5424 Match, Next);
5425
5426 CGF.EmitBlock(Match);
5427 }
5428
5429 if (CatchBody) {
5430 llvm::BasicBlock *MatchEnd = CGF.createBasicBlock("match.end");
5431 llvm::BasicBlock *MatchHandler = CGF.createBasicBlock("match.handler");
5432
5433 // Cleanups must call objc_end_catch.
5434 //
5435 // FIXME: It seems incorrect for objc_begin_catch to be inside
5436 // this context, but this matches gcc.
5437 CGF.PushCleanupBlock(MatchEnd);
5438 CGF.setInvokeDest(MatchHandler);
5439
5440 llvm::Value *ExcObject =
5441 CGF.Builder.CreateCall(ObjCTypes.ObjCBeginCatchFn, Exc);
5442
5443 // Bind the catch parameter if it exists.
5444 if (CatchParam) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005445 ExcObject =
5446 CGF.Builder.CreateBitCast(ExcObject,
5447 CGF.ConvertType(CatchParam->getType()));
5448 // CatchParam is a ParmVarDecl because of the grammar
5449 // construction used to handle this, but for codegen purposes
5450 // we treat this as a local decl.
5451 CGF.EmitLocalBlockVarDecl(*CatchParam);
5452 CGF.Builder.CreateStore(ExcObject, CGF.GetAddrOfLocalVar(CatchParam));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005453 }
5454
5455 CGF.ObjCEHValueStack.push_back(ExcObject);
5456 CGF.EmitStmt(CatchBody);
5457 CGF.ObjCEHValueStack.pop_back();
5458
5459 CGF.EmitBranchThroughCleanup(FinallyEnd);
5460
5461 CGF.EmitBlock(MatchHandler);
5462
5463 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5464 // We are required to emit this call to satisfy LLVM, even
5465 // though we don't use the result.
5466 llvm::SmallVector<llvm::Value*, 8> Args;
5467 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005468 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005469 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5470 0));
5471 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5472 CGF.Builder.CreateStore(Exc, RethrowPtr);
5473 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5474
5475 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5476
5477 CGF.EmitBlock(MatchEnd);
5478
5479 // Unfortunately, we also have to generate another EH frame here
5480 // in case this throws.
5481 llvm::BasicBlock *MatchEndHandler =
5482 CGF.createBasicBlock("match.end.handler");
5483 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
5484 CGF.Builder.CreateInvoke(ObjCTypes.ObjCEndCatchFn,
5485 Cont, MatchEndHandler,
5486 Args.begin(), Args.begin());
5487
5488 CGF.EmitBlock(Cont);
5489 if (Info.SwitchBlock)
5490 CGF.EmitBlock(Info.SwitchBlock);
5491 if (Info.EndBlock)
5492 CGF.EmitBlock(Info.EndBlock);
5493
5494 CGF.EmitBlock(MatchEndHandler);
5495 Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5496 // We are required to emit this call to satisfy LLVM, even
5497 // though we don't use the result.
5498 Args.clear();
5499 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005500 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005501 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5502 0));
5503 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5504 CGF.Builder.CreateStore(Exc, RethrowPtr);
5505 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5506
5507 if (Next)
5508 CGF.EmitBlock(Next);
5509 } else {
5510 assert(!Next && "catchup should be last handler.");
5511
5512 CGF.Builder.CreateStore(Exc, RethrowPtr);
5513 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5514 }
5515 }
5516
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005517 // Pop the cleanup entry, the @finally is outside this cleanup
5518 // scope.
5519 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5520 CGF.setInvokeDest(PrevLandingPad);
5521
5522 CGF.EmitBlock(FinallyBlock);
5523
5524 if (isTry) {
5525 if (const ObjCAtFinallyStmt* FinallyStmt =
5526 cast<ObjCAtTryStmt>(S).getFinallyStmt())
5527 CGF.EmitStmt(FinallyStmt->getFinallyBody());
5528 } else {
5529 // Emit 'objc_sync_exit(expr)' as finally's sole statement for
5530 // @synchronized.
5531 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, SyncArg);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005532 }
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005533
5534 if (Info.SwitchBlock)
5535 CGF.EmitBlock(Info.SwitchBlock);
5536 if (Info.EndBlock)
5537 CGF.EmitBlock(Info.EndBlock);
5538
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005539 // Branch around the rethrow code.
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005540 CGF.EmitBranch(FinallyEnd);
5541
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005542 CGF.EmitBlock(FinallyRethrow);
5543 CGF.Builder.CreateCall(ObjCTypes.UnwindResumeOrRethrowFn,
5544 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005545 CGF.Builder.CreateUnreachable();
5546
5547 CGF.EmitBlock(FinallyEnd);
5548}
5549
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005550/// EmitThrowStmt - Generate code for a throw statement.
5551void CGObjCNonFragileABIMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
5552 const ObjCAtThrowStmt &S) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005553 llvm::Value *Exception;
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005554 if (const Expr *ThrowExpr = S.getThrowExpr()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005555 Exception = CGF.EmitScalarExpr(ThrowExpr);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005556 } else {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005557 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
5558 "Unexpected rethrow outside @catch block.");
5559 Exception = CGF.ObjCEHValueStack.back();
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005560 }
5561
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005562 llvm::Value *ExceptionAsObject =
5563 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
5564 llvm::BasicBlock *InvokeDest = CGF.getInvokeDest();
5565 if (InvokeDest) {
5566 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
5567 CGF.Builder.CreateInvoke(ObjCTypes.ExceptionThrowFn,
5568 Cont, InvokeDest,
5569 &ExceptionAsObject, &ExceptionAsObject + 1);
5570 CGF.EmitBlock(Cont);
5571 } else
5572 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
5573 CGF.Builder.CreateUnreachable();
5574
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005575 // Clear the insertion point to indicate we are in unreachable code.
5576 CGF.Builder.ClearInsertionPoint();
5577}
Daniel Dunbare588b992009-03-01 04:46:24 +00005578
5579llvm::Value *
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005580CGObjCNonFragileABIMac::GetInterfaceEHType(const ObjCInterfaceDecl *ID,
5581 bool ForDefinition) {
Daniel Dunbare588b992009-03-01 04:46:24 +00005582 llvm::GlobalVariable * &Entry = EHTypeReferences[ID->getIdentifier()];
Daniel Dunbare588b992009-03-01 04:46:24 +00005583
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005584 // If we don't need a definition, return the entry if found or check
5585 // if we use an external reference.
5586 if (!ForDefinition) {
5587 if (Entry)
5588 return Entry;
Daniel Dunbar7e075cb2009-04-07 06:43:45 +00005589
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005590 // If this type (or a super class) has the __objc_exception__
5591 // attribute, emit an external reference.
5592 if (hasObjCExceptionAttribute(ID))
5593 return Entry =
5594 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5595 llvm::GlobalValue::ExternalLinkage,
5596 0,
5597 (std::string("OBJC_EHTYPE_$_") +
5598 ID->getIdentifier()->getName()),
5599 &CGM.getModule());
5600 }
5601
5602 // Otherwise we need to either make a new entry or fill in the
5603 // initializer.
5604 assert((!Entry || !Entry->hasInitializer()) && "Duplicate EHType definition");
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005605 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbare588b992009-03-01 04:46:24 +00005606 std::string VTableName = "objc_ehtype_vtable";
5607 llvm::GlobalVariable *VTableGV =
5608 CGM.getModule().getGlobalVariable(VTableName);
5609 if (!VTableGV)
5610 VTableGV = new llvm::GlobalVariable(ObjCTypes.Int8PtrTy, false,
5611 llvm::GlobalValue::ExternalLinkage,
5612 0, VTableName, &CGM.getModule());
5613
5614 llvm::Value *VTableIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, 2);
5615
5616 std::vector<llvm::Constant*> Values(3);
5617 Values[0] = llvm::ConstantExpr::getGetElementPtr(VTableGV, &VTableIdx, 1);
5618 Values[1] = GetClassName(ID->getIdentifier());
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005619 Values[2] = GetClassGlobal(ClassName, false);
Daniel Dunbare588b992009-03-01 04:46:24 +00005620 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.EHTypeTy, Values);
5621
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005622 if (Entry) {
5623 Entry->setInitializer(Init);
5624 } else {
5625 Entry = new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5626 llvm::GlobalValue::WeakAnyLinkage,
5627 Init,
5628 (std::string("OBJC_EHTYPE_$_") +
5629 ID->getIdentifier()->getName()),
5630 &CGM.getModule());
5631 }
5632
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005633 if (CGM.getLangOptions().getVisibilityMode() ==
5634 LangOptions::HiddenVisibility)
5635 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005636 Entry->setAlignment(8);
5637
5638 if (ForDefinition) {
5639 Entry->setSection("__DATA,__objc_const");
5640 Entry->setLinkage(llvm::GlobalValue::ExternalLinkage);
5641 } else {
5642 Entry->setSection("__DATA,__datacoal_nt,coalesced");
5643 }
Daniel Dunbare588b992009-03-01 04:46:24 +00005644
5645 return Entry;
5646}
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005647
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00005648/* *** */
5649
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00005650CodeGen::CGObjCRuntime *
5651CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00005652 return new CGObjCMac(CGM);
5653}
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005654
5655CodeGen::CGObjCRuntime *
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00005656CodeGen::CreateMacNonFragileABIObjCRuntime(CodeGen::CodeGenModule &CGM) {
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00005657 return new CGObjCNonFragileABIMac(CGM);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005658}