blob: e1b14913cd85ed30646a327ffcdba7b3959ef596 [file] [log] [blame]
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001//===------- CGObjCMac.cpp - Interface to Apple Objective-C Runtime -------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This provides Objective-C code generation targetting the Apple runtime.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CGObjCRuntime.h"
Daniel Dunbarf77ac862008-08-11 21:35:06 +000015
16#include "CodeGenModule.h"
Daniel Dunbarb7ec2462008-08-16 03:19:19 +000017#include "CodeGenFunction.h"
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000018#include "clang/AST/ASTContext.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000019#include "clang/AST/Decl.h"
Daniel Dunbar6efc0c52008-08-13 03:21:16 +000020#include "clang/AST/DeclObjC.h"
Daniel Dunbarf77ac862008-08-11 21:35:06 +000021#include "clang/Basic/LangOptions.h"
22
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +000023#include "llvm/Intrinsics.h"
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000024#include "llvm/Module.h"
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +000025#include "llvm/ADT/DenseSet.h"
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +000026#include "llvm/Target/TargetData.h"
Daniel Dunbarb7ec2462008-08-16 03:19:19 +000027#include <sstream>
Daniel Dunbarc17a4d32008-08-11 02:45:11 +000028
29using namespace clang;
Daniel Dunbar46f45b92008-09-09 01:06:48 +000030using namespace CodeGen;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +000031
32namespace {
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000033
Daniel Dunbarae226fa2008-08-27 02:31:56 +000034 typedef std::vector<llvm::Constant*> ConstantVector;
35
Daniel Dunbar6efc0c52008-08-13 03:21:16 +000036 // FIXME: We should find a nicer way to make the labels for
37 // metadata, string concatenation is lame.
38
Fariborz Jahanianee0af742009-01-21 22:04:16 +000039class ObjCCommonTypesHelper {
40protected:
41 CodeGen::CodeGenModule &CGM;
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000042
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000043public:
Fariborz Jahanian0a855d02009-03-23 19:10:40 +000044 const llvm::Type *ShortTy, *IntTy, *LongTy, *LongLongTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +000045 const llvm::Type *Int8PtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +000046
Daniel Dunbar2bedbf82008-08-12 05:28:47 +000047 /// ObjectPtrTy - LLVM type for object handles (typeof(id))
48 const llvm::Type *ObjectPtrTy;
Fariborz Jahanian6d657c42008-11-18 20:18:11 +000049
50 /// PtrObjectPtrTy - LLVM type for id *
51 const llvm::Type *PtrObjectPtrTy;
52
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +000053 /// SelectorPtrTy - LLVM type for selector handles (typeof(SEL))
Daniel Dunbar2bedbf82008-08-12 05:28:47 +000054 const llvm::Type *SelectorPtrTy;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +000055 /// ProtocolPtrTy - LLVM type for external protocol handles
56 /// (typeof(Protocol))
57 const llvm::Type *ExternalProtocolPtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +000058
Daniel Dunbar19cd87e2008-08-30 03:02:31 +000059 // SuperCTy - clang type for struct objc_super.
60 QualType SuperCTy;
61 // SuperPtrCTy - clang type for struct objc_super *.
62 QualType SuperPtrCTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +000063
Daniel Dunbare8b470d2008-08-23 04:28:29 +000064 /// SuperTy - LLVM type for struct objc_super.
65 const llvm::StructType *SuperTy;
Daniel Dunbar14c80b72008-08-23 09:25:55 +000066 /// SuperPtrTy - LLVM type for struct objc_super *.
67 const llvm::Type *SuperPtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +000068
Fariborz Jahanian30bc5712009-01-22 23:02:58 +000069 /// PropertyTy - LLVM type for struct objc_property (struct _prop_t
70 /// in GCC parlance).
71 const llvm::StructType *PropertyTy;
72
73 /// PropertyListTy - LLVM type for struct objc_property_list
74 /// (_prop_list_t in GCC parlance).
75 const llvm::StructType *PropertyListTy;
76 /// PropertyListPtrTy - LLVM type for struct objc_property_list*.
77 const llvm::Type *PropertyListPtrTy;
78
79 // MethodTy - LLVM type for struct objc_method.
80 const llvm::StructType *MethodTy;
81
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +000082 /// CacheTy - LLVM type for struct objc_cache.
83 const llvm::Type *CacheTy;
84 /// CachePtrTy - LLVM type for struct objc_cache *.
85 const llvm::Type *CachePtrTy;
86
Chris Lattner74391b42009-03-22 21:03:39 +000087 llvm::Constant *GetPropertyFn, *SetPropertyFn;
Fariborz Jahaniandb286862009-01-22 00:37:21 +000088
Chris Lattner74391b42009-03-22 21:03:39 +000089 llvm::Constant *EnumerationMutationFn;
Fariborz Jahaniandb286862009-01-22 00:37:21 +000090
91 /// GcReadWeakFn -- LLVM objc_read_weak (id *src) function.
Chris Lattner74391b42009-03-22 21:03:39 +000092 llvm::Constant *GcReadWeakFn;
Fariborz Jahaniandb286862009-01-22 00:37:21 +000093
94 /// GcAssignWeakFn -- LLVM objc_assign_weak function.
Chris Lattner74391b42009-03-22 21:03:39 +000095 llvm::Constant *GcAssignWeakFn;
Fariborz Jahaniandb286862009-01-22 00:37:21 +000096
97 /// GcAssignGlobalFn -- LLVM objc_assign_global function.
Chris Lattner74391b42009-03-22 21:03:39 +000098 llvm::Constant *GcAssignGlobalFn;
Fariborz Jahaniandb286862009-01-22 00:37:21 +000099
100 /// GcAssignIvarFn -- LLVM objc_assign_ivar function.
Chris Lattner74391b42009-03-22 21:03:39 +0000101 llvm::Constant *GcAssignIvarFn;
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000102
103 /// GcAssignStrongCastFn -- LLVM objc_assign_strongCast function.
Chris Lattner74391b42009-03-22 21:03:39 +0000104 llvm::Constant *GcAssignStrongCastFn;
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000105
106 /// ExceptionThrowFn - LLVM objc_exception_throw function.
Chris Lattner74391b42009-03-22 21:03:39 +0000107 llvm::Constant *ExceptionThrowFn;
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000108
Daniel Dunbar1c566672009-02-24 01:43:46 +0000109 /// SyncEnterFn - LLVM object_sync_enter function.
Chris Lattnerb02e53b2009-04-06 16:53:45 +0000110 llvm::Constant *getSyncEnterFn() {
111 // void objc_sync_enter (id)
112 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
113 llvm::FunctionType *FTy =
114 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
115 return CGM.CreateRuntimeFunction(FTy, "objc_sync_enter");
116 }
Daniel Dunbar1c566672009-02-24 01:43:46 +0000117
118 /// SyncExitFn - LLVM object_sync_exit function.
Chris Lattner74391b42009-03-22 21:03:39 +0000119 llvm::Constant *SyncExitFn;
Daniel Dunbar1c566672009-02-24 01:43:46 +0000120
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000121 ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm);
122 ~ObjCCommonTypesHelper(){}
123};
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000124
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000125/// ObjCTypesHelper - Helper class that encapsulates lazy
126/// construction of varies types used during ObjC generation.
127class ObjCTypesHelper : public ObjCCommonTypesHelper {
128private:
129
Chris Lattner74391b42009-03-22 21:03:39 +0000130 llvm::Constant *MessageSendFn, *MessageSendStretFn, *MessageSendFpretFn;
131 llvm::Constant *MessageSendSuperFn, *MessageSendSuperStretFn,
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000132 *MessageSendSuperFpretFn;
133
134public:
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000135 /// SymtabTy - LLVM type for struct objc_symtab.
136 const llvm::StructType *SymtabTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000137 /// SymtabPtrTy - LLVM type for struct objc_symtab *.
138 const llvm::Type *SymtabPtrTy;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000139 /// ModuleTy - LLVM type for struct objc_module.
140 const llvm::StructType *ModuleTy;
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000141
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000142 /// ProtocolTy - LLVM type for struct objc_protocol.
143 const llvm::StructType *ProtocolTy;
144 /// ProtocolPtrTy - LLVM type for struct objc_protocol *.
145 const llvm::Type *ProtocolPtrTy;
146 /// ProtocolExtensionTy - LLVM type for struct
147 /// objc_protocol_extension.
148 const llvm::StructType *ProtocolExtensionTy;
149 /// ProtocolExtensionTy - LLVM type for struct
150 /// objc_protocol_extension *.
151 const llvm::Type *ProtocolExtensionPtrTy;
152 /// MethodDescriptionTy - LLVM type for struct
153 /// objc_method_description.
154 const llvm::StructType *MethodDescriptionTy;
155 /// MethodDescriptionListTy - LLVM type for struct
156 /// objc_method_description_list.
157 const llvm::StructType *MethodDescriptionListTy;
158 /// MethodDescriptionListPtrTy - LLVM type for struct
159 /// objc_method_description_list *.
160 const llvm::Type *MethodDescriptionListPtrTy;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000161 /// ProtocolListTy - LLVM type for struct objc_property_list.
162 const llvm::Type *ProtocolListTy;
163 /// ProtocolListPtrTy - LLVM type for struct objc_property_list*.
164 const llvm::Type *ProtocolListPtrTy;
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000165 /// CategoryTy - LLVM type for struct objc_category.
166 const llvm::StructType *CategoryTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000167 /// ClassTy - LLVM type for struct objc_class.
168 const llvm::StructType *ClassTy;
169 /// ClassPtrTy - LLVM type for struct objc_class *.
170 const llvm::Type *ClassPtrTy;
171 /// ClassExtensionTy - LLVM type for struct objc_class_ext.
172 const llvm::StructType *ClassExtensionTy;
173 /// ClassExtensionPtrTy - LLVM type for struct objc_class_ext *.
174 const llvm::Type *ClassExtensionPtrTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000175 // IvarTy - LLVM type for struct objc_ivar.
176 const llvm::StructType *IvarTy;
177 /// IvarListTy - LLVM type for struct objc_ivar_list.
178 const llvm::Type *IvarListTy;
179 /// IvarListPtrTy - LLVM type for struct objc_ivar_list *.
180 const llvm::Type *IvarListPtrTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000181 /// MethodListTy - LLVM type for struct objc_method_list.
182 const llvm::Type *MethodListTy;
183 /// MethodListPtrTy - LLVM type for struct objc_method_list *.
184 const llvm::Type *MethodListPtrTy;
Anders Carlsson124526b2008-09-09 10:10:21 +0000185
186 /// ExceptionDataTy - LLVM type for struct _objc_exception_data.
187 const llvm::Type *ExceptionDataTy;
188
Anders Carlsson124526b2008-09-09 10:10:21 +0000189 /// ExceptionTryEnterFn - LLVM objc_exception_try_enter function.
Chris Lattner74391b42009-03-22 21:03:39 +0000190 llvm::Constant *ExceptionTryEnterFn;
Anders Carlsson124526b2008-09-09 10:10:21 +0000191
192 /// ExceptionTryExitFn - LLVM objc_exception_try_exit function.
Chris Lattner74391b42009-03-22 21:03:39 +0000193 llvm::Constant *ExceptionTryExitFn;
Anders Carlsson124526b2008-09-09 10:10:21 +0000194
195 /// ExceptionExtractFn - LLVM objc_exception_extract function.
Chris Lattner74391b42009-03-22 21:03:39 +0000196 llvm::Constant *ExceptionExtractFn;
Anders Carlsson124526b2008-09-09 10:10:21 +0000197
198 /// ExceptionMatchFn - LLVM objc_exception_match function.
Chris Lattner74391b42009-03-22 21:03:39 +0000199 llvm::Constant *ExceptionMatchFn;
Anders Carlsson124526b2008-09-09 10:10:21 +0000200
201 /// SetJmpFn - LLVM _setjmp function.
Chris Lattner74391b42009-03-22 21:03:39 +0000202 llvm::Constant *SetJmpFn;
Chris Lattner10cac6f2008-11-15 21:26:17 +0000203
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000204public:
205 ObjCTypesHelper(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000206 ~ObjCTypesHelper() {}
Daniel Dunbar5669e572008-10-17 03:24:53 +0000207
208
Chris Lattner74391b42009-03-22 21:03:39 +0000209 llvm::Constant *getSendFn(bool IsSuper) {
Daniel Dunbar5669e572008-10-17 03:24:53 +0000210 return IsSuper ? MessageSendSuperFn : MessageSendFn;
211 }
212
Chris Lattner74391b42009-03-22 21:03:39 +0000213 llvm::Constant *getSendStretFn(bool IsSuper) {
Daniel Dunbar5669e572008-10-17 03:24:53 +0000214 return IsSuper ? MessageSendSuperStretFn : MessageSendStretFn;
215 }
216
Chris Lattner74391b42009-03-22 21:03:39 +0000217 llvm::Constant *getSendFpretFn(bool IsSuper) {
Daniel Dunbar5669e572008-10-17 03:24:53 +0000218 return IsSuper ? MessageSendSuperFpretFn : MessageSendFpretFn;
219 }
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000220};
221
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000222/// ObjCNonFragileABITypesHelper - will have all types needed by objective-c's
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000223/// modern abi
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000224class ObjCNonFragileABITypesHelper : public ObjCCommonTypesHelper {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000225public:
Chris Lattner74391b42009-03-22 21:03:39 +0000226 llvm::Constant *MessageSendFixupFn, *MessageSendFpretFixupFn,
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000227 *MessageSendStretFixupFn, *MessageSendIdFixupFn,
228 *MessageSendIdStretFixupFn, *MessageSendSuper2FixupFn,
229 *MessageSendSuper2StretFixupFn;
230
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000231 // MethodListnfABITy - LLVM for struct _method_list_t
232 const llvm::StructType *MethodListnfABITy;
233
234 // MethodListnfABIPtrTy - LLVM for struct _method_list_t*
235 const llvm::Type *MethodListnfABIPtrTy;
236
237 // ProtocolnfABITy = LLVM for struct _protocol_t
238 const llvm::StructType *ProtocolnfABITy;
239
Daniel Dunbar948e2582009-02-15 07:36:20 +0000240 // ProtocolnfABIPtrTy = LLVM for struct _protocol_t*
241 const llvm::Type *ProtocolnfABIPtrTy;
242
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000243 // ProtocolListnfABITy - LLVM for struct _objc_protocol_list
244 const llvm::StructType *ProtocolListnfABITy;
245
246 // ProtocolListnfABIPtrTy - LLVM for struct _objc_protocol_list*
247 const llvm::Type *ProtocolListnfABIPtrTy;
248
249 // ClassnfABITy - LLVM for struct _class_t
250 const llvm::StructType *ClassnfABITy;
251
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000252 // ClassnfABIPtrTy - LLVM for struct _class_t*
253 const llvm::Type *ClassnfABIPtrTy;
254
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000255 // IvarnfABITy - LLVM for struct _ivar_t
256 const llvm::StructType *IvarnfABITy;
257
258 // IvarListnfABITy - LLVM for struct _ivar_list_t
259 const llvm::StructType *IvarListnfABITy;
260
261 // IvarListnfABIPtrTy = LLVM for struct _ivar_list_t*
262 const llvm::Type *IvarListnfABIPtrTy;
263
264 // ClassRonfABITy - LLVM for struct _class_ro_t
265 const llvm::StructType *ClassRonfABITy;
266
267 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
268 const llvm::Type *ImpnfABITy;
269
270 // CategorynfABITy - LLVM for struct _category_t
271 const llvm::StructType *CategorynfABITy;
272
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000273 // New types for nonfragile abi messaging.
274
275 // MessageRefTy - LLVM for:
276 // struct _message_ref_t {
277 // IMP messenger;
278 // SEL name;
279 // };
280 const llvm::StructType *MessageRefTy;
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000281 // MessageRefCTy - clang type for struct _message_ref_t
282 QualType MessageRefCTy;
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000283
284 // MessageRefPtrTy - LLVM for struct _message_ref_t*
285 const llvm::Type *MessageRefPtrTy;
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000286 // MessageRefCPtrTy - clang type for struct _message_ref_t*
287 QualType MessageRefCPtrTy;
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000288
Fariborz Jahanianef163782009-02-05 01:13:09 +0000289 // MessengerTy - Type of the messenger (shown as IMP above)
290 const llvm::FunctionType *MessengerTy;
291
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000292 // SuperMessageRefTy - LLVM for:
293 // struct _super_message_ref_t {
294 // SUPER_IMP messenger;
295 // SEL name;
296 // };
297 const llvm::StructType *SuperMessageRefTy;
298
299 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
300 const llvm::Type *SuperMessageRefPtrTy;
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000301
302 /// EHPersonalityPtr - LLVM value for an i8* to the Objective-C
303 /// exception personality function.
Chris Lattnerb02e53b2009-04-06 16:53:45 +0000304 llvm::Value *getEHPersonalityPtr() {
305 llvm::Constant *Personality =
306 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
307 std::vector<const llvm::Type*>(),
308 true),
309 "__objc_personality_v0");
310 return llvm::ConstantExpr::getBitCast(Personality, Int8PtrTy);
311 }
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000312
Chris Lattner74391b42009-03-22 21:03:39 +0000313 llvm::Constant *UnwindResumeOrRethrowFn, *ObjCBeginCatchFn, *ObjCEndCatchFn;
Daniel Dunbare588b992009-03-01 04:46:24 +0000314
315 const llvm::StructType *EHTypeTy;
316 const llvm::Type *EHTypePtrTy;
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000317
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000318 ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm);
319 ~ObjCNonFragileABITypesHelper(){}
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000320};
321
322class CGObjCCommonMac : public CodeGen::CGObjCRuntime {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000323public:
324 // FIXME - accessibility
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000325 class GC_IVAR {
Fariborz Jahanian820e0202009-03-11 00:07:04 +0000326 public:
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000327 unsigned int ivar_bytepos;
328 unsigned int ivar_size;
329 GC_IVAR() : ivar_bytepos(0), ivar_size(0) {}
330 };
331
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000332 class SKIP_SCAN {
333 public:
334 unsigned int skip;
335 unsigned int scan;
336 SKIP_SCAN() : skip(0), scan(0) {}
337 };
338
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000339protected:
340 CodeGen::CodeGenModule &CGM;
341 // FIXME! May not be needing this after all.
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000342 unsigned ObjCABI;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000343
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000344 // gc ivar layout bitmap calculation helper caches.
345 llvm::SmallVector<GC_IVAR, 16> SkipIvars;
346 llvm::SmallVector<GC_IVAR, 16> IvarsInfo;
347 llvm::SmallVector<SKIP_SCAN, 32> SkipScanIvars;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000348
Daniel Dunbar242d4dc2008-08-25 06:02:07 +0000349 /// LazySymbols - Symbols to generate a lazy reference for. See
350 /// DefinedSymbols and FinishModule().
351 std::set<IdentifierInfo*> LazySymbols;
352
353 /// DefinedSymbols - External symbols which are defined by this
354 /// module. The symbols in this list and LazySymbols are used to add
355 /// special linker symbols which ensure that Objective-C modules are
356 /// linked properly.
357 std::set<IdentifierInfo*> DefinedSymbols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000358
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000359 /// ClassNames - uniqued class names.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000360 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000361
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000362 /// MethodVarNames - uniqued method variable names.
363 llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000364
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000365 /// MethodVarTypes - uniqued method type signatures. We have to use
366 /// a StringMap here because have no other unique reference.
367 llvm::StringMap<llvm::GlobalVariable*> MethodVarTypes;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000368
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000369 /// MethodDefinitions - map of methods which have been defined in
370 /// this translation unit.
371 llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> MethodDefinitions;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000372
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000373 /// PropertyNames - uniqued method variable names.
374 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000375
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000376 /// ClassReferences - uniqued class references.
377 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000378
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000379 /// SelectorReferences - uniqued selector references.
380 llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000381
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000382 /// Protocols - Protocols for which an objc_protocol structure has
383 /// been emitted. Forward declarations are handled by creating an
384 /// empty structure whose initializer is filled in when/if defined.
385 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> Protocols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000386
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000387 /// DefinedProtocols - Protocols which have actually been
388 /// defined. We should not need this, see FIXME in GenerateProtocol.
389 llvm::DenseSet<IdentifierInfo*> DefinedProtocols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000390
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000391 /// DefinedClasses - List of defined classes.
392 std::vector<llvm::GlobalValue*> DefinedClasses;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000393
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000394 /// DefinedCategories - List of defined categories.
395 std::vector<llvm::GlobalValue*> DefinedCategories;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000396
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000397 /// UsedGlobals - List of globals to pack into the llvm.used metadata
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000398 /// to prevent them from being clobbered.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000399 std::vector<llvm::GlobalVariable*> UsedGlobals;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000400
Fariborz Jahanian56210f72009-01-21 23:34:32 +0000401 /// GetNameForMethod - Return a name for the given method.
402 /// \param[out] NameOut - The return value.
403 void GetNameForMethod(const ObjCMethodDecl *OMD,
404 const ObjCContainerDecl *CD,
405 std::string &NameOut);
406
407 /// GetMethodVarName - Return a unique constant for the given
408 /// selector's name. The return value has type char *.
409 llvm::Constant *GetMethodVarName(Selector Sel);
410 llvm::Constant *GetMethodVarName(IdentifierInfo *Ident);
411 llvm::Constant *GetMethodVarName(const std::string &Name);
412
413 /// GetMethodVarType - Return a unique constant for the given
414 /// selector's name. The return value has type char *.
415
416 // FIXME: This is a horrible name.
417 llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D);
Devang Patel7794bb82009-03-04 18:21:39 +0000418 llvm::Constant *GetMethodVarType(FieldDecl *D);
Fariborz Jahanian56210f72009-01-21 23:34:32 +0000419
420 /// GetPropertyName - Return a unique constant for the given
421 /// name. The return value has type char *.
422 llvm::Constant *GetPropertyName(IdentifierInfo *Ident);
423
424 // FIXME: This can be dropped once string functions are unified.
425 llvm::Constant *GetPropertyTypeString(const ObjCPropertyDecl *PD,
426 const Decl *Container);
427
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000428 /// GetClassName - Return a unique constant for the given selector's
429 /// name. The return value has type char *.
430 llvm::Constant *GetClassName(IdentifierInfo *Ident);
431
Fariborz Jahanian21e6f172009-03-11 21:42:00 +0000432 /// GetInterfaceDeclStructLayout - Get layout for ivars of given
433 /// interface declaration.
434 const llvm::StructLayout *GetInterfaceDeclStructLayout(
435 const ObjCInterfaceDecl *ID) const;
436
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000437 /// BuildIvarLayout - Builds ivar layout bitmap for the class
438 /// implementation for the __strong or __weak case.
439 ///
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000440 llvm::Constant *BuildIvarLayout(const ObjCImplementationDecl *OI,
441 bool ForStrongLayout);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000442
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000443 void BuildAggrIvarLayout(const ObjCInterfaceDecl *OI,
444 const llvm::StructLayout *Layout,
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000445 const RecordDecl *RD,
Chris Lattnerf1690852009-03-31 08:48:01 +0000446 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000447 unsigned int BytePos, bool ForStrongLayout,
448 int &Index, int &SkIndex, bool &HasUnion);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000449
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +0000450 /// GetIvarLayoutName - Returns a unique constant for the given
451 /// ivar layout bitmap.
452 llvm::Constant *GetIvarLayoutName(IdentifierInfo *Ident,
453 const ObjCCommonTypesHelper &ObjCTypes);
454
Fariborz Jahanian46b86c62009-01-28 19:12:34 +0000455 const RecordDecl *GetFirstIvarInRecord(const ObjCInterfaceDecl *OID,
456 RecordDecl::field_iterator &FIV,
457 RecordDecl::field_iterator &PIV);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +0000458 /// EmitPropertyList - Emit the given property list. The return
459 /// value has type PropertyListPtrTy.
460 llvm::Constant *EmitPropertyList(const std::string &Name,
461 const Decl *Container,
462 const ObjCContainerDecl *OCD,
463 const ObjCCommonTypesHelper &ObjCTypes);
464
Fariborz Jahanianda320092009-01-29 19:24:30 +0000465 /// GetProtocolRef - Return a reference to the internal protocol
466 /// description, creating an empty one if it has not been
467 /// defined. The return value has type ProtocolPtrTy.
468 llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +0000469
470 /// GetIvarBaseOffset - returns ivars byte offset.
471 uint64_t GetIvarBaseOffset(const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +0000472 const FieldDecl *Field);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000473
Chris Lattnercd0ee142009-03-31 08:33:16 +0000474 /// GetFieldBaseOffset - return's field byte offset.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000475 uint64_t GetFieldBaseOffset(const ObjCInterfaceDecl *OI,
476 const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +0000477 const FieldDecl *Field);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000478
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000479 /// CreateMetadataVar - Create a global variable with internal
480 /// linkage for use by the Objective-C runtime.
481 ///
482 /// This is a convenience wrapper which not only creates the
483 /// variable, but also sets the section and alignment and adds the
484 /// global to the UsedGlobals list.
Daniel Dunbar35bd7632009-03-09 20:50:13 +0000485 ///
486 /// \param Name - The variable name.
487 /// \param Init - The variable initializer; this is also used to
488 /// define the type of the variable.
489 /// \param Section - The section the variable should go into, or 0.
490 /// \param Align - The alignment for the variable, or 0.
491 /// \param AddToUsed - Whether the variable should be added to
Daniel Dunbarc1583062009-04-14 17:42:51 +0000492 /// "llvm.used".
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000493 llvm::GlobalVariable *CreateMetadataVar(const std::string &Name,
494 llvm::Constant *Init,
495 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +0000496 unsigned Align,
497 bool AddToUsed);
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000498
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000499public:
500 CGObjCCommonMac(CodeGen::CodeGenModule &cgm) : CGM(cgm)
501 { }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000502
Steve Naroff33fdb732009-03-31 16:53:37 +0000503 virtual llvm::Constant *GenerateConstantString(const ObjCStringLiteral *SL);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000504
505 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
506 const ObjCContainerDecl *CD=0);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000507
508 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
509
510 /// GetOrEmitProtocol - Get the protocol object for the given
511 /// declaration, emitting it if necessary. The return value has type
512 /// ProtocolPtrTy.
513 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD)=0;
514
515 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
516 /// object for the given declaration, emitting it if needed. These
517 /// forward references will be filled in with empty bodies if no
518 /// definition is seen. The return value has type ProtocolPtrTy.
519 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD)=0;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000520};
521
522class CGObjCMac : public CGObjCCommonMac {
523private:
524 ObjCTypesHelper ObjCTypes;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000525 /// EmitImageInfo - Emit the image info marker used to encode some module
526 /// level information.
527 void EmitImageInfo();
528
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000529 /// EmitModuleInfo - Another marker encoding module level
530 /// information.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000531 void EmitModuleInfo();
532
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000533 /// EmitModuleSymols - Emit module symbols, the list of defined
534 /// classes and categories. The result has type SymtabPtrTy.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000535 llvm::Constant *EmitModuleSymbols();
536
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000537 /// FinishModule - Write out global data structures at the end of
538 /// processing a translation unit.
539 void FinishModule();
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000540
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000541 /// EmitClassExtension - Generate the class extension structure used
542 /// to store the weak ivar layout and properties. The return value
543 /// has type ClassExtensionPtrTy.
544 llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID);
545
546 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
547 /// for the given class.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000548 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000549 const ObjCInterfaceDecl *ID);
550
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000551 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000552 QualType ResultType,
553 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000554 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000555 QualType Arg0Ty,
556 bool IsSuper,
557 const CallArgList &CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000558
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000559 /// EmitIvarList - Emit the ivar list for the given
560 /// implementation. If ForClass is true the list of class ivars
561 /// (i.e. metaclass ivars) is emitted, otherwise the list of
562 /// interface ivars will be emitted. The return value has type
563 /// IvarListPtrTy.
564 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +0000565 bool ForClass);
566
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000567 /// EmitMetaClass - Emit a forward reference to the class structure
568 /// for the metaclass of the given interface. The return value has
569 /// type ClassPtrTy.
570 llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
571
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000572 /// EmitMetaClass - Emit a class structure for the metaclass of the
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000573 /// given implementation. The return value has type ClassPtrTy.
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000574 llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
575 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000576 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000577 const ConstantVector &Methods);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000578
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000579 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000580
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000581 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000582
583 /// EmitMethodList - Emit the method list for the given
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000584 /// implementation. The return value has type MethodListPtrTy.
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000585 llvm::Constant *EmitMethodList(const std::string &Name,
586 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000587 const ConstantVector &Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000588
589 /// EmitMethodDescList - Emit a method description list for a list of
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000590 /// method declarations.
591 /// - TypeName: The name for the type containing the methods.
592 /// - IsProtocol: True iff these methods are for a protocol.
593 /// - ClassMethds: True iff these are class methods.
594 /// - Required: When true, only "required" methods are
595 /// listed. Similarly, when false only "optional" methods are
596 /// listed. For classes this should always be true.
597 /// - begin, end: The method list to output.
598 ///
599 /// The return value has type MethodDescriptionListPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000600 llvm::Constant *EmitMethodDescList(const std::string &Name,
601 const char *Section,
602 const ConstantVector &Methods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000603
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000604 /// GetOrEmitProtocol - Get the protocol object for the given
605 /// declaration, emitting it if necessary. The return value has type
606 /// ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +0000607 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000608
609 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
610 /// object for the given declaration, emitting it if needed. These
611 /// forward references will be filled in with empty bodies if no
612 /// definition is seen. The return value has type ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +0000613 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000614
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000615 /// EmitProtocolExtension - Generate the protocol extension
616 /// structure used to store optional instance and class methods, and
617 /// protocol properties. The return value has type
618 /// ProtocolExtensionPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000619 llvm::Constant *
620 EmitProtocolExtension(const ObjCProtocolDecl *PD,
621 const ConstantVector &OptInstanceMethods,
622 const ConstantVector &OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000623
624 /// EmitProtocolList - Generate the list of referenced
625 /// protocols. The return value has type ProtocolListPtrTy.
Daniel Dunbardbc933702008-08-21 21:57:41 +0000626 llvm::Constant *EmitProtocolList(const std::string &Name,
627 ObjCProtocolDecl::protocol_iterator begin,
628 ObjCProtocolDecl::protocol_iterator end);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000629
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000630 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
631 /// for the given selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000632 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000633
Fariborz Jahanianda320092009-01-29 19:24:30 +0000634 public:
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000635 CGObjCMac(CodeGen::CodeGenModule &cgm);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000636
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000637 virtual llvm::Function *ModuleInitFunction();
638
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000639 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000640 QualType ResultType,
641 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000642 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000643 bool IsClassMessage,
644 const CallArgList &CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000645
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000646 virtual CodeGen::RValue
647 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000648 QualType ResultType,
649 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000650 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000651 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000652 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000653 bool IsClassMessage,
654 const CallArgList &CallArgs);
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000655
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000656 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000657 const ObjCInterfaceDecl *ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000658
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000659 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000660
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000661 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000662
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000663 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000664
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000665 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000666 const ObjCProtocolDecl *PD);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000667
Chris Lattner74391b42009-03-22 21:03:39 +0000668 virtual llvm::Constant *GetPropertyGetFunction();
669 virtual llvm::Constant *GetPropertySetFunction();
670 virtual llvm::Constant *EnumerationMutationFunction();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000671
Fariborz Jahanianbd71be42008-11-21 00:49:24 +0000672 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
673 const Stmt &S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000674 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
675 const ObjCAtThrowStmt &S);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000676 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +0000677 llvm::Value *AddrWeakObj);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000678 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
679 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000680 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
681 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian7eda8362008-11-20 19:23:36 +0000682 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
683 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000684 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
685 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian0bb20362009-02-02 20:02:29 +0000686
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000687 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
688 QualType ObjectTy,
689 llvm::Value *BaseValue,
690 const ObjCIvarDecl *Ivar,
691 const FieldDecl *Field,
692 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000693 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
694 ObjCInterfaceDecl *Interface,
695 const ObjCIvarDecl *Ivar);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000696};
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000697
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000698class CGObjCNonFragileABIMac : public CGObjCCommonMac {
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000699private:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000700 ObjCNonFragileABITypesHelper ObjCTypes;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000701 llvm::GlobalVariable* ObjCEmptyCacheVar;
702 llvm::GlobalVariable* ObjCEmptyVtableVar;
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000703
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000704 /// MetaClassReferences - uniqued meta class references.
705 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> MetaClassReferences;
Daniel Dunbare588b992009-03-01 04:46:24 +0000706
707 /// EHTypeReferences - uniqued class ehtype references.
708 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> EHTypeReferences;
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000709
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000710 /// FinishNonFragileABIModule - Write out global data structures at the end of
711 /// processing a translation unit.
712 void FinishNonFragileABIModule();
Daniel Dunbar8158a2f2009-04-08 04:21:03 +0000713
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000714 llvm::GlobalVariable * BuildClassRoTInitializer(unsigned flags,
715 unsigned InstanceStart,
716 unsigned InstanceSize,
717 const ObjCImplementationDecl *ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +0000718 llvm::GlobalVariable * BuildClassMetaData(std::string &ClassName,
719 llvm::Constant *IsAGV,
720 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +0000721 llvm::Constant *ClassRoGV,
722 bool HiddenVisibility);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000723
724 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
725
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +0000726 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
727
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000728 /// EmitMethodList - Emit the method list for the given
729 /// implementation. The return value has type MethodListnfABITy.
730 llvm::Constant *EmitMethodList(const std::string &Name,
731 const char *Section,
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +0000732 const ConstantVector &Methods);
733 /// EmitIvarList - Emit the ivar list for the given
734 /// implementation. If ForClass is true the list of class ivars
735 /// (i.e. metaclass ivars) is emitted, otherwise the list of
736 /// interface ivars will be emitted. The return value has type
737 /// IvarListnfABIPtrTy.
738 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000739
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000740 llvm::Constant *EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +0000741 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +0000742 unsigned long int offset);
743
Fariborz Jahanianda320092009-01-29 19:24:30 +0000744 /// GetOrEmitProtocol - Get the protocol object for the given
745 /// declaration, emitting it if necessary. The return value has type
746 /// ProtocolPtrTy.
747 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
748
749 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
750 /// object for the given declaration, emitting it if needed. These
751 /// forward references will be filled in with empty bodies if no
752 /// definition is seen. The return value has type ProtocolPtrTy.
753 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
754
755 /// EmitProtocolList - Generate the list of referenced
756 /// protocols. The return value has type ProtocolListPtrTy.
757 llvm::Constant *EmitProtocolList(const std::string &Name,
758 ObjCProtocolDecl::protocol_iterator begin,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000759 ObjCProtocolDecl::protocol_iterator end);
760
761 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
762 QualType ResultType,
763 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000764 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000765 QualType Arg0Ty,
766 bool IsSuper,
767 const CallArgList &CallArgs);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +0000768
769 /// GetClassGlobal - Return the global variable for the Objective-C
770 /// class of the given name.
Fariborz Jahanian0f902942009-04-14 18:41:56 +0000771 llvm::GlobalVariable *GetClassGlobal(const std::string &Name);
772
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000773 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
774 /// for the given class.
775 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000776 const ObjCInterfaceDecl *ID,
777 bool IsSuper = false);
778
779 /// EmitMetaClassRef - Return a Value * of the address of _class_t
780 /// meta-data
781 llvm::Value *EmitMetaClassRef(CGBuilderTy &Builder,
782 const ObjCInterfaceDecl *ID);
783
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000784 /// ObjCIvarOffsetVariable - Returns the ivar offset variable for
785 /// the given ivar.
786 ///
787 llvm::GlobalVariable * ObjCIvarOffsetVariable(std::string &Name,
Fariborz Jahanian01a0c362009-02-12 18:51:23 +0000788 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000789 const ObjCIvarDecl *Ivar);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000790
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +0000791 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
792 /// for the given selector.
793 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbare588b992009-03-01 04:46:24 +0000794
Daniel Dunbar8158a2f2009-04-08 04:21:03 +0000795 /// GetInterfaceEHType - Get the cached ehtype for the given Objective-C
Daniel Dunbare588b992009-03-01 04:46:24 +0000796 /// interface. The return value has type EHTypePtrTy.
Daniel Dunbar8158a2f2009-04-08 04:21:03 +0000797 llvm::Value *GetInterfaceEHType(const ObjCInterfaceDecl *ID,
798 bool ForDefinition);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +0000799
800 const char *getMetaclassSymbolPrefix() const {
801 return "OBJC_METACLASS_$_";
802 }
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000803
Daniel Dunbar6ab187a2009-04-07 05:48:37 +0000804 const char *getClassSymbolPrefix() const {
805 return "OBJC_CLASS_$_";
806 }
807
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000808public:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000809 CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000810 // FIXME. All stubs for now!
811 virtual llvm::Function *ModuleInitFunction();
812
813 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
814 QualType ResultType,
815 Selector Sel,
816 llvm::Value *Receiver,
817 bool IsClassMessage,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000818 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000819
820 virtual CodeGen::RValue
821 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
822 QualType ResultType,
823 Selector Sel,
824 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000825 bool isCategoryImpl,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000826 llvm::Value *Receiver,
827 bool IsClassMessage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000828 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000829
830 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000831 const ObjCInterfaceDecl *ID);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000832
833 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel)
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +0000834 { return EmitSelector(Builder, Sel); }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000835
Fariborz Jahanianeb062d92009-01-26 18:32:24 +0000836 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000837
838 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000839 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +0000840 const ObjCProtocolDecl *PD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000841
Chris Lattner74391b42009-03-22 21:03:39 +0000842 virtual llvm::Constant *GetPropertyGetFunction() {
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000843 return ObjCTypes.GetPropertyFn;
844 }
Chris Lattner74391b42009-03-22 21:03:39 +0000845 virtual llvm::Constant *GetPropertySetFunction() {
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000846 return ObjCTypes.SetPropertyFn;
847 }
Chris Lattner74391b42009-03-22 21:03:39 +0000848 virtual llvm::Constant *EnumerationMutationFunction() {
Daniel Dunbar28ed0842009-02-16 18:48:45 +0000849 return ObjCTypes.EnumerationMutationFn;
850 }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000851
852 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000853 const Stmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000854 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000855 const ObjCAtThrowStmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000856 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000857 llvm::Value *AddrWeakObj);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000858 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000859 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000860 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000861 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000862 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000863 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000864 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000865 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000866 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
867 QualType ObjectTy,
868 llvm::Value *BaseValue,
869 const ObjCIvarDecl *Ivar,
870 const FieldDecl *Field,
871 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000872 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
873 ObjCInterfaceDecl *Interface,
874 const ObjCIvarDecl *Ivar);
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000875};
876
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000877} // end anonymous namespace
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000878
879/* *** Helper Functions *** */
880
881/// getConstantGEP() - Help routine to construct simple GEPs.
882static llvm::Constant *getConstantGEP(llvm::Constant *C,
883 unsigned idx0,
884 unsigned idx1) {
885 llvm::Value *Idxs[] = {
886 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx0),
887 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx1)
888 };
889 return llvm::ConstantExpr::getGetElementPtr(C, Idxs, 2);
890}
891
Daniel Dunbar8158a2f2009-04-08 04:21:03 +0000892/// hasObjCExceptionAttribute - Return true if this class or any super
893/// class has the __objc_exception__ attribute.
894static bool hasObjCExceptionAttribute(const ObjCInterfaceDecl *OID) {
Daniel Dunbarb11fa0d2009-04-13 21:08:27 +0000895 if (OID->hasAttr<ObjCExceptionAttr>())
Daniel Dunbar8158a2f2009-04-08 04:21:03 +0000896 return true;
897 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
898 return hasObjCExceptionAttribute(Super);
899 return false;
900}
901
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000902/* *** CGObjCMac Public Interface *** */
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000903
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000904CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm),
905 ObjCTypes(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000906{
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000907 ObjCABI = 1;
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000908 EmitImageInfo();
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000909}
910
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000911/// GetClass - Return a reference to the class for the given interface
912/// decl.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000913llvm::Value *CGObjCMac::GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000914 const ObjCInterfaceDecl *ID) {
915 return EmitClassRef(Builder, ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000916}
917
918/// GetSelector - Return the pointer to the unique'd string for this selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000919llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000920 return EmitSelector(Builder, Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000921}
922
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000923/// Generate a constant CFString object.
924/*
925 struct __builtin_CFString {
926 const int *isa; // point to __CFConstantStringClassReference
927 int flags;
928 const char *str;
929 long length;
930 };
931*/
932
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000933llvm::Constant *CGObjCCommonMac::GenerateConstantString(
Steve Naroff33fdb732009-03-31 16:53:37 +0000934 const ObjCStringLiteral *SL) {
Steve Naroff8d4141f2009-04-01 13:55:36 +0000935 return CGM.GetAddrOfConstantCFString(SL->getString());
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000936}
937
938/// Generates a message send where the super is the receiver. This is
939/// a message send to self with special delivery semantics indicating
940/// which class's method should be called.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000941CodeGen::RValue
942CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000943 QualType ResultType,
944 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000945 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000946 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000947 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000948 bool IsClassMessage,
Daniel Dunbar46f45b92008-09-09 01:06:48 +0000949 const CodeGen::CallArgList &CallArgs) {
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000950 // Create and init a super structure; this is a (receiver, class)
951 // pair we will pass to objc_msgSendSuper.
952 llvm::Value *ObjCSuper =
953 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
954 llvm::Value *ReceiverAsObject =
955 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
956 CGF.Builder.CreateStore(ReceiverAsObject,
957 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000958
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000959 // If this is a class message the metaclass is passed as the target.
960 llvm::Value *Target;
961 if (IsClassMessage) {
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000962 if (isCategoryImpl) {
963 // Message sent to 'super' in a class method defined in a category
964 // implementation requires an odd treatment.
965 // If we are in a class method, we must retrieve the
966 // _metaclass_ for the current class, pointed at by
967 // the class's "isa" pointer. The following assumes that
968 // isa" is the first ivar in a class (which it must be).
969 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
970 Target = CGF.Builder.CreateStructGEP(Target, 0);
971 Target = CGF.Builder.CreateLoad(Target);
972 }
973 else {
974 llvm::Value *MetaClassPtr = EmitMetaClassRef(Class);
975 llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1);
976 llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr);
977 Target = Super;
978 }
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000979 } else {
980 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
981 }
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000982 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
983 // and ObjCTypes types.
984 const llvm::Type *ClassTy =
985 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000986 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000987 CGF.Builder.CreateStore(Target,
988 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
989
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000990 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000991 ObjCSuper, ObjCTypes.SuperPtrCTy,
992 true, CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000993}
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000994
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000995/// Generate code for a message send expression.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000996CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000997 QualType ResultType,
998 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000999 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001000 bool IsClassMessage,
1001 const CallArgList &CallArgs) {
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001002 llvm::Value *Arg0 =
1003 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy, "tmp");
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001004 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001005 Arg0, CGF.getContext().getObjCIdType(),
1006 false, CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001007}
1008
1009CodeGen::RValue CGObjCMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001010 QualType ResultType,
1011 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001012 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001013 QualType Arg0Ty,
1014 bool IsSuper,
1015 const CallArgList &CallArgs) {
1016 CallArgList ActualArgs;
Daniel Dunbar46f45b92008-09-09 01:06:48 +00001017 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
1018 ActualArgs.push_back(std::make_pair(RValue::get(EmitSelector(CGF.Builder,
1019 Sel)),
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001020 CGF.getContext().getObjCSelType()));
1021 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001022
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001023 CodeGenTypes &Types = CGM.getTypes();
1024 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs);
1025 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo, false);
Daniel Dunbar5669e572008-10-17 03:24:53 +00001026
1027 llvm::Constant *Fn;
Daniel Dunbar88b53962009-02-02 22:03:45 +00001028 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Daniel Dunbar5669e572008-10-17 03:24:53 +00001029 Fn = ObjCTypes.getSendStretFn(IsSuper);
1030 } else if (ResultType->isFloatingType()) {
1031 // FIXME: Sadly, this is wrong. This actually depends on the
1032 // architecture. This happens to be right for x86-32 though.
1033 Fn = ObjCTypes.getSendFpretFn(IsSuper);
1034 } else {
1035 Fn = ObjCTypes.getSendFn(IsSuper);
1036 }
Daniel Dunbar62d5c1b2008-09-10 07:00:50 +00001037 Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy));
Daniel Dunbar88b53962009-02-02 22:03:45 +00001038 return CGF.EmitCall(FnInfo, Fn, ActualArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001039}
1040
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001041llvm::Value *CGObjCMac::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001042 const ObjCProtocolDecl *PD) {
Daniel Dunbarc67876d2008-09-04 04:33:15 +00001043 // FIXME: I don't understand why gcc generates this, or where it is
1044 // resolved. Investigate. Its also wasteful to look this up over and
1045 // over.
1046 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1047
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001048 return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
1049 ObjCTypes.ExternalProtocolPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001050}
1051
Fariborz Jahanianda320092009-01-29 19:24:30 +00001052void CGObjCCommonMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001053 // FIXME: We shouldn't need this, the protocol decl should contain
1054 // enough information to tell us whether this was a declaration or a
1055 // definition.
1056 DefinedProtocols.insert(PD->getIdentifier());
1057
1058 // If we have generated a forward reference to this protocol, emit
1059 // it now. Otherwise do nothing, the protocol objects are lazily
1060 // emitted.
1061 if (Protocols.count(PD->getIdentifier()))
1062 GetOrEmitProtocol(PD);
1063}
1064
Fariborz Jahanianda320092009-01-29 19:24:30 +00001065llvm::Constant *CGObjCCommonMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001066 if (DefinedProtocols.count(PD->getIdentifier()))
1067 return GetOrEmitProtocol(PD);
1068 return GetOrEmitProtocolRef(PD);
1069}
1070
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001071/*
1072 // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions
1073 struct _objc_protocol {
1074 struct _objc_protocol_extension *isa;
1075 char *protocol_name;
1076 struct _objc_protocol_list *protocol_list;
1077 struct _objc__method_prototype_list *instance_methods;
1078 struct _objc__method_prototype_list *class_methods
1079 };
1080
1081 See EmitProtocolExtension().
1082*/
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001083llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
1084 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1085
1086 // Early exit if a defining object has already been generated.
1087 if (Entry && Entry->hasInitializer())
1088 return Entry;
1089
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001090 // FIXME: I don't understand why gcc generates this, or where it is
1091 // resolved. Investigate. Its also wasteful to look this up over and
1092 // over.
1093 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1094
Chris Lattner8ec03f52008-11-24 03:54:41 +00001095 const char *ProtocolName = PD->getNameAsCString();
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001096
1097 // Construct method lists.
1098 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1099 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregor6ab35242009-04-09 21:40:53 +00001100 for (ObjCProtocolDecl::instmeth_iterator
1101 i = PD->instmeth_begin(CGM.getContext()),
1102 e = PD->instmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001103 ObjCMethodDecl *MD = *i;
1104 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1105 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1106 OptInstanceMethods.push_back(C);
1107 } else {
1108 InstanceMethods.push_back(C);
1109 }
1110 }
1111
Douglas Gregor6ab35242009-04-09 21:40:53 +00001112 for (ObjCProtocolDecl::classmeth_iterator
1113 i = PD->classmeth_begin(CGM.getContext()),
1114 e = PD->classmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001115 ObjCMethodDecl *MD = *i;
1116 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1117 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1118 OptClassMethods.push_back(C);
1119 } else {
1120 ClassMethods.push_back(C);
1121 }
1122 }
1123
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001124 std::vector<llvm::Constant*> Values(5);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001125 Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001126 Values[1] = GetClassName(PD->getIdentifier());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001127 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001128 EmitProtocolList("\01L_OBJC_PROTOCOL_REFS_" + PD->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001129 PD->protocol_begin(),
1130 PD->protocol_end());
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001131 Values[3] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001132 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_"
1133 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001134 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1135 InstanceMethods);
1136 Values[4] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001137 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_"
1138 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001139 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1140 ClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001141 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
1142 Values);
1143
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001144 if (Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001145 // Already created, fix the linkage and update the initializer.
1146 Entry->setLinkage(llvm::GlobalValue::InternalLinkage);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001147 Entry->setInitializer(Init);
1148 } else {
1149 Entry =
1150 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
1151 llvm::GlobalValue::InternalLinkage,
1152 Init,
1153 std::string("\01L_OBJC_PROTOCOL_")+ProtocolName,
1154 &CGM.getModule());
1155 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001156 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001157 UsedGlobals.push_back(Entry);
1158 // FIXME: Is this necessary? Why only for protocol?
1159 Entry->setAlignment(4);
1160 }
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001161
1162 return Entry;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001163}
1164
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001165llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001166 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1167
1168 if (!Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001169 // We use the initializer as a marker of whether this is a forward
1170 // reference or not. At module finalization we add the empty
1171 // contents for protocols which were referenced but never defined.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001172 Entry =
1173 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001174 llvm::GlobalValue::ExternalLinkage,
1175 0,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001176 "\01L_OBJC_PROTOCOL_" + PD->getNameAsString(),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001177 &CGM.getModule());
1178 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001179 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001180 UsedGlobals.push_back(Entry);
1181 // FIXME: Is this necessary? Why only for protocol?
1182 Entry->setAlignment(4);
1183 }
1184
1185 return Entry;
1186}
1187
1188/*
1189 struct _objc_protocol_extension {
1190 uint32_t size;
1191 struct objc_method_description_list *optional_instance_methods;
1192 struct objc_method_description_list *optional_class_methods;
1193 struct objc_property_list *instance_properties;
1194 };
1195*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001196llvm::Constant *
1197CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
1198 const ConstantVector &OptInstanceMethods,
1199 const ConstantVector &OptClassMethods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001200 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001201 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolExtensionTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001202 std::vector<llvm::Constant*> Values(4);
1203 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001204 Values[1] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001205 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_"
1206 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001207 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1208 OptInstanceMethods);
1209 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001210 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_"
1211 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001212 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1213 OptClassMethods);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001214 Values[3] = EmitPropertyList("\01L_OBJC_$_PROP_PROTO_LIST_" +
1215 PD->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001216 0, PD, ObjCTypes);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001217
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001218 // Return null if no extension bits are used.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001219 if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
1220 Values[3]->isNullValue())
1221 return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
1222
1223 llvm::Constant *Init =
1224 llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001225
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001226 // No special section, but goes in llvm.used
1227 return CreateMetadataVar("\01L_OBJC_PROTOCOLEXT_" + PD->getNameAsString(),
1228 Init,
1229 0, 0, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001230}
1231
1232/*
1233 struct objc_protocol_list {
1234 struct objc_protocol_list *next;
1235 long count;
1236 Protocol *list[];
1237 };
1238*/
Daniel Dunbardbc933702008-08-21 21:57:41 +00001239llvm::Constant *
1240CGObjCMac::EmitProtocolList(const std::string &Name,
1241 ObjCProtocolDecl::protocol_iterator begin,
1242 ObjCProtocolDecl::protocol_iterator end) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001243 std::vector<llvm::Constant*> ProtocolRefs;
1244
Daniel Dunbardbc933702008-08-21 21:57:41 +00001245 for (; begin != end; ++begin)
1246 ProtocolRefs.push_back(GetProtocolRef(*begin));
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001247
1248 // Just return null for empty protocol lists
1249 if (ProtocolRefs.empty())
1250 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1251
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001252 // This list is null terminated.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001253 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
1254
1255 std::vector<llvm::Constant*> Values(3);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001256 // This field is only used by the runtime.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001257 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1258 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
1259 Values[2] =
1260 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
1261 ProtocolRefs.size()),
1262 ProtocolRefs);
1263
1264 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1265 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001266 CreateMetadataVar(Name, Init, "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001267 4, false);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001268 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
1269}
1270
1271/*
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001272 struct _objc_property {
1273 const char * const name;
1274 const char * const attributes;
1275 };
1276
1277 struct _objc_property_list {
1278 uint32_t entsize; // sizeof (struct _objc_property)
1279 uint32_t prop_count;
1280 struct _objc_property[prop_count];
1281 };
1282*/
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001283llvm::Constant *CGObjCCommonMac::EmitPropertyList(const std::string &Name,
1284 const Decl *Container,
1285 const ObjCContainerDecl *OCD,
1286 const ObjCCommonTypesHelper &ObjCTypes) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001287 std::vector<llvm::Constant*> Properties, Prop(2);
Douglas Gregor6ab35242009-04-09 21:40:53 +00001288 for (ObjCContainerDecl::prop_iterator I = OCD->prop_begin(CGM.getContext()),
1289 E = OCD->prop_end(CGM.getContext()); I != E; ++I) {
Steve Naroff93983f82009-01-11 12:47:58 +00001290 const ObjCPropertyDecl *PD = *I;
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001291 Prop[0] = GetPropertyName(PD->getIdentifier());
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00001292 Prop[1] = GetPropertyTypeString(PD, Container);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001293 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
1294 Prop));
1295 }
1296
1297 // Return null for empty list.
1298 if (Properties.empty())
1299 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1300
1301 unsigned PropertySize =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001302 CGM.getTargetData().getTypePaddedSize(ObjCTypes.PropertyTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001303 std::vector<llvm::Constant*> Values(3);
1304 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
1305 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
1306 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
1307 Properties.size());
1308 Values[2] = llvm::ConstantArray::get(AT, Properties);
1309 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1310
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001311 llvm::GlobalVariable *GV =
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001312 CreateMetadataVar(Name, Init,
1313 (ObjCABI == 2) ? "__DATA, __objc_const" :
1314 "__OBJC,__property,regular,no_dead_strip",
1315 (ObjCABI == 2) ? 8 : 4,
1316 true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001317 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.PropertyListPtrTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001318}
1319
1320/*
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001321 struct objc_method_description_list {
1322 int count;
1323 struct objc_method_description list[];
1324 };
1325*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001326llvm::Constant *
1327CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
1328 std::vector<llvm::Constant*> Desc(2);
1329 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1330 ObjCTypes.SelectorPtrTy);
1331 Desc[1] = GetMethodVarType(MD);
1332 return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
1333 Desc);
1334}
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001335
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001336llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name,
1337 const char *Section,
1338 const ConstantVector &Methods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001339 // Return null for empty list.
1340 if (Methods.empty())
1341 return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
1342
1343 std::vector<llvm::Constant*> Values(2);
1344 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1345 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
1346 Methods.size());
1347 Values[1] = llvm::ConstantArray::get(AT, Methods);
1348 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1349
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001350 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001351 return llvm::ConstantExpr::getBitCast(GV,
1352 ObjCTypes.MethodDescriptionListPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001353}
1354
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001355/*
1356 struct _objc_category {
1357 char *category_name;
1358 char *class_name;
1359 struct _objc_method_list *instance_methods;
1360 struct _objc_method_list *class_methods;
1361 struct _objc_protocol_list *protocols;
1362 uint32_t size; // <rdar://4585769>
1363 struct _objc_property_list *instance_properties;
1364 };
1365 */
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001366void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001367 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.CategoryTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001368
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001369 // FIXME: This is poor design, the OCD should have a pointer to the
1370 // category decl. Additionally, note that Category can be null for
1371 // the @implementation w/o an @interface case. Sema should just
1372 // create one for us as it does for @implementation so everyone else
1373 // can live life under a clear blue sky.
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001374 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001375 const ObjCCategoryDecl *Category =
1376 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001377 std::string ExtName(Interface->getNameAsString() + "_" +
1378 OCD->getNameAsString());
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001379
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001380 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1381 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
1382 e = OCD->instmeth_end(); i != e; ++i) {
1383 // Instance methods should always be defined.
1384 InstanceMethods.push_back(GetMethodConstant(*i));
1385 }
1386 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
1387 e = OCD->classmeth_end(); i != e; ++i) {
1388 // Class methods should always be defined.
1389 ClassMethods.push_back(GetMethodConstant(*i));
1390 }
1391
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001392 std::vector<llvm::Constant*> Values(7);
1393 Values[0] = GetClassName(OCD->getIdentifier());
1394 Values[1] = GetClassName(Interface->getIdentifier());
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001395 Values[2] =
1396 EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") +
1397 ExtName,
1398 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001399 InstanceMethods);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001400 Values[3] =
1401 EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName,
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001402 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001403 ClassMethods);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001404 if (Category) {
1405 Values[4] =
1406 EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName,
1407 Category->protocol_begin(),
1408 Category->protocol_end());
1409 } else {
1410 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1411 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001412 Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001413
1414 // If there is no category @interface then there can be no properties.
1415 if (Category) {
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001416 Values[6] = EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001417 OCD, Category, ObjCTypes);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001418 } else {
1419 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1420 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001421
1422 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
1423 Values);
1424
1425 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001426 CreateMetadataVar(std::string("\01L_OBJC_CATEGORY_")+ExtName, Init,
1427 "__OBJC,__category,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001428 4, true);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001429 DefinedCategories.push_back(GV);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001430}
1431
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001432// FIXME: Get from somewhere?
1433enum ClassFlags {
1434 eClassFlags_Factory = 0x00001,
1435 eClassFlags_Meta = 0x00002,
1436 // <rdr://5142207>
1437 eClassFlags_HasCXXStructors = 0x02000,
1438 eClassFlags_Hidden = 0x20000,
1439 eClassFlags_ABI2_Hidden = 0x00010,
1440 eClassFlags_ABI2_HasCXXStructors = 0x00004 // <rdr://4923634>
1441};
1442
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001443/*
1444 struct _objc_class {
1445 Class isa;
1446 Class super_class;
1447 const char *name;
1448 long version;
1449 long info;
1450 long instance_size;
1451 struct _objc_ivar_list *ivars;
1452 struct _objc_method_list *methods;
1453 struct _objc_cache *cache;
1454 struct _objc_protocol_list *protocols;
1455 // Objective-C 1.0 extensions (<rdr://4585769>)
1456 const char *ivar_layout;
1457 struct _objc_class_ext *ext;
1458 };
1459
1460 See EmitClassExtension();
1461 */
1462void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001463 DefinedSymbols.insert(ID->getIdentifier());
1464
Chris Lattner8ec03f52008-11-24 03:54:41 +00001465 std::string ClassName = ID->getNameAsString();
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001466 // FIXME: Gross
1467 ObjCInterfaceDecl *Interface =
1468 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001469 llvm::Constant *Protocols =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001470 EmitProtocolList("\01L_OBJC_CLASS_PROTOCOLS_" + ID->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001471 Interface->protocol_begin(),
1472 Interface->protocol_end());
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001473 const llvm::Type *InterfaceTy =
Chris Lattner03d9f342009-04-01 06:23:52 +00001474 CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(Interface));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001475 unsigned Flags = eClassFlags_Factory;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001476 unsigned Size = CGM.getTargetData().getTypePaddedSize(InterfaceTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001477
1478 // FIXME: Set CXX-structors flag.
Daniel Dunbar04d40782009-04-14 06:00:08 +00001479 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001480 Flags |= eClassFlags_Hidden;
1481
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001482 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1483 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
1484 e = ID->instmeth_end(); i != e; ++i) {
1485 // Instance methods should always be defined.
1486 InstanceMethods.push_back(GetMethodConstant(*i));
1487 }
1488 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
1489 e = ID->classmeth_end(); i != e; ++i) {
1490 // Class methods should always be defined.
1491 ClassMethods.push_back(GetMethodConstant(*i));
1492 }
1493
1494 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
1495 e = ID->propimpl_end(); i != e; ++i) {
1496 ObjCPropertyImplDecl *PID = *i;
1497
1498 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1499 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1500
1501 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
1502 if (llvm::Constant *C = GetMethodConstant(MD))
1503 InstanceMethods.push_back(C);
1504 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
1505 if (llvm::Constant *C = GetMethodConstant(MD))
1506 InstanceMethods.push_back(C);
1507 }
1508 }
1509
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001510 std::vector<llvm::Constant*> Values(12);
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001511 Values[ 0] = EmitMetaClass(ID, Protocols, InterfaceTy, ClassMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001512 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001513 // Record a reference to the super class.
1514 LazySymbols.insert(Super->getIdentifier());
1515
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001516 Values[ 1] =
1517 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1518 ObjCTypes.ClassPtrTy);
1519 } else {
1520 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1521 }
1522 Values[ 2] = GetClassName(ID->getIdentifier());
1523 // Version is always 0.
1524 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1525 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1526 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001527 Values[ 6] = EmitIvarList(ID, false);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001528 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001529 EmitMethodList("\01L_OBJC_INSTANCE_METHODS_" + ID->getNameAsString(),
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001530 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001531 InstanceMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001532 // cache is always NULL.
1533 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1534 Values[ 9] = Protocols;
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001535 // FIXME: Set ivar_layout
Fariborz Jahanian667423a2009-03-25 22:36:49 +00001536 // Values[10] = BuildIvarLayout(ID, true);
1537 Values[10] = GetIvarLayoutName(0, ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001538 Values[11] = EmitClassExtension(ID);
1539 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1540 Values);
1541
1542 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001543 CreateMetadataVar(std::string("\01L_OBJC_CLASS_")+ClassName, Init,
1544 "__OBJC,__class,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001545 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001546 DefinedClasses.push_back(GV);
1547}
1548
1549llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
1550 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001551 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001552 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001553 unsigned Flags = eClassFlags_Meta;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001554 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001555
Daniel Dunbar04d40782009-04-14 06:00:08 +00001556 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001557 Flags |= eClassFlags_Hidden;
1558
1559 std::vector<llvm::Constant*> Values(12);
1560 // The isa for the metaclass is the root of the hierarchy.
1561 const ObjCInterfaceDecl *Root = ID->getClassInterface();
1562 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
1563 Root = Super;
1564 Values[ 0] =
1565 llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
1566 ObjCTypes.ClassPtrTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001567 // The super class for the metaclass is emitted as the name of the
1568 // super class. The runtime fixes this up to point to the
1569 // *metaclass* for the super class.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001570 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
1571 Values[ 1] =
1572 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1573 ObjCTypes.ClassPtrTy);
1574 } else {
1575 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1576 }
1577 Values[ 2] = GetClassName(ID->getIdentifier());
1578 // Version is always 0.
1579 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1580 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1581 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001582 Values[ 6] = EmitIvarList(ID, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001583 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001584 EmitMethodList("\01L_OBJC_CLASS_METHODS_" + ID->getNameAsString(),
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001585 "__OBJC,__cls_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001586 Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001587 // cache is always NULL.
1588 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1589 Values[ 9] = Protocols;
1590 // ivar_layout for metaclass is always NULL.
1591 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1592 // The class extension is always unused for metaclasses.
1593 Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1594 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1595 Values);
1596
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001597 std::string Name("\01L_OBJC_METACLASS_");
Chris Lattner8ec03f52008-11-24 03:54:41 +00001598 Name += ID->getNameAsCString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001599
1600 // Check for a forward reference.
1601 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
1602 if (GV) {
1603 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1604 "Forward metaclass reference has incorrect type.");
1605 GV->setLinkage(llvm::GlobalValue::InternalLinkage);
1606 GV->setInitializer(Init);
1607 } else {
1608 GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1609 llvm::GlobalValue::InternalLinkage,
1610 Init, Name,
1611 &CGM.getModule());
1612 }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001613 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001614 GV->setAlignment(4);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001615 UsedGlobals.push_back(GV);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001616
1617 return GV;
1618}
1619
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001620llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001621 std::string Name = "\01L_OBJC_METACLASS_" + ID->getNameAsString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001622
1623 // FIXME: Should we look these up somewhere other than the
1624 // module. Its a bit silly since we only generate these while
1625 // processing an implementation, so exactly one pointer would work
1626 // if know when we entered/exitted an implementation block.
1627
1628 // Check for an existing forward reference.
Fariborz Jahanianb0d27942009-01-07 20:11:22 +00001629 // Previously, metaclass with internal linkage may have been defined.
1630 // pass 'true' as 2nd argument so it is returned.
1631 if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true)) {
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001632 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1633 "Forward metaclass reference has incorrect type.");
1634 return GV;
1635 } else {
1636 // Generate as an external reference to keep a consistent
1637 // module. This will be patched up when we emit the metaclass.
1638 return new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1639 llvm::GlobalValue::ExternalLinkage,
1640 0,
1641 Name,
1642 &CGM.getModule());
1643 }
1644}
1645
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001646/*
1647 struct objc_class_ext {
1648 uint32_t size;
1649 const char *weak_ivar_layout;
1650 struct _objc_property_list *properties;
1651 };
1652*/
1653llvm::Constant *
1654CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
1655 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001656 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassExtensionTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001657
1658 std::vector<llvm::Constant*> Values(3);
1659 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001660 // FIXME: Output weak_ivar_layout string.
Fariborz Jahanian667423a2009-03-25 22:36:49 +00001661 // Values[1] = BuildIvarLayout(ID, false);
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00001662 Values[1] = GetIvarLayoutName(0, ObjCTypes);
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001663 Values[2] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001664 ID, ID->getClassInterface(), ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001665
1666 // Return null if no extension bits are used.
1667 if (Values[1]->isNullValue() && Values[2]->isNullValue())
1668 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1669
1670 llvm::Constant *Init =
1671 llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001672 return CreateMetadataVar("\01L_OBJC_CLASSEXT_" + ID->getNameAsString(),
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001673 Init, "__OBJC,__class_ext,regular,no_dead_strip",
1674 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001675}
1676
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001677/// countInheritedIvars - count number of ivars in class and its super class(s)
1678///
Douglas Gregor6ab35242009-04-09 21:40:53 +00001679static int countInheritedIvars(const ObjCInterfaceDecl *OI,
1680 ASTContext &Context) {
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001681 int count = 0;
1682 if (!OI)
1683 return 0;
1684 const ObjCInterfaceDecl *SuperClass = OI->getSuperClass();
1685 if (SuperClass)
Douglas Gregor6ab35242009-04-09 21:40:53 +00001686 count += countInheritedIvars(SuperClass, Context);
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001687 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1688 E = OI->ivar_end(); I != E; ++I)
1689 ++count;
Fariborz Jahanian18191882009-03-31 18:11:23 +00001690 // look into properties.
Douglas Gregor6ab35242009-04-09 21:40:53 +00001691 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(Context),
1692 E = OI->prop_end(Context); I != E; ++I) {
Fariborz Jahanian18191882009-03-31 18:11:23 +00001693 if ((*I)->getPropertyIvarDecl())
1694 ++count;
1695 }
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001696 return count;
1697}
1698
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001699/// getInterfaceDeclForIvar - Get the interface declaration node where
1700/// this ivar is declared in.
1701/// FIXME. Ideally, this info should be in the ivar node. But currently
1702/// it is not and prevailing wisdom is that ASTs should not have more
1703/// info than is absolutely needed, even though this info reflects the
1704/// source language.
1705///
1706static const ObjCInterfaceDecl *getInterfaceDeclForIvar(
1707 const ObjCInterfaceDecl *OI,
Douglas Gregor6ab35242009-04-09 21:40:53 +00001708 const ObjCIvarDecl *IVD,
1709 ASTContext &Context) {
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001710 if (!OI)
1711 return 0;
1712 assert(isa<ObjCInterfaceDecl>(OI) && "OI is not an interface");
1713 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1714 E = OI->ivar_end(); I != E; ++I)
1715 if ((*I)->getIdentifier() == IVD->getIdentifier())
1716 return OI;
Fariborz Jahanian5a4b4532009-03-31 17:00:52 +00001717 // look into properties.
Douglas Gregor6ab35242009-04-09 21:40:53 +00001718 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(Context),
1719 E = OI->prop_end(Context); I != E; ++I) {
Fariborz Jahanian5a4b4532009-03-31 17:00:52 +00001720 ObjCPropertyDecl *PDecl = (*I);
1721 if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl())
1722 if (IV->getIdentifier() == IVD->getIdentifier())
1723 return OI;
1724 }
Douglas Gregor6ab35242009-04-09 21:40:53 +00001725 return getInterfaceDeclForIvar(OI->getSuperClass(), IVD, Context);
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001726}
1727
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001728/*
1729 struct objc_ivar {
1730 char *ivar_name;
1731 char *ivar_type;
1732 int ivar_offset;
1733 };
1734
1735 struct objc_ivar_list {
1736 int ivar_count;
1737 struct objc_ivar list[count];
1738 };
1739 */
1740llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001741 bool ForClass) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001742 std::vector<llvm::Constant*> Ivars, Ivar(3);
1743
1744 // When emitting the root class GCC emits ivar entries for the
1745 // actual class structure. It is not clear if we need to follow this
1746 // behavior; for now lets try and get away with not doing it. If so,
1747 // the cleanest solution would be to make up an ObjCInterfaceDecl
1748 // for the class.
1749 if (ForClass)
1750 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001751
1752 ObjCInterfaceDecl *OID =
1753 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00001754 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001755
1756 RecordDecl::field_iterator ifield, pfield;
1757 const RecordDecl *RD = GetFirstIvarInRecord(OID, ifield, pfield);
Douglas Gregor6ab35242009-04-09 21:40:53 +00001758 for (RecordDecl::field_iterator e = RD->field_end(CGM.getContext());
1759 ifield != e; ++ifield) {
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001760 FieldDecl *Field = *ifield;
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00001761 uint64_t Offset = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001762 if (Field->getIdentifier())
1763 Ivar[0] = GetMethodVarName(Field->getIdentifier());
1764 else
1765 Ivar[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Devang Patel7794bb82009-03-04 18:21:39 +00001766 Ivar[1] = GetMethodVarType(Field);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001767 Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy, Offset);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001768 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001769 }
1770
1771 // Return null for empty list.
1772 if (Ivars.empty())
1773 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
1774
1775 std::vector<llvm::Constant*> Values(2);
1776 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
1777 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
1778 Ivars.size());
1779 Values[1] = llvm::ConstantArray::get(AT, Ivars);
1780 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1781
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001782 llvm::GlobalVariable *GV;
1783 if (ForClass)
1784 GV = CreateMetadataVar("\01L_OBJC_CLASS_VARIABLES_" + ID->getNameAsString(),
Daniel Dunbar58a29122009-03-09 22:18:41 +00001785 Init, "__OBJC,__class_vars,regular,no_dead_strip",
1786 4, true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001787 else
1788 GV = CreateMetadataVar("\01L_OBJC_INSTANCE_VARIABLES_"
1789 + ID->getNameAsString(),
1790 Init, "__OBJC,__instance_vars,regular,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001791 4, true);
1792 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.IvarListPtrTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001793}
1794
1795/*
1796 struct objc_method {
1797 SEL method_name;
1798 char *method_types;
1799 void *method;
1800 };
1801
1802 struct objc_method_list {
1803 struct objc_method_list *obsolete;
1804 int count;
1805 struct objc_method methods_list[count];
1806 };
1807*/
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001808
1809/// GetMethodConstant - Return a struct objc_method constant for the
1810/// given method if it has been defined. The result is null if the
1811/// method has not been defined. The return value has type MethodPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001812llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001813 // FIXME: Use DenseMap::lookup
1814 llvm::Function *Fn = MethodDefinitions[MD];
1815 if (!Fn)
1816 return 0;
1817
1818 std::vector<llvm::Constant*> Method(3);
1819 Method[0] =
1820 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1821 ObjCTypes.SelectorPtrTy);
1822 Method[1] = GetMethodVarType(MD);
1823 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
1824 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
1825}
1826
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001827llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name,
1828 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001829 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001830 // Return null for empty list.
1831 if (Methods.empty())
1832 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
1833
1834 std::vector<llvm::Constant*> Values(3);
1835 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1836 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1837 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
1838 Methods.size());
1839 Values[2] = llvm::ConstantArray::get(AT, Methods);
1840 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1841
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001842 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001843 return llvm::ConstantExpr::getBitCast(GV,
1844 ObjCTypes.MethodListPtrTy);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001845}
1846
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001847llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD,
Daniel Dunbarbb36d332009-02-02 21:43:58 +00001848 const ObjCContainerDecl *CD) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001849 std::string Name;
Fariborz Jahanian679a5022009-01-10 21:06:09 +00001850 GetNameForMethod(OMD, CD, Name);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001851
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001852 CodeGenTypes &Types = CGM.getTypes();
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001853 const llvm::FunctionType *MethodTy =
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001854 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001855 llvm::Function *Method =
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001856 llvm::Function::Create(MethodTy,
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001857 llvm::GlobalValue::InternalLinkage,
1858 Name,
1859 &CGM.getModule());
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001860 MethodDefinitions.insert(std::make_pair(OMD, Method));
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001861
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001862 return Method;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001863}
1864
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00001865uint64_t CGObjCCommonMac::GetIvarBaseOffset(const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +00001866 const FieldDecl *Field) {
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00001867 if (!Field->isBitField())
1868 return Layout->getElementOffset(
1869 CGM.getTypes().getLLVMFieldNo(Field));
1870 // FIXME. Must be a better way of getting a bitfield base offset.
1871 uint64_t offset = CGM.getTypes().getLLVMFieldNo(Field);
1872 const llvm::Type *Ty = CGM.getTypes().ConvertTypeForMemRecursive(Field->getType());
1873 uint64_t size = CGM.getTypes().getTargetData().getTypePaddedSizeInBits(Ty);
1874 offset = (offset*size)/8;
1875 return offset;
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00001876}
1877
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00001878/// GetFieldBaseOffset - return's field byt offset.
1879uint64_t CGObjCCommonMac::GetFieldBaseOffset(const ObjCInterfaceDecl *OI,
1880 const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +00001881 const FieldDecl *Field) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00001882 const ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
Chris Lattnercd0ee142009-03-31 08:33:16 +00001883 const FieldDecl *FD = OI->lookupFieldDeclForIvar(CGM.getContext(), Ivar);
1884 return GetIvarBaseOffset(Layout, FD);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00001885}
1886
Daniel Dunbarfd65d372009-03-09 20:09:19 +00001887llvm::GlobalVariable *
1888CGObjCCommonMac::CreateMetadataVar(const std::string &Name,
1889 llvm::Constant *Init,
1890 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +00001891 unsigned Align,
1892 bool AddToUsed) {
Daniel Dunbarfd65d372009-03-09 20:09:19 +00001893 const llvm::Type *Ty = Init->getType();
1894 llvm::GlobalVariable *GV =
1895 new llvm::GlobalVariable(Ty, false,
1896 llvm::GlobalValue::InternalLinkage,
1897 Init,
1898 Name,
1899 &CGM.getModule());
1900 if (Section)
1901 GV->setSection(Section);
Daniel Dunbar35bd7632009-03-09 20:50:13 +00001902 if (Align)
1903 GV->setAlignment(Align);
1904 if (AddToUsed)
Daniel Dunbarfd65d372009-03-09 20:09:19 +00001905 UsedGlobals.push_back(GV);
1906 return GV;
1907}
1908
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001909llvm::Function *CGObjCMac::ModuleInitFunction() {
Daniel Dunbarf77ac862008-08-11 21:35:06 +00001910 // Abuse this interface function as a place to finalize.
1911 FinishModule();
1912
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001913 return NULL;
1914}
1915
Chris Lattner74391b42009-03-22 21:03:39 +00001916llvm::Constant *CGObjCMac::GetPropertyGetFunction() {
Daniel Dunbar49f66022008-09-24 03:38:44 +00001917 return ObjCTypes.GetPropertyFn;
1918}
1919
Chris Lattner74391b42009-03-22 21:03:39 +00001920llvm::Constant *CGObjCMac::GetPropertySetFunction() {
Daniel Dunbar49f66022008-09-24 03:38:44 +00001921 return ObjCTypes.SetPropertyFn;
1922}
1923
Chris Lattner74391b42009-03-22 21:03:39 +00001924llvm::Constant *CGObjCMac::EnumerationMutationFunction() {
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001925 return ObjCTypes.EnumerationMutationFn;
1926}
1927
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001928/*
1929
1930Objective-C setjmp-longjmp (sjlj) Exception Handling
1931--
1932
1933The basic framework for a @try-catch-finally is as follows:
1934{
1935 objc_exception_data d;
1936 id _rethrow = null;
Anders Carlsson190d00e2009-02-07 21:26:04 +00001937 bool _call_try_exit = true;
1938
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001939 objc_exception_try_enter(&d);
1940 if (!setjmp(d.jmp_buf)) {
1941 ... try body ...
1942 } else {
1943 // exception path
1944 id _caught = objc_exception_extract(&d);
1945
1946 // enter new try scope for handlers
1947 if (!setjmp(d.jmp_buf)) {
1948 ... match exception and execute catch blocks ...
1949
1950 // fell off end, rethrow.
1951 _rethrow = _caught;
Daniel Dunbar898d5082008-09-30 01:06:03 +00001952 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001953 } else {
1954 // exception in catch block
1955 _rethrow = objc_exception_extract(&d);
Anders Carlsson190d00e2009-02-07 21:26:04 +00001956 _call_try_exit = false;
1957 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001958 }
1959 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00001960 ... jump-through-finally to finally_end ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001961
1962finally:
Anders Carlsson190d00e2009-02-07 21:26:04 +00001963 if (_call_try_exit)
1964 objc_exception_try_exit(&d);
1965
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001966 ... finally block ....
Daniel Dunbar898d5082008-09-30 01:06:03 +00001967 ... dispatch to finally destination ...
1968
1969finally_rethrow:
1970 objc_exception_throw(_rethrow);
1971
1972finally_end:
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001973}
1974
1975This framework differs slightly from the one gcc uses, in that gcc
Daniel Dunbar898d5082008-09-30 01:06:03 +00001976uses _rethrow to determine if objc_exception_try_exit should be called
1977and if the object should be rethrown. This breaks in the face of
1978throwing nil and introduces unnecessary branches.
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001979
1980We specialize this framework for a few particular circumstances:
1981
1982 - If there are no catch blocks, then we avoid emitting the second
1983 exception handling context.
1984
1985 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
1986 e)) we avoid emitting the code to rethrow an uncaught exception.
1987
1988 - FIXME: If there is no @finally block we can do a few more
1989 simplifications.
1990
1991Rethrows and Jumps-Through-Finally
1992--
1993
1994Support for implicit rethrows and jumping through the finally block is
1995handled by storing the current exception-handling context in
1996ObjCEHStack.
1997
Daniel Dunbar898d5082008-09-30 01:06:03 +00001998In order to implement proper @finally semantics, we support one basic
1999mechanism for jumping through the finally block to an arbitrary
2000destination. Constructs which generate exits from a @try or @catch
2001block use this mechanism to implement the proper semantics by chaining
2002jumps, as necessary.
2003
2004This mechanism works like the one used for indirect goto: we
2005arbitrarily assign an ID to each destination and store the ID for the
2006destination in a variable prior to entering the finally block. At the
2007end of the finally block we simply create a switch to the proper
2008destination.
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002009
2010Code gen for @synchronized(expr) stmt;
2011Effectively generating code for:
2012objc_sync_enter(expr);
2013@try stmt @finally { objc_sync_exit(expr); }
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002014*/
2015
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002016void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
2017 const Stmt &S) {
2018 bool isTry = isa<ObjCAtTryStmt>(S);
Daniel Dunbar898d5082008-09-30 01:06:03 +00002019 // Create various blocks we refer to for handling @finally.
Daniel Dunbar55e87422008-11-11 02:29:29 +00002020 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002021 llvm::BasicBlock *FinallyExit = CGF.createBasicBlock("finally.exit");
Daniel Dunbar55e87422008-11-11 02:29:29 +00002022 llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
2023 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
2024 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
Daniel Dunbar1c566672009-02-24 01:43:46 +00002025
2026 // For @synchronized, call objc_sync_enter(sync.expr). The
2027 // evaluation of the expression must occur before we enter the
2028 // @synchronized. We can safely avoid a temp here because jumps into
2029 // @synchronized are illegal & this will dominate uses.
2030 llvm::Value *SyncArg = 0;
2031 if (!isTry) {
2032 SyncArg =
2033 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
2034 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00002035 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar1c566672009-02-24 01:43:46 +00002036 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00002037
2038 // Push an EH context entry, used for handling rethrows and jumps
2039 // through finally.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002040 CGF.PushCleanupBlock(FinallyBlock);
2041
Anders Carlsson273558f2009-02-07 21:37:21 +00002042 CGF.ObjCEHValueStack.push_back(0);
2043
Daniel Dunbar898d5082008-09-30 01:06:03 +00002044 // Allocate memory for the exception data and rethrow pointer.
Anders Carlsson80f25672008-09-09 17:59:25 +00002045 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
2046 "exceptiondata.ptr");
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002047 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
2048 "_rethrow");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002049 llvm::Value *CallTryExitPtr = CGF.CreateTempAlloca(llvm::Type::Int1Ty,
2050 "_call_try_exit");
2051 CGF.Builder.CreateStore(llvm::ConstantInt::getTrue(), CallTryExitPtr);
2052
Anders Carlsson80f25672008-09-09 17:59:25 +00002053 // Enter a new try block and call setjmp.
2054 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
2055 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
2056 "jmpbufarray");
2057 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
2058 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
2059 JmpBufPtr, "result");
Daniel Dunbar898d5082008-09-30 01:06:03 +00002060
Daniel Dunbar55e87422008-11-11 02:29:29 +00002061 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
2062 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002063 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002064 TryHandler, TryBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002065
2066 // Emit the @try block.
2067 CGF.EmitBlock(TryBlock);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002068 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
2069 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002070 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002071
2072 // Emit the "exception in @try" block.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002073 CGF.EmitBlock(TryHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002074
2075 // Retrieve the exception object. We may emit multiple blocks but
2076 // nothing can cross this so the value is already in SSA form.
2077 llvm::Value *Caught = CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
2078 ExceptionData,
2079 "caught");
Anders Carlsson273558f2009-02-07 21:37:21 +00002080 CGF.ObjCEHValueStack.back() = Caught;
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002081 if (!isTry)
2082 {
2083 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002084 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002085 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002086 }
2087 else if (const ObjCAtCatchStmt* CatchStmt =
2088 cast<ObjCAtTryStmt>(S).getCatchStmts())
2089 {
Daniel Dunbar55e40722008-09-27 07:03:52 +00002090 // Enter a new exception try block (in case a @catch block throws
2091 // an exception).
Anders Carlsson80f25672008-09-09 17:59:25 +00002092 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002093
Anders Carlsson80f25672008-09-09 17:59:25 +00002094 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
2095 JmpBufPtr, "result");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002096 llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw");
Anders Carlsson80f25672008-09-09 17:59:25 +00002097
Daniel Dunbar55e87422008-11-11 02:29:29 +00002098 llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch");
2099 llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler");
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002100 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002101
2102 CGF.EmitBlock(CatchBlock);
2103
Daniel Dunbar55e40722008-09-27 07:03:52 +00002104 // Handle catch list. As a special case we check if everything is
2105 // matched and avoid generating code for falling off the end if
2106 // so.
2107 bool AllMatched = false;
Anders Carlsson80f25672008-09-09 17:59:25 +00002108 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbar55e87422008-11-11 02:29:29 +00002109 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch");
Anders Carlsson80f25672008-09-09 17:59:25 +00002110
Steve Naroff7ba138a2009-03-03 19:52:17 +00002111 const ParmVarDecl *CatchParam = CatchStmt->getCatchParamDecl();
Daniel Dunbar129271a2008-09-27 07:36:24 +00002112 const PointerType *PT = 0;
2113
Anders Carlsson80f25672008-09-09 17:59:25 +00002114 // catch(...) always matches.
Daniel Dunbar55e40722008-09-27 07:03:52 +00002115 if (!CatchParam) {
2116 AllMatched = true;
2117 } else {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002118 PT = CatchParam->getType()->getAsPointerType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002119
Daniel Dunbar97f61d12008-09-27 22:21:14 +00002120 // catch(id e) always matches.
2121 // FIXME: For the time being we also match id<X>; this should
2122 // be rejected by Sema instead.
Steve Naroff389bf462009-02-12 17:52:19 +00002123 if ((PT && CGF.getContext().isObjCIdStructType(PT->getPointeeType())) ||
Steve Naroff7ba138a2009-03-03 19:52:17 +00002124 CatchParam->getType()->isObjCQualifiedIdType())
Daniel Dunbar55e40722008-09-27 07:03:52 +00002125 AllMatched = true;
Anders Carlsson80f25672008-09-09 17:59:25 +00002126 }
2127
Daniel Dunbar55e40722008-09-27 07:03:52 +00002128 if (AllMatched) {
Anders Carlssondde0a942008-09-11 09:15:33 +00002129 if (CatchParam) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002130 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002131 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002132 CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002133 }
Anders Carlsson1452f552008-09-11 08:21:54 +00002134
Anders Carlssondde0a942008-09-11 09:15:33 +00002135 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002136 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002137 break;
2138 }
2139
Daniel Dunbar129271a2008-09-27 07:36:24 +00002140 assert(PT && "Unexpected non-pointer type in @catch");
2141 QualType T = PT->getPointeeType();
Anders Carlsson4b7ff6e2008-09-11 06:35:14 +00002142 const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002143 assert(ObjCType && "Catch parameter must have Objective-C type!");
2144
2145 // Check if the @catch block matches the exception object.
2146 llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl());
2147
Anders Carlsson80f25672008-09-09 17:59:25 +00002148 llvm::Value *Match = CGF.Builder.CreateCall2(ObjCTypes.ExceptionMatchFn,
2149 Class, Caught, "match");
Anders Carlsson80f25672008-09-09 17:59:25 +00002150
Daniel Dunbar55e87422008-11-11 02:29:29 +00002151 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched");
Anders Carlsson80f25672008-09-09 17:59:25 +00002152
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002153 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002154 MatchedBlock, NextCatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002155
2156 // Emit the @catch block.
2157 CGF.EmitBlock(MatchedBlock);
Steve Naroff7ba138a2009-03-03 19:52:17 +00002158 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002159 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002160
2161 llvm::Value *Tmp =
Steve Naroff7ba138a2009-03-03 19:52:17 +00002162 CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(CatchParam->getType()),
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002163 "tmp");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002164 CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002165
2166 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002167 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002168
2169 CGF.EmitBlock(NextCatchBlock);
2170 }
2171
Daniel Dunbar55e40722008-09-27 07:03:52 +00002172 if (!AllMatched) {
2173 // None of the handlers caught the exception, so store it to be
2174 // rethrown at the end of the @finally block.
2175 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002176 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002177 }
2178
2179 // Emit the exception handler for the @catch blocks.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002180 CGF.EmitBlock(CatchHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002181 CGF.Builder.CreateStore(CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
2182 ExceptionData),
2183 RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002184 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002185 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002186 } else {
Anders Carlsson80f25672008-09-09 17:59:25 +00002187 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002188 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002189 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Anders Carlsson80f25672008-09-09 17:59:25 +00002190 }
2191
Daniel Dunbar898d5082008-09-30 01:06:03 +00002192 // Pop the exception-handling stack entry. It is important to do
2193 // this now, because the code in the @finally block is not in this
2194 // context.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002195 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
2196
Anders Carlsson273558f2009-02-07 21:37:21 +00002197 CGF.ObjCEHValueStack.pop_back();
2198
Anders Carlsson80f25672008-09-09 17:59:25 +00002199 // Emit the @finally block.
2200 CGF.EmitBlock(FinallyBlock);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002201 llvm::Value* CallTryExit = CGF.Builder.CreateLoad(CallTryExitPtr, "tmp");
2202
2203 CGF.Builder.CreateCondBr(CallTryExit, FinallyExit, FinallyNoExit);
2204
2205 CGF.EmitBlock(FinallyExit);
Anders Carlsson80f25672008-09-09 17:59:25 +00002206 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryExitFn, ExceptionData);
Daniel Dunbar129271a2008-09-27 07:36:24 +00002207
2208 CGF.EmitBlock(FinallyNoExit);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002209 if (isTry) {
2210 if (const ObjCAtFinallyStmt* FinallyStmt =
2211 cast<ObjCAtTryStmt>(S).getFinallyStmt())
2212 CGF.EmitStmt(FinallyStmt->getFinallyBody());
Daniel Dunbar1c566672009-02-24 01:43:46 +00002213 } else {
2214 // Emit objc_sync_exit(expr); as finally's sole statement for
2215 // @synchronized.
2216 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, SyncArg);
Fariborz Jahanianf2878e52008-11-21 19:21:53 +00002217 }
Anders Carlsson80f25672008-09-09 17:59:25 +00002218
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002219 // Emit the switch block
2220 if (Info.SwitchBlock)
2221 CGF.EmitBlock(Info.SwitchBlock);
2222 if (Info.EndBlock)
2223 CGF.EmitBlock(Info.EndBlock);
2224
Daniel Dunbar898d5082008-09-30 01:06:03 +00002225 CGF.EmitBlock(FinallyRethrow);
2226 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn,
2227 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002228 CGF.Builder.CreateUnreachable();
Daniel Dunbar898d5082008-09-30 01:06:03 +00002229
2230 CGF.EmitBlock(FinallyEnd);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002231}
2232
2233void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar898d5082008-09-30 01:06:03 +00002234 const ObjCAtThrowStmt &S) {
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002235 llvm::Value *ExceptionAsObject;
2236
2237 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2238 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
2239 ExceptionAsObject =
2240 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
2241 } else {
Anders Carlsson273558f2009-02-07 21:37:21 +00002242 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002243 "Unexpected rethrow outside @catch block.");
Anders Carlsson273558f2009-02-07 21:37:21 +00002244 ExceptionAsObject = CGF.ObjCEHValueStack.back();
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002245 }
2246
2247 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
Anders Carlsson80f25672008-09-09 17:59:25 +00002248 CGF.Builder.CreateUnreachable();
Daniel Dunbara448fb22008-11-11 23:11:34 +00002249
2250 // Clear the insertion point to indicate we are in unreachable code.
2251 CGF.Builder.ClearInsertionPoint();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002252}
2253
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002254/// EmitObjCWeakRead - Code gen for loading value of a __weak
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002255/// object: objc_read_weak (id *src)
2256///
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002257llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002258 llvm::Value *AddrWeakObj)
2259{
Eli Friedman8339b352009-03-07 03:57:15 +00002260 const llvm::Type* DestTy =
2261 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002262 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002263 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002264 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00002265 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002266 return read_weak;
2267}
2268
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002269/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
2270/// objc_assign_weak (id src, id *dst)
2271///
2272void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
2273 llvm::Value *src, llvm::Value *dst)
2274{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002275 const llvm::Type * SrcTy = src->getType();
2276 if (!isa<llvm::PointerType>(SrcTy)) {
2277 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2278 assert(Size <= 8 && "does not support size > 8");
2279 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2280 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002281 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2282 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002283 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2284 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002285 CGF.Builder.CreateCall2(ObjCTypes.GcAssignWeakFn,
2286 src, dst, "weakassign");
2287 return;
2288}
2289
Fariborz Jahanian58626502008-11-19 00:59:10 +00002290/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
2291/// objc_assign_global (id src, id *dst)
2292///
2293void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
2294 llvm::Value *src, llvm::Value *dst)
2295{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002296 const llvm::Type * SrcTy = src->getType();
2297 if (!isa<llvm::PointerType>(SrcTy)) {
2298 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2299 assert(Size <= 8 && "does not support size > 8");
2300 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2301 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002302 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2303 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002304 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2305 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian58626502008-11-19 00:59:10 +00002306 CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn,
2307 src, dst, "globalassign");
2308 return;
2309}
2310
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002311/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
2312/// objc_assign_ivar (id src, id *dst)
2313///
2314void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
2315 llvm::Value *src, llvm::Value *dst)
2316{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002317 const llvm::Type * SrcTy = src->getType();
2318 if (!isa<llvm::PointerType>(SrcTy)) {
2319 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2320 assert(Size <= 8 && "does not support size > 8");
2321 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2322 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002323 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2324 }
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002325 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2326 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
2327 CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn,
2328 src, dst, "assignivar");
2329 return;
2330}
2331
Fariborz Jahanian58626502008-11-19 00:59:10 +00002332/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
2333/// objc_assign_strongCast (id src, id *dst)
2334///
2335void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
2336 llvm::Value *src, llvm::Value *dst)
2337{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002338 const llvm::Type * SrcTy = src->getType();
2339 if (!isa<llvm::PointerType>(SrcTy)) {
2340 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2341 assert(Size <= 8 && "does not support size > 8");
2342 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2343 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002344 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2345 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002346 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2347 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian58626502008-11-19 00:59:10 +00002348 CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn,
2349 src, dst, "weakassign");
2350 return;
2351}
2352
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002353/// EmitObjCValueForIvar - Code Gen for ivar reference.
2354///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002355LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
2356 QualType ObjectTy,
2357 llvm::Value *BaseValue,
2358 const ObjCIvarDecl *Ivar,
2359 const FieldDecl *Field,
2360 unsigned CVRQualifiers) {
2361 if (Ivar->isBitField())
2362 return CGF.EmitLValueForBitfield(BaseValue, const_cast<FieldDecl *>(Field),
2363 CVRQualifiers);
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002364 // TODO: Add a special case for isa (index 0)
2365 unsigned Index = CGM.getTypes().getLLVMFieldNo(Field);
2366 llvm::Value *V = CGF.Builder.CreateStructGEP(BaseValue, Index, "tmp");
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002367 LValue LV = LValue::MakeAddr(V,
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00002368 Ivar->getType().getCVRQualifiers()|CVRQualifiers,
2369 CGM.getContext().getObjCGCAttrKind(Ivar->getType()));
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002370 LValue::SetObjCIvar(LV, true);
2371 return LV;
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002372}
2373
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002374llvm::Value *CGObjCMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
2375 ObjCInterfaceDecl *Interface,
2376 const ObjCIvarDecl *Ivar) {
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002377 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(Interface);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002378 FieldDecl *Field = Interface->lookupFieldDeclForIvar(CGM.getContext(), Ivar);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00002379 uint64_t Offset = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002380 return llvm::ConstantInt::get(
2381 CGM.getTypes().ConvertType(CGM.getContext().LongTy),
2382 Offset);
2383}
2384
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002385/* *** Private Interface *** */
2386
2387/// EmitImageInfo - Emit the image info marker used to encode some module
2388/// level information.
2389///
2390/// See: <rdr://4810609&4810587&4810587>
2391/// struct IMAGE_INFO {
2392/// unsigned version;
2393/// unsigned flags;
2394/// };
2395enum ImageInfoFlags {
2396 eImageInfo_FixAndContinue = (1 << 0), // FIXME: Not sure what this implies
2397 eImageInfo_GarbageCollected = (1 << 1),
2398 eImageInfo_GCOnly = (1 << 2)
2399};
2400
2401void CGObjCMac::EmitImageInfo() {
2402 unsigned version = 0; // Version is unused?
2403 unsigned flags = 0;
2404
2405 // FIXME: Fix and continue?
2406 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
2407 flags |= eImageInfo_GarbageCollected;
2408 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
2409 flags |= eImageInfo_GCOnly;
2410
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002411 // Emitted as int[2];
2412 llvm::Constant *values[2] = {
2413 llvm::ConstantInt::get(llvm::Type::Int32Ty, version),
2414 llvm::ConstantInt::get(llvm::Type::Int32Ty, flags)
2415 };
2416 llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002417
2418 const char *Section;
2419 if (ObjCABI == 1)
2420 Section = "__OBJC, __image_info,regular";
2421 else
2422 Section = "__DATA, __objc_imageinfo, regular, no_dead_strip";
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002423 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002424 CreateMetadataVar("\01L_OBJC_IMAGE_INFO",
2425 llvm::ConstantArray::get(AT, values, 2),
2426 Section,
2427 0,
2428 true);
2429 GV->setConstant(true);
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002430}
2431
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002432
2433// struct objc_module {
2434// unsigned long version;
2435// unsigned long size;
2436// const char *name;
2437// Symtab symtab;
2438// };
2439
2440// FIXME: Get from somewhere
2441static const int ModuleVersion = 7;
2442
2443void CGObjCMac::EmitModuleInfo() {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00002444 uint64_t Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ModuleTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002445
2446 std::vector<llvm::Constant*> Values(4);
2447 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
2448 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002449 // This used to be the filename, now it is unused. <rdr://4327263>
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002450 Values[2] = GetClassName(&CGM.getContext().Idents.get(""));
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002451 Values[3] = EmitModuleSymbols();
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002452 CreateMetadataVar("\01L_OBJC_MODULES",
2453 llvm::ConstantStruct::get(ObjCTypes.ModuleTy, Values),
2454 "__OBJC,__module_info,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00002455 4, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002456}
2457
2458llvm::Constant *CGObjCMac::EmitModuleSymbols() {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002459 unsigned NumClasses = DefinedClasses.size();
2460 unsigned NumCategories = DefinedCategories.size();
2461
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002462 // Return null if no symbols were defined.
2463 if (!NumClasses && !NumCategories)
2464 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
2465
2466 std::vector<llvm::Constant*> Values(5);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002467 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2468 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
2469 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
2470 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
2471
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002472 // The runtime expects exactly the list of defined classes followed
2473 // by the list of defined categories, in a single array.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002474 std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002475 for (unsigned i=0; i<NumClasses; i++)
2476 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
2477 ObjCTypes.Int8PtrTy);
2478 for (unsigned i=0; i<NumCategories; i++)
2479 Symbols[NumClasses + i] =
2480 llvm::ConstantExpr::getBitCast(DefinedCategories[i],
2481 ObjCTypes.Int8PtrTy);
2482
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002483 Values[4] =
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002484 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002485 NumClasses + NumCategories),
2486 Symbols);
2487
2488 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2489
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002490 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002491 CreateMetadataVar("\01L_OBJC_SYMBOLS", Init,
2492 "__OBJC,__symbols,regular,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002493 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002494 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
2495}
2496
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002497llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002498 const ObjCInterfaceDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002499 LazySymbols.insert(ID->getIdentifier());
2500
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002501 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
2502
2503 if (!Entry) {
2504 llvm::Constant *Casted =
2505 llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()),
2506 ObjCTypes.ClassPtrTy);
2507 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002508 CreateMetadataVar("\01L_OBJC_CLASS_REFERENCES_", Casted,
2509 "__OBJC,__cls_refs,literal_pointers,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002510 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002511 }
2512
2513 return Builder.CreateLoad(Entry, false, "tmp");
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002514}
2515
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002516llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002517 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
2518
2519 if (!Entry) {
2520 llvm::Constant *Casted =
2521 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
2522 ObjCTypes.SelectorPtrTy);
2523 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002524 CreateMetadataVar("\01L_OBJC_SELECTOR_REFERENCES_", Casted,
2525 "__OBJC,__message_refs,literal_pointers,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002526 4, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002527 }
2528
2529 return Builder.CreateLoad(Entry, false, "tmp");
2530}
2531
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00002532llvm::Constant *CGObjCCommonMac::GetClassName(IdentifierInfo *Ident) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002533 llvm::GlobalVariable *&Entry = ClassNames[Ident];
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002534
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002535 if (!Entry)
2536 Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
2537 llvm::ConstantArray::get(Ident->getName()),
2538 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00002539 1, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002540
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002541 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002542}
2543
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002544/// GetInterfaceDeclStructLayout - Get layout for ivars of given
2545/// interface declaration.
2546const llvm::StructLayout *CGObjCCommonMac::GetInterfaceDeclStructLayout(
2547 const ObjCInterfaceDecl *OID) const {
2548 const llvm::Type *InterfaceTy =
2549 CGM.getTypes().ConvertType(
2550 CGM.getContext().getObjCInterfaceType(
2551 const_cast<ObjCInterfaceDecl*>(OID)));
2552 const llvm::StructLayout *Layout =
2553 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceTy));
2554 return Layout;
2555}
2556
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00002557/// GetIvarLayoutName - Returns a unique constant for the given
2558/// ivar layout bitmap.
2559llvm::Constant *CGObjCCommonMac::GetIvarLayoutName(IdentifierInfo *Ident,
2560 const ObjCCommonTypesHelper &ObjCTypes) {
2561 return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2562}
2563
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002564void CGObjCCommonMac::BuildAggrIvarLayout(const ObjCInterfaceDecl *OI,
2565 const llvm::StructLayout *Layout,
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002566 const RecordDecl *RD,
Chris Lattnerf1690852009-03-31 08:48:01 +00002567 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002568 unsigned int BytePos, bool ForStrongLayout,
2569 int &Index, int &SkIndex, bool &HasUnion) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002570 bool IsUnion = (RD && RD->isUnion());
2571 uint64_t MaxUnionIvarSize = 0;
2572 uint64_t MaxSkippedUnionIvarSize = 0;
2573 FieldDecl *MaxField = 0;
2574 FieldDecl *MaxSkippedField = 0;
Chris Lattnerf1690852009-03-31 08:48:01 +00002575 unsigned base = 0;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002576 if (RecFields.empty())
2577 return;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002578 if (IsUnion)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002579 base = BytePos + GetFieldBaseOffset(OI, Layout, RecFields[0]);
Chris Lattnerf1690852009-03-31 08:48:01 +00002580 unsigned WordSizeInBits = CGM.getContext().Target.getPointerWidth(0);
2581 unsigned ByteSizeInBits = CGM.getContext().Target.getCharWidth();
2582
2583 llvm::SmallVector<FieldDecl*, 16> TmpRecFields;
2584
2585 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002586 FieldDecl *Field = RecFields[i];
2587 // Skip over unnamed or bitfields
2588 if (!Field->getIdentifier() || Field->isBitField())
2589 continue;
2590 QualType FQT = Field->getType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002591 if (FQT->isRecordType() || FQT->isUnionType()) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002592 if (FQT->isUnionType())
2593 HasUnion = true;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002594 else
2595 assert(FQT->isRecordType() &&
2596 "only union/record is supported for ivar layout bitmap");
2597
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002598 const RecordType *RT = FQT->getAsRecordType();
2599 const RecordDecl *RD = RT->getDecl();
2600 // FIXME - Find a more efficiant way of passing records down.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002601 TmpRecFields.append(RD->field_begin(CGM.getContext()),
2602 RD->field_end(CGM.getContext()));
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002603 // FIXME - Is Layout correct?
Chris Lattnerf1690852009-03-31 08:48:01 +00002604 BuildAggrIvarLayout(OI, Layout, RD, TmpRecFields,
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002605 BytePos + GetFieldBaseOffset(OI, Layout, Field),
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002606 ForStrongLayout, Index, SkIndex,
2607 HasUnion);
Chris Lattnerf1690852009-03-31 08:48:01 +00002608 TmpRecFields.clear();
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002609 continue;
2610 }
Chris Lattnerf1690852009-03-31 08:48:01 +00002611
2612 if (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002613 const ConstantArrayType *CArray =
2614 dyn_cast_or_null<ConstantArrayType>(Array);
2615 assert(CArray && "only array with know element size is supported");
2616 FQT = CArray->getElementType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002617 while (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
2618 const ConstantArrayType *CArray =
2619 dyn_cast_or_null<ConstantArrayType>(Array);
2620 FQT = CArray->getElementType();
2621 }
2622
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002623 assert(!FQT->isUnionType() &&
2624 "layout for array of unions not supported");
2625 if (FQT->isRecordType()) {
2626 uint64_t ElCount = CArray->getSize().getZExtValue();
2627 int OldIndex = Index;
2628 int OldSkIndex = SkIndex;
2629
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002630 // FIXME - Use a common routine with the above!
2631 const RecordType *RT = FQT->getAsRecordType();
2632 const RecordDecl *RD = RT->getDecl();
2633 // FIXME - Find a more efficiant way of passing records down.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002634 TmpRecFields.append(RD->field_begin(CGM.getContext()),
2635 RD->field_end(CGM.getContext()));
Chris Lattnerf1690852009-03-31 08:48:01 +00002636
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002637 BuildAggrIvarLayout(OI, Layout, RD,
Chris Lattnerf1690852009-03-31 08:48:01 +00002638 TmpRecFields,
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002639 BytePos + GetFieldBaseOffset(OI, Layout, Field),
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002640 ForStrongLayout, Index, SkIndex,
2641 HasUnion);
Chris Lattnerf1690852009-03-31 08:48:01 +00002642 TmpRecFields.clear();
2643
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002644 // Replicate layout information for each array element. Note that
2645 // one element is already done.
2646 uint64_t ElIx = 1;
2647 for (int FirstIndex = Index, FirstSkIndex = SkIndex;
2648 ElIx < ElCount; ElIx++) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002649 uint64_t Size = CGM.getContext().getTypeSize(RT)/ByteSizeInBits;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002650 for (int i = OldIndex+1; i <= FirstIndex; ++i)
2651 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002652 GC_IVAR gcivar;
2653 gcivar.ivar_bytepos = IvarsInfo[i].ivar_bytepos + Size*ElIx;
2654 gcivar.ivar_size = IvarsInfo[i].ivar_size;
2655 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002656 }
2657
Chris Lattnerf1690852009-03-31 08:48:01 +00002658 for (int i = OldSkIndex+1; i <= FirstSkIndex; ++i) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002659 GC_IVAR skivar;
2660 skivar.ivar_bytepos = SkipIvars[i].ivar_bytepos + Size*ElIx;
2661 skivar.ivar_size = SkipIvars[i].ivar_size;
2662 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002663 }
2664 }
2665 continue;
2666 }
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002667 }
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002668 // At this point, we are done with Record/Union and array there of.
2669 // For other arrays we are down to its element type.
2670 QualType::GCAttrTypes GCAttr = QualType::GCNone;
2671 do {
2672 if (FQT.isObjCGCStrong() || FQT.isObjCGCWeak()) {
2673 GCAttr = FQT.isObjCGCStrong() ? QualType::Strong : QualType::Weak;
2674 break;
2675 }
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002676 else if (CGM.getContext().isObjCObjectPointerType(FQT)) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002677 GCAttr = QualType::Strong;
2678 break;
2679 }
2680 else if (const PointerType *PT = FQT->getAsPointerType()) {
2681 FQT = PT->getPointeeType();
2682 }
2683 else {
2684 break;
2685 }
2686 } while (true);
Chris Lattnerf1690852009-03-31 08:48:01 +00002687
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002688 if ((ForStrongLayout && GCAttr == QualType::Strong)
2689 || (!ForStrongLayout && GCAttr == QualType::Weak)) {
2690 if (IsUnion)
2691 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002692 uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType())
2693 / WordSizeInBits;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002694 if (UnionIvarSize > MaxUnionIvarSize)
2695 {
2696 MaxUnionIvarSize = UnionIvarSize;
2697 MaxField = Field;
2698 }
2699 }
2700 else
2701 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002702 GC_IVAR gcivar;
2703 gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field);
2704 gcivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) /
2705 WordSizeInBits;
2706 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002707 }
2708 }
2709 else if ((ForStrongLayout &&
2710 (GCAttr == QualType::GCNone || GCAttr == QualType::Weak))
2711 || (!ForStrongLayout && GCAttr != QualType::Weak)) {
2712 if (IsUnion)
2713 {
2714 uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType());
2715 if (UnionIvarSize > MaxSkippedUnionIvarSize)
2716 {
2717 MaxSkippedUnionIvarSize = UnionIvarSize;
2718 MaxSkippedField = Field;
2719 }
2720 }
2721 else
2722 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002723 GC_IVAR skivar;
2724 skivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field);
2725 skivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) /
2726 WordSizeInBits;
2727 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002728 }
2729 }
2730 }
Chris Lattnerf1690852009-03-31 08:48:01 +00002731 if (MaxField) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002732 GC_IVAR gcivar;
2733 gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, MaxField);
2734 gcivar.ivar_size = MaxUnionIvarSize;
2735 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002736 }
Chris Lattnerf1690852009-03-31 08:48:01 +00002737
2738 if (MaxSkippedField) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002739 GC_IVAR skivar;
2740 skivar.ivar_bytepos = BytePos +
2741 GetFieldBaseOffset(OI, Layout, MaxSkippedField);
2742 skivar.ivar_size = MaxSkippedUnionIvarSize;
2743 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002744 }
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002745}
2746
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002747static int
Chris Lattnerf1690852009-03-31 08:48:01 +00002748IvarBytePosCompare(const void *a, const void *b)
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002749{
2750 unsigned int sa = ((CGObjCCommonMac::GC_IVAR *)a)->ivar_bytepos;
2751 unsigned int sb = ((CGObjCCommonMac::GC_IVAR *)b)->ivar_bytepos;
2752
2753 if (sa < sb)
2754 return -1;
2755 if (sa > sb)
2756 return 1;
2757 return 0;
2758}
2759
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002760/// BuildIvarLayout - Builds ivar layout bitmap for the class
2761/// implementation for the __strong or __weak case.
2762/// The layout map displays which words in ivar list must be skipped
2763/// and which must be scanned by GC (see below). String is built of bytes.
2764/// Each byte is divided up in two nibbles (4-bit each). Left nibble is count
2765/// of words to skip and right nibble is count of words to scan. So, each
2766/// nibble represents up to 15 workds to skip or scan. Skipping the rest is
2767/// represented by a 0x00 byte which also ends the string.
2768/// 1. when ForStrongLayout is true, following ivars are scanned:
2769/// - id, Class
2770/// - object *
2771/// - __strong anything
2772///
2773/// 2. When ForStrongLayout is false, following ivars are scanned:
2774/// - __weak anything
2775///
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002776llvm::Constant *CGObjCCommonMac::BuildIvarLayout(
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002777 const ObjCImplementationDecl *OMD,
2778 bool ForStrongLayout) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002779 int Index = -1;
2780 int SkIndex = -1;
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002781 bool hasUnion = false;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002782 int SkipScan;
2783 unsigned int WordsToScan, WordsToSkip;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002784 const llvm::Type *PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
2785 if (CGM.getLangOptions().getGCMode() == LangOptions::NonGC)
2786 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002787
Chris Lattnerf1690852009-03-31 08:48:01 +00002788 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002789 const ObjCInterfaceDecl *OI = OMD->getClassInterface();
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002790 CGM.getContext().CollectObjCIvars(OI, RecFields);
2791 if (RecFields.empty())
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002792 return llvm::Constant::getNullValue(PtrTy);
Chris Lattnerf1690852009-03-31 08:48:01 +00002793
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002794 SkipIvars.clear();
2795 IvarsInfo.clear();
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002796
2797 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OI);
Chris Lattnerf1690852009-03-31 08:48:01 +00002798 BuildAggrIvarLayout(OI, Layout, 0, RecFields, 0, ForStrongLayout,
2799 Index, SkIndex, hasUnion);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002800 if (Index == -1)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002801 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002802
2803 // Sort on byte position in case we encounterred a union nested in
2804 // the ivar list.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002805 if (hasUnion && !IvarsInfo.empty())
2806 qsort(&IvarsInfo[0], Index+1, sizeof(GC_IVAR), IvarBytePosCompare);
2807 if (hasUnion && !SkipIvars.empty())
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002808 qsort(&SkipIvars[0], Index+1, sizeof(GC_IVAR), IvarBytePosCompare);
2809
2810 // Build the string of skip/scan nibbles
2811 SkipScan = -1;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002812 SkipScanIvars.clear();
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002813 unsigned int WordSize =
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002814 CGM.getTypes().getTargetData().getTypePaddedSize(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002815 if (IvarsInfo[0].ivar_bytepos == 0) {
2816 WordsToSkip = 0;
2817 WordsToScan = IvarsInfo[0].ivar_size;
2818 }
2819 else {
2820 WordsToSkip = IvarsInfo[0].ivar_bytepos/WordSize;
2821 WordsToScan = IvarsInfo[0].ivar_size;
2822 }
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002823 for (unsigned int i=1, Last=IvarsInfo.size(); i != Last; i++)
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002824 {
2825 unsigned int TailPrevGCObjC =
2826 IvarsInfo[i-1].ivar_bytepos + IvarsInfo[i-1].ivar_size * WordSize;
2827 if (IvarsInfo[i].ivar_bytepos == TailPrevGCObjC)
2828 {
2829 // consecutive 'scanned' object pointers.
2830 WordsToScan += IvarsInfo[i].ivar_size;
2831 }
2832 else
2833 {
2834 // Skip over 'gc'able object pointer which lay over each other.
2835 if (TailPrevGCObjC > IvarsInfo[i].ivar_bytepos)
2836 continue;
2837 // Must skip over 1 or more words. We save current skip/scan values
2838 // and start a new pair.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002839 SKIP_SCAN SkScan;
2840 SkScan.skip = WordsToSkip;
2841 SkScan.scan = WordsToScan;
2842 SkipScanIvars.push_back(SkScan); ++SkipScan;
2843
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002844 // Skip the hole.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002845 SkScan.skip = (IvarsInfo[i].ivar_bytepos - TailPrevGCObjC) / WordSize;
2846 SkScan.scan = 0;
2847 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002848 WordsToSkip = 0;
2849 WordsToScan = IvarsInfo[i].ivar_size;
2850 }
2851 }
2852 if (WordsToScan > 0)
2853 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002854 SKIP_SCAN SkScan;
2855 SkScan.skip = WordsToSkip;
2856 SkScan.scan = WordsToScan;
2857 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002858 }
2859
2860 bool BytesSkipped = false;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002861 if (!SkipIvars.empty())
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002862 {
2863 int LastByteSkipped =
2864 SkipIvars[SkIndex].ivar_bytepos + SkipIvars[SkIndex].ivar_size;
2865 int LastByteScanned =
2866 IvarsInfo[Index].ivar_bytepos + IvarsInfo[Index].ivar_size * WordSize;
2867 BytesSkipped = (LastByteSkipped > LastByteScanned);
2868 // Compute number of bytes to skip at the tail end of the last ivar scanned.
2869 if (BytesSkipped)
2870 {
2871 unsigned int TotalWords = (LastByteSkipped + (WordSize -1)) / WordSize;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002872 SKIP_SCAN SkScan;
2873 SkScan.skip = TotalWords - (LastByteScanned/WordSize);
2874 SkScan.scan = 0;
2875 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002876 }
2877 }
2878 // Mini optimization of nibbles such that an 0xM0 followed by 0x0N is produced
2879 // as 0xMN.
2880 for (int i = 0; i <= SkipScan; i++)
2881 {
2882 if ((i < SkipScan) && SkipScanIvars[i].skip && SkipScanIvars[i].scan == 0
2883 && SkipScanIvars[i+1].skip == 0 && SkipScanIvars[i+1].scan) {
2884 // 0xM0 followed by 0x0N detected.
2885 SkipScanIvars[i].scan = SkipScanIvars[i+1].scan;
2886 for (int j = i+1; j < SkipScan; j++)
2887 SkipScanIvars[j] = SkipScanIvars[j+1];
2888 --SkipScan;
2889 }
2890 }
2891
2892 // Generate the string.
2893 std::string BitMap;
2894 for (int i = 0; i <= SkipScan; i++)
2895 {
2896 unsigned char byte;
2897 unsigned int skip_small = SkipScanIvars[i].skip % 0xf;
2898 unsigned int scan_small = SkipScanIvars[i].scan % 0xf;
2899 unsigned int skip_big = SkipScanIvars[i].skip / 0xf;
2900 unsigned int scan_big = SkipScanIvars[i].scan / 0xf;
2901
2902 if (skip_small > 0 || skip_big > 0)
2903 BytesSkipped = true;
2904 // first skip big.
2905 for (unsigned int ix = 0; ix < skip_big; ix++)
2906 BitMap += (unsigned char)(0xf0);
2907
2908 // next (skip small, scan)
2909 if (skip_small)
2910 {
2911 byte = skip_small << 4;
2912 if (scan_big > 0)
2913 {
2914 byte |= 0xf;
2915 --scan_big;
2916 }
2917 else if (scan_small)
2918 {
2919 byte |= scan_small;
2920 scan_small = 0;
2921 }
2922 BitMap += byte;
2923 }
2924 // next scan big
2925 for (unsigned int ix = 0; ix < scan_big; ix++)
2926 BitMap += (unsigned char)(0x0f);
2927 // last scan small
2928 if (scan_small)
2929 {
2930 byte = scan_small;
2931 BitMap += byte;
2932 }
2933 }
2934 // null terminate string.
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002935 unsigned char zero = 0;
2936 BitMap += zero;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002937 // if ivar_layout bitmap is all 1 bits (nothing skipped) then use NULL as
2938 // final layout.
2939 if (ForStrongLayout && !BytesSkipped)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002940 return llvm::Constant::getNullValue(PtrTy);
2941 llvm::GlobalVariable * Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
2942 llvm::ConstantArray::get(BitMap.c_str()),
2943 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00002944 1, true);
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002945 // FIXME. Need a commomand-line option for this eventually.
2946 if (ForStrongLayout)
2947 printf("\nstrong ivar layout: ");
2948 else
2949 printf("\nweak ivar layout: ");
2950 const unsigned char *s = (unsigned char*)BitMap.c_str();
2951 for (unsigned i = 0; i < BitMap.size(); i++)
Fariborz Jahaniandbf15cb2009-03-26 19:10:36 +00002952 if (!(s[i] & 0xf0))
2953 printf("0x0%x%s", s[i], s[i] != 0 ? ", " : "");
2954 else
2955 printf("0x%x%s", s[i], s[i] != 0 ? ", " : "");
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002956 printf("\n");
2957
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002958 return getConstantGEP(Entry, 0, 0);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002959}
2960
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002961llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002962 llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
2963
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002964 // FIXME: Avoid std::string copying.
2965 if (!Entry)
2966 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_NAME_",
2967 llvm::ConstantArray::get(Sel.getAsString()),
2968 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00002969 1, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002970
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002971 return getConstantGEP(Entry, 0, 0);
2972}
2973
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002974// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002975llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002976 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
2977}
2978
2979// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002980llvm::Constant *CGObjCCommonMac::GetMethodVarName(const std::string &Name) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002981 return GetMethodVarName(&CGM.getContext().Idents.get(Name));
2982}
2983
Devang Patel7794bb82009-03-04 18:21:39 +00002984llvm::Constant *CGObjCCommonMac::GetMethodVarType(FieldDecl *Field) {
2985 std::string TypeStr;
2986 CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
2987
2988 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002989
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002990 if (!Entry)
2991 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
2992 llvm::ConstantArray::get(TypeStr),
2993 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00002994 1, true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002995
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002996 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002997}
2998
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002999llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003000 std::string TypeStr;
Daniel Dunbarc45ef602008-08-26 21:51:14 +00003001 CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D),
3002 TypeStr);
Devang Patel7794bb82009-03-04 18:21:39 +00003003
3004 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
3005
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003006 if (!Entry)
3007 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3008 llvm::ConstantArray::get(TypeStr),
3009 "__TEXT,__cstring,cstring_literals",
3010 1, true);
Devang Patel7794bb82009-03-04 18:21:39 +00003011
3012 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003013}
3014
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003015// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003016llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003017 llvm::GlobalVariable *&Entry = PropertyNames[Ident];
3018
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003019 if (!Entry)
3020 Entry = CreateMetadataVar("\01L_OBJC_PROP_NAME_ATTR_",
3021 llvm::ConstantArray::get(Ident->getName()),
3022 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003023 1, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003024
3025 return getConstantGEP(Entry, 0, 0);
3026}
3027
3028// FIXME: Merge into a single cstring creation function.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003029// FIXME: This Decl should be more precise.
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003030llvm::Constant *
3031 CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
3032 const Decl *Container) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003033 std::string TypeStr;
3034 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003035 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
3036}
3037
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003038void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D,
3039 const ObjCContainerDecl *CD,
3040 std::string &NameOut) {
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00003041 NameOut = '\01';
3042 NameOut += (D->isInstanceMethod() ? '-' : '+');
Chris Lattner077bf5e2008-11-24 03:33:13 +00003043 NameOut += '[';
Fariborz Jahanian679a5022009-01-10 21:06:09 +00003044 assert (CD && "Missing container decl in GetNameForMethod");
3045 NameOut += CD->getNameAsString();
Fariborz Jahanian52847332009-01-26 23:49:05 +00003046 // FIXME. For a method in a category, (CAT_NAME) is inserted here.
3047 // Right now! there is not enough info. to do this.
Chris Lattner077bf5e2008-11-24 03:33:13 +00003048 NameOut += ' ';
3049 NameOut += D->getSelector().getAsString();
3050 NameOut += ']';
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00003051}
3052
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00003053/// GetFirstIvarInRecord - This routine returns the record for the
3054/// implementation of the fiven class OID. It also returns field
3055/// corresponding to the first ivar in the class in FIV. It also
3056/// returns the one before the first ivar.
3057///
3058const RecordDecl *CGObjCCommonMac::GetFirstIvarInRecord(
3059 const ObjCInterfaceDecl *OID,
3060 RecordDecl::field_iterator &FIV,
3061 RecordDecl::field_iterator &PIV) {
Douglas Gregor6ab35242009-04-09 21:40:53 +00003062 int countSuperClassIvars = countInheritedIvars(OID->getSuperClass(),
3063 CGM.getContext());
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00003064 const RecordDecl *RD = CGM.getContext().addRecordToClass(OID);
Douglas Gregor6ab35242009-04-09 21:40:53 +00003065 RecordDecl::field_iterator ifield = RD->field_begin(CGM.getContext());
3066 RecordDecl::field_iterator pfield = RD->field_end(CGM.getContext());
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00003067 while (countSuperClassIvars-- > 0) {
3068 pfield = ifield;
3069 ++ifield;
3070 }
3071 FIV = ifield;
3072 PIV = pfield;
3073 return RD;
3074}
3075
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003076void CGObjCMac::FinishModule() {
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003077 EmitModuleInfo();
3078
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003079 // Emit the dummy bodies for any protocols which were referenced but
3080 // never defined.
3081 for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
3082 i = Protocols.begin(), e = Protocols.end(); i != e; ++i) {
3083 if (i->second->hasInitializer())
3084 continue;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003085
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003086 std::vector<llvm::Constant*> Values(5);
3087 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
3088 Values[1] = GetClassName(i->first);
3089 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
3090 Values[3] = Values[4] =
3091 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
3092 i->second->setLinkage(llvm::GlobalValue::InternalLinkage);
3093 i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
3094 Values));
3095 }
3096
3097 std::vector<llvm::Constant*> Used;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003098 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003099 e = UsedGlobals.end(); i != e; ++i) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003100 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003101 }
3102
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003103 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003104 llvm::GlobalValue *GV =
3105 new llvm::GlobalVariable(AT, false,
3106 llvm::GlobalValue::AppendingLinkage,
3107 llvm::ConstantArray::get(AT, Used),
3108 "llvm.used",
3109 &CGM.getModule());
3110
3111 GV->setSection("llvm.metadata");
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003112
3113 // Add assembler directives to add lazy undefined symbol references
3114 // for classes which are referenced but not defined. This is
3115 // important for correct linker interaction.
3116
3117 // FIXME: Uh, this isn't particularly portable.
3118 std::stringstream s;
Anders Carlsson565c99f2008-12-10 02:21:04 +00003119
3120 if (!CGM.getModule().getModuleInlineAsm().empty())
3121 s << "\n";
3122
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003123 for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(),
3124 e = LazySymbols.end(); i != e; ++i) {
3125 s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n";
3126 }
3127 for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(),
3128 e = DefinedSymbols.end(); i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003129 s << "\t.objc_class_name_" << (*i)->getName() << "=0\n"
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003130 << "\t.globl .objc_class_name_" << (*i)->getName() << "\n";
3131 }
Anders Carlsson565c99f2008-12-10 02:21:04 +00003132
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003133 CGM.getModule().appendModuleInlineAsm(s.str());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003134}
3135
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003136CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003137 : CGObjCCommonMac(cgm),
3138 ObjCTypes(cgm)
3139{
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003140 ObjCEmptyCacheVar = ObjCEmptyVtableVar = NULL;
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003141 ObjCABI = 2;
3142}
3143
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003144/* *** */
3145
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003146ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm)
3147: CGM(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003148{
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003149 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3150 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003151
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003152 ShortTy = Types.ConvertType(Ctx.ShortTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003153 IntTy = Types.ConvertType(Ctx.IntTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003154 LongTy = Types.ConvertType(Ctx.LongTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00003155 LongLongTy = Types.ConvertType(Ctx.LongLongTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003156 Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3157
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003158 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00003159 PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003160 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003161
3162 // FIXME: It would be nice to unify this with the opaque type, so
3163 // that the IR comes out a bit cleaner.
3164 const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
3165 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003166
3167 // I'm not sure I like this. The implicit coordination is a bit
3168 // gross. We should solve this in a reasonable fashion because this
3169 // is a pretty common task (match some runtime data structure with
3170 // an LLVM data structure).
3171
3172 // FIXME: This is leaked.
3173 // FIXME: Merge with rewriter code?
3174
3175 // struct _objc_super {
3176 // id self;
3177 // Class cls;
3178 // }
3179 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3180 SourceLocation(),
3181 &Ctx.Idents.get("_objc_super"));
Douglas Gregor6ab35242009-04-09 21:40:53 +00003182 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3183 Ctx.getObjCIdType(), 0, false));
3184 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3185 Ctx.getObjCClassType(), 0, false));
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003186 RD->completeDefinition(Ctx);
3187
3188 SuperCTy = Ctx.getTagDeclType(RD);
3189 SuperPtrCTy = Ctx.getPointerType(SuperCTy);
3190
3191 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003192 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
3193
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003194 // struct _prop_t {
3195 // char *name;
3196 // char *attributes;
3197 // }
3198 PropertyTy = llvm::StructType::get(Int8PtrTy,
3199 Int8PtrTy,
3200 NULL);
3201 CGM.getModule().addTypeName("struct._prop_t",
3202 PropertyTy);
3203
3204 // struct _prop_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003205 // uint32_t entsize; // sizeof(struct _prop_t)
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003206 // uint32_t count_of_properties;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003207 // struct _prop_t prop_list[count_of_properties];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003208 // }
3209 PropertyListTy = llvm::StructType::get(IntTy,
3210 IntTy,
3211 llvm::ArrayType::get(PropertyTy, 0),
3212 NULL);
3213 CGM.getModule().addTypeName("struct._prop_list_t",
3214 PropertyListTy);
3215 // struct _prop_list_t *
3216 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
3217
3218 // struct _objc_method {
3219 // SEL _cmd;
3220 // char *method_type;
3221 // char *_imp;
3222 // }
3223 MethodTy = llvm::StructType::get(SelectorPtrTy,
3224 Int8PtrTy,
3225 Int8PtrTy,
3226 NULL);
3227 CGM.getModule().addTypeName("struct._objc_method", MethodTy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003228
3229 // struct _objc_cache *
3230 CacheTy = llvm::OpaqueType::get();
3231 CGM.getModule().addTypeName("struct._objc_cache", CacheTy);
3232 CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003233
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003234 // Property manipulation functions.
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003235
3236 QualType IdType = Ctx.getObjCIdType();
3237 QualType SelType = Ctx.getObjCSelType();
3238 llvm::SmallVector<QualType,16> Params;
3239 const llvm::FunctionType *FTy;
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003240
3241 // id objc_getProperty (id, SEL, ptrdiff_t, bool)
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003242 Params.push_back(IdType);
3243 Params.push_back(SelType);
3244 Params.push_back(Ctx.LongTy);
3245 Params.push_back(Ctx.BoolTy);
3246 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params),
3247 false);
3248 GetPropertyFn = CGM.CreateRuntimeFunction(FTy, "objc_getProperty");
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003249
3250 // void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool)
3251 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003252 Params.push_back(IdType);
3253 Params.push_back(SelType);
3254 Params.push_back(Ctx.LongTy);
3255 Params.push_back(IdType);
3256 Params.push_back(Ctx.BoolTy);
3257 Params.push_back(Ctx.BoolTy);
3258 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
3259 SetPropertyFn = CGM.CreateRuntimeFunction(FTy, "objc_setProperty");
3260
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003261 // Enumeration mutation.
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003262
3263 // void objc_enumerationMutation (id)
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003264 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003265 Params.push_back(IdType);
3266 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
3267 EnumerationMutationFn = CGM.CreateRuntimeFunction(FTy,
3268 "objc_enumerationMutation");
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003269
3270 // gc's API
3271 // id objc_read_weak (id *)
3272 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003273 Params.push_back(Ctx.getPointerType(IdType));
3274 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
3275 GcReadWeakFn = CGM.CreateRuntimeFunction(FTy, "objc_read_weak");
3276
3277 // id objc_assign_weak (id, id *)
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003278 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003279 Params.push_back(IdType);
3280 Params.push_back(Ctx.getPointerType(IdType));
3281
3282 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
3283 GcAssignWeakFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_weak");
3284 GcAssignGlobalFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_global");
3285 GcAssignIvarFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_ivar");
3286 GcAssignStrongCastFn =
3287 CGM.CreateRuntimeFunction(FTy, "objc_assign_strongCast");
Anders Carlssonf57c5b22009-02-16 22:59:18 +00003288
3289 // void objc_exception_throw(id)
3290 Params.clear();
3291 Params.push_back(IdType);
3292
3293 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00003294 ExceptionThrowFn =
3295 CGM.CreateRuntimeFunction(FTy, "objc_exception_throw");
Daniel Dunbar1c566672009-02-24 01:43:46 +00003296
3297 // synchronized APIs
Daniel Dunbar1c566672009-02-24 01:43:46 +00003298 // void objc_sync_exit (id)
3299 Params.clear();
3300 Params.push_back(IdType);
3301
3302 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
Daniel Dunbar1c566672009-02-24 01:43:46 +00003303 SyncExitFn = CGM.CreateRuntimeFunction(FTy, "objc_sync_exit");
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003304}
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003305
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003306ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
3307 : ObjCCommonTypesHelper(cgm)
3308{
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003309 // struct _objc_method_description {
3310 // SEL name;
3311 // char *types;
3312 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003313 MethodDescriptionTy =
3314 llvm::StructType::get(SelectorPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003315 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003316 NULL);
3317 CGM.getModule().addTypeName("struct._objc_method_description",
3318 MethodDescriptionTy);
3319
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003320 // struct _objc_method_description_list {
3321 // int count;
3322 // struct _objc_method_description[1];
3323 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003324 MethodDescriptionListTy =
3325 llvm::StructType::get(IntTy,
3326 llvm::ArrayType::get(MethodDescriptionTy, 0),
3327 NULL);
3328 CGM.getModule().addTypeName("struct._objc_method_description_list",
3329 MethodDescriptionListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003330
3331 // struct _objc_method_description_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003332 MethodDescriptionListPtrTy =
3333 llvm::PointerType::getUnqual(MethodDescriptionListTy);
3334
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003335 // Protocol description structures
3336
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003337 // struct _objc_protocol_extension {
3338 // uint32_t size; // sizeof(struct _objc_protocol_extension)
3339 // struct _objc_method_description_list *optional_instance_methods;
3340 // struct _objc_method_description_list *optional_class_methods;
3341 // struct _objc_property_list *instance_properties;
3342 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003343 ProtocolExtensionTy =
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003344 llvm::StructType::get(IntTy,
3345 MethodDescriptionListPtrTy,
3346 MethodDescriptionListPtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003347 PropertyListPtrTy,
3348 NULL);
3349 CGM.getModule().addTypeName("struct._objc_protocol_extension",
3350 ProtocolExtensionTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003351
3352 // struct _objc_protocol_extension *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003353 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
3354
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003355 // Handle recursive construction of Protocol and ProtocolList types
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003356
3357 llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get();
3358 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3359
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003360 const llvm::Type *T =
3361 llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder),
3362 LongTy,
3363 llvm::ArrayType::get(ProtocolTyHolder, 0),
3364 NULL);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003365 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T);
3366
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003367 // struct _objc_protocol {
3368 // struct _objc_protocol_extension *isa;
3369 // char *protocol_name;
3370 // struct _objc_protocol **_objc_protocol_list;
3371 // struct _objc_method_description_list *instance_methods;
3372 // struct _objc_method_description_list *class_methods;
3373 // }
3374 T = llvm::StructType::get(ProtocolExtensionPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003375 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003376 llvm::PointerType::getUnqual(ProtocolListTyHolder),
3377 MethodDescriptionListPtrTy,
3378 MethodDescriptionListPtrTy,
3379 NULL);
3380 cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T);
3381
3382 ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get());
3383 CGM.getModule().addTypeName("struct._objc_protocol_list",
3384 ProtocolListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003385 // struct _objc_protocol_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003386 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
3387
3388 ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get());
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003389 CGM.getModule().addTypeName("struct._objc_protocol", ProtocolTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003390 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003391
3392 // Class description structures
3393
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003394 // struct _objc_ivar {
3395 // char *ivar_name;
3396 // char *ivar_type;
3397 // int ivar_offset;
3398 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003399 IvarTy = llvm::StructType::get(Int8PtrTy,
3400 Int8PtrTy,
3401 IntTy,
3402 NULL);
3403 CGM.getModule().addTypeName("struct._objc_ivar", IvarTy);
3404
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003405 // struct _objc_ivar_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003406 IvarListTy = llvm::OpaqueType::get();
3407 CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy);
3408 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
3409
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003410 // struct _objc_method_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003411 MethodListTy = llvm::OpaqueType::get();
3412 CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy);
3413 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
3414
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003415 // struct _objc_class_extension *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003416 ClassExtensionTy =
3417 llvm::StructType::get(IntTy,
3418 Int8PtrTy,
3419 PropertyListPtrTy,
3420 NULL);
3421 CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy);
3422 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
3423
3424 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3425
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003426 // struct _objc_class {
3427 // Class isa;
3428 // Class super_class;
3429 // char *name;
3430 // long version;
3431 // long info;
3432 // long instance_size;
3433 // struct _objc_ivar_list *ivars;
3434 // struct _objc_method_list *methods;
3435 // struct _objc_cache *cache;
3436 // struct _objc_protocol_list *protocols;
3437 // char *ivar_layout;
3438 // struct _objc_class_ext *ext;
3439 // };
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003440 T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3441 llvm::PointerType::getUnqual(ClassTyHolder),
3442 Int8PtrTy,
3443 LongTy,
3444 LongTy,
3445 LongTy,
3446 IvarListPtrTy,
3447 MethodListPtrTy,
3448 CachePtrTy,
3449 ProtocolListPtrTy,
3450 Int8PtrTy,
3451 ClassExtensionPtrTy,
3452 NULL);
3453 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T);
3454
3455 ClassTy = cast<llvm::StructType>(ClassTyHolder.get());
3456 CGM.getModule().addTypeName("struct._objc_class", ClassTy);
3457 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
3458
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003459 // struct _objc_category {
3460 // char *category_name;
3461 // char *class_name;
3462 // struct _objc_method_list *instance_method;
3463 // struct _objc_method_list *class_method;
3464 // uint32_t size; // sizeof(struct _objc_category)
3465 // struct _objc_property_list *instance_properties;// category's @property
3466 // }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003467 CategoryTy = llvm::StructType::get(Int8PtrTy,
3468 Int8PtrTy,
3469 MethodListPtrTy,
3470 MethodListPtrTy,
3471 ProtocolListPtrTy,
3472 IntTy,
3473 PropertyListPtrTy,
3474 NULL);
3475 CGM.getModule().addTypeName("struct._objc_category", CategoryTy);
3476
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003477 // Global metadata structures
3478
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003479 // struct _objc_symtab {
3480 // long sel_ref_cnt;
3481 // SEL *refs;
3482 // short cls_def_cnt;
3483 // short cat_def_cnt;
3484 // char *defs[cls_def_cnt + cat_def_cnt];
3485 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003486 SymtabTy = llvm::StructType::get(LongTy,
3487 SelectorPtrTy,
3488 ShortTy,
3489 ShortTy,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003490 llvm::ArrayType::get(Int8PtrTy, 0),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003491 NULL);
3492 CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy);
3493 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
3494
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003495 // struct _objc_module {
3496 // long version;
3497 // long size; // sizeof(struct _objc_module)
3498 // char *name;
3499 // struct _objc_symtab* symtab;
3500 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003501 ModuleTy =
3502 llvm::StructType::get(LongTy,
3503 LongTy,
3504 Int8PtrTy,
3505 SymtabPtrTy,
3506 NULL);
3507 CGM.getModule().addTypeName("struct._objc_module", ModuleTy);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003508
Daniel Dunbar49f66022008-09-24 03:38:44 +00003509 // Message send functions.
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003510
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003511 // id objc_msgSend (id, SEL, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003512 std::vector<const llvm::Type*> Params;
3513 Params.push_back(ObjectPtrTy);
3514 Params.push_back(SelectorPtrTy);
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003515 MessageSendFn =
3516 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3517 Params,
3518 true),
3519 "objc_msgSend");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003520
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003521 // id objc_msgSend_stret (id, SEL, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003522 Params.clear();
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003523 Params.push_back(ObjectPtrTy);
3524 Params.push_back(SelectorPtrTy);
3525 MessageSendStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003526 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3527 Params,
3528 true),
3529 "objc_msgSend_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00003530
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003531 //
Daniel Dunbar5669e572008-10-17 03:24:53 +00003532 Params.clear();
3533 Params.push_back(ObjectPtrTy);
3534 Params.push_back(SelectorPtrTy);
3535 // FIXME: This should be long double on x86_64?
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003536 // [double | long double] objc_msgSend_fpret(id self, SEL op, ...)
Daniel Dunbar5669e572008-10-17 03:24:53 +00003537 MessageSendFpretFn =
3538 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::DoubleTy,
3539 Params,
3540 true),
3541 "objc_msgSend_fpret");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003542
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003543 // id objc_msgSendSuper(struct objc_super *super, SEL op, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003544 Params.clear();
3545 Params.push_back(SuperPtrTy);
3546 Params.push_back(SelectorPtrTy);
3547 MessageSendSuperFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003548 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3549 Params,
3550 true),
3551 "objc_msgSendSuper");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003552
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003553 // void objc_msgSendSuper_stret(void * stretAddr, struct objc_super *super,
3554 // SEL op, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003555 Params.clear();
3556 Params.push_back(Int8PtrTy);
3557 Params.push_back(SuperPtrTy);
3558 Params.push_back(SelectorPtrTy);
3559 MessageSendSuperStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003560 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3561 Params,
3562 true),
3563 "objc_msgSendSuper_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00003564
3565 // There is no objc_msgSendSuper_fpret? How can that work?
3566 MessageSendSuperFpretFn = MessageSendSuperFn;
Anders Carlsson2abd89c2008-08-31 04:05:03 +00003567
Anders Carlsson124526b2008-09-09 10:10:21 +00003568 // FIXME: This is the size of the setjmp buffer and should be
3569 // target specific. 18 is what's used on 32-bit X86.
3570 uint64_t SetJmpBufferSize = 18;
3571
3572 // Exceptions
3573 const llvm::Type *StackPtrTy =
Daniel Dunbar10004912008-09-27 06:32:25 +00003574 llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4);
Anders Carlsson124526b2008-09-09 10:10:21 +00003575
3576 ExceptionDataTy =
3577 llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty,
3578 SetJmpBufferSize),
3579 StackPtrTy, NULL);
3580 CGM.getModule().addTypeName("struct._objc_exception_data",
3581 ExceptionDataTy);
3582
3583 Params.clear();
Anders Carlsson124526b2008-09-09 10:10:21 +00003584 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
3585 ExceptionTryEnterFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003586 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3587 Params,
3588 false),
3589 "objc_exception_try_enter");
Anders Carlsson124526b2008-09-09 10:10:21 +00003590 ExceptionTryExitFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003591 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3592 Params,
3593 false),
3594 "objc_exception_try_exit");
Anders Carlsson124526b2008-09-09 10:10:21 +00003595 ExceptionExtractFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003596 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3597 Params,
3598 false),
3599 "objc_exception_extract");
Anders Carlsson124526b2008-09-09 10:10:21 +00003600
3601 Params.clear();
3602 Params.push_back(ClassPtrTy);
3603 Params.push_back(ObjectPtrTy);
3604 ExceptionMatchFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003605 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
3606 Params,
3607 false),
3608 "objc_exception_match");
Chris Lattner10cac6f2008-11-15 21:26:17 +00003609
Anders Carlsson124526b2008-09-09 10:10:21 +00003610 Params.clear();
3611 Params.push_back(llvm::PointerType::getUnqual(llvm::Type::Int32Ty));
3612 SetJmpFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003613 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
3614 Params,
3615 false),
3616 "_setjmp");
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00003617
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003618}
3619
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003620ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003621: ObjCCommonTypesHelper(cgm)
3622{
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003623 // struct _method_list_t {
3624 // uint32_t entsize; // sizeof(struct _objc_method)
3625 // uint32_t method_count;
3626 // struct _objc_method method_list[method_count];
3627 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003628 MethodListnfABITy = llvm::StructType::get(IntTy,
3629 IntTy,
3630 llvm::ArrayType::get(MethodTy, 0),
3631 NULL);
3632 CGM.getModule().addTypeName("struct.__method_list_t",
3633 MethodListnfABITy);
3634 // struct method_list_t *
3635 MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003636
3637 // struct _protocol_t {
3638 // id isa; // NULL
3639 // const char * const protocol_name;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003640 // const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003641 // const struct method_list_t * const instance_methods;
3642 // const struct method_list_t * const class_methods;
3643 // const struct method_list_t *optionalInstanceMethods;
3644 // const struct method_list_t *optionalClassMethods;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003645 // const struct _prop_list_t * properties;
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003646 // const uint32_t size; // sizeof(struct _protocol_t)
3647 // const uint32_t flags; // = 0
3648 // }
3649
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003650 // Holder for struct _protocol_list_t *
3651 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3652
3653 ProtocolnfABITy = llvm::StructType::get(ObjectPtrTy,
3654 Int8PtrTy,
3655 llvm::PointerType::getUnqual(
3656 ProtocolListTyHolder),
3657 MethodListnfABIPtrTy,
3658 MethodListnfABIPtrTy,
3659 MethodListnfABIPtrTy,
3660 MethodListnfABIPtrTy,
3661 PropertyListPtrTy,
3662 IntTy,
3663 IntTy,
3664 NULL);
3665 CGM.getModule().addTypeName("struct._protocol_t",
3666 ProtocolnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003667
3668 // struct _protocol_t*
3669 ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003670
Fariborz Jahanianda320092009-01-29 19:24:30 +00003671 // struct _protocol_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003672 // long protocol_count; // Note, this is 32/64 bit
Daniel Dunbar948e2582009-02-15 07:36:20 +00003673 // struct _protocol_t *[protocol_count];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003674 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003675 ProtocolListnfABITy = llvm::StructType::get(LongTy,
3676 llvm::ArrayType::get(
Daniel Dunbar948e2582009-02-15 07:36:20 +00003677 ProtocolnfABIPtrTy, 0),
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003678 NULL);
3679 CGM.getModule().addTypeName("struct._objc_protocol_list",
3680 ProtocolListnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003681 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(
3682 ProtocolListnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003683
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003684 // struct _objc_protocol_list*
3685 ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003686
3687 // struct _ivar_t {
3688 // unsigned long int *offset; // pointer to ivar offset location
3689 // char *name;
3690 // char *type;
3691 // uint32_t alignment;
3692 // uint32_t size;
3693 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003694 IvarnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(LongTy),
3695 Int8PtrTy,
3696 Int8PtrTy,
3697 IntTy,
3698 IntTy,
3699 NULL);
3700 CGM.getModule().addTypeName("struct._ivar_t", IvarnfABITy);
3701
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003702 // struct _ivar_list_t {
3703 // uint32 entsize; // sizeof(struct _ivar_t)
3704 // uint32 count;
3705 // struct _iver_t list[count];
3706 // }
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003707 IvarListnfABITy = llvm::StructType::get(IntTy,
3708 IntTy,
3709 llvm::ArrayType::get(
3710 IvarnfABITy, 0),
3711 NULL);
3712 CGM.getModule().addTypeName("struct._ivar_list_t", IvarListnfABITy);
3713
3714 IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003715
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003716 // struct _class_ro_t {
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003717 // uint32_t const flags;
3718 // uint32_t const instanceStart;
3719 // uint32_t const instanceSize;
3720 // uint32_t const reserved; // only when building for 64bit targets
3721 // const uint8_t * const ivarLayout;
3722 // const char *const name;
3723 // const struct _method_list_t * const baseMethods;
3724 // const struct _objc_protocol_list *const baseProtocols;
3725 // const struct _ivar_list_t *const ivars;
3726 // const uint8_t * const weakIvarLayout;
3727 // const struct _prop_list_t * const properties;
3728 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003729
3730 // FIXME. Add 'reserved' field in 64bit abi mode!
3731 ClassRonfABITy = llvm::StructType::get(IntTy,
3732 IntTy,
3733 IntTy,
3734 Int8PtrTy,
3735 Int8PtrTy,
3736 MethodListnfABIPtrTy,
3737 ProtocolListnfABIPtrTy,
3738 IvarListnfABIPtrTy,
3739 Int8PtrTy,
3740 PropertyListPtrTy,
3741 NULL);
3742 CGM.getModule().addTypeName("struct._class_ro_t",
3743 ClassRonfABITy);
3744
3745 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
3746 std::vector<const llvm::Type*> Params;
3747 Params.push_back(ObjectPtrTy);
3748 Params.push_back(SelectorPtrTy);
3749 ImpnfABITy = llvm::PointerType::getUnqual(
3750 llvm::FunctionType::get(ObjectPtrTy, Params, false));
3751
3752 // struct _class_t {
3753 // struct _class_t *isa;
3754 // struct _class_t * const superclass;
3755 // void *cache;
3756 // IMP *vtable;
3757 // struct class_ro_t *ro;
3758 // }
3759
3760 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3761 ClassnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3762 llvm::PointerType::getUnqual(ClassTyHolder),
3763 CachePtrTy,
3764 llvm::PointerType::getUnqual(ImpnfABITy),
3765 llvm::PointerType::getUnqual(
3766 ClassRonfABITy),
3767 NULL);
3768 CGM.getModule().addTypeName("struct._class_t", ClassnfABITy);
3769
3770 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(
3771 ClassnfABITy);
3772
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003773 // LLVM for struct _class_t *
3774 ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy);
3775
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003776 // struct _category_t {
3777 // const char * const name;
3778 // struct _class_t *const cls;
3779 // const struct _method_list_t * const instance_methods;
3780 // const struct _method_list_t * const class_methods;
3781 // const struct _protocol_list_t * const protocols;
3782 // const struct _prop_list_t * const properties;
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003783 // }
3784 CategorynfABITy = llvm::StructType::get(Int8PtrTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003785 ClassnfABIPtrTy,
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003786 MethodListnfABIPtrTy,
3787 MethodListnfABIPtrTy,
3788 ProtocolListnfABIPtrTy,
3789 PropertyListPtrTy,
3790 NULL);
3791 CGM.getModule().addTypeName("struct._category_t", CategorynfABITy);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003792
3793 // New types for nonfragile abi messaging.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003794 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3795 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003796
3797 // MessageRefTy - LLVM for:
3798 // struct _message_ref_t {
3799 // IMP messenger;
3800 // SEL name;
3801 // };
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003802
3803 // First the clang type for struct _message_ref_t
3804 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3805 SourceLocation(),
3806 &Ctx.Idents.get("_message_ref_t"));
Douglas Gregor6ab35242009-04-09 21:40:53 +00003807 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3808 Ctx.VoidPtrTy, 0, false));
3809 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3810 Ctx.getObjCSelType(), 0, false));
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003811 RD->completeDefinition(Ctx);
3812
3813 MessageRefCTy = Ctx.getTagDeclType(RD);
3814 MessageRefCPtrTy = Ctx.getPointerType(MessageRefCTy);
3815 MessageRefTy = cast<llvm::StructType>(Types.ConvertType(MessageRefCTy));
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003816
3817 // MessageRefPtrTy - LLVM for struct _message_ref_t*
3818 MessageRefPtrTy = llvm::PointerType::getUnqual(MessageRefTy);
3819
3820 // SuperMessageRefTy - LLVM for:
3821 // struct _super_message_ref_t {
3822 // SUPER_IMP messenger;
3823 // SEL name;
3824 // };
3825 SuperMessageRefTy = llvm::StructType::get(ImpnfABITy,
3826 SelectorPtrTy,
3827 NULL);
3828 CGM.getModule().addTypeName("struct._super_message_ref_t", SuperMessageRefTy);
3829
3830 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
3831 SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy);
3832
3833 // id objc_msgSend_fixup (id, struct message_ref_t*, ...)
3834 Params.clear();
3835 Params.push_back(ObjectPtrTy);
3836 Params.push_back(MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00003837 MessengerTy = llvm::FunctionType::get(ObjectPtrTy,
3838 Params,
3839 true);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003840 MessageSendFixupFn =
Fariborz Jahanianef163782009-02-05 01:13:09 +00003841 CGM.CreateRuntimeFunction(MessengerTy,
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003842 "objc_msgSend_fixup");
3843
3844 // id objc_msgSend_fpret_fixup (id, struct message_ref_t*, ...)
3845 MessageSendFpretFixupFn =
3846 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3847 Params,
3848 true),
3849 "objc_msgSend_fpret_fixup");
3850
3851 // id objc_msgSend_stret_fixup (id, struct message_ref_t*, ...)
3852 MessageSendStretFixupFn =
3853 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3854 Params,
3855 true),
3856 "objc_msgSend_stret_fixup");
3857
3858 // id objc_msgSendId_fixup (id, struct message_ref_t*, ...)
3859 MessageSendIdFixupFn =
3860 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3861 Params,
3862 true),
3863 "objc_msgSendId_fixup");
3864
3865
3866 // id objc_msgSendId_stret_fixup (id, struct message_ref_t*, ...)
3867 MessageSendIdStretFixupFn =
3868 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3869 Params,
3870 true),
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003871 "objc_msgSendId_stret_fixup");
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003872
3873 // id objc_msgSendSuper2_fixup (struct objc_super *,
3874 // struct _super_message_ref_t*, ...)
3875 Params.clear();
3876 Params.push_back(SuperPtrTy);
3877 Params.push_back(SuperMessageRefPtrTy);
3878 MessageSendSuper2FixupFn =
3879 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3880 Params,
3881 true),
3882 "objc_msgSendSuper2_fixup");
3883
3884
3885 // id objc_msgSendSuper2_stret_fixup (struct objc_super *,
3886 // struct _super_message_ref_t*, ...)
3887 MessageSendSuper2StretFixupFn =
3888 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3889 Params,
3890 true),
3891 "objc_msgSendSuper2_stret_fixup");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00003892
3893 Params.clear();
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00003894 Params.push_back(Int8PtrTy);
3895 UnwindResumeOrRethrowFn =
3896 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3897 Params,
3898 false),
3899 "_Unwind_Resume_or_Rethrow");
Daniel Dunbare588b992009-03-01 04:46:24 +00003900 ObjCBeginCatchFn =
3901 CGM.CreateRuntimeFunction(llvm::FunctionType::get(Int8PtrTy,
3902 Params,
3903 false),
3904 "objc_begin_catch");
3905
3906 Params.clear();
3907 ObjCEndCatchFn =
3908 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3909 Params,
3910 false),
3911 "objc_end_catch");
3912
3913 // struct objc_typeinfo {
3914 // const void** vtable; // objc_ehtype_vtable + 2
3915 // const char* name; // c++ typeinfo string
3916 // Class cls;
3917 // };
3918 EHTypeTy = llvm::StructType::get(llvm::PointerType::getUnqual(Int8PtrTy),
3919 Int8PtrTy,
3920 ClassnfABIPtrTy,
3921 NULL);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00003922 CGM.getModule().addTypeName("struct._objc_typeinfo", EHTypeTy);
Daniel Dunbare588b992009-03-01 04:46:24 +00003923 EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy);
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003924}
3925
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003926llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() {
3927 FinishNonFragileABIModule();
3928
3929 return NULL;
3930}
3931
3932void CGObjCNonFragileABIMac::FinishNonFragileABIModule() {
3933 // nonfragile abi has no module definition.
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003934
3935 // Build list of all implemented classe addresses in array
3936 // L_OBJC_LABEL_CLASS_$.
3937 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CLASS_$
3938 // list of 'nonlazy' implementations (defined as those with a +load{}
3939 // method!!).
3940 unsigned NumClasses = DefinedClasses.size();
3941 if (NumClasses) {
3942 std::vector<llvm::Constant*> Symbols(NumClasses);
3943 for (unsigned i=0; i<NumClasses; i++)
3944 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
3945 ObjCTypes.Int8PtrTy);
3946 llvm::Constant* Init =
3947 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
3948 NumClasses),
3949 Symbols);
3950
3951 llvm::GlobalVariable *GV =
3952 new llvm::GlobalVariable(Init->getType(), false,
3953 llvm::GlobalValue::InternalLinkage,
3954 Init,
3955 "\01L_OBJC_LABEL_CLASS_$",
3956 &CGM.getModule());
Daniel Dunbar58a29122009-03-09 22:18:41 +00003957 GV->setAlignment(8);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003958 GV->setSection("__DATA, __objc_classlist, regular, no_dead_strip");
3959 UsedGlobals.push_back(GV);
3960 }
3961
3962 // Build list of all implemented category addresses in array
3963 // L_OBJC_LABEL_CATEGORY_$.
3964 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CATEGORY_$
3965 // list of 'nonlazy' category implementations (defined as those with a +load{}
3966 // method!!).
3967 unsigned NumCategory = DefinedCategories.size();
3968 if (NumCategory) {
3969 std::vector<llvm::Constant*> Symbols(NumCategory);
3970 for (unsigned i=0; i<NumCategory; i++)
3971 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedCategories[i],
3972 ObjCTypes.Int8PtrTy);
3973 llvm::Constant* Init =
3974 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
3975 NumCategory),
3976 Symbols);
3977
3978 llvm::GlobalVariable *GV =
3979 new llvm::GlobalVariable(Init->getType(), false,
3980 llvm::GlobalValue::InternalLinkage,
3981 Init,
3982 "\01L_OBJC_LABEL_CATEGORY_$",
3983 &CGM.getModule());
Daniel Dunbar58a29122009-03-09 22:18:41 +00003984 GV->setAlignment(8);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003985 GV->setSection("__DATA, __objc_catlist, regular, no_dead_strip");
3986 UsedGlobals.push_back(GV);
3987 }
3988
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00003989 // static int L_OBJC_IMAGE_INFO[2] = { 0, flags };
3990 // FIXME. flags can be 0 | 1 | 2 | 6. For now just use 0
3991 std::vector<llvm::Constant*> Values(2);
3992 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, 0);
Fariborz Jahanian067986e2009-02-24 21:08:09 +00003993 unsigned int flags = 0;
Fariborz Jahanian66a5c2c2009-02-24 23:34:44 +00003994 // FIXME: Fix and continue?
3995 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
3996 flags |= eImageInfo_GarbageCollected;
3997 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
3998 flags |= eImageInfo_GCOnly;
Fariborz Jahanian067986e2009-02-24 21:08:09 +00003999 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004000 llvm::Constant* Init = llvm::ConstantArray::get(
4001 llvm::ArrayType::get(ObjCTypes.IntTy, 2),
4002 Values);
4003 llvm::GlobalVariable *IMGV =
4004 new llvm::GlobalVariable(Init->getType(), false,
4005 llvm::GlobalValue::InternalLinkage,
4006 Init,
4007 "\01L_OBJC_IMAGE_INFO",
4008 &CGM.getModule());
4009 IMGV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
4010 UsedGlobals.push_back(IMGV);
4011
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004012 std::vector<llvm::Constant*> Used;
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004013
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004014 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
4015 e = UsedGlobals.end(); i != e; ++i) {
4016 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
4017 }
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004018
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004019 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
4020 llvm::GlobalValue *GV =
4021 new llvm::GlobalVariable(AT, false,
4022 llvm::GlobalValue::AppendingLinkage,
4023 llvm::ConstantArray::get(AT, Used),
4024 "llvm.used",
4025 &CGM.getModule());
4026
4027 GV->setSection("llvm.metadata");
4028
4029}
4030
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004031// Metadata flags
4032enum MetaDataDlags {
4033 CLS = 0x0,
4034 CLS_META = 0x1,
4035 CLS_ROOT = 0x2,
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004036 OBJC2_CLS_HIDDEN = 0x10,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004037 CLS_EXCEPTION = 0x20
4038};
4039/// BuildClassRoTInitializer - generate meta-data for:
4040/// struct _class_ro_t {
4041/// uint32_t const flags;
4042/// uint32_t const instanceStart;
4043/// uint32_t const instanceSize;
4044/// uint32_t const reserved; // only when building for 64bit targets
4045/// const uint8_t * const ivarLayout;
4046/// const char *const name;
4047/// const struct _method_list_t * const baseMethods;
Fariborz Jahanianda320092009-01-29 19:24:30 +00004048/// const struct _protocol_list_t *const baseProtocols;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004049/// const struct _ivar_list_t *const ivars;
4050/// const uint8_t * const weakIvarLayout;
4051/// const struct _prop_list_t * const properties;
4052/// }
4053///
4054llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer(
4055 unsigned flags,
4056 unsigned InstanceStart,
4057 unsigned InstanceSize,
4058 const ObjCImplementationDecl *ID) {
4059 std::string ClassName = ID->getNameAsString();
4060 std::vector<llvm::Constant*> Values(10); // 11 for 64bit targets!
4061 Values[ 0] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
4062 Values[ 1] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceStart);
4063 Values[ 2] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceSize);
4064 // FIXME. For 64bit targets add 0 here.
Fariborz Jahanianda320092009-01-29 19:24:30 +00004065 // FIXME. ivarLayout is currently null!
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00004066 Values[ 3] = GetIvarLayoutName(0, ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004067 Values[ 4] = GetClassName(ID->getIdentifier());
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004068 // const struct _method_list_t * const baseMethods;
4069 std::vector<llvm::Constant*> Methods;
4070 std::string MethodListName("\01l_OBJC_$_");
4071 if (flags & CLS_META) {
4072 MethodListName += "CLASS_METHODS_" + ID->getNameAsString();
4073 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
4074 e = ID->classmeth_end(); i != e; ++i) {
4075 // Class methods should always be defined.
4076 Methods.push_back(GetMethodConstant(*i));
4077 }
4078 } else {
4079 MethodListName += "INSTANCE_METHODS_" + ID->getNameAsString();
4080 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
4081 e = ID->instmeth_end(); i != e; ++i) {
4082 // Instance methods should always be defined.
4083 Methods.push_back(GetMethodConstant(*i));
4084 }
Fariborz Jahanian939abce2009-01-28 22:46:49 +00004085 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
4086 e = ID->propimpl_end(); i != e; ++i) {
4087 ObjCPropertyImplDecl *PID = *i;
4088
4089 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize){
4090 ObjCPropertyDecl *PD = PID->getPropertyDecl();
4091
4092 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
4093 if (llvm::Constant *C = GetMethodConstant(MD))
4094 Methods.push_back(C);
4095 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
4096 if (llvm::Constant *C = GetMethodConstant(MD))
4097 Methods.push_back(C);
4098 }
4099 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004100 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004101 Values[ 5] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004102 "__DATA, __objc_const", Methods);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004103
4104 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4105 assert(OID && "CGObjCNonFragileABIMac::BuildClassRoTInitializer");
4106 Values[ 6] = EmitProtocolList("\01l_OBJC_CLASS_PROTOCOLS_$_"
4107 + OID->getNameAsString(),
4108 OID->protocol_begin(),
4109 OID->protocol_end());
4110
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004111 if (flags & CLS_META)
4112 Values[ 7] = llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4113 else
4114 Values[ 7] = EmitIvarList(ID);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004115 // FIXME. weakIvarLayout is currently null.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00004116 Values[ 8] = GetIvarLayoutName(0, ObjCTypes);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004117 if (flags & CLS_META)
4118 Values[ 9] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4119 else
4120 Values[ 9] =
4121 EmitPropertyList(
4122 "\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
4123 ID, ID->getClassInterface(), ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004124 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassRonfABITy,
4125 Values);
4126 llvm::GlobalVariable *CLASS_RO_GV =
4127 new llvm::GlobalVariable(ObjCTypes.ClassRonfABITy, false,
4128 llvm::GlobalValue::InternalLinkage,
4129 Init,
4130 (flags & CLS_META) ?
4131 std::string("\01l_OBJC_METACLASS_RO_$_")+ClassName :
4132 std::string("\01l_OBJC_CLASS_RO_$_")+ClassName,
4133 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004134 CLASS_RO_GV->setAlignment(
4135 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassRonfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004136 CLASS_RO_GV->setSection("__DATA, __objc_const");
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004137 return CLASS_RO_GV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004138
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004139}
4140
4141/// BuildClassMetaData - This routine defines that to-level meta-data
4142/// for the given ClassName for:
4143/// struct _class_t {
4144/// struct _class_t *isa;
4145/// struct _class_t * const superclass;
4146/// void *cache;
4147/// IMP *vtable;
4148/// struct class_ro_t *ro;
4149/// }
4150///
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004151llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassMetaData(
4152 std::string &ClassName,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004153 llvm::Constant *IsAGV,
4154 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004155 llvm::Constant *ClassRoGV,
4156 bool HiddenVisibility) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004157 std::vector<llvm::Constant*> Values(5);
4158 Values[0] = IsAGV;
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004159 Values[1] = SuperClassGV
4160 ? SuperClassGV
4161 : llvm::Constant::getNullValue(ObjCTypes.ClassnfABIPtrTy);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004162 Values[2] = ObjCEmptyCacheVar; // &ObjCEmptyCacheVar
4163 Values[3] = ObjCEmptyVtableVar; // &ObjCEmptyVtableVar
4164 Values[4] = ClassRoGV; // &CLASS_RO_GV
4165 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassnfABITy,
4166 Values);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004167 llvm::GlobalVariable *GV = GetClassGlobal(ClassName);
4168 GV->setInitializer(Init);
Fariborz Jahaniandd0db2a2009-01-31 01:07:39 +00004169 GV->setSection("__DATA, __objc_data");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004170 GV->setAlignment(
4171 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassnfABITy));
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004172 if (HiddenVisibility)
4173 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004174 return GV;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004175}
4176
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004177void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) {
4178 std::string ClassName = ID->getNameAsString();
4179 if (!ObjCEmptyCacheVar) {
4180 ObjCEmptyCacheVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004181 ObjCTypes.CacheTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004182 false,
4183 llvm::GlobalValue::ExternalLinkage,
4184 0,
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004185 "_objc_empty_cache",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004186 &CGM.getModule());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004187
4188 ObjCEmptyVtableVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004189 ObjCTypes.ImpnfABITy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004190 false,
4191 llvm::GlobalValue::ExternalLinkage,
4192 0,
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004193 "_objc_empty_vtable",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004194 &CGM.getModule());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004195 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004196 assert(ID->getClassInterface() &&
4197 "CGObjCNonFragileABIMac::GenerateClass - class is 0");
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004198 uint32_t InstanceStart =
4199 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassnfABITy);
4200 uint32_t InstanceSize = InstanceStart;
4201 uint32_t flags = CLS_META;
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004202 std::string ObjCMetaClassName(getMetaclassSymbolPrefix());
4203 std::string ObjCClassName(getClassSymbolPrefix());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004204
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004205 llvm::GlobalVariable *SuperClassGV, *IsAGV;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004206
Daniel Dunbar04d40782009-04-14 06:00:08 +00004207 bool classIsHidden =
4208 CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004209 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004210 flags |= OBJC2_CLS_HIDDEN;
4211 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004212 // class is root
4213 flags |= CLS_ROOT;
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004214 SuperClassGV = GetClassGlobal(ObjCClassName + ClassName);
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004215 IsAGV = GetClassGlobal(ObjCMetaClassName + ClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004216 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004217 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004218 const ObjCInterfaceDecl *Root = ID->getClassInterface();
4219 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
4220 Root = Super;
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004221 IsAGV = GetClassGlobal(ObjCMetaClassName + Root->getNameAsString());
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004222 // work on super class metadata symbol.
4223 std::string SuperClassName =
4224 ObjCMetaClassName + ID->getClassInterface()->getSuperClass()->getNameAsString();
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004225 SuperClassGV = GetClassGlobal(SuperClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004226 }
4227 llvm::GlobalVariable *CLASS_RO_GV = BuildClassRoTInitializer(flags,
4228 InstanceStart,
4229 InstanceSize,ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004230 std::string TClassName = ObjCMetaClassName + ClassName;
4231 llvm::GlobalVariable *MetaTClass =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004232 BuildClassMetaData(TClassName, IsAGV, SuperClassGV, CLASS_RO_GV,
4233 classIsHidden);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004234
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004235 // Metadata for the class
4236 flags = CLS;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004237 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004238 flags |= OBJC2_CLS_HIDDEN;
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004239
4240 if (hasObjCExceptionAttribute(ID->getClassInterface()))
4241 flags |= CLS_EXCEPTION;
4242
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004243 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004244 flags |= CLS_ROOT;
4245 SuperClassGV = 0;
4246 }
4247 else {
4248 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004249 std::string RootClassName =
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004250 ID->getClassInterface()->getSuperClass()->getNameAsString();
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004251 SuperClassGV = GetClassGlobal(ObjCClassName + RootClassName);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004252 }
Fariborz Jahanianebf9ed32009-03-20 20:48:19 +00004253 // FIXME: Gross
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004254 InstanceStart = InstanceSize = 0;
4255 if (ObjCInterfaceDecl *OID =
4256 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface())) {
4257 // FIXME. Share this with the one in EmitIvarList.
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00004258 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID);
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004259
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00004260 RecordDecl::field_iterator firstField, lastField;
4261 const RecordDecl *RD = GetFirstIvarInRecord(OID, firstField, lastField);
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004262
Douglas Gregor6ab35242009-04-09 21:40:53 +00004263 for (RecordDecl::field_iterator e = RD->field_end(CGM.getContext()),
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004264 ifield = firstField; ifield != e; ++ifield)
4265 lastField = ifield;
4266
Douglas Gregor6ab35242009-04-09 21:40:53 +00004267 if (lastField != RD->field_end(CGM.getContext())) {
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004268 FieldDecl *Field = *lastField;
4269 const llvm::Type *FieldTy =
4270 CGM.getTypes().ConvertTypeForMem(Field->getType());
4271 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00004272 InstanceSize = GetIvarBaseOffset(Layout, Field) + Size;
Douglas Gregor6ab35242009-04-09 21:40:53 +00004273 if (firstField == RD->field_end(CGM.getContext()))
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004274 InstanceStart = InstanceSize;
Fariborz Jahanian11894a42009-03-07 19:43:20 +00004275 else {
4276 Field = *firstField;
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00004277 InstanceStart = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanian11894a42009-03-07 19:43:20 +00004278 }
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004279 }
4280 }
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004281 CLASS_RO_GV = BuildClassRoTInitializer(flags,
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004282 InstanceStart,
4283 InstanceSize,
4284 ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004285
4286 TClassName = ObjCClassName + ClassName;
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004287 llvm::GlobalVariable *ClassMD =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004288 BuildClassMetaData(TClassName, MetaTClass, SuperClassGV, CLASS_RO_GV,
4289 classIsHidden);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004290 DefinedClasses.push_back(ClassMD);
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004291
4292 // Force the definition of the EHType if necessary.
4293 if (flags & CLS_EXCEPTION)
4294 GetInterfaceEHType(ID->getClassInterface(), true);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004295}
4296
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004297/// GenerateProtocolRef - This routine is called to generate code for
4298/// a protocol reference expression; as in:
4299/// @code
4300/// @protocol(Proto1);
4301/// @endcode
4302/// It generates a weak reference to l_OBJC_PROTOCOL_REFERENCE_$_Proto1
4303/// which will hold address of the protocol meta-data.
4304///
4305llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CGBuilderTy &Builder,
4306 const ObjCProtocolDecl *PD) {
4307
Fariborz Jahanian960cd062009-04-10 18:47:34 +00004308 // This routine is called for @protocol only. So, we must build definition
4309 // of protocol's meta-data (not a reference to it!)
4310 //
4311 llvm::Constant *Init = llvm::ConstantExpr::getBitCast(GetOrEmitProtocol(PD),
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004312 ObjCTypes.ExternalProtocolPtrTy);
4313
4314 std::string ProtocolName("\01l_OBJC_PROTOCOL_REFERENCE_$_");
4315 ProtocolName += PD->getNameAsCString();
4316
4317 llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName);
4318 if (PTGV)
4319 return Builder.CreateLoad(PTGV, false, "tmp");
4320 PTGV = new llvm::GlobalVariable(
4321 Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00004322 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004323 Init,
4324 ProtocolName,
4325 &CGM.getModule());
4326 PTGV->setSection("__DATA, __objc_protorefs, coalesced, no_dead_strip");
4327 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4328 UsedGlobals.push_back(PTGV);
4329 return Builder.CreateLoad(PTGV, false, "tmp");
4330}
4331
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004332/// GenerateCategory - Build metadata for a category implementation.
4333/// struct _category_t {
4334/// const char * const name;
4335/// struct _class_t *const cls;
4336/// const struct _method_list_t * const instance_methods;
4337/// const struct _method_list_t * const class_methods;
4338/// const struct _protocol_list_t * const protocols;
4339/// const struct _prop_list_t * const properties;
4340/// }
4341///
4342void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD)
4343{
4344 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004345 const char *Prefix = "\01l_OBJC_$_CATEGORY_";
4346 std::string ExtCatName(Prefix + Interface->getNameAsString()+
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004347 "_$_" + OCD->getNameAsString());
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004348 std::string ExtClassName(getClassSymbolPrefix() +
4349 Interface->getNameAsString());
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004350
4351 std::vector<llvm::Constant*> Values(6);
4352 Values[0] = GetClassName(OCD->getIdentifier());
4353 // meta-class entry symbol
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004354 llvm::GlobalVariable *ClassGV = GetClassGlobal(ExtClassName);
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004355 Values[1] = ClassGV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004356 std::vector<llvm::Constant*> Methods;
4357 std::string MethodListName(Prefix);
4358 MethodListName += "INSTANCE_METHODS_" + Interface->getNameAsString() +
4359 "_$_" + OCD->getNameAsString();
4360
4361 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
4362 e = OCD->instmeth_end(); i != e; ++i) {
4363 // Instance methods should always be defined.
4364 Methods.push_back(GetMethodConstant(*i));
4365 }
4366
4367 Values[2] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004368 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004369 Methods);
4370
4371 MethodListName = Prefix;
4372 MethodListName += "CLASS_METHODS_" + Interface->getNameAsString() + "_$_" +
4373 OCD->getNameAsString();
4374 Methods.clear();
4375 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
4376 e = OCD->classmeth_end(); i != e; ++i) {
4377 // Class methods should always be defined.
4378 Methods.push_back(GetMethodConstant(*i));
4379 }
4380
4381 Values[3] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004382 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004383 Methods);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004384 const ObjCCategoryDecl *Category =
4385 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Fariborz Jahanian943ed6f2009-02-13 17:52:22 +00004386 if (Category) {
4387 std::string ExtName(Interface->getNameAsString() + "_$_" +
4388 OCD->getNameAsString());
4389 Values[4] = EmitProtocolList("\01l_OBJC_CATEGORY_PROTOCOLS_$_"
4390 + Interface->getNameAsString() + "_$_"
4391 + Category->getNameAsString(),
4392 Category->protocol_begin(),
4393 Category->protocol_end());
4394 Values[5] =
4395 EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
4396 OCD, Category, ObjCTypes);
4397 }
4398 else {
4399 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4400 Values[5] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4401 }
4402
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004403 llvm::Constant *Init =
4404 llvm::ConstantStruct::get(ObjCTypes.CategorynfABITy,
4405 Values);
4406 llvm::GlobalVariable *GCATV
4407 = new llvm::GlobalVariable(ObjCTypes.CategorynfABITy,
4408 false,
4409 llvm::GlobalValue::InternalLinkage,
4410 Init,
4411 ExtCatName,
4412 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004413 GCATV->setAlignment(
4414 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.CategorynfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004415 GCATV->setSection("__DATA, __objc_const");
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004416 UsedGlobals.push_back(GCATV);
4417 DefinedCategories.push_back(GCATV);
4418}
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004419
4420/// GetMethodConstant - Return a struct objc_method constant for the
4421/// given method if it has been defined. The result is null if the
4422/// method has not been defined. The return value has type MethodPtrTy.
4423llvm::Constant *CGObjCNonFragileABIMac::GetMethodConstant(
4424 const ObjCMethodDecl *MD) {
4425 // FIXME: Use DenseMap::lookup
4426 llvm::Function *Fn = MethodDefinitions[MD];
4427 if (!Fn)
4428 return 0;
4429
4430 std::vector<llvm::Constant*> Method(3);
4431 Method[0] =
4432 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4433 ObjCTypes.SelectorPtrTy);
4434 Method[1] = GetMethodVarType(MD);
4435 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
4436 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
4437}
4438
4439/// EmitMethodList - Build meta-data for method declarations
4440/// struct _method_list_t {
4441/// uint32_t entsize; // sizeof(struct _objc_method)
4442/// uint32_t method_count;
4443/// struct _objc_method method_list[method_count];
4444/// }
4445///
4446llvm::Constant *CGObjCNonFragileABIMac::EmitMethodList(
4447 const std::string &Name,
4448 const char *Section,
4449 const ConstantVector &Methods) {
4450 // Return null for empty list.
4451 if (Methods.empty())
4452 return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy);
4453
4454 std::vector<llvm::Constant*> Values(3);
4455 // sizeof(struct _objc_method)
4456 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.MethodTy);
4457 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4458 // method_count
4459 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
4460 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
4461 Methods.size());
4462 Values[2] = llvm::ConstantArray::get(AT, Methods);
4463 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4464
4465 llvm::GlobalVariable *GV =
4466 new llvm::GlobalVariable(Init->getType(), false,
4467 llvm::GlobalValue::InternalLinkage,
4468 Init,
4469 Name,
4470 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004471 GV->setAlignment(
4472 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004473 GV->setSection(Section);
4474 UsedGlobals.push_back(GV);
4475 return llvm::ConstantExpr::getBitCast(GV,
4476 ObjCTypes.MethodListnfABIPtrTy);
4477}
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004478
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004479/// ObjCIvarOffsetVariable - Returns the ivar offset variable for
4480/// the given ivar.
4481///
4482llvm::GlobalVariable * CGObjCNonFragileABIMac::ObjCIvarOffsetVariable(
4483 std::string &Name,
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004484 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004485 const ObjCIvarDecl *Ivar) {
Daniel Dunbardd131982009-04-14 22:44:26 +00004486 Name += "OBJC_IVAR_$_" +
Douglas Gregor6ab35242009-04-09 21:40:53 +00004487 getInterfaceDeclForIvar(ID, Ivar, CGM.getContext())->getNameAsString() +
4488 '.' + Ivar->getNameAsString();
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004489 llvm::GlobalVariable *IvarOffsetGV =
4490 CGM.getModule().getGlobalVariable(Name);
4491 if (!IvarOffsetGV)
4492 IvarOffsetGV =
4493 new llvm::GlobalVariable(ObjCTypes.LongTy,
4494 false,
4495 llvm::GlobalValue::ExternalLinkage,
4496 0,
4497 Name,
4498 &CGM.getModule());
4499 return IvarOffsetGV;
4500}
4501
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004502llvm::Constant * CGObjCNonFragileABIMac::EmitIvarOffsetVar(
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004503 const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004504 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004505 unsigned long int Offset) {
4506
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004507 assert(ID && "EmitIvarOffsetVar - null interface decl.");
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004508 std::string ExternalName("\01_OBJC_IVAR_$_" + ID->getNameAsString() + '.'
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004509 + Ivar->getNameAsString());
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004510 llvm::Constant *Init = llvm::ConstantInt::get(ObjCTypes.LongTy, Offset);
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004511 llvm::GlobalVariable *IvarOffsetGV =
4512 CGM.getModule().getGlobalVariable(ExternalName);
Fariborz Jahanian77c9fd22009-04-06 18:30:00 +00004513 if (IvarOffsetGV)
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004514 // ivar offset symbol already built due to user code referencing it.
4515 IvarOffsetGV->setInitializer(Init);
Fariborz Jahanian77c9fd22009-04-06 18:30:00 +00004516 else
4517 IvarOffsetGV =
4518 new llvm::GlobalVariable(Init->getType(),
4519 false,
4520 llvm::GlobalValue::ExternalLinkage,
4521 Init,
4522 ExternalName,
4523 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004524 IvarOffsetGV->setAlignment(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004525 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.LongTy));
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004526 // @private and @package have hidden visibility.
4527 bool globalVisibility = (Ivar->getAccessControl() == ObjCIvarDecl::Public ||
Daniel Dunbar04d40782009-04-14 06:00:08 +00004528 Ivar->getAccessControl() == ObjCIvarDecl::Protected);
4529 if (!globalVisibility || CGM.getDeclVisibilityMode(ID) == LangOptions::Hidden)
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004530 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar04d40782009-04-14 06:00:08 +00004531 else
Fariborz Jahanian77c9fd22009-04-06 18:30:00 +00004532 IvarOffsetGV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004533 IvarOffsetGV->setSection("__DATA, __objc_const");
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004534 return IvarOffsetGV;
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004535}
4536
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004537/// EmitIvarList - Emit the ivar list for the given
4538/// implementation. If ForClass is true the list of class ivars
4539/// (i.e. metaclass ivars) is emitted, otherwise the list of
4540/// interface ivars will be emitted. The return value has type
4541/// IvarListnfABIPtrTy.
4542/// struct _ivar_t {
4543/// unsigned long int *offset; // pointer to ivar offset location
4544/// char *name;
4545/// char *type;
4546/// uint32_t alignment;
4547/// uint32_t size;
4548/// }
4549/// struct _ivar_list_t {
4550/// uint32 entsize; // sizeof(struct _ivar_t)
4551/// uint32 count;
4552/// struct _iver_t list[count];
4553/// }
4554///
4555llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList(
4556 const ObjCImplementationDecl *ID) {
4557
4558 std::vector<llvm::Constant*> Ivars, Ivar(5);
4559
4560 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4561 assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface");
4562
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004563 // FIXME. Consolidate this with similar code in GenerateClass.
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00004564 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00004565
4566 RecordDecl::field_iterator i,p;
4567 const RecordDecl *RD = GetFirstIvarInRecord(OID, i,p);
Fariborz Jahanian18191882009-03-31 18:11:23 +00004568 // collect declared and synthesized ivars in a small vector.
4569 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
4570 for (ObjCInterfaceDecl::ivar_iterator I = OID->ivar_begin(),
4571 E = OID->ivar_end(); I != E; ++I)
4572 OIvars.push_back(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +00004573 for (ObjCInterfaceDecl::prop_iterator I = OID->prop_begin(CGM.getContext()),
4574 E = OID->prop_end(CGM.getContext()); I != E; ++I)
Fariborz Jahanian18191882009-03-31 18:11:23 +00004575 if (ObjCIvarDecl *IV = (*I)->getPropertyIvarDecl())
4576 OIvars.push_back(IV);
Fariborz Jahanian99eee362009-04-01 19:37:34 +00004577
Fariborz Jahanian18191882009-03-31 18:11:23 +00004578 unsigned iv = 0;
Douglas Gregor6ab35242009-04-09 21:40:53 +00004579 for (RecordDecl::field_iterator e = RD->field_end(CGM.getContext());
4580 i != e; ++i) {
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004581 FieldDecl *Field = *i;
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00004582 uint64_t offset = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanian18191882009-03-31 18:11:23 +00004583 Ivar[0] = EmitIvarOffsetVar(ID->getClassInterface(), OIvars[iv++], offset);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004584 if (Field->getIdentifier())
4585 Ivar[1] = GetMethodVarName(Field->getIdentifier());
4586 else
4587 Ivar[1] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Devang Patel7794bb82009-03-04 18:21:39 +00004588 Ivar[2] = GetMethodVarType(Field);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004589 const llvm::Type *FieldTy =
4590 CGM.getTypes().ConvertTypeForMem(Field->getType());
4591 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
4592 unsigned Align = CGM.getContext().getPreferredTypeAlign(
4593 Field->getType().getTypePtr()) >> 3;
4594 Align = llvm::Log2_32(Align);
4595 Ivar[3] = llvm::ConstantInt::get(ObjCTypes.IntTy, Align);
Fariborz Jahanian07236ba2009-01-27 22:27:56 +00004596 // NOTE. Size of a bitfield does not match gcc's, because of the way
4597 // bitfields are treated special in each. But I am told that 'size'
4598 // for bitfield ivars is ignored by the runtime so it does not matter.
4599 // (even if it matters, some day, there is enough info. to get the bitfield
4600 // right!
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004601 Ivar[4] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4602 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarnfABITy, Ivar));
4603 }
4604 // Return null for empty list.
4605 if (Ivars.empty())
4606 return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4607 std::vector<llvm::Constant*> Values(3);
4608 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.IvarnfABITy);
4609 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4610 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
4611 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarnfABITy,
4612 Ivars.size());
4613 Values[2] = llvm::ConstantArray::get(AT, Ivars);
4614 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4615 const char *Prefix = "\01l_OBJC_$_INSTANCE_VARIABLES_";
4616 llvm::GlobalVariable *GV =
4617 new llvm::GlobalVariable(Init->getType(), false,
4618 llvm::GlobalValue::InternalLinkage,
4619 Init,
4620 Prefix + OID->getNameAsString(),
4621 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004622 GV->setAlignment(
4623 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004624 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004625
4626 UsedGlobals.push_back(GV);
4627 return llvm::ConstantExpr::getBitCast(GV,
4628 ObjCTypes.IvarListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004629}
4630
4631llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef(
4632 const ObjCProtocolDecl *PD) {
4633 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4634
4635 if (!Entry) {
4636 // We use the initializer as a marker of whether this is a forward
4637 // reference or not. At module finalization we add the empty
4638 // contents for protocols which were referenced but never defined.
4639 Entry =
4640 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
4641 llvm::GlobalValue::ExternalLinkage,
4642 0,
4643 "\01l_OBJC_PROTOCOL_$_" + PD->getNameAsString(),
4644 &CGM.getModule());
4645 Entry->setSection("__DATA,__datacoal_nt,coalesced");
4646 UsedGlobals.push_back(Entry);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004647 }
4648
4649 return Entry;
4650}
4651
4652/// GetOrEmitProtocol - Generate the protocol meta-data:
4653/// @code
4654/// struct _protocol_t {
4655/// id isa; // NULL
4656/// const char * const protocol_name;
4657/// const struct _protocol_list_t * protocol_list; // super protocols
4658/// const struct method_list_t * const instance_methods;
4659/// const struct method_list_t * const class_methods;
4660/// const struct method_list_t *optionalInstanceMethods;
4661/// const struct method_list_t *optionalClassMethods;
4662/// const struct _prop_list_t * properties;
4663/// const uint32_t size; // sizeof(struct _protocol_t)
4664/// const uint32_t flags; // = 0
4665/// }
4666/// @endcode
4667///
4668
4669llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol(
4670 const ObjCProtocolDecl *PD) {
4671 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4672
4673 // Early exit if a defining object has already been generated.
4674 if (Entry && Entry->hasInitializer())
4675 return Entry;
4676
4677 const char *ProtocolName = PD->getNameAsCString();
4678
4679 // Construct method lists.
4680 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
4681 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregor6ab35242009-04-09 21:40:53 +00004682 for (ObjCProtocolDecl::instmeth_iterator
4683 i = PD->instmeth_begin(CGM.getContext()),
4684 e = PD->instmeth_end(CGM.getContext());
4685 i != e; ++i) {
Fariborz Jahanianda320092009-01-29 19:24:30 +00004686 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004687 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004688 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4689 OptInstanceMethods.push_back(C);
4690 } else {
4691 InstanceMethods.push_back(C);
4692 }
4693 }
4694
Douglas Gregor6ab35242009-04-09 21:40:53 +00004695 for (ObjCProtocolDecl::classmeth_iterator
4696 i = PD->classmeth_begin(CGM.getContext()),
4697 e = PD->classmeth_end(CGM.getContext());
4698 i != e; ++i) {
Fariborz Jahanianda320092009-01-29 19:24:30 +00004699 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004700 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004701 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4702 OptClassMethods.push_back(C);
4703 } else {
4704 ClassMethods.push_back(C);
4705 }
4706 }
4707
4708 std::vector<llvm::Constant*> Values(10);
4709 // isa is NULL
4710 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ObjectPtrTy);
4711 Values[1] = GetClassName(PD->getIdentifier());
4712 Values[2] = EmitProtocolList(
4713 "\01l_OBJC_$_PROTOCOL_REFS_" + PD->getNameAsString(),
4714 PD->protocol_begin(),
4715 PD->protocol_end());
4716
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004717 Values[3] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004718 + PD->getNameAsString(),
4719 "__DATA, __objc_const",
4720 InstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004721 Values[4] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004722 + PD->getNameAsString(),
4723 "__DATA, __objc_const",
4724 ClassMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004725 Values[5] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004726 + PD->getNameAsString(),
4727 "__DATA, __objc_const",
4728 OptInstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004729 Values[6] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004730 + PD->getNameAsString(),
4731 "__DATA, __objc_const",
4732 OptClassMethods);
4733 Values[7] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + PD->getNameAsString(),
4734 0, PD, ObjCTypes);
4735 uint32_t Size =
4736 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolnfABITy);
4737 Values[8] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4738 Values[9] = llvm::Constant::getNullValue(ObjCTypes.IntTy);
4739 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolnfABITy,
4740 Values);
4741
4742 if (Entry) {
4743 // Already created, fix the linkage and update the initializer.
Mike Stump286acbd2009-03-07 16:33:28 +00004744 Entry->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004745 Entry->setInitializer(Init);
4746 } else {
4747 Entry =
4748 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004749 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004750 Init,
4751 std::string("\01l_OBJC_PROTOCOL_$_")+ProtocolName,
4752 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004753 Entry->setAlignment(
4754 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABITy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004755 Entry->setSection("__DATA,__datacoal_nt,coalesced");
Fariborz Jahanianda320092009-01-29 19:24:30 +00004756 }
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004757 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
4758
4759 // Use this protocol meta-data to build protocol list table in section
4760 // __DATA, __objc_protolist
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004761 llvm::GlobalVariable *PTGV = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004762 ObjCTypes.ProtocolnfABIPtrTy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004763 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004764 Entry,
4765 std::string("\01l_OBJC_LABEL_PROTOCOL_$_")
4766 +ProtocolName,
4767 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004768 PTGV->setAlignment(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004769 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABIPtrTy));
Daniel Dunbar0bf21992009-04-15 02:56:18 +00004770 PTGV->setSection("__DATA, __objc_protolist, coalesced, no_dead_strip");
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004771 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4772 UsedGlobals.push_back(PTGV);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004773 return Entry;
4774}
4775
4776/// EmitProtocolList - Generate protocol list meta-data:
4777/// @code
4778/// struct _protocol_list_t {
4779/// long protocol_count; // Note, this is 32/64 bit
4780/// struct _protocol_t[protocol_count];
4781/// }
4782/// @endcode
4783///
4784llvm::Constant *
4785CGObjCNonFragileABIMac::EmitProtocolList(const std::string &Name,
4786 ObjCProtocolDecl::protocol_iterator begin,
4787 ObjCProtocolDecl::protocol_iterator end) {
4788 std::vector<llvm::Constant*> ProtocolRefs;
4789
Fariborz Jahanianda320092009-01-29 19:24:30 +00004790 // Just return null for empty protocol lists
Daniel Dunbar948e2582009-02-15 07:36:20 +00004791 if (begin == end)
Fariborz Jahanianda320092009-01-29 19:24:30 +00004792 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4793
Daniel Dunbar948e2582009-02-15 07:36:20 +00004794 // FIXME: We shouldn't need to do this lookup here, should we?
Fariborz Jahanianda320092009-01-29 19:24:30 +00004795 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
4796 if (GV)
Daniel Dunbar948e2582009-02-15 07:36:20 +00004797 return llvm::ConstantExpr::getBitCast(GV,
4798 ObjCTypes.ProtocolListnfABIPtrTy);
4799
4800 for (; begin != end; ++begin)
4801 ProtocolRefs.push_back(GetProtocolRef(*begin)); // Implemented???
4802
Fariborz Jahanianda320092009-01-29 19:24:30 +00004803 // This list is null terminated.
4804 ProtocolRefs.push_back(llvm::Constant::getNullValue(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004805 ObjCTypes.ProtocolnfABIPtrTy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004806
4807 std::vector<llvm::Constant*> Values(2);
4808 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
4809 Values[1] =
Daniel Dunbar948e2582009-02-15 07:36:20 +00004810 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolnfABIPtrTy,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004811 ProtocolRefs.size()),
4812 ProtocolRefs);
4813
4814 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4815 GV = new llvm::GlobalVariable(Init->getType(), false,
4816 llvm::GlobalValue::InternalLinkage,
4817 Init,
4818 Name,
4819 &CGM.getModule());
4820 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004821 GV->setAlignment(
4822 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004823 UsedGlobals.push_back(GV);
Daniel Dunbar948e2582009-02-15 07:36:20 +00004824 return llvm::ConstantExpr::getBitCast(GV,
4825 ObjCTypes.ProtocolListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004826}
4827
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004828/// GetMethodDescriptionConstant - This routine build following meta-data:
4829/// struct _objc_method {
4830/// SEL _cmd;
4831/// char *method_type;
4832/// char *_imp;
4833/// }
4834
4835llvm::Constant *
4836CGObjCNonFragileABIMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
4837 std::vector<llvm::Constant*> Desc(3);
4838 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4839 ObjCTypes.SelectorPtrTy);
4840 Desc[1] = GetMethodVarType(MD);
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004841 // Protocol methods have no implementation. So, this entry is always NULL.
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004842 Desc[2] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
4843 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Desc);
4844}
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004845
4846/// EmitObjCValueForIvar - Code Gen for nonfragile ivar reference.
4847/// This code gen. amounts to generating code for:
4848/// @code
4849/// (type *)((char *)base + _OBJC_IVAR_$_.ivar;
4850/// @encode
4851///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004852LValue CGObjCNonFragileABIMac::EmitObjCValueForIvar(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004853 CodeGen::CodeGenFunction &CGF,
4854 QualType ObjectTy,
4855 llvm::Value *BaseValue,
4856 const ObjCIvarDecl *Ivar,
4857 const FieldDecl *Field,
4858 unsigned CVRQualifiers) {
4859 assert(ObjectTy->isObjCInterfaceType() &&
4860 "CGObjCNonFragileABIMac::EmitObjCValueForIvar");
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004861 ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004862 std::string ExternalName;
4863 llvm::GlobalVariable *IvarOffsetGV =
4864 ObjCIvarOffsetVariable(ExternalName, ID, Ivar);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004865
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004866 // (char *) BaseValue
4867 llvm::Value *V = CGF.Builder.CreateBitCast(BaseValue,
4868 ObjCTypes.Int8PtrTy);
4869 llvm::Value *Offset = CGF.Builder.CreateLoad(IvarOffsetGV);
4870 // (char*)BaseValue + Offset_symbol
4871 V = CGF.Builder.CreateGEP(V, Offset, "add.ptr");
4872 // (type *)((char*)BaseValue + Offset_symbol)
4873 const llvm::Type *IvarTy =
4874 CGM.getTypes().ConvertType(Ivar->getType());
4875 llvm::Type *ptrIvarTy = llvm::PointerType::getUnqual(IvarTy);
4876 V = CGF.Builder.CreateBitCast(V, ptrIvarTy);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004877
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00004878 if (Ivar->isBitField()) {
4879 CodeGenTypes::BitFieldInfo bitFieldInfo =
4880 CGM.getTypes().getBitFieldInfo(Field);
4881 return LValue::MakeBitfield(V, bitFieldInfo.Begin, bitFieldInfo.Size,
4882 Field->getType()->isSignedIntegerType(),
4883 Field->getType().getCVRQualifiers()|CVRQualifiers);
4884 }
4885
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004886 LValue LV = LValue::MakeAddr(V,
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004887 Ivar->getType().getCVRQualifiers()|CVRQualifiers,
4888 CGM.getContext().getObjCGCAttrKind(Ivar->getType()));
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004889 LValue::SetObjCIvar(LV, true);
4890 return LV;
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004891}
4892
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004893llvm::Value *CGObjCNonFragileABIMac::EmitIvarOffset(
4894 CodeGen::CodeGenFunction &CGF,
4895 ObjCInterfaceDecl *Interface,
4896 const ObjCIvarDecl *Ivar) {
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004897 std::string ExternalName;
4898 llvm::GlobalVariable *IvarOffsetGV =
4899 ObjCIvarOffsetVariable(ExternalName, Interface, Ivar);
4900
4901 return CGF.Builder.CreateLoad(IvarOffsetGV, false, "ivar");
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004902}
4903
Fariborz Jahanian46551122009-02-04 00:22:57 +00004904CodeGen::RValue CGObjCNonFragileABIMac::EmitMessageSend(
4905 CodeGen::CodeGenFunction &CGF,
4906 QualType ResultType,
4907 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004908 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +00004909 QualType Arg0Ty,
4910 bool IsSuper,
4911 const CallArgList &CallArgs) {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004912 // FIXME. Even though IsSuper is passes. This function doese not
4913 // handle calls to 'super' receivers.
4914 CodeGenTypes &Types = CGM.getTypes();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004915 llvm::Value *Arg0 = Receiver;
4916 if (!IsSuper)
4917 Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy, "tmp");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004918
4919 // Find the message function name.
Fariborz Jahanianef163782009-02-05 01:13:09 +00004920 // FIXME. This is too much work to get the ABI-specific result type
4921 // needed to find the message name.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004922 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType,
4923 llvm::SmallVector<QualType, 16>());
4924 llvm::Constant *Fn;
4925 std::string Name("\01l_");
4926 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004927#if 0
4928 // unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004929 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
4930 Fn = ObjCTypes.MessageSendIdStretFixupFn;
4931 // FIXME. Is there a better way of getting these names.
4932 // They are available in RuntimeFunctions vector pair.
4933 Name += "objc_msgSendId_stret_fixup";
4934 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004935 else
4936#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004937 if (IsSuper) {
4938 Fn = ObjCTypes.MessageSendSuper2StretFixupFn;
4939 Name += "objc_msgSendSuper2_stret_fixup";
4940 }
4941 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004942 {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004943 Fn = ObjCTypes.MessageSendStretFixupFn;
4944 Name += "objc_msgSend_stret_fixup";
4945 }
4946 }
Fariborz Jahanian1a6b3682009-02-05 19:35:43 +00004947 else if (ResultType->isFloatingType() &&
4948 // Selection of frret API only happens in 32bit nonfragile ABI.
4949 CGM.getTargetData().getTypePaddedSize(ObjCTypes.LongTy) == 4) {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004950 Fn = ObjCTypes.MessageSendFpretFixupFn;
4951 Name += "objc_msgSend_fpret_fixup";
4952 }
4953 else {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004954#if 0
4955// unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004956 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
4957 Fn = ObjCTypes.MessageSendIdFixupFn;
4958 Name += "objc_msgSendId_fixup";
4959 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004960 else
4961#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004962 if (IsSuper) {
4963 Fn = ObjCTypes.MessageSendSuper2FixupFn;
4964 Name += "objc_msgSendSuper2_fixup";
4965 }
4966 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004967 {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004968 Fn = ObjCTypes.MessageSendFixupFn;
4969 Name += "objc_msgSend_fixup";
4970 }
4971 }
4972 Name += '_';
4973 std::string SelName(Sel.getAsString());
4974 // Replace all ':' in selector name with '_' ouch!
4975 for(unsigned i = 0; i < SelName.size(); i++)
4976 if (SelName[i] == ':')
4977 SelName[i] = '_';
4978 Name += SelName;
4979 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
4980 if (!GV) {
Daniel Dunbar33af70f2009-04-15 19:03:14 +00004981 // Build message ref table entry.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004982 std::vector<llvm::Constant*> Values(2);
4983 Values[0] = Fn;
4984 Values[1] = GetMethodVarName(Sel);
4985 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4986 GV = new llvm::GlobalVariable(Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00004987 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004988 Init,
4989 Name,
4990 &CGM.getModule());
4991 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4992 GV->setAlignment(
4993 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.MessageRefTy));
4994 GV->setSection("__DATA, __objc_msgrefs, coalesced");
4995 UsedGlobals.push_back(GV);
4996 }
4997 llvm::Value *Arg1 = CGF.Builder.CreateBitCast(GV, ObjCTypes.MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00004998
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004999 CallArgList ActualArgs;
5000 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
5001 ActualArgs.push_back(std::make_pair(RValue::get(Arg1),
5002 ObjCTypes.MessageRefCPtrTy));
5003 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Fariborz Jahanianef163782009-02-05 01:13:09 +00005004 const CGFunctionInfo &FnInfo1 = Types.getFunctionInfo(ResultType, ActualArgs);
5005 llvm::Value *Callee = CGF.Builder.CreateStructGEP(Arg1, 0);
5006 Callee = CGF.Builder.CreateLoad(Callee);
Fariborz Jahanian3ab75bd2009-02-14 21:25:36 +00005007 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo1, true);
Fariborz Jahanianef163782009-02-05 01:13:09 +00005008 Callee = CGF.Builder.CreateBitCast(Callee,
5009 llvm::PointerType::getUnqual(FTy));
5010 return CGF.EmitCall(FnInfo1, Callee, ActualArgs);
Fariborz Jahanian46551122009-02-04 00:22:57 +00005011}
5012
5013/// Generate code for a message send expression in the nonfragile abi.
5014CodeGen::RValue CGObjCNonFragileABIMac::GenerateMessageSend(
5015 CodeGen::CodeGenFunction &CGF,
5016 QualType ResultType,
5017 Selector Sel,
5018 llvm::Value *Receiver,
5019 bool IsClassMessage,
5020 const CallArgList &CallArgs) {
Fariborz Jahanian46551122009-02-04 00:22:57 +00005021 return EmitMessageSend(CGF, ResultType, Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005022 Receiver, CGF.getContext().getObjCIdType(),
Fariborz Jahanian46551122009-02-04 00:22:57 +00005023 false, CallArgs);
5024}
5025
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005026llvm::GlobalVariable *
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005027CGObjCNonFragileABIMac::GetClassGlobal(const std::string &Name) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005028 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5029
Daniel Dunbardfff2302009-03-02 05:18:14 +00005030 if (!GV) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005031 GV = new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
5032 llvm::GlobalValue::ExternalLinkage,
5033 0, Name, &CGM.getModule());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005034 }
5035
5036 return GV;
5037}
5038
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005039llvm::Value *CGObjCNonFragileABIMac::EmitClassRef(CGBuilderTy &Builder,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005040 const ObjCInterfaceDecl *ID,
5041 bool IsSuper) {
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005042
5043 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
5044
5045 if (!Entry) {
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005046 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005047 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005048 Entry =
5049 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5050 llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005051 ClassGV,
5052 IsSuper ? "\01L_OBJC_CLASSLIST_SUP_REFS_$_"
5053 : "\01L_OBJC_CLASSLIST_REFERENCES_$_",
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005054 &CGM.getModule());
5055 Entry->setAlignment(
5056 CGM.getTargetData().getPrefTypeAlignment(
5057 ObjCTypes.ClassnfABIPtrTy));
5058
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005059 if (IsSuper)
Daniel Dunbar0bf21992009-04-15 02:56:18 +00005060 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005061 else
Daniel Dunbar0bf21992009-04-15 02:56:18 +00005062 Entry->setSection("__DATA, __objc_classrefs, regular, no_dead_strip");
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005063 UsedGlobals.push_back(Entry);
5064 }
5065
5066 return Builder.CreateLoad(Entry, false, "tmp");
5067}
5068
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005069/// EmitMetaClassRef - Return a Value * of the address of _class_t
5070/// meta-data
5071///
5072llvm::Value *CGObjCNonFragileABIMac::EmitMetaClassRef(CGBuilderTy &Builder,
5073 const ObjCInterfaceDecl *ID) {
5074 llvm::GlobalVariable * &Entry = MetaClassReferences[ID->getIdentifier()];
5075 if (Entry)
5076 return Builder.CreateLoad(Entry, false, "tmp");
5077
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005078 std::string MetaClassName(getMetaclassSymbolPrefix() + ID->getNameAsString());
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005079 llvm::GlobalVariable *MetaClassGV = GetClassGlobal(MetaClassName);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005080 Entry =
5081 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5082 llvm::GlobalValue::InternalLinkage,
5083 MetaClassGV,
5084 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5085 &CGM.getModule());
5086 Entry->setAlignment(
5087 CGM.getTargetData().getPrefTypeAlignment(
5088 ObjCTypes.ClassnfABIPtrTy));
5089
Daniel Dunbar33af70f2009-04-15 19:03:14 +00005090 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005091 UsedGlobals.push_back(Entry);
5092
5093 return Builder.CreateLoad(Entry, false, "tmp");
5094}
5095
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005096/// GetClass - Return a reference to the class for the given interface
5097/// decl.
5098llvm::Value *CGObjCNonFragileABIMac::GetClass(CGBuilderTy &Builder,
5099 const ObjCInterfaceDecl *ID) {
5100 return EmitClassRef(Builder, ID);
5101}
5102
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005103/// Generates a message send where the super is the receiver. This is
5104/// a message send to self with special delivery semantics indicating
5105/// which class's method should be called.
5106CodeGen::RValue
5107CGObjCNonFragileABIMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
5108 QualType ResultType,
5109 Selector Sel,
5110 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005111 bool isCategoryImpl,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005112 llvm::Value *Receiver,
5113 bool IsClassMessage,
5114 const CodeGen::CallArgList &CallArgs) {
5115 // ...
5116 // Create and init a super structure; this is a (receiver, class)
5117 // pair we will pass to objc_msgSendSuper.
5118 llvm::Value *ObjCSuper =
5119 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
5120
5121 llvm::Value *ReceiverAsObject =
5122 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
5123 CGF.Builder.CreateStore(ReceiverAsObject,
5124 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
5125
5126 // If this is a class message the metaclass is passed as the target.
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005127 llvm::Value *Target;
5128 if (IsClassMessage) {
5129 if (isCategoryImpl) {
5130 // Message sent to "super' in a class method defined in
5131 // a category implementation.
5132 Target = EmitClassRef(CGF.Builder, Class, false);
5133 Target = CGF.Builder.CreateStructGEP(Target, 0);
5134 Target = CGF.Builder.CreateLoad(Target);
5135 }
5136 else
5137 Target = EmitMetaClassRef(CGF.Builder, Class);
5138 }
5139 else
5140 Target = EmitClassRef(CGF.Builder, Class, true);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005141
5142 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
5143 // and ObjCTypes types.
5144 const llvm::Type *ClassTy =
5145 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
5146 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
5147 CGF.Builder.CreateStore(Target,
5148 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
5149
5150 return EmitMessageSend(CGF, ResultType, Sel,
5151 ObjCSuper, ObjCTypes.SuperPtrCTy,
5152 true, CallArgs);
5153}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005154
5155llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CGBuilderTy &Builder,
5156 Selector Sel) {
5157 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
5158
5159 if (!Entry) {
5160 llvm::Constant *Casted =
5161 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
5162 ObjCTypes.SelectorPtrTy);
5163 Entry =
5164 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
5165 llvm::GlobalValue::InternalLinkage,
5166 Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
5167 &CGM.getModule());
5168 Entry->setSection("__DATA,__objc_selrefs,literal_pointers,no_dead_strip");
5169 UsedGlobals.push_back(Entry);
5170 }
5171
5172 return Builder.CreateLoad(Entry, false, "tmp");
5173}
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005174/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
5175/// objc_assign_ivar (id src, id *dst)
5176///
5177void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
5178 llvm::Value *src, llvm::Value *dst)
5179{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005180 const llvm::Type * SrcTy = src->getType();
5181 if (!isa<llvm::PointerType>(SrcTy)) {
5182 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5183 assert(Size <= 8 && "does not support size > 8");
5184 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5185 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005186 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5187 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005188 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5189 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5190 CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn,
5191 src, dst, "assignivar");
5192 return;
5193}
5194
5195/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
5196/// objc_assign_strongCast (id src, id *dst)
5197///
5198void CGObjCNonFragileABIMac::EmitObjCStrongCastAssign(
5199 CodeGen::CodeGenFunction &CGF,
5200 llvm::Value *src, llvm::Value *dst)
5201{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005202 const llvm::Type * SrcTy = src->getType();
5203 if (!isa<llvm::PointerType>(SrcTy)) {
5204 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5205 assert(Size <= 8 && "does not support size > 8");
5206 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5207 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005208 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5209 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005210 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5211 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5212 CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn,
5213 src, dst, "weakassign");
5214 return;
5215}
5216
5217/// EmitObjCWeakRead - Code gen for loading value of a __weak
5218/// object: objc_read_weak (id *src)
5219///
5220llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead(
5221 CodeGen::CodeGenFunction &CGF,
5222 llvm::Value *AddrWeakObj)
5223{
Eli Friedman8339b352009-03-07 03:57:15 +00005224 const llvm::Type* DestTy =
5225 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005226 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
5227 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
5228 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00005229 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005230 return read_weak;
5231}
5232
5233/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
5234/// objc_assign_weak (id src, id *dst)
5235///
5236void CGObjCNonFragileABIMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
5237 llvm::Value *src, llvm::Value *dst)
5238{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005239 const llvm::Type * SrcTy = src->getType();
5240 if (!isa<llvm::PointerType>(SrcTy)) {
5241 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5242 assert(Size <= 8 && "does not support size > 8");
5243 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5244 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005245 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5246 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005247 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5248 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5249 CGF.Builder.CreateCall2(ObjCTypes.GcAssignWeakFn,
5250 src, dst, "weakassign");
5251 return;
5252}
5253
5254/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
5255/// objc_assign_global (id src, id *dst)
5256///
5257void CGObjCNonFragileABIMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
5258 llvm::Value *src, llvm::Value *dst)
5259{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005260 const llvm::Type * SrcTy = src->getType();
5261 if (!isa<llvm::PointerType>(SrcTy)) {
5262 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5263 assert(Size <= 8 && "does not support size > 8");
5264 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5265 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005266 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5267 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005268 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5269 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5270 CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn,
5271 src, dst, "globalassign");
5272 return;
5273}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005274
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005275void
5276CGObjCNonFragileABIMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
5277 const Stmt &S) {
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005278 bool isTry = isa<ObjCAtTryStmt>(S);
5279 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
5280 llvm::BasicBlock *PrevLandingPad = CGF.getInvokeDest();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005281 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005282 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005283 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005284 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
5285
5286 // For @synchronized, call objc_sync_enter(sync.expr). The
5287 // evaluation of the expression must occur before we enter the
5288 // @synchronized. We can safely avoid a temp here because jumps into
5289 // @synchronized are illegal & this will dominate uses.
5290 llvm::Value *SyncArg = 0;
5291 if (!isTry) {
5292 SyncArg =
5293 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
5294 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005295 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005296 }
5297
5298 // Push an EH context entry, used for handling rethrows and jumps
5299 // through finally.
5300 CGF.PushCleanupBlock(FinallyBlock);
5301
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005302 CGF.setInvokeDest(TryHandler);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005303
5304 CGF.EmitBlock(TryBlock);
5305 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
5306 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
5307 CGF.EmitBranchThroughCleanup(FinallyEnd);
5308
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005309 // Emit the exception handler.
5310
5311 CGF.EmitBlock(TryHandler);
5312
5313 llvm::Value *llvm_eh_exception =
5314 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_exception);
5315 llvm::Value *llvm_eh_selector_i64 =
5316 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector_i64);
5317 llvm::Value *llvm_eh_typeid_for_i64 =
5318 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for_i64);
5319 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5320 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(Exc->getType(), "_rethrow");
5321
5322 llvm::SmallVector<llvm::Value*, 8> SelectorArgs;
5323 SelectorArgs.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005324 SelectorArgs.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005325
5326 // Construct the lists of (type, catch body) to handle.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005327 llvm::SmallVector<std::pair<const ParmVarDecl*, const Stmt*>, 8> Handlers;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005328 bool HasCatchAll = false;
5329 if (isTry) {
5330 if (const ObjCAtCatchStmt* CatchStmt =
5331 cast<ObjCAtTryStmt>(S).getCatchStmts()) {
5332 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005333 const ParmVarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
Steve Naroff7ba138a2009-03-03 19:52:17 +00005334 Handlers.push_back(std::make_pair(CatchDecl, CatchStmt->getCatchBody()));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005335
5336 // catch(...) always matches.
Steve Naroff7ba138a2009-03-03 19:52:17 +00005337 if (!CatchDecl) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005338 // Use i8* null here to signal this is a catch all, not a cleanup.
5339 llvm::Value *Null = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
5340 SelectorArgs.push_back(Null);
5341 HasCatchAll = true;
5342 break;
5343 }
5344
Daniel Dunbarede8de92009-03-06 00:01:21 +00005345 if (CGF.getContext().isObjCIdType(CatchDecl->getType()) ||
5346 CatchDecl->getType()->isObjCQualifiedIdType()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005347 llvm::Value *IDEHType =
5348 CGM.getModule().getGlobalVariable("OBJC_EHTYPE_id");
5349 if (!IDEHType)
5350 IDEHType =
5351 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5352 llvm::GlobalValue::ExternalLinkage,
5353 0, "OBJC_EHTYPE_id", &CGM.getModule());
5354 SelectorArgs.push_back(IDEHType);
5355 HasCatchAll = true;
5356 break;
5357 }
5358
5359 // All other types should be Objective-C interface pointer types.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005360 const PointerType *PT = CatchDecl->getType()->getAsPointerType();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005361 assert(PT && "Invalid @catch type.");
5362 const ObjCInterfaceType *IT =
5363 PT->getPointeeType()->getAsObjCInterfaceType();
5364 assert(IT && "Invalid @catch type.");
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005365 llvm::Value *EHType = GetInterfaceEHType(IT->getDecl(), false);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005366 SelectorArgs.push_back(EHType);
5367 }
5368 }
5369 }
5370
5371 // We use a cleanup unless there was already a catch all.
5372 if (!HasCatchAll) {
5373 SelectorArgs.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
Daniel Dunbarede8de92009-03-06 00:01:21 +00005374 Handlers.push_back(std::make_pair((const ParmVarDecl*) 0, (const Stmt*) 0));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005375 }
5376
5377 llvm::Value *Selector =
5378 CGF.Builder.CreateCall(llvm_eh_selector_i64,
5379 SelectorArgs.begin(), SelectorArgs.end(),
5380 "selector");
5381 for (unsigned i = 0, e = Handlers.size(); i != e; ++i) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005382 const ParmVarDecl *CatchParam = Handlers[i].first;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005383 const Stmt *CatchBody = Handlers[i].second;
5384
5385 llvm::BasicBlock *Next = 0;
5386
5387 // The last handler always matches.
5388 if (i + 1 != e) {
5389 assert(CatchParam && "Only last handler can be a catch all.");
5390
5391 llvm::BasicBlock *Match = CGF.createBasicBlock("match");
5392 Next = CGF.createBasicBlock("catch.next");
5393 llvm::Value *Id =
5394 CGF.Builder.CreateCall(llvm_eh_typeid_for_i64,
5395 CGF.Builder.CreateBitCast(SelectorArgs[i+2],
5396 ObjCTypes.Int8PtrTy));
5397 CGF.Builder.CreateCondBr(CGF.Builder.CreateICmpEQ(Selector, Id),
5398 Match, Next);
5399
5400 CGF.EmitBlock(Match);
5401 }
5402
5403 if (CatchBody) {
5404 llvm::BasicBlock *MatchEnd = CGF.createBasicBlock("match.end");
5405 llvm::BasicBlock *MatchHandler = CGF.createBasicBlock("match.handler");
5406
5407 // Cleanups must call objc_end_catch.
5408 //
5409 // FIXME: It seems incorrect for objc_begin_catch to be inside
5410 // this context, but this matches gcc.
5411 CGF.PushCleanupBlock(MatchEnd);
5412 CGF.setInvokeDest(MatchHandler);
5413
5414 llvm::Value *ExcObject =
5415 CGF.Builder.CreateCall(ObjCTypes.ObjCBeginCatchFn, Exc);
5416
5417 // Bind the catch parameter if it exists.
5418 if (CatchParam) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005419 ExcObject =
5420 CGF.Builder.CreateBitCast(ExcObject,
5421 CGF.ConvertType(CatchParam->getType()));
5422 // CatchParam is a ParmVarDecl because of the grammar
5423 // construction used to handle this, but for codegen purposes
5424 // we treat this as a local decl.
5425 CGF.EmitLocalBlockVarDecl(*CatchParam);
5426 CGF.Builder.CreateStore(ExcObject, CGF.GetAddrOfLocalVar(CatchParam));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005427 }
5428
5429 CGF.ObjCEHValueStack.push_back(ExcObject);
5430 CGF.EmitStmt(CatchBody);
5431 CGF.ObjCEHValueStack.pop_back();
5432
5433 CGF.EmitBranchThroughCleanup(FinallyEnd);
5434
5435 CGF.EmitBlock(MatchHandler);
5436
5437 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5438 // We are required to emit this call to satisfy LLVM, even
5439 // though we don't use the result.
5440 llvm::SmallVector<llvm::Value*, 8> Args;
5441 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005442 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005443 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5444 0));
5445 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5446 CGF.Builder.CreateStore(Exc, RethrowPtr);
5447 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5448
5449 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5450
5451 CGF.EmitBlock(MatchEnd);
5452
5453 // Unfortunately, we also have to generate another EH frame here
5454 // in case this throws.
5455 llvm::BasicBlock *MatchEndHandler =
5456 CGF.createBasicBlock("match.end.handler");
5457 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
5458 CGF.Builder.CreateInvoke(ObjCTypes.ObjCEndCatchFn,
5459 Cont, MatchEndHandler,
5460 Args.begin(), Args.begin());
5461
5462 CGF.EmitBlock(Cont);
5463 if (Info.SwitchBlock)
5464 CGF.EmitBlock(Info.SwitchBlock);
5465 if (Info.EndBlock)
5466 CGF.EmitBlock(Info.EndBlock);
5467
5468 CGF.EmitBlock(MatchEndHandler);
5469 Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5470 // We are required to emit this call to satisfy LLVM, even
5471 // though we don't use the result.
5472 Args.clear();
5473 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005474 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005475 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5476 0));
5477 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5478 CGF.Builder.CreateStore(Exc, RethrowPtr);
5479 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5480
5481 if (Next)
5482 CGF.EmitBlock(Next);
5483 } else {
5484 assert(!Next && "catchup should be last handler.");
5485
5486 CGF.Builder.CreateStore(Exc, RethrowPtr);
5487 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5488 }
5489 }
5490
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005491 // Pop the cleanup entry, the @finally is outside this cleanup
5492 // scope.
5493 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5494 CGF.setInvokeDest(PrevLandingPad);
5495
5496 CGF.EmitBlock(FinallyBlock);
5497
5498 if (isTry) {
5499 if (const ObjCAtFinallyStmt* FinallyStmt =
5500 cast<ObjCAtTryStmt>(S).getFinallyStmt())
5501 CGF.EmitStmt(FinallyStmt->getFinallyBody());
5502 } else {
5503 // Emit 'objc_sync_exit(expr)' as finally's sole statement for
5504 // @synchronized.
5505 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, SyncArg);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005506 }
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005507
5508 if (Info.SwitchBlock)
5509 CGF.EmitBlock(Info.SwitchBlock);
5510 if (Info.EndBlock)
5511 CGF.EmitBlock(Info.EndBlock);
5512
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005513 // Branch around the rethrow code.
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005514 CGF.EmitBranch(FinallyEnd);
5515
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005516 CGF.EmitBlock(FinallyRethrow);
5517 CGF.Builder.CreateCall(ObjCTypes.UnwindResumeOrRethrowFn,
5518 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005519 CGF.Builder.CreateUnreachable();
5520
5521 CGF.EmitBlock(FinallyEnd);
5522}
5523
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005524/// EmitThrowStmt - Generate code for a throw statement.
5525void CGObjCNonFragileABIMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
5526 const ObjCAtThrowStmt &S) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005527 llvm::Value *Exception;
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005528 if (const Expr *ThrowExpr = S.getThrowExpr()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005529 Exception = CGF.EmitScalarExpr(ThrowExpr);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005530 } else {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005531 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
5532 "Unexpected rethrow outside @catch block.");
5533 Exception = CGF.ObjCEHValueStack.back();
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005534 }
5535
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005536 llvm::Value *ExceptionAsObject =
5537 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
5538 llvm::BasicBlock *InvokeDest = CGF.getInvokeDest();
5539 if (InvokeDest) {
5540 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
5541 CGF.Builder.CreateInvoke(ObjCTypes.ExceptionThrowFn,
5542 Cont, InvokeDest,
5543 &ExceptionAsObject, &ExceptionAsObject + 1);
5544 CGF.EmitBlock(Cont);
5545 } else
5546 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
5547 CGF.Builder.CreateUnreachable();
5548
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005549 // Clear the insertion point to indicate we are in unreachable code.
5550 CGF.Builder.ClearInsertionPoint();
5551}
Daniel Dunbare588b992009-03-01 04:46:24 +00005552
5553llvm::Value *
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005554CGObjCNonFragileABIMac::GetInterfaceEHType(const ObjCInterfaceDecl *ID,
5555 bool ForDefinition) {
Daniel Dunbare588b992009-03-01 04:46:24 +00005556 llvm::GlobalVariable * &Entry = EHTypeReferences[ID->getIdentifier()];
Daniel Dunbare588b992009-03-01 04:46:24 +00005557
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005558 // If we don't need a definition, return the entry if found or check
5559 // if we use an external reference.
5560 if (!ForDefinition) {
5561 if (Entry)
5562 return Entry;
Daniel Dunbar7e075cb2009-04-07 06:43:45 +00005563
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005564 // If this type (or a super class) has the __objc_exception__
5565 // attribute, emit an external reference.
5566 if (hasObjCExceptionAttribute(ID))
5567 return Entry =
5568 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5569 llvm::GlobalValue::ExternalLinkage,
5570 0,
5571 (std::string("OBJC_EHTYPE_$_") +
5572 ID->getIdentifier()->getName()),
5573 &CGM.getModule());
5574 }
5575
5576 // Otherwise we need to either make a new entry or fill in the
5577 // initializer.
5578 assert((!Entry || !Entry->hasInitializer()) && "Duplicate EHType definition");
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005579 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbare588b992009-03-01 04:46:24 +00005580 std::string VTableName = "objc_ehtype_vtable";
5581 llvm::GlobalVariable *VTableGV =
5582 CGM.getModule().getGlobalVariable(VTableName);
5583 if (!VTableGV)
5584 VTableGV = new llvm::GlobalVariable(ObjCTypes.Int8PtrTy, false,
5585 llvm::GlobalValue::ExternalLinkage,
5586 0, VTableName, &CGM.getModule());
5587
5588 llvm::Value *VTableIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, 2);
5589
5590 std::vector<llvm::Constant*> Values(3);
5591 Values[0] = llvm::ConstantExpr::getGetElementPtr(VTableGV, &VTableIdx, 1);
5592 Values[1] = GetClassName(ID->getIdentifier());
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005593 Values[2] = GetClassGlobal(ClassName);
Daniel Dunbare588b992009-03-01 04:46:24 +00005594 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.EHTypeTy, Values);
5595
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005596 if (Entry) {
5597 Entry->setInitializer(Init);
5598 } else {
5599 Entry = new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5600 llvm::GlobalValue::WeakAnyLinkage,
5601 Init,
5602 (std::string("OBJC_EHTYPE_$_") +
5603 ID->getIdentifier()->getName()),
5604 &CGM.getModule());
5605 }
5606
Daniel Dunbar04d40782009-04-14 06:00:08 +00005607 if (CGM.getLangOptions().getVisibilityMode() == LangOptions::Hidden)
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005608 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005609 Entry->setAlignment(8);
5610
5611 if (ForDefinition) {
5612 Entry->setSection("__DATA,__objc_const");
5613 Entry->setLinkage(llvm::GlobalValue::ExternalLinkage);
5614 } else {
5615 Entry->setSection("__DATA,__datacoal_nt,coalesced");
5616 }
Daniel Dunbare588b992009-03-01 04:46:24 +00005617
5618 return Entry;
5619}
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005620
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00005621/* *** */
5622
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00005623CodeGen::CGObjCRuntime *
5624CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00005625 return new CGObjCMac(CGM);
5626}
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005627
5628CodeGen::CGObjCRuntime *
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00005629CodeGen::CreateMacNonFragileABIObjCRuntime(CodeGen::CodeGenModule &CGM) {
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00005630 return new CGObjCNonFragileABIMac(CGM);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005631}