blob: 1f12d85a9f622e836cdf071eabcd5e35b46a4fd5 [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 Lattner96508e12009-04-17 22:12:36 +000095 llvm::Constant *getGcAssignWeakFn() {
96 // id objc_assign_weak (id, id *)
97 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
98 Args.push_back(ObjectPtrTy->getPointerTo());
99 llvm::FunctionType *FTy =
100 llvm::FunctionType::get(ObjectPtrTy, Args, false);
101 return CGM.CreateRuntimeFunction(FTy, "objc_assign_weak");
102 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000103
104 /// GcAssignGlobalFn -- LLVM objc_assign_global function.
Chris Lattner74391b42009-03-22 21:03:39 +0000105 llvm::Constant *GcAssignGlobalFn;
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000106
107 /// GcAssignIvarFn -- LLVM objc_assign_ivar function.
Chris Lattner74391b42009-03-22 21:03:39 +0000108 llvm::Constant *GcAssignIvarFn;
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000109
110 /// GcAssignStrongCastFn -- LLVM objc_assign_strongCast function.
Chris Lattner74391b42009-03-22 21:03:39 +0000111 llvm::Constant *GcAssignStrongCastFn;
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000112
113 /// ExceptionThrowFn - LLVM objc_exception_throw function.
Chris Lattner74391b42009-03-22 21:03:39 +0000114 llvm::Constant *ExceptionThrowFn;
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000115
Daniel Dunbar1c566672009-02-24 01:43:46 +0000116 /// SyncEnterFn - LLVM object_sync_enter function.
Chris Lattnerb02e53b2009-04-06 16:53:45 +0000117 llvm::Constant *getSyncEnterFn() {
118 // void objc_sync_enter (id)
119 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
120 llvm::FunctionType *FTy =
121 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
122 return CGM.CreateRuntimeFunction(FTy, "objc_sync_enter");
123 }
Daniel Dunbar1c566672009-02-24 01:43:46 +0000124
125 /// SyncExitFn - LLVM object_sync_exit function.
Chris Lattner74391b42009-03-22 21:03:39 +0000126 llvm::Constant *SyncExitFn;
Daniel Dunbar1c566672009-02-24 01:43:46 +0000127
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000128 ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm);
129 ~ObjCCommonTypesHelper(){}
130};
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000131
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000132/// ObjCTypesHelper - Helper class that encapsulates lazy
133/// construction of varies types used during ObjC generation.
134class ObjCTypesHelper : public ObjCCommonTypesHelper {
135private:
136
Chris Lattner74391b42009-03-22 21:03:39 +0000137 llvm::Constant *MessageSendFn, *MessageSendStretFn, *MessageSendFpretFn;
138 llvm::Constant *MessageSendSuperFn, *MessageSendSuperStretFn,
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000139 *MessageSendSuperFpretFn;
140
141public:
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000142 /// SymtabTy - LLVM type for struct objc_symtab.
143 const llvm::StructType *SymtabTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000144 /// SymtabPtrTy - LLVM type for struct objc_symtab *.
145 const llvm::Type *SymtabPtrTy;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000146 /// ModuleTy - LLVM type for struct objc_module.
147 const llvm::StructType *ModuleTy;
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000148
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000149 /// ProtocolTy - LLVM type for struct objc_protocol.
150 const llvm::StructType *ProtocolTy;
151 /// ProtocolPtrTy - LLVM type for struct objc_protocol *.
152 const llvm::Type *ProtocolPtrTy;
153 /// ProtocolExtensionTy - LLVM type for struct
154 /// objc_protocol_extension.
155 const llvm::StructType *ProtocolExtensionTy;
156 /// ProtocolExtensionTy - LLVM type for struct
157 /// objc_protocol_extension *.
158 const llvm::Type *ProtocolExtensionPtrTy;
159 /// MethodDescriptionTy - LLVM type for struct
160 /// objc_method_description.
161 const llvm::StructType *MethodDescriptionTy;
162 /// MethodDescriptionListTy - LLVM type for struct
163 /// objc_method_description_list.
164 const llvm::StructType *MethodDescriptionListTy;
165 /// MethodDescriptionListPtrTy - LLVM type for struct
166 /// objc_method_description_list *.
167 const llvm::Type *MethodDescriptionListPtrTy;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000168 /// ProtocolListTy - LLVM type for struct objc_property_list.
169 const llvm::Type *ProtocolListTy;
170 /// ProtocolListPtrTy - LLVM type for struct objc_property_list*.
171 const llvm::Type *ProtocolListPtrTy;
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000172 /// CategoryTy - LLVM type for struct objc_category.
173 const llvm::StructType *CategoryTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000174 /// ClassTy - LLVM type for struct objc_class.
175 const llvm::StructType *ClassTy;
176 /// ClassPtrTy - LLVM type for struct objc_class *.
177 const llvm::Type *ClassPtrTy;
178 /// ClassExtensionTy - LLVM type for struct objc_class_ext.
179 const llvm::StructType *ClassExtensionTy;
180 /// ClassExtensionPtrTy - LLVM type for struct objc_class_ext *.
181 const llvm::Type *ClassExtensionPtrTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000182 // IvarTy - LLVM type for struct objc_ivar.
183 const llvm::StructType *IvarTy;
184 /// IvarListTy - LLVM type for struct objc_ivar_list.
185 const llvm::Type *IvarListTy;
186 /// IvarListPtrTy - LLVM type for struct objc_ivar_list *.
187 const llvm::Type *IvarListPtrTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000188 /// MethodListTy - LLVM type for struct objc_method_list.
189 const llvm::Type *MethodListTy;
190 /// MethodListPtrTy - LLVM type for struct objc_method_list *.
191 const llvm::Type *MethodListPtrTy;
Anders Carlsson124526b2008-09-09 10:10:21 +0000192
193 /// ExceptionDataTy - LLVM type for struct _objc_exception_data.
194 const llvm::Type *ExceptionDataTy;
195
Anders Carlsson124526b2008-09-09 10:10:21 +0000196 /// ExceptionTryEnterFn - LLVM objc_exception_try_enter function.
Chris Lattner74391b42009-03-22 21:03:39 +0000197 llvm::Constant *ExceptionTryEnterFn;
Anders Carlsson124526b2008-09-09 10:10:21 +0000198
199 /// ExceptionTryExitFn - LLVM objc_exception_try_exit function.
Chris Lattner74391b42009-03-22 21:03:39 +0000200 llvm::Constant *ExceptionTryExitFn;
Anders Carlsson124526b2008-09-09 10:10:21 +0000201
202 /// ExceptionExtractFn - LLVM objc_exception_extract function.
Chris Lattner74391b42009-03-22 21:03:39 +0000203 llvm::Constant *ExceptionExtractFn;
Anders Carlsson124526b2008-09-09 10:10:21 +0000204
205 /// ExceptionMatchFn - LLVM objc_exception_match function.
Chris Lattner74391b42009-03-22 21:03:39 +0000206 llvm::Constant *ExceptionMatchFn;
Anders Carlsson124526b2008-09-09 10:10:21 +0000207
208 /// SetJmpFn - LLVM _setjmp function.
Chris Lattner74391b42009-03-22 21:03:39 +0000209 llvm::Constant *SetJmpFn;
Chris Lattner10cac6f2008-11-15 21:26:17 +0000210
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000211public:
212 ObjCTypesHelper(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000213 ~ObjCTypesHelper() {}
Daniel Dunbar5669e572008-10-17 03:24:53 +0000214
215
Chris Lattner74391b42009-03-22 21:03:39 +0000216 llvm::Constant *getSendFn(bool IsSuper) {
Daniel Dunbar5669e572008-10-17 03:24:53 +0000217 return IsSuper ? MessageSendSuperFn : MessageSendFn;
218 }
219
Chris Lattner74391b42009-03-22 21:03:39 +0000220 llvm::Constant *getSendStretFn(bool IsSuper) {
Daniel Dunbar5669e572008-10-17 03:24:53 +0000221 return IsSuper ? MessageSendSuperStretFn : MessageSendStretFn;
222 }
223
Chris Lattner74391b42009-03-22 21:03:39 +0000224 llvm::Constant *getSendFpretFn(bool IsSuper) {
Daniel Dunbar5669e572008-10-17 03:24:53 +0000225 return IsSuper ? MessageSendSuperFpretFn : MessageSendFpretFn;
226 }
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000227};
228
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000229/// ObjCNonFragileABITypesHelper - will have all types needed by objective-c's
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000230/// modern abi
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000231class ObjCNonFragileABITypesHelper : public ObjCCommonTypesHelper {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000232public:
Chris Lattner74391b42009-03-22 21:03:39 +0000233 llvm::Constant *MessageSendFixupFn, *MessageSendFpretFixupFn,
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000234 *MessageSendStretFixupFn, *MessageSendIdFixupFn,
235 *MessageSendIdStretFixupFn, *MessageSendSuper2FixupFn,
236 *MessageSendSuper2StretFixupFn;
237
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000238 // MethodListnfABITy - LLVM for struct _method_list_t
239 const llvm::StructType *MethodListnfABITy;
240
241 // MethodListnfABIPtrTy - LLVM for struct _method_list_t*
242 const llvm::Type *MethodListnfABIPtrTy;
243
244 // ProtocolnfABITy = LLVM for struct _protocol_t
245 const llvm::StructType *ProtocolnfABITy;
246
Daniel Dunbar948e2582009-02-15 07:36:20 +0000247 // ProtocolnfABIPtrTy = LLVM for struct _protocol_t*
248 const llvm::Type *ProtocolnfABIPtrTy;
249
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000250 // ProtocolListnfABITy - LLVM for struct _objc_protocol_list
251 const llvm::StructType *ProtocolListnfABITy;
252
253 // ProtocolListnfABIPtrTy - LLVM for struct _objc_protocol_list*
254 const llvm::Type *ProtocolListnfABIPtrTy;
255
256 // ClassnfABITy - LLVM for struct _class_t
257 const llvm::StructType *ClassnfABITy;
258
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000259 // ClassnfABIPtrTy - LLVM for struct _class_t*
260 const llvm::Type *ClassnfABIPtrTy;
261
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000262 // IvarnfABITy - LLVM for struct _ivar_t
263 const llvm::StructType *IvarnfABITy;
264
265 // IvarListnfABITy - LLVM for struct _ivar_list_t
266 const llvm::StructType *IvarListnfABITy;
267
268 // IvarListnfABIPtrTy = LLVM for struct _ivar_list_t*
269 const llvm::Type *IvarListnfABIPtrTy;
270
271 // ClassRonfABITy - LLVM for struct _class_ro_t
272 const llvm::StructType *ClassRonfABITy;
273
274 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
275 const llvm::Type *ImpnfABITy;
276
277 // CategorynfABITy - LLVM for struct _category_t
278 const llvm::StructType *CategorynfABITy;
279
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000280 // New types for nonfragile abi messaging.
281
282 // MessageRefTy - LLVM for:
283 // struct _message_ref_t {
284 // IMP messenger;
285 // SEL name;
286 // };
287 const llvm::StructType *MessageRefTy;
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000288 // MessageRefCTy - clang type for struct _message_ref_t
289 QualType MessageRefCTy;
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000290
291 // MessageRefPtrTy - LLVM for struct _message_ref_t*
292 const llvm::Type *MessageRefPtrTy;
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000293 // MessageRefCPtrTy - clang type for struct _message_ref_t*
294 QualType MessageRefCPtrTy;
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000295
Fariborz Jahanianef163782009-02-05 01:13:09 +0000296 // MessengerTy - Type of the messenger (shown as IMP above)
297 const llvm::FunctionType *MessengerTy;
298
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000299 // SuperMessageRefTy - LLVM for:
300 // struct _super_message_ref_t {
301 // SUPER_IMP messenger;
302 // SEL name;
303 // };
304 const llvm::StructType *SuperMessageRefTy;
305
306 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
307 const llvm::Type *SuperMessageRefPtrTy;
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000308
309 /// EHPersonalityPtr - LLVM value for an i8* to the Objective-C
310 /// exception personality function.
Chris Lattnerb02e53b2009-04-06 16:53:45 +0000311 llvm::Value *getEHPersonalityPtr() {
312 llvm::Constant *Personality =
313 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
314 std::vector<const llvm::Type*>(),
315 true),
316 "__objc_personality_v0");
317 return llvm::ConstantExpr::getBitCast(Personality, Int8PtrTy);
318 }
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000319
Chris Lattner74391b42009-03-22 21:03:39 +0000320 llvm::Constant *UnwindResumeOrRethrowFn, *ObjCBeginCatchFn, *ObjCEndCatchFn;
Daniel Dunbare588b992009-03-01 04:46:24 +0000321
322 const llvm::StructType *EHTypeTy;
323 const llvm::Type *EHTypePtrTy;
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000324
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000325 ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm);
326 ~ObjCNonFragileABITypesHelper(){}
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000327};
328
329class CGObjCCommonMac : public CodeGen::CGObjCRuntime {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000330public:
331 // FIXME - accessibility
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000332 class GC_IVAR {
Fariborz Jahanian820e0202009-03-11 00:07:04 +0000333 public:
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000334 unsigned int ivar_bytepos;
335 unsigned int ivar_size;
336 GC_IVAR() : ivar_bytepos(0), ivar_size(0) {}
337 };
338
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000339 class SKIP_SCAN {
340 public:
341 unsigned int skip;
342 unsigned int scan;
343 SKIP_SCAN() : skip(0), scan(0) {}
344 };
345
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000346protected:
347 CodeGen::CodeGenModule &CGM;
348 // FIXME! May not be needing this after all.
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000349 unsigned ObjCABI;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000350
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000351 // gc ivar layout bitmap calculation helper caches.
352 llvm::SmallVector<GC_IVAR, 16> SkipIvars;
353 llvm::SmallVector<GC_IVAR, 16> IvarsInfo;
354 llvm::SmallVector<SKIP_SCAN, 32> SkipScanIvars;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000355
Daniel Dunbar242d4dc2008-08-25 06:02:07 +0000356 /// LazySymbols - Symbols to generate a lazy reference for. See
357 /// DefinedSymbols and FinishModule().
358 std::set<IdentifierInfo*> LazySymbols;
359
360 /// DefinedSymbols - External symbols which are defined by this
361 /// module. The symbols in this list and LazySymbols are used to add
362 /// special linker symbols which ensure that Objective-C modules are
363 /// linked properly.
364 std::set<IdentifierInfo*> DefinedSymbols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000365
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000366 /// ClassNames - uniqued class names.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000367 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000368
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000369 /// MethodVarNames - uniqued method variable names.
370 llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000371
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000372 /// MethodVarTypes - uniqued method type signatures. We have to use
373 /// a StringMap here because have no other unique reference.
374 llvm::StringMap<llvm::GlobalVariable*> MethodVarTypes;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000375
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000376 /// MethodDefinitions - map of methods which have been defined in
377 /// this translation unit.
378 llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> MethodDefinitions;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000379
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000380 /// PropertyNames - uniqued method variable names.
381 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000382
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000383 /// ClassReferences - uniqued class references.
384 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000385
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000386 /// SelectorReferences - uniqued selector references.
387 llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000388
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000389 /// Protocols - Protocols for which an objc_protocol structure has
390 /// been emitted. Forward declarations are handled by creating an
391 /// empty structure whose initializer is filled in when/if defined.
392 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> Protocols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000393
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000394 /// DefinedProtocols - Protocols which have actually been
395 /// defined. We should not need this, see FIXME in GenerateProtocol.
396 llvm::DenseSet<IdentifierInfo*> DefinedProtocols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000397
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000398 /// DefinedClasses - List of defined classes.
399 std::vector<llvm::GlobalValue*> DefinedClasses;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000400
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000401 /// DefinedCategories - List of defined categories.
402 std::vector<llvm::GlobalValue*> DefinedCategories;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000403
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000404 /// UsedGlobals - List of globals to pack into the llvm.used metadata
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000405 /// to prevent them from being clobbered.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000406 std::vector<llvm::GlobalVariable*> UsedGlobals;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000407
Fariborz Jahanian56210f72009-01-21 23:34:32 +0000408 /// GetNameForMethod - Return a name for the given method.
409 /// \param[out] NameOut - The return value.
410 void GetNameForMethod(const ObjCMethodDecl *OMD,
411 const ObjCContainerDecl *CD,
412 std::string &NameOut);
413
414 /// GetMethodVarName - Return a unique constant for the given
415 /// selector's name. The return value has type char *.
416 llvm::Constant *GetMethodVarName(Selector Sel);
417 llvm::Constant *GetMethodVarName(IdentifierInfo *Ident);
418 llvm::Constant *GetMethodVarName(const std::string &Name);
419
420 /// GetMethodVarType - Return a unique constant for the given
421 /// selector's name. The return value has type char *.
422
423 // FIXME: This is a horrible name.
424 llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D);
Devang Patel7794bb82009-03-04 18:21:39 +0000425 llvm::Constant *GetMethodVarType(FieldDecl *D);
Fariborz Jahanian56210f72009-01-21 23:34:32 +0000426
427 /// GetPropertyName - Return a unique constant for the given
428 /// name. The return value has type char *.
429 llvm::Constant *GetPropertyName(IdentifierInfo *Ident);
430
431 // FIXME: This can be dropped once string functions are unified.
432 llvm::Constant *GetPropertyTypeString(const ObjCPropertyDecl *PD,
433 const Decl *Container);
434
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000435 /// GetClassName - Return a unique constant for the given selector's
436 /// name. The return value has type char *.
437 llvm::Constant *GetClassName(IdentifierInfo *Ident);
438
Fariborz Jahanian21e6f172009-03-11 21:42:00 +0000439 /// GetInterfaceDeclStructLayout - Get layout for ivars of given
440 /// interface declaration.
441 const llvm::StructLayout *GetInterfaceDeclStructLayout(
442 const ObjCInterfaceDecl *ID) const;
443
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000444 /// BuildIvarLayout - Builds ivar layout bitmap for the class
445 /// implementation for the __strong or __weak case.
446 ///
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000447 llvm::Constant *BuildIvarLayout(const ObjCImplementationDecl *OI,
448 bool ForStrongLayout);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000449
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000450 void BuildAggrIvarLayout(const ObjCInterfaceDecl *OI,
451 const llvm::StructLayout *Layout,
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000452 const RecordDecl *RD,
Chris Lattnerf1690852009-03-31 08:48:01 +0000453 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000454 unsigned int BytePos, bool ForStrongLayout,
455 int &Index, int &SkIndex, bool &HasUnion);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000456
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +0000457 /// GetIvarLayoutName - Returns a unique constant for the given
458 /// ivar layout bitmap.
459 llvm::Constant *GetIvarLayoutName(IdentifierInfo *Ident,
460 const ObjCCommonTypesHelper &ObjCTypes);
461
Fariborz Jahanian46b86c62009-01-28 19:12:34 +0000462 const RecordDecl *GetFirstIvarInRecord(const ObjCInterfaceDecl *OID,
463 RecordDecl::field_iterator &FIV,
464 RecordDecl::field_iterator &PIV);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +0000465 /// EmitPropertyList - Emit the given property list. The return
466 /// value has type PropertyListPtrTy.
467 llvm::Constant *EmitPropertyList(const std::string &Name,
468 const Decl *Container,
469 const ObjCContainerDecl *OCD,
470 const ObjCCommonTypesHelper &ObjCTypes);
471
Fariborz Jahanianda320092009-01-29 19:24:30 +0000472 /// GetProtocolRef - Return a reference to the internal protocol
473 /// description, creating an empty one if it has not been
474 /// defined. The return value has type ProtocolPtrTy.
475 llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +0000476
477 /// GetIvarBaseOffset - returns ivars byte offset.
478 uint64_t GetIvarBaseOffset(const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +0000479 const FieldDecl *Field);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000480
Chris Lattnercd0ee142009-03-31 08:33:16 +0000481 /// GetFieldBaseOffset - return's field byte offset.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000482 uint64_t GetFieldBaseOffset(const ObjCInterfaceDecl *OI,
483 const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +0000484 const FieldDecl *Field);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000485
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000486 /// CreateMetadataVar - Create a global variable with internal
487 /// linkage for use by the Objective-C runtime.
488 ///
489 /// This is a convenience wrapper which not only creates the
490 /// variable, but also sets the section and alignment and adds the
491 /// global to the UsedGlobals list.
Daniel Dunbar35bd7632009-03-09 20:50:13 +0000492 ///
493 /// \param Name - The variable name.
494 /// \param Init - The variable initializer; this is also used to
495 /// define the type of the variable.
496 /// \param Section - The section the variable should go into, or 0.
497 /// \param Align - The alignment for the variable, or 0.
498 /// \param AddToUsed - Whether the variable should be added to
Daniel Dunbarc1583062009-04-14 17:42:51 +0000499 /// "llvm.used".
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000500 llvm::GlobalVariable *CreateMetadataVar(const std::string &Name,
501 llvm::Constant *Init,
502 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +0000503 unsigned Align,
504 bool AddToUsed);
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000505
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000506public:
507 CGObjCCommonMac(CodeGen::CodeGenModule &cgm) : CGM(cgm)
508 { }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000509
Steve Naroff33fdb732009-03-31 16:53:37 +0000510 virtual llvm::Constant *GenerateConstantString(const ObjCStringLiteral *SL);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000511
512 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
513 const ObjCContainerDecl *CD=0);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000514
515 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
516
517 /// GetOrEmitProtocol - Get the protocol object for the given
518 /// declaration, emitting it if necessary. The return value has type
519 /// ProtocolPtrTy.
520 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD)=0;
521
522 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
523 /// object for the given declaration, emitting it if needed. These
524 /// forward references will be filled in with empty bodies if no
525 /// definition is seen. The return value has type ProtocolPtrTy.
526 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD)=0;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000527};
528
529class CGObjCMac : public CGObjCCommonMac {
530private:
531 ObjCTypesHelper ObjCTypes;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000532 /// EmitImageInfo - Emit the image info marker used to encode some module
533 /// level information.
534 void EmitImageInfo();
535
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000536 /// EmitModuleInfo - Another marker encoding module level
537 /// information.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000538 void EmitModuleInfo();
539
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000540 /// EmitModuleSymols - Emit module symbols, the list of defined
541 /// classes and categories. The result has type SymtabPtrTy.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000542 llvm::Constant *EmitModuleSymbols();
543
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000544 /// FinishModule - Write out global data structures at the end of
545 /// processing a translation unit.
546 void FinishModule();
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000547
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000548 /// EmitClassExtension - Generate the class extension structure used
549 /// to store the weak ivar layout and properties. The return value
550 /// has type ClassExtensionPtrTy.
551 llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID);
552
553 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
554 /// for the given class.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000555 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000556 const ObjCInterfaceDecl *ID);
557
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000558 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000559 QualType ResultType,
560 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000561 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000562 QualType Arg0Ty,
563 bool IsSuper,
564 const CallArgList &CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000565
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000566 /// EmitIvarList - Emit the ivar list for the given
567 /// implementation. If ForClass is true the list of class ivars
568 /// (i.e. metaclass ivars) is emitted, otherwise the list of
569 /// interface ivars will be emitted. The return value has type
570 /// IvarListPtrTy.
571 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +0000572 bool ForClass);
573
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000574 /// EmitMetaClass - Emit a forward reference to the class structure
575 /// for the metaclass of the given interface. The return value has
576 /// type ClassPtrTy.
577 llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
578
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000579 /// EmitMetaClass - Emit a class structure for the metaclass of the
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000580 /// given implementation. The return value has type ClassPtrTy.
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000581 llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
582 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000583 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000584 const ConstantVector &Methods);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000585
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000586 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000587
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000588 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000589
590 /// EmitMethodList - Emit the method list for the given
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000591 /// implementation. The return value has type MethodListPtrTy.
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000592 llvm::Constant *EmitMethodList(const std::string &Name,
593 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000594 const ConstantVector &Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000595
596 /// EmitMethodDescList - Emit a method description list for a list of
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000597 /// method declarations.
598 /// - TypeName: The name for the type containing the methods.
599 /// - IsProtocol: True iff these methods are for a protocol.
600 /// - ClassMethds: True iff these are class methods.
601 /// - Required: When true, only "required" methods are
602 /// listed. Similarly, when false only "optional" methods are
603 /// listed. For classes this should always be true.
604 /// - begin, end: The method list to output.
605 ///
606 /// The return value has type MethodDescriptionListPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000607 llvm::Constant *EmitMethodDescList(const std::string &Name,
608 const char *Section,
609 const ConstantVector &Methods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000610
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000611 /// GetOrEmitProtocol - Get the protocol object for the given
612 /// declaration, emitting it if necessary. The return value has type
613 /// ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +0000614 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000615
616 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
617 /// object for the given declaration, emitting it if needed. These
618 /// forward references will be filled in with empty bodies if no
619 /// definition is seen. The return value has type ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +0000620 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000621
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000622 /// EmitProtocolExtension - Generate the protocol extension
623 /// structure used to store optional instance and class methods, and
624 /// protocol properties. The return value has type
625 /// ProtocolExtensionPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000626 llvm::Constant *
627 EmitProtocolExtension(const ObjCProtocolDecl *PD,
628 const ConstantVector &OptInstanceMethods,
629 const ConstantVector &OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000630
631 /// EmitProtocolList - Generate the list of referenced
632 /// protocols. The return value has type ProtocolListPtrTy.
Daniel Dunbardbc933702008-08-21 21:57:41 +0000633 llvm::Constant *EmitProtocolList(const std::string &Name,
634 ObjCProtocolDecl::protocol_iterator begin,
635 ObjCProtocolDecl::protocol_iterator end);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000636
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000637 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
638 /// for the given selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000639 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000640
Fariborz Jahanianda320092009-01-29 19:24:30 +0000641 public:
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000642 CGObjCMac(CodeGen::CodeGenModule &cgm);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000643
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000644 virtual llvm::Function *ModuleInitFunction();
645
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000646 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000647 QualType ResultType,
648 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000649 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000650 bool IsClassMessage,
651 const CallArgList &CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000652
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000653 virtual CodeGen::RValue
654 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000655 QualType ResultType,
656 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000657 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000658 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000659 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000660 bool IsClassMessage,
661 const CallArgList &CallArgs);
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000662
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000663 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000664 const ObjCInterfaceDecl *ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000665
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000666 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000667
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000668 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000669
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000670 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000671
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000672 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000673 const ObjCProtocolDecl *PD);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000674
Chris Lattner74391b42009-03-22 21:03:39 +0000675 virtual llvm::Constant *GetPropertyGetFunction();
676 virtual llvm::Constant *GetPropertySetFunction();
677 virtual llvm::Constant *EnumerationMutationFunction();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000678
Fariborz Jahanianbd71be42008-11-21 00:49:24 +0000679 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
680 const Stmt &S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000681 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
682 const ObjCAtThrowStmt &S);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000683 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +0000684 llvm::Value *AddrWeakObj);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000685 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
686 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000687 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
688 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian7eda8362008-11-20 19:23:36 +0000689 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
690 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000691 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
692 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian0bb20362009-02-02 20:02:29 +0000693
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000694 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
695 QualType ObjectTy,
696 llvm::Value *BaseValue,
697 const ObjCIvarDecl *Ivar,
698 const FieldDecl *Field,
699 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000700 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
701 ObjCInterfaceDecl *Interface,
702 const ObjCIvarDecl *Ivar);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000703};
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000704
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000705class CGObjCNonFragileABIMac : public CGObjCCommonMac {
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000706private:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000707 ObjCNonFragileABITypesHelper ObjCTypes;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000708 llvm::GlobalVariable* ObjCEmptyCacheVar;
709 llvm::GlobalVariable* ObjCEmptyVtableVar;
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000710
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000711 /// MetaClassReferences - uniqued meta class references.
712 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> MetaClassReferences;
Daniel Dunbare588b992009-03-01 04:46:24 +0000713
714 /// EHTypeReferences - uniqued class ehtype references.
715 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> EHTypeReferences;
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000716
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000717 /// FinishNonFragileABIModule - Write out global data structures at the end of
718 /// processing a translation unit.
719 void FinishNonFragileABIModule();
Daniel Dunbar8158a2f2009-04-08 04:21:03 +0000720
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000721 llvm::GlobalVariable * BuildClassRoTInitializer(unsigned flags,
722 unsigned InstanceStart,
723 unsigned InstanceSize,
724 const ObjCImplementationDecl *ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +0000725 llvm::GlobalVariable * BuildClassMetaData(std::string &ClassName,
726 llvm::Constant *IsAGV,
727 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +0000728 llvm::Constant *ClassRoGV,
729 bool HiddenVisibility);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000730
731 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
732
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +0000733 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
734
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000735 /// EmitMethodList - Emit the method list for the given
736 /// implementation. The return value has type MethodListnfABITy.
737 llvm::Constant *EmitMethodList(const std::string &Name,
738 const char *Section,
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +0000739 const ConstantVector &Methods);
740 /// EmitIvarList - Emit the ivar list for the given
741 /// implementation. If ForClass is true the list of class ivars
742 /// (i.e. metaclass ivars) is emitted, otherwise the list of
743 /// interface ivars will be emitted. The return value has type
744 /// IvarListnfABIPtrTy.
745 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000746
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000747 llvm::Constant *EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +0000748 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +0000749 unsigned long int offset);
750
Fariborz Jahanianda320092009-01-29 19:24:30 +0000751 /// GetOrEmitProtocol - Get the protocol object for the given
752 /// declaration, emitting it if necessary. The return value has type
753 /// ProtocolPtrTy.
754 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
755
756 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
757 /// object for the given declaration, emitting it if needed. These
758 /// forward references will be filled in with empty bodies if no
759 /// definition is seen. The return value has type ProtocolPtrTy.
760 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
761
762 /// EmitProtocolList - Generate the list of referenced
763 /// protocols. The return value has type ProtocolListPtrTy.
764 llvm::Constant *EmitProtocolList(const std::string &Name,
765 ObjCProtocolDecl::protocol_iterator begin,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000766 ObjCProtocolDecl::protocol_iterator end);
767
768 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
769 QualType ResultType,
770 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000771 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000772 QualType Arg0Ty,
773 bool IsSuper,
774 const CallArgList &CallArgs);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +0000775
776 /// GetClassGlobal - Return the global variable for the Objective-C
777 /// class of the given name.
Fariborz Jahanian0f902942009-04-14 18:41:56 +0000778 llvm::GlobalVariable *GetClassGlobal(const std::string &Name);
779
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000780 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
781 /// for the given class.
782 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000783 const ObjCInterfaceDecl *ID,
784 bool IsSuper = false);
785
786 /// EmitMetaClassRef - Return a Value * of the address of _class_t
787 /// meta-data
788 llvm::Value *EmitMetaClassRef(CGBuilderTy &Builder,
789 const ObjCInterfaceDecl *ID);
790
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000791 /// ObjCIvarOffsetVariable - Returns the ivar offset variable for
792 /// the given ivar.
793 ///
794 llvm::GlobalVariable * ObjCIvarOffsetVariable(std::string &Name,
Fariborz Jahanian01a0c362009-02-12 18:51:23 +0000795 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000796 const ObjCIvarDecl *Ivar);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000797
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +0000798 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
799 /// for the given selector.
800 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbare588b992009-03-01 04:46:24 +0000801
Daniel Dunbar8158a2f2009-04-08 04:21:03 +0000802 /// GetInterfaceEHType - Get the cached ehtype for the given Objective-C
Daniel Dunbare588b992009-03-01 04:46:24 +0000803 /// interface. The return value has type EHTypePtrTy.
Daniel Dunbar8158a2f2009-04-08 04:21:03 +0000804 llvm::Value *GetInterfaceEHType(const ObjCInterfaceDecl *ID,
805 bool ForDefinition);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +0000806
807 const char *getMetaclassSymbolPrefix() const {
808 return "OBJC_METACLASS_$_";
809 }
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000810
Daniel Dunbar6ab187a2009-04-07 05:48:37 +0000811 const char *getClassSymbolPrefix() const {
812 return "OBJC_CLASS_$_";
813 }
814
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000815public:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000816 CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000817 // FIXME. All stubs for now!
818 virtual llvm::Function *ModuleInitFunction();
819
820 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
821 QualType ResultType,
822 Selector Sel,
823 llvm::Value *Receiver,
824 bool IsClassMessage,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000825 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000826
827 virtual CodeGen::RValue
828 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
829 QualType ResultType,
830 Selector Sel,
831 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000832 bool isCategoryImpl,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000833 llvm::Value *Receiver,
834 bool IsClassMessage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000835 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000836
837 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000838 const ObjCInterfaceDecl *ID);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000839
840 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel)
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +0000841 { return EmitSelector(Builder, Sel); }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000842
Fariborz Jahanianeb062d92009-01-26 18:32:24 +0000843 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000844
845 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000846 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +0000847 const ObjCProtocolDecl *PD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000848
Chris Lattner74391b42009-03-22 21:03:39 +0000849 virtual llvm::Constant *GetPropertyGetFunction() {
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000850 return ObjCTypes.GetPropertyFn;
851 }
Chris Lattner74391b42009-03-22 21:03:39 +0000852 virtual llvm::Constant *GetPropertySetFunction() {
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000853 return ObjCTypes.SetPropertyFn;
854 }
Chris Lattner74391b42009-03-22 21:03:39 +0000855 virtual llvm::Constant *EnumerationMutationFunction() {
Daniel Dunbar28ed0842009-02-16 18:48:45 +0000856 return ObjCTypes.EnumerationMutationFn;
857 }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000858
859 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000860 const Stmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000861 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000862 const ObjCAtThrowStmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000863 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000864 llvm::Value *AddrWeakObj);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000865 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000866 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000867 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000868 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000869 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000870 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000871 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000872 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000873 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
874 QualType ObjectTy,
875 llvm::Value *BaseValue,
876 const ObjCIvarDecl *Ivar,
877 const FieldDecl *Field,
878 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000879 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
880 ObjCInterfaceDecl *Interface,
881 const ObjCIvarDecl *Ivar);
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000882};
883
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000884} // end anonymous namespace
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000885
886/* *** Helper Functions *** */
887
888/// getConstantGEP() - Help routine to construct simple GEPs.
889static llvm::Constant *getConstantGEP(llvm::Constant *C,
890 unsigned idx0,
891 unsigned idx1) {
892 llvm::Value *Idxs[] = {
893 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx0),
894 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx1)
895 };
896 return llvm::ConstantExpr::getGetElementPtr(C, Idxs, 2);
897}
898
Daniel Dunbar8158a2f2009-04-08 04:21:03 +0000899/// hasObjCExceptionAttribute - Return true if this class or any super
900/// class has the __objc_exception__ attribute.
901static bool hasObjCExceptionAttribute(const ObjCInterfaceDecl *OID) {
Daniel Dunbarb11fa0d2009-04-13 21:08:27 +0000902 if (OID->hasAttr<ObjCExceptionAttr>())
Daniel Dunbar8158a2f2009-04-08 04:21:03 +0000903 return true;
904 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
905 return hasObjCExceptionAttribute(Super);
906 return false;
907}
908
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000909/* *** CGObjCMac Public Interface *** */
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000910
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000911CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm),
912 ObjCTypes(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000913{
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000914 ObjCABI = 1;
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000915 EmitImageInfo();
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000916}
917
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000918/// GetClass - Return a reference to the class for the given interface
919/// decl.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000920llvm::Value *CGObjCMac::GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000921 const ObjCInterfaceDecl *ID) {
922 return EmitClassRef(Builder, ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000923}
924
925/// GetSelector - Return the pointer to the unique'd string for this selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000926llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000927 return EmitSelector(Builder, Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000928}
929
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000930/// Generate a constant CFString object.
931/*
932 struct __builtin_CFString {
933 const int *isa; // point to __CFConstantStringClassReference
934 int flags;
935 const char *str;
936 long length;
937 };
938*/
939
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000940llvm::Constant *CGObjCCommonMac::GenerateConstantString(
Steve Naroff33fdb732009-03-31 16:53:37 +0000941 const ObjCStringLiteral *SL) {
Steve Naroff8d4141f2009-04-01 13:55:36 +0000942 return CGM.GetAddrOfConstantCFString(SL->getString());
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000943}
944
945/// Generates a message send where the super is the receiver. This is
946/// a message send to self with special delivery semantics indicating
947/// which class's method should be called.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000948CodeGen::RValue
949CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000950 QualType ResultType,
951 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000952 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000953 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000954 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000955 bool IsClassMessage,
Daniel Dunbar46f45b92008-09-09 01:06:48 +0000956 const CodeGen::CallArgList &CallArgs) {
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000957 // Create and init a super structure; this is a (receiver, class)
958 // pair we will pass to objc_msgSendSuper.
959 llvm::Value *ObjCSuper =
960 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
961 llvm::Value *ReceiverAsObject =
962 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
963 CGF.Builder.CreateStore(ReceiverAsObject,
964 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000965
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000966 // If this is a class message the metaclass is passed as the target.
967 llvm::Value *Target;
968 if (IsClassMessage) {
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000969 if (isCategoryImpl) {
970 // Message sent to 'super' in a class method defined in a category
971 // implementation requires an odd treatment.
972 // If we are in a class method, we must retrieve the
973 // _metaclass_ for the current class, pointed at by
974 // the class's "isa" pointer. The following assumes that
975 // isa" is the first ivar in a class (which it must be).
976 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
977 Target = CGF.Builder.CreateStructGEP(Target, 0);
978 Target = CGF.Builder.CreateLoad(Target);
979 }
980 else {
981 llvm::Value *MetaClassPtr = EmitMetaClassRef(Class);
982 llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1);
983 llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr);
984 Target = Super;
985 }
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000986 } else {
987 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
988 }
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000989 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
990 // and ObjCTypes types.
991 const llvm::Type *ClassTy =
992 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000993 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000994 CGF.Builder.CreateStore(Target,
995 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
996
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000997 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000998 ObjCSuper, ObjCTypes.SuperPtrCTy,
999 true, CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001000}
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001001
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001002/// Generate code for a message send expression.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +00001003CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001004 QualType ResultType,
1005 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001006 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001007 bool IsClassMessage,
1008 const CallArgList &CallArgs) {
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001009 llvm::Value *Arg0 =
1010 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy, "tmp");
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001011 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001012 Arg0, CGF.getContext().getObjCIdType(),
1013 false, CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001014}
1015
1016CodeGen::RValue CGObjCMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001017 QualType ResultType,
1018 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001019 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001020 QualType Arg0Ty,
1021 bool IsSuper,
1022 const CallArgList &CallArgs) {
1023 CallArgList ActualArgs;
Daniel Dunbar46f45b92008-09-09 01:06:48 +00001024 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
1025 ActualArgs.push_back(std::make_pair(RValue::get(EmitSelector(CGF.Builder,
1026 Sel)),
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001027 CGF.getContext().getObjCSelType()));
1028 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001029
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001030 CodeGenTypes &Types = CGM.getTypes();
1031 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs);
1032 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo, false);
Daniel Dunbar5669e572008-10-17 03:24:53 +00001033
1034 llvm::Constant *Fn;
Daniel Dunbar88b53962009-02-02 22:03:45 +00001035 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Daniel Dunbar5669e572008-10-17 03:24:53 +00001036 Fn = ObjCTypes.getSendStretFn(IsSuper);
1037 } else if (ResultType->isFloatingType()) {
1038 // FIXME: Sadly, this is wrong. This actually depends on the
1039 // architecture. This happens to be right for x86-32 though.
1040 Fn = ObjCTypes.getSendFpretFn(IsSuper);
1041 } else {
1042 Fn = ObjCTypes.getSendFn(IsSuper);
1043 }
Daniel Dunbar62d5c1b2008-09-10 07:00:50 +00001044 Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy));
Daniel Dunbar88b53962009-02-02 22:03:45 +00001045 return CGF.EmitCall(FnInfo, Fn, ActualArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001046}
1047
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001048llvm::Value *CGObjCMac::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001049 const ObjCProtocolDecl *PD) {
Daniel Dunbarc67876d2008-09-04 04:33:15 +00001050 // FIXME: I don't understand why gcc generates this, or where it is
1051 // resolved. Investigate. Its also wasteful to look this up over and
1052 // over.
1053 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1054
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001055 return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
1056 ObjCTypes.ExternalProtocolPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001057}
1058
Fariborz Jahanianda320092009-01-29 19:24:30 +00001059void CGObjCCommonMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001060 // FIXME: We shouldn't need this, the protocol decl should contain
1061 // enough information to tell us whether this was a declaration or a
1062 // definition.
1063 DefinedProtocols.insert(PD->getIdentifier());
1064
1065 // If we have generated a forward reference to this protocol, emit
1066 // it now. Otherwise do nothing, the protocol objects are lazily
1067 // emitted.
1068 if (Protocols.count(PD->getIdentifier()))
1069 GetOrEmitProtocol(PD);
1070}
1071
Fariborz Jahanianda320092009-01-29 19:24:30 +00001072llvm::Constant *CGObjCCommonMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001073 if (DefinedProtocols.count(PD->getIdentifier()))
1074 return GetOrEmitProtocol(PD);
1075 return GetOrEmitProtocolRef(PD);
1076}
1077
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001078/*
1079 // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions
1080 struct _objc_protocol {
1081 struct _objc_protocol_extension *isa;
1082 char *protocol_name;
1083 struct _objc_protocol_list *protocol_list;
1084 struct _objc__method_prototype_list *instance_methods;
1085 struct _objc__method_prototype_list *class_methods
1086 };
1087
1088 See EmitProtocolExtension().
1089*/
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001090llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
1091 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1092
1093 // Early exit if a defining object has already been generated.
1094 if (Entry && Entry->hasInitializer())
1095 return Entry;
1096
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001097 // FIXME: I don't understand why gcc generates this, or where it is
1098 // resolved. Investigate. Its also wasteful to look this up over and
1099 // over.
1100 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1101
Chris Lattner8ec03f52008-11-24 03:54:41 +00001102 const char *ProtocolName = PD->getNameAsCString();
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001103
1104 // Construct method lists.
1105 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1106 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregor6ab35242009-04-09 21:40:53 +00001107 for (ObjCProtocolDecl::instmeth_iterator
1108 i = PD->instmeth_begin(CGM.getContext()),
1109 e = PD->instmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001110 ObjCMethodDecl *MD = *i;
1111 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1112 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1113 OptInstanceMethods.push_back(C);
1114 } else {
1115 InstanceMethods.push_back(C);
1116 }
1117 }
1118
Douglas Gregor6ab35242009-04-09 21:40:53 +00001119 for (ObjCProtocolDecl::classmeth_iterator
1120 i = PD->classmeth_begin(CGM.getContext()),
1121 e = PD->classmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001122 ObjCMethodDecl *MD = *i;
1123 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1124 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1125 OptClassMethods.push_back(C);
1126 } else {
1127 ClassMethods.push_back(C);
1128 }
1129 }
1130
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001131 std::vector<llvm::Constant*> Values(5);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001132 Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001133 Values[1] = GetClassName(PD->getIdentifier());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001134 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001135 EmitProtocolList("\01L_OBJC_PROTOCOL_REFS_" + PD->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001136 PD->protocol_begin(),
1137 PD->protocol_end());
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001138 Values[3] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001139 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_"
1140 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001141 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1142 InstanceMethods);
1143 Values[4] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001144 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_"
1145 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001146 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1147 ClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001148 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
1149 Values);
1150
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001151 if (Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001152 // Already created, fix the linkage and update the initializer.
1153 Entry->setLinkage(llvm::GlobalValue::InternalLinkage);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001154 Entry->setInitializer(Init);
1155 } else {
1156 Entry =
1157 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
1158 llvm::GlobalValue::InternalLinkage,
1159 Init,
1160 std::string("\01L_OBJC_PROTOCOL_")+ProtocolName,
1161 &CGM.getModule());
1162 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001163 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001164 UsedGlobals.push_back(Entry);
1165 // FIXME: Is this necessary? Why only for protocol?
1166 Entry->setAlignment(4);
1167 }
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001168
1169 return Entry;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001170}
1171
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001172llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001173 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1174
1175 if (!Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001176 // We use the initializer as a marker of whether this is a forward
1177 // reference or not. At module finalization we add the empty
1178 // contents for protocols which were referenced but never defined.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001179 Entry =
1180 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001181 llvm::GlobalValue::ExternalLinkage,
1182 0,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001183 "\01L_OBJC_PROTOCOL_" + PD->getNameAsString(),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001184 &CGM.getModule());
1185 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001186 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001187 UsedGlobals.push_back(Entry);
1188 // FIXME: Is this necessary? Why only for protocol?
1189 Entry->setAlignment(4);
1190 }
1191
1192 return Entry;
1193}
1194
1195/*
1196 struct _objc_protocol_extension {
1197 uint32_t size;
1198 struct objc_method_description_list *optional_instance_methods;
1199 struct objc_method_description_list *optional_class_methods;
1200 struct objc_property_list *instance_properties;
1201 };
1202*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001203llvm::Constant *
1204CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
1205 const ConstantVector &OptInstanceMethods,
1206 const ConstantVector &OptClassMethods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001207 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001208 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolExtensionTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001209 std::vector<llvm::Constant*> Values(4);
1210 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001211 Values[1] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001212 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_"
1213 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001214 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1215 OptInstanceMethods);
1216 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001217 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_"
1218 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001219 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1220 OptClassMethods);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001221 Values[3] = EmitPropertyList("\01L_OBJC_$_PROP_PROTO_LIST_" +
1222 PD->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001223 0, PD, ObjCTypes);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001224
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001225 // Return null if no extension bits are used.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001226 if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
1227 Values[3]->isNullValue())
1228 return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
1229
1230 llvm::Constant *Init =
1231 llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001232
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001233 // No special section, but goes in llvm.used
1234 return CreateMetadataVar("\01L_OBJC_PROTOCOLEXT_" + PD->getNameAsString(),
1235 Init,
1236 0, 0, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001237}
1238
1239/*
1240 struct objc_protocol_list {
1241 struct objc_protocol_list *next;
1242 long count;
1243 Protocol *list[];
1244 };
1245*/
Daniel Dunbardbc933702008-08-21 21:57:41 +00001246llvm::Constant *
1247CGObjCMac::EmitProtocolList(const std::string &Name,
1248 ObjCProtocolDecl::protocol_iterator begin,
1249 ObjCProtocolDecl::protocol_iterator end) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001250 std::vector<llvm::Constant*> ProtocolRefs;
1251
Daniel Dunbardbc933702008-08-21 21:57:41 +00001252 for (; begin != end; ++begin)
1253 ProtocolRefs.push_back(GetProtocolRef(*begin));
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001254
1255 // Just return null for empty protocol lists
1256 if (ProtocolRefs.empty())
1257 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1258
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001259 // This list is null terminated.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001260 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
1261
1262 std::vector<llvm::Constant*> Values(3);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001263 // This field is only used by the runtime.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001264 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1265 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
1266 Values[2] =
1267 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
1268 ProtocolRefs.size()),
1269 ProtocolRefs);
1270
1271 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1272 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001273 CreateMetadataVar(Name, Init, "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001274 4, false);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001275 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
1276}
1277
1278/*
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001279 struct _objc_property {
1280 const char * const name;
1281 const char * const attributes;
1282 };
1283
1284 struct _objc_property_list {
1285 uint32_t entsize; // sizeof (struct _objc_property)
1286 uint32_t prop_count;
1287 struct _objc_property[prop_count];
1288 };
1289*/
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001290llvm::Constant *CGObjCCommonMac::EmitPropertyList(const std::string &Name,
1291 const Decl *Container,
1292 const ObjCContainerDecl *OCD,
1293 const ObjCCommonTypesHelper &ObjCTypes) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001294 std::vector<llvm::Constant*> Properties, Prop(2);
Douglas Gregor6ab35242009-04-09 21:40:53 +00001295 for (ObjCContainerDecl::prop_iterator I = OCD->prop_begin(CGM.getContext()),
1296 E = OCD->prop_end(CGM.getContext()); I != E; ++I) {
Steve Naroff93983f82009-01-11 12:47:58 +00001297 const ObjCPropertyDecl *PD = *I;
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001298 Prop[0] = GetPropertyName(PD->getIdentifier());
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00001299 Prop[1] = GetPropertyTypeString(PD, Container);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001300 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
1301 Prop));
1302 }
1303
1304 // Return null for empty list.
1305 if (Properties.empty())
1306 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1307
1308 unsigned PropertySize =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001309 CGM.getTargetData().getTypePaddedSize(ObjCTypes.PropertyTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001310 std::vector<llvm::Constant*> Values(3);
1311 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
1312 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
1313 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
1314 Properties.size());
1315 Values[2] = llvm::ConstantArray::get(AT, Properties);
1316 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1317
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001318 llvm::GlobalVariable *GV =
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001319 CreateMetadataVar(Name, Init,
1320 (ObjCABI == 2) ? "__DATA, __objc_const" :
1321 "__OBJC,__property,regular,no_dead_strip",
1322 (ObjCABI == 2) ? 8 : 4,
1323 true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001324 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.PropertyListPtrTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001325}
1326
1327/*
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001328 struct objc_method_description_list {
1329 int count;
1330 struct objc_method_description list[];
1331 };
1332*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001333llvm::Constant *
1334CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
1335 std::vector<llvm::Constant*> Desc(2);
1336 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1337 ObjCTypes.SelectorPtrTy);
1338 Desc[1] = GetMethodVarType(MD);
1339 return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
1340 Desc);
1341}
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001342
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001343llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name,
1344 const char *Section,
1345 const ConstantVector &Methods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001346 // Return null for empty list.
1347 if (Methods.empty())
1348 return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
1349
1350 std::vector<llvm::Constant*> Values(2);
1351 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1352 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
1353 Methods.size());
1354 Values[1] = llvm::ConstantArray::get(AT, Methods);
1355 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1356
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001357 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001358 return llvm::ConstantExpr::getBitCast(GV,
1359 ObjCTypes.MethodDescriptionListPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001360}
1361
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001362/*
1363 struct _objc_category {
1364 char *category_name;
1365 char *class_name;
1366 struct _objc_method_list *instance_methods;
1367 struct _objc_method_list *class_methods;
1368 struct _objc_protocol_list *protocols;
1369 uint32_t size; // <rdar://4585769>
1370 struct _objc_property_list *instance_properties;
1371 };
1372 */
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001373void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001374 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.CategoryTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001375
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001376 // FIXME: This is poor design, the OCD should have a pointer to the
1377 // category decl. Additionally, note that Category can be null for
1378 // the @implementation w/o an @interface case. Sema should just
1379 // create one for us as it does for @implementation so everyone else
1380 // can live life under a clear blue sky.
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001381 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001382 const ObjCCategoryDecl *Category =
1383 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001384 std::string ExtName(Interface->getNameAsString() + "_" +
1385 OCD->getNameAsString());
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001386
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001387 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1388 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
1389 e = OCD->instmeth_end(); i != e; ++i) {
1390 // Instance methods should always be defined.
1391 InstanceMethods.push_back(GetMethodConstant(*i));
1392 }
1393 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
1394 e = OCD->classmeth_end(); i != e; ++i) {
1395 // Class methods should always be defined.
1396 ClassMethods.push_back(GetMethodConstant(*i));
1397 }
1398
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001399 std::vector<llvm::Constant*> Values(7);
1400 Values[0] = GetClassName(OCD->getIdentifier());
1401 Values[1] = GetClassName(Interface->getIdentifier());
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001402 Values[2] =
1403 EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") +
1404 ExtName,
1405 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001406 InstanceMethods);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001407 Values[3] =
1408 EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName,
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001409 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001410 ClassMethods);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001411 if (Category) {
1412 Values[4] =
1413 EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName,
1414 Category->protocol_begin(),
1415 Category->protocol_end());
1416 } else {
1417 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1418 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001419 Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001420
1421 // If there is no category @interface then there can be no properties.
1422 if (Category) {
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001423 Values[6] = EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001424 OCD, Category, ObjCTypes);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001425 } else {
1426 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1427 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001428
1429 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
1430 Values);
1431
1432 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001433 CreateMetadataVar(std::string("\01L_OBJC_CATEGORY_")+ExtName, Init,
1434 "__OBJC,__category,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001435 4, true);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001436 DefinedCategories.push_back(GV);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001437}
1438
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001439// FIXME: Get from somewhere?
1440enum ClassFlags {
1441 eClassFlags_Factory = 0x00001,
1442 eClassFlags_Meta = 0x00002,
1443 // <rdr://5142207>
1444 eClassFlags_HasCXXStructors = 0x02000,
1445 eClassFlags_Hidden = 0x20000,
1446 eClassFlags_ABI2_Hidden = 0x00010,
1447 eClassFlags_ABI2_HasCXXStructors = 0x00004 // <rdr://4923634>
1448};
1449
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001450/*
1451 struct _objc_class {
1452 Class isa;
1453 Class super_class;
1454 const char *name;
1455 long version;
1456 long info;
1457 long instance_size;
1458 struct _objc_ivar_list *ivars;
1459 struct _objc_method_list *methods;
1460 struct _objc_cache *cache;
1461 struct _objc_protocol_list *protocols;
1462 // Objective-C 1.0 extensions (<rdr://4585769>)
1463 const char *ivar_layout;
1464 struct _objc_class_ext *ext;
1465 };
1466
1467 See EmitClassExtension();
1468 */
1469void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001470 DefinedSymbols.insert(ID->getIdentifier());
1471
Chris Lattner8ec03f52008-11-24 03:54:41 +00001472 std::string ClassName = ID->getNameAsString();
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001473 // FIXME: Gross
1474 ObjCInterfaceDecl *Interface =
1475 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001476 llvm::Constant *Protocols =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001477 EmitProtocolList("\01L_OBJC_CLASS_PROTOCOLS_" + ID->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001478 Interface->protocol_begin(),
1479 Interface->protocol_end());
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001480 const llvm::Type *InterfaceTy =
Chris Lattner03d9f342009-04-01 06:23:52 +00001481 CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(Interface));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001482 unsigned Flags = eClassFlags_Factory;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001483 unsigned Size = CGM.getTargetData().getTypePaddedSize(InterfaceTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001484
1485 // FIXME: Set CXX-structors flag.
Daniel Dunbar04d40782009-04-14 06:00:08 +00001486 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001487 Flags |= eClassFlags_Hidden;
1488
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001489 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1490 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
1491 e = ID->instmeth_end(); i != e; ++i) {
1492 // Instance methods should always be defined.
1493 InstanceMethods.push_back(GetMethodConstant(*i));
1494 }
1495 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
1496 e = ID->classmeth_end(); i != e; ++i) {
1497 // Class methods should always be defined.
1498 ClassMethods.push_back(GetMethodConstant(*i));
1499 }
1500
1501 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
1502 e = ID->propimpl_end(); i != e; ++i) {
1503 ObjCPropertyImplDecl *PID = *i;
1504
1505 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1506 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1507
1508 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
1509 if (llvm::Constant *C = GetMethodConstant(MD))
1510 InstanceMethods.push_back(C);
1511 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
1512 if (llvm::Constant *C = GetMethodConstant(MD))
1513 InstanceMethods.push_back(C);
1514 }
1515 }
1516
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001517 std::vector<llvm::Constant*> Values(12);
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001518 Values[ 0] = EmitMetaClass(ID, Protocols, InterfaceTy, ClassMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001519 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001520 // Record a reference to the super class.
1521 LazySymbols.insert(Super->getIdentifier());
1522
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001523 Values[ 1] =
1524 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1525 ObjCTypes.ClassPtrTy);
1526 } else {
1527 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1528 }
1529 Values[ 2] = GetClassName(ID->getIdentifier());
1530 // Version is always 0.
1531 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1532 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1533 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001534 Values[ 6] = EmitIvarList(ID, false);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001535 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001536 EmitMethodList("\01L_OBJC_INSTANCE_METHODS_" + ID->getNameAsString(),
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001537 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001538 InstanceMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001539 // cache is always NULL.
1540 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1541 Values[ 9] = Protocols;
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001542 // FIXME: Set ivar_layout
Fariborz Jahanian667423a2009-03-25 22:36:49 +00001543 // Values[10] = BuildIvarLayout(ID, true);
1544 Values[10] = GetIvarLayoutName(0, ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001545 Values[11] = EmitClassExtension(ID);
1546 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1547 Values);
1548
1549 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001550 CreateMetadataVar(std::string("\01L_OBJC_CLASS_")+ClassName, Init,
1551 "__OBJC,__class,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001552 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001553 DefinedClasses.push_back(GV);
1554}
1555
1556llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
1557 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001558 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001559 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001560 unsigned Flags = eClassFlags_Meta;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001561 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001562
Daniel Dunbar04d40782009-04-14 06:00:08 +00001563 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001564 Flags |= eClassFlags_Hidden;
1565
1566 std::vector<llvm::Constant*> Values(12);
1567 // The isa for the metaclass is the root of the hierarchy.
1568 const ObjCInterfaceDecl *Root = ID->getClassInterface();
1569 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
1570 Root = Super;
1571 Values[ 0] =
1572 llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
1573 ObjCTypes.ClassPtrTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001574 // The super class for the metaclass is emitted as the name of the
1575 // super class. The runtime fixes this up to point to the
1576 // *metaclass* for the super class.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001577 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
1578 Values[ 1] =
1579 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1580 ObjCTypes.ClassPtrTy);
1581 } else {
1582 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1583 }
1584 Values[ 2] = GetClassName(ID->getIdentifier());
1585 // Version is always 0.
1586 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1587 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1588 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001589 Values[ 6] = EmitIvarList(ID, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001590 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001591 EmitMethodList("\01L_OBJC_CLASS_METHODS_" + ID->getNameAsString(),
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001592 "__OBJC,__cls_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001593 Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001594 // cache is always NULL.
1595 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1596 Values[ 9] = Protocols;
1597 // ivar_layout for metaclass is always NULL.
1598 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1599 // The class extension is always unused for metaclasses.
1600 Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1601 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1602 Values);
1603
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001604 std::string Name("\01L_OBJC_METACLASS_");
Chris Lattner8ec03f52008-11-24 03:54:41 +00001605 Name += ID->getNameAsCString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001606
1607 // Check for a forward reference.
1608 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
1609 if (GV) {
1610 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1611 "Forward metaclass reference has incorrect type.");
1612 GV->setLinkage(llvm::GlobalValue::InternalLinkage);
1613 GV->setInitializer(Init);
1614 } else {
1615 GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1616 llvm::GlobalValue::InternalLinkage,
1617 Init, Name,
1618 &CGM.getModule());
1619 }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001620 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001621 GV->setAlignment(4);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001622 UsedGlobals.push_back(GV);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001623
1624 return GV;
1625}
1626
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001627llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001628 std::string Name = "\01L_OBJC_METACLASS_" + ID->getNameAsString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001629
1630 // FIXME: Should we look these up somewhere other than the
1631 // module. Its a bit silly since we only generate these while
1632 // processing an implementation, so exactly one pointer would work
1633 // if know when we entered/exitted an implementation block.
1634
1635 // Check for an existing forward reference.
Fariborz Jahanianb0d27942009-01-07 20:11:22 +00001636 // Previously, metaclass with internal linkage may have been defined.
1637 // pass 'true' as 2nd argument so it is returned.
1638 if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true)) {
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001639 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1640 "Forward metaclass reference has incorrect type.");
1641 return GV;
1642 } else {
1643 // Generate as an external reference to keep a consistent
1644 // module. This will be patched up when we emit the metaclass.
1645 return new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1646 llvm::GlobalValue::ExternalLinkage,
1647 0,
1648 Name,
1649 &CGM.getModule());
1650 }
1651}
1652
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001653/*
1654 struct objc_class_ext {
1655 uint32_t size;
1656 const char *weak_ivar_layout;
1657 struct _objc_property_list *properties;
1658 };
1659*/
1660llvm::Constant *
1661CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
1662 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001663 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassExtensionTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001664
1665 std::vector<llvm::Constant*> Values(3);
1666 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001667 // FIXME: Output weak_ivar_layout string.
Fariborz Jahanian667423a2009-03-25 22:36:49 +00001668 // Values[1] = BuildIvarLayout(ID, false);
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00001669 Values[1] = GetIvarLayoutName(0, ObjCTypes);
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001670 Values[2] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001671 ID, ID->getClassInterface(), ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001672
1673 // Return null if no extension bits are used.
1674 if (Values[1]->isNullValue() && Values[2]->isNullValue())
1675 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1676
1677 llvm::Constant *Init =
1678 llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001679 return CreateMetadataVar("\01L_OBJC_CLASSEXT_" + ID->getNameAsString(),
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001680 Init, "__OBJC,__class_ext,regular,no_dead_strip",
1681 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001682}
1683
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001684/// countInheritedIvars - count number of ivars in class and its super class(s)
1685///
Douglas Gregor6ab35242009-04-09 21:40:53 +00001686static int countInheritedIvars(const ObjCInterfaceDecl *OI,
1687 ASTContext &Context) {
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001688 int count = 0;
1689 if (!OI)
1690 return 0;
1691 const ObjCInterfaceDecl *SuperClass = OI->getSuperClass();
1692 if (SuperClass)
Douglas Gregor6ab35242009-04-09 21:40:53 +00001693 count += countInheritedIvars(SuperClass, Context);
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001694 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1695 E = OI->ivar_end(); I != E; ++I)
1696 ++count;
Fariborz Jahanian18191882009-03-31 18:11:23 +00001697 // look into properties.
Douglas Gregor6ab35242009-04-09 21:40:53 +00001698 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(Context),
1699 E = OI->prop_end(Context); I != E; ++I) {
Fariborz Jahanian18191882009-03-31 18:11:23 +00001700 if ((*I)->getPropertyIvarDecl())
1701 ++count;
1702 }
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001703 return count;
1704}
1705
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001706/// getInterfaceDeclForIvar - Get the interface declaration node where
1707/// this ivar is declared in.
1708/// FIXME. Ideally, this info should be in the ivar node. But currently
1709/// it is not and prevailing wisdom is that ASTs should not have more
1710/// info than is absolutely needed, even though this info reflects the
1711/// source language.
1712///
1713static const ObjCInterfaceDecl *getInterfaceDeclForIvar(
1714 const ObjCInterfaceDecl *OI,
Douglas Gregor6ab35242009-04-09 21:40:53 +00001715 const ObjCIvarDecl *IVD,
1716 ASTContext &Context) {
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001717 if (!OI)
1718 return 0;
1719 assert(isa<ObjCInterfaceDecl>(OI) && "OI is not an interface");
1720 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1721 E = OI->ivar_end(); I != E; ++I)
1722 if ((*I)->getIdentifier() == IVD->getIdentifier())
1723 return OI;
Fariborz Jahanian5a4b4532009-03-31 17:00:52 +00001724 // look into properties.
Douglas Gregor6ab35242009-04-09 21:40:53 +00001725 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(Context),
1726 E = OI->prop_end(Context); I != E; ++I) {
Fariborz Jahanian5a4b4532009-03-31 17:00:52 +00001727 ObjCPropertyDecl *PDecl = (*I);
1728 if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl())
1729 if (IV->getIdentifier() == IVD->getIdentifier())
1730 return OI;
1731 }
Douglas Gregor6ab35242009-04-09 21:40:53 +00001732 return getInterfaceDeclForIvar(OI->getSuperClass(), IVD, Context);
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001733}
1734
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001735/*
1736 struct objc_ivar {
1737 char *ivar_name;
1738 char *ivar_type;
1739 int ivar_offset;
1740 };
1741
1742 struct objc_ivar_list {
1743 int ivar_count;
1744 struct objc_ivar list[count];
1745 };
1746 */
1747llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001748 bool ForClass) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001749 std::vector<llvm::Constant*> Ivars, Ivar(3);
1750
1751 // When emitting the root class GCC emits ivar entries for the
1752 // actual class structure. It is not clear if we need to follow this
1753 // behavior; for now lets try and get away with not doing it. If so,
1754 // the cleanest solution would be to make up an ObjCInterfaceDecl
1755 // for the class.
1756 if (ForClass)
1757 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001758
1759 ObjCInterfaceDecl *OID =
1760 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00001761 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001762
1763 RecordDecl::field_iterator ifield, pfield;
1764 const RecordDecl *RD = GetFirstIvarInRecord(OID, ifield, pfield);
Douglas Gregor6ab35242009-04-09 21:40:53 +00001765 for (RecordDecl::field_iterator e = RD->field_end(CGM.getContext());
1766 ifield != e; ++ifield) {
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001767 FieldDecl *Field = *ifield;
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00001768 uint64_t Offset = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001769 if (Field->getIdentifier())
1770 Ivar[0] = GetMethodVarName(Field->getIdentifier());
1771 else
1772 Ivar[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Devang Patel7794bb82009-03-04 18:21:39 +00001773 Ivar[1] = GetMethodVarType(Field);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001774 Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy, Offset);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001775 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001776 }
1777
1778 // Return null for empty list.
1779 if (Ivars.empty())
1780 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
1781
1782 std::vector<llvm::Constant*> Values(2);
1783 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
1784 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
1785 Ivars.size());
1786 Values[1] = llvm::ConstantArray::get(AT, Ivars);
1787 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1788
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001789 llvm::GlobalVariable *GV;
1790 if (ForClass)
1791 GV = CreateMetadataVar("\01L_OBJC_CLASS_VARIABLES_" + ID->getNameAsString(),
Daniel Dunbar58a29122009-03-09 22:18:41 +00001792 Init, "__OBJC,__class_vars,regular,no_dead_strip",
1793 4, true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001794 else
1795 GV = CreateMetadataVar("\01L_OBJC_INSTANCE_VARIABLES_"
1796 + ID->getNameAsString(),
1797 Init, "__OBJC,__instance_vars,regular,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001798 4, true);
1799 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.IvarListPtrTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001800}
1801
1802/*
1803 struct objc_method {
1804 SEL method_name;
1805 char *method_types;
1806 void *method;
1807 };
1808
1809 struct objc_method_list {
1810 struct objc_method_list *obsolete;
1811 int count;
1812 struct objc_method methods_list[count];
1813 };
1814*/
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001815
1816/// GetMethodConstant - Return a struct objc_method constant for the
1817/// given method if it has been defined. The result is null if the
1818/// method has not been defined. The return value has type MethodPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001819llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001820 // FIXME: Use DenseMap::lookup
1821 llvm::Function *Fn = MethodDefinitions[MD];
1822 if (!Fn)
1823 return 0;
1824
1825 std::vector<llvm::Constant*> Method(3);
1826 Method[0] =
1827 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1828 ObjCTypes.SelectorPtrTy);
1829 Method[1] = GetMethodVarType(MD);
1830 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
1831 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
1832}
1833
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001834llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name,
1835 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001836 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001837 // Return null for empty list.
1838 if (Methods.empty())
1839 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
1840
1841 std::vector<llvm::Constant*> Values(3);
1842 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1843 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1844 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
1845 Methods.size());
1846 Values[2] = llvm::ConstantArray::get(AT, Methods);
1847 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1848
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001849 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001850 return llvm::ConstantExpr::getBitCast(GV,
1851 ObjCTypes.MethodListPtrTy);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001852}
1853
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001854llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD,
Daniel Dunbarbb36d332009-02-02 21:43:58 +00001855 const ObjCContainerDecl *CD) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001856 std::string Name;
Fariborz Jahanian679a5022009-01-10 21:06:09 +00001857 GetNameForMethod(OMD, CD, Name);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001858
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001859 CodeGenTypes &Types = CGM.getTypes();
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001860 const llvm::FunctionType *MethodTy =
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001861 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001862 llvm::Function *Method =
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001863 llvm::Function::Create(MethodTy,
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001864 llvm::GlobalValue::InternalLinkage,
1865 Name,
1866 &CGM.getModule());
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001867 MethodDefinitions.insert(std::make_pair(OMD, Method));
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001868
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001869 return Method;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001870}
1871
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00001872uint64_t CGObjCCommonMac::GetIvarBaseOffset(const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +00001873 const FieldDecl *Field) {
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00001874 if (!Field->isBitField())
1875 return Layout->getElementOffset(
1876 CGM.getTypes().getLLVMFieldNo(Field));
1877 // FIXME. Must be a better way of getting a bitfield base offset.
1878 uint64_t offset = CGM.getTypes().getLLVMFieldNo(Field);
1879 const llvm::Type *Ty = CGM.getTypes().ConvertTypeForMemRecursive(Field->getType());
1880 uint64_t size = CGM.getTypes().getTargetData().getTypePaddedSizeInBits(Ty);
1881 offset = (offset*size)/8;
1882 return offset;
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00001883}
1884
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00001885/// GetFieldBaseOffset - return's field byt offset.
1886uint64_t CGObjCCommonMac::GetFieldBaseOffset(const ObjCInterfaceDecl *OI,
1887 const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +00001888 const FieldDecl *Field) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00001889 const ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
Chris Lattnercd0ee142009-03-31 08:33:16 +00001890 const FieldDecl *FD = OI->lookupFieldDeclForIvar(CGM.getContext(), Ivar);
1891 return GetIvarBaseOffset(Layout, FD);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00001892}
1893
Daniel Dunbarfd65d372009-03-09 20:09:19 +00001894llvm::GlobalVariable *
1895CGObjCCommonMac::CreateMetadataVar(const std::string &Name,
1896 llvm::Constant *Init,
1897 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +00001898 unsigned Align,
1899 bool AddToUsed) {
Daniel Dunbarfd65d372009-03-09 20:09:19 +00001900 const llvm::Type *Ty = Init->getType();
1901 llvm::GlobalVariable *GV =
1902 new llvm::GlobalVariable(Ty, false,
1903 llvm::GlobalValue::InternalLinkage,
1904 Init,
1905 Name,
1906 &CGM.getModule());
1907 if (Section)
1908 GV->setSection(Section);
Daniel Dunbar35bd7632009-03-09 20:50:13 +00001909 if (Align)
1910 GV->setAlignment(Align);
1911 if (AddToUsed)
Daniel Dunbarfd65d372009-03-09 20:09:19 +00001912 UsedGlobals.push_back(GV);
1913 return GV;
1914}
1915
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001916llvm::Function *CGObjCMac::ModuleInitFunction() {
Daniel Dunbarf77ac862008-08-11 21:35:06 +00001917 // Abuse this interface function as a place to finalize.
1918 FinishModule();
1919
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001920 return NULL;
1921}
1922
Chris Lattner74391b42009-03-22 21:03:39 +00001923llvm::Constant *CGObjCMac::GetPropertyGetFunction() {
Daniel Dunbar49f66022008-09-24 03:38:44 +00001924 return ObjCTypes.GetPropertyFn;
1925}
1926
Chris Lattner74391b42009-03-22 21:03:39 +00001927llvm::Constant *CGObjCMac::GetPropertySetFunction() {
Daniel Dunbar49f66022008-09-24 03:38:44 +00001928 return ObjCTypes.SetPropertyFn;
1929}
1930
Chris Lattner74391b42009-03-22 21:03:39 +00001931llvm::Constant *CGObjCMac::EnumerationMutationFunction() {
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001932 return ObjCTypes.EnumerationMutationFn;
1933}
1934
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001935/*
1936
1937Objective-C setjmp-longjmp (sjlj) Exception Handling
1938--
1939
1940The basic framework for a @try-catch-finally is as follows:
1941{
1942 objc_exception_data d;
1943 id _rethrow = null;
Anders Carlsson190d00e2009-02-07 21:26:04 +00001944 bool _call_try_exit = true;
1945
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001946 objc_exception_try_enter(&d);
1947 if (!setjmp(d.jmp_buf)) {
1948 ... try body ...
1949 } else {
1950 // exception path
1951 id _caught = objc_exception_extract(&d);
1952
1953 // enter new try scope for handlers
1954 if (!setjmp(d.jmp_buf)) {
1955 ... match exception and execute catch blocks ...
1956
1957 // fell off end, rethrow.
1958 _rethrow = _caught;
Daniel Dunbar898d5082008-09-30 01:06:03 +00001959 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001960 } else {
1961 // exception in catch block
1962 _rethrow = objc_exception_extract(&d);
Anders Carlsson190d00e2009-02-07 21:26:04 +00001963 _call_try_exit = false;
1964 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001965 }
1966 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00001967 ... jump-through-finally to finally_end ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001968
1969finally:
Anders Carlsson190d00e2009-02-07 21:26:04 +00001970 if (_call_try_exit)
1971 objc_exception_try_exit(&d);
1972
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001973 ... finally block ....
Daniel Dunbar898d5082008-09-30 01:06:03 +00001974 ... dispatch to finally destination ...
1975
1976finally_rethrow:
1977 objc_exception_throw(_rethrow);
1978
1979finally_end:
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001980}
1981
1982This framework differs slightly from the one gcc uses, in that gcc
Daniel Dunbar898d5082008-09-30 01:06:03 +00001983uses _rethrow to determine if objc_exception_try_exit should be called
1984and if the object should be rethrown. This breaks in the face of
1985throwing nil and introduces unnecessary branches.
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001986
1987We specialize this framework for a few particular circumstances:
1988
1989 - If there are no catch blocks, then we avoid emitting the second
1990 exception handling context.
1991
1992 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
1993 e)) we avoid emitting the code to rethrow an uncaught exception.
1994
1995 - FIXME: If there is no @finally block we can do a few more
1996 simplifications.
1997
1998Rethrows and Jumps-Through-Finally
1999--
2000
2001Support for implicit rethrows and jumping through the finally block is
2002handled by storing the current exception-handling context in
2003ObjCEHStack.
2004
Daniel Dunbar898d5082008-09-30 01:06:03 +00002005In order to implement proper @finally semantics, we support one basic
2006mechanism for jumping through the finally block to an arbitrary
2007destination. Constructs which generate exits from a @try or @catch
2008block use this mechanism to implement the proper semantics by chaining
2009jumps, as necessary.
2010
2011This mechanism works like the one used for indirect goto: we
2012arbitrarily assign an ID to each destination and store the ID for the
2013destination in a variable prior to entering the finally block. At the
2014end of the finally block we simply create a switch to the proper
2015destination.
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002016
2017Code gen for @synchronized(expr) stmt;
2018Effectively generating code for:
2019objc_sync_enter(expr);
2020@try stmt @finally { objc_sync_exit(expr); }
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002021*/
2022
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002023void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
2024 const Stmt &S) {
2025 bool isTry = isa<ObjCAtTryStmt>(S);
Daniel Dunbar898d5082008-09-30 01:06:03 +00002026 // Create various blocks we refer to for handling @finally.
Daniel Dunbar55e87422008-11-11 02:29:29 +00002027 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002028 llvm::BasicBlock *FinallyExit = CGF.createBasicBlock("finally.exit");
Daniel Dunbar55e87422008-11-11 02:29:29 +00002029 llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
2030 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
2031 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
Daniel Dunbar1c566672009-02-24 01:43:46 +00002032
2033 // For @synchronized, call objc_sync_enter(sync.expr). The
2034 // evaluation of the expression must occur before we enter the
2035 // @synchronized. We can safely avoid a temp here because jumps into
2036 // @synchronized are illegal & this will dominate uses.
2037 llvm::Value *SyncArg = 0;
2038 if (!isTry) {
2039 SyncArg =
2040 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
2041 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00002042 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar1c566672009-02-24 01:43:46 +00002043 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00002044
2045 // Push an EH context entry, used for handling rethrows and jumps
2046 // through finally.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002047 CGF.PushCleanupBlock(FinallyBlock);
2048
Anders Carlsson273558f2009-02-07 21:37:21 +00002049 CGF.ObjCEHValueStack.push_back(0);
2050
Daniel Dunbar898d5082008-09-30 01:06:03 +00002051 // Allocate memory for the exception data and rethrow pointer.
Anders Carlsson80f25672008-09-09 17:59:25 +00002052 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
2053 "exceptiondata.ptr");
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002054 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
2055 "_rethrow");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002056 llvm::Value *CallTryExitPtr = CGF.CreateTempAlloca(llvm::Type::Int1Ty,
2057 "_call_try_exit");
2058 CGF.Builder.CreateStore(llvm::ConstantInt::getTrue(), CallTryExitPtr);
2059
Anders Carlsson80f25672008-09-09 17:59:25 +00002060 // Enter a new try block and call setjmp.
2061 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
2062 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
2063 "jmpbufarray");
2064 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
2065 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
2066 JmpBufPtr, "result");
Daniel Dunbar898d5082008-09-30 01:06:03 +00002067
Daniel Dunbar55e87422008-11-11 02:29:29 +00002068 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
2069 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002070 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002071 TryHandler, TryBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002072
2073 // Emit the @try block.
2074 CGF.EmitBlock(TryBlock);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002075 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
2076 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002077 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002078
2079 // Emit the "exception in @try" block.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002080 CGF.EmitBlock(TryHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002081
2082 // Retrieve the exception object. We may emit multiple blocks but
2083 // nothing can cross this so the value is already in SSA form.
2084 llvm::Value *Caught = CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
2085 ExceptionData,
2086 "caught");
Anders Carlsson273558f2009-02-07 21:37:21 +00002087 CGF.ObjCEHValueStack.back() = Caught;
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002088 if (!isTry)
2089 {
2090 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002091 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002092 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002093 }
2094 else if (const ObjCAtCatchStmt* CatchStmt =
2095 cast<ObjCAtTryStmt>(S).getCatchStmts())
2096 {
Daniel Dunbar55e40722008-09-27 07:03:52 +00002097 // Enter a new exception try block (in case a @catch block throws
2098 // an exception).
Anders Carlsson80f25672008-09-09 17:59:25 +00002099 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002100
Anders Carlsson80f25672008-09-09 17:59:25 +00002101 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
2102 JmpBufPtr, "result");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002103 llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw");
Anders Carlsson80f25672008-09-09 17:59:25 +00002104
Daniel Dunbar55e87422008-11-11 02:29:29 +00002105 llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch");
2106 llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler");
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002107 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002108
2109 CGF.EmitBlock(CatchBlock);
2110
Daniel Dunbar55e40722008-09-27 07:03:52 +00002111 // Handle catch list. As a special case we check if everything is
2112 // matched and avoid generating code for falling off the end if
2113 // so.
2114 bool AllMatched = false;
Anders Carlsson80f25672008-09-09 17:59:25 +00002115 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbar55e87422008-11-11 02:29:29 +00002116 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch");
Anders Carlsson80f25672008-09-09 17:59:25 +00002117
Steve Naroff7ba138a2009-03-03 19:52:17 +00002118 const ParmVarDecl *CatchParam = CatchStmt->getCatchParamDecl();
Daniel Dunbar129271a2008-09-27 07:36:24 +00002119 const PointerType *PT = 0;
2120
Anders Carlsson80f25672008-09-09 17:59:25 +00002121 // catch(...) always matches.
Daniel Dunbar55e40722008-09-27 07:03:52 +00002122 if (!CatchParam) {
2123 AllMatched = true;
2124 } else {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002125 PT = CatchParam->getType()->getAsPointerType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002126
Daniel Dunbar97f61d12008-09-27 22:21:14 +00002127 // catch(id e) always matches.
2128 // FIXME: For the time being we also match id<X>; this should
2129 // be rejected by Sema instead.
Steve Naroff389bf462009-02-12 17:52:19 +00002130 if ((PT && CGF.getContext().isObjCIdStructType(PT->getPointeeType())) ||
Steve Naroff7ba138a2009-03-03 19:52:17 +00002131 CatchParam->getType()->isObjCQualifiedIdType())
Daniel Dunbar55e40722008-09-27 07:03:52 +00002132 AllMatched = true;
Anders Carlsson80f25672008-09-09 17:59:25 +00002133 }
2134
Daniel Dunbar55e40722008-09-27 07:03:52 +00002135 if (AllMatched) {
Anders Carlssondde0a942008-09-11 09:15:33 +00002136 if (CatchParam) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002137 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002138 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002139 CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002140 }
Anders Carlsson1452f552008-09-11 08:21:54 +00002141
Anders Carlssondde0a942008-09-11 09:15:33 +00002142 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002143 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002144 break;
2145 }
2146
Daniel Dunbar129271a2008-09-27 07:36:24 +00002147 assert(PT && "Unexpected non-pointer type in @catch");
2148 QualType T = PT->getPointeeType();
Anders Carlsson4b7ff6e2008-09-11 06:35:14 +00002149 const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002150 assert(ObjCType && "Catch parameter must have Objective-C type!");
2151
2152 // Check if the @catch block matches the exception object.
2153 llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl());
2154
Anders Carlsson80f25672008-09-09 17:59:25 +00002155 llvm::Value *Match = CGF.Builder.CreateCall2(ObjCTypes.ExceptionMatchFn,
2156 Class, Caught, "match");
Anders Carlsson80f25672008-09-09 17:59:25 +00002157
Daniel Dunbar55e87422008-11-11 02:29:29 +00002158 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched");
Anders Carlsson80f25672008-09-09 17:59:25 +00002159
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002160 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002161 MatchedBlock, NextCatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002162
2163 // Emit the @catch block.
2164 CGF.EmitBlock(MatchedBlock);
Steve Naroff7ba138a2009-03-03 19:52:17 +00002165 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002166 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002167
2168 llvm::Value *Tmp =
Steve Naroff7ba138a2009-03-03 19:52:17 +00002169 CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(CatchParam->getType()),
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002170 "tmp");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002171 CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002172
2173 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002174 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002175
2176 CGF.EmitBlock(NextCatchBlock);
2177 }
2178
Daniel Dunbar55e40722008-09-27 07:03:52 +00002179 if (!AllMatched) {
2180 // None of the handlers caught the exception, so store it to be
2181 // rethrown at the end of the @finally block.
2182 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002183 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002184 }
2185
2186 // Emit the exception handler for the @catch blocks.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002187 CGF.EmitBlock(CatchHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002188 CGF.Builder.CreateStore(CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
2189 ExceptionData),
2190 RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002191 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002192 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002193 } else {
Anders Carlsson80f25672008-09-09 17:59:25 +00002194 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002195 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002196 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Anders Carlsson80f25672008-09-09 17:59:25 +00002197 }
2198
Daniel Dunbar898d5082008-09-30 01:06:03 +00002199 // Pop the exception-handling stack entry. It is important to do
2200 // this now, because the code in the @finally block is not in this
2201 // context.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002202 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
2203
Anders Carlsson273558f2009-02-07 21:37:21 +00002204 CGF.ObjCEHValueStack.pop_back();
2205
Anders Carlsson80f25672008-09-09 17:59:25 +00002206 // Emit the @finally block.
2207 CGF.EmitBlock(FinallyBlock);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002208 llvm::Value* CallTryExit = CGF.Builder.CreateLoad(CallTryExitPtr, "tmp");
2209
2210 CGF.Builder.CreateCondBr(CallTryExit, FinallyExit, FinallyNoExit);
2211
2212 CGF.EmitBlock(FinallyExit);
Anders Carlsson80f25672008-09-09 17:59:25 +00002213 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryExitFn, ExceptionData);
Daniel Dunbar129271a2008-09-27 07:36:24 +00002214
2215 CGF.EmitBlock(FinallyNoExit);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002216 if (isTry) {
2217 if (const ObjCAtFinallyStmt* FinallyStmt =
2218 cast<ObjCAtTryStmt>(S).getFinallyStmt())
2219 CGF.EmitStmt(FinallyStmt->getFinallyBody());
Daniel Dunbar1c566672009-02-24 01:43:46 +00002220 } else {
2221 // Emit objc_sync_exit(expr); as finally's sole statement for
2222 // @synchronized.
2223 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, SyncArg);
Fariborz Jahanianf2878e52008-11-21 19:21:53 +00002224 }
Anders Carlsson80f25672008-09-09 17:59:25 +00002225
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002226 // Emit the switch block
2227 if (Info.SwitchBlock)
2228 CGF.EmitBlock(Info.SwitchBlock);
2229 if (Info.EndBlock)
2230 CGF.EmitBlock(Info.EndBlock);
2231
Daniel Dunbar898d5082008-09-30 01:06:03 +00002232 CGF.EmitBlock(FinallyRethrow);
2233 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn,
2234 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002235 CGF.Builder.CreateUnreachable();
Daniel Dunbar898d5082008-09-30 01:06:03 +00002236
2237 CGF.EmitBlock(FinallyEnd);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002238}
2239
2240void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar898d5082008-09-30 01:06:03 +00002241 const ObjCAtThrowStmt &S) {
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002242 llvm::Value *ExceptionAsObject;
2243
2244 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2245 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
2246 ExceptionAsObject =
2247 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
2248 } else {
Anders Carlsson273558f2009-02-07 21:37:21 +00002249 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002250 "Unexpected rethrow outside @catch block.");
Anders Carlsson273558f2009-02-07 21:37:21 +00002251 ExceptionAsObject = CGF.ObjCEHValueStack.back();
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002252 }
2253
2254 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
Anders Carlsson80f25672008-09-09 17:59:25 +00002255 CGF.Builder.CreateUnreachable();
Daniel Dunbara448fb22008-11-11 23:11:34 +00002256
2257 // Clear the insertion point to indicate we are in unreachable code.
2258 CGF.Builder.ClearInsertionPoint();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002259}
2260
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002261/// EmitObjCWeakRead - Code gen for loading value of a __weak
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002262/// object: objc_read_weak (id *src)
2263///
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002264llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002265 llvm::Value *AddrWeakObj)
2266{
Eli Friedman8339b352009-03-07 03:57:15 +00002267 const llvm::Type* DestTy =
2268 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002269 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002270 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002271 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00002272 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002273 return read_weak;
2274}
2275
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002276/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
2277/// objc_assign_weak (id src, id *dst)
2278///
2279void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
2280 llvm::Value *src, llvm::Value *dst)
2281{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002282 const llvm::Type * SrcTy = src->getType();
2283 if (!isa<llvm::PointerType>(SrcTy)) {
2284 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2285 assert(Size <= 8 && "does not support size > 8");
2286 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2287 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002288 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2289 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002290 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2291 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattner96508e12009-04-17 22:12:36 +00002292 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002293 src, dst, "weakassign");
2294 return;
2295}
2296
Fariborz Jahanian58626502008-11-19 00:59:10 +00002297/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
2298/// objc_assign_global (id src, id *dst)
2299///
2300void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
2301 llvm::Value *src, llvm::Value *dst)
2302{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002303 const llvm::Type * SrcTy = src->getType();
2304 if (!isa<llvm::PointerType>(SrcTy)) {
2305 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2306 assert(Size <= 8 && "does not support size > 8");
2307 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2308 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002309 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2310 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002311 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2312 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian58626502008-11-19 00:59:10 +00002313 CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn,
2314 src, dst, "globalassign");
2315 return;
2316}
2317
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002318/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
2319/// objc_assign_ivar (id src, id *dst)
2320///
2321void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
2322 llvm::Value *src, llvm::Value *dst)
2323{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002324 const llvm::Type * SrcTy = src->getType();
2325 if (!isa<llvm::PointerType>(SrcTy)) {
2326 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2327 assert(Size <= 8 && "does not support size > 8");
2328 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2329 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002330 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2331 }
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002332 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2333 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
2334 CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn,
2335 src, dst, "assignivar");
2336 return;
2337}
2338
Fariborz Jahanian58626502008-11-19 00:59:10 +00002339/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
2340/// objc_assign_strongCast (id src, id *dst)
2341///
2342void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
2343 llvm::Value *src, llvm::Value *dst)
2344{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002345 const llvm::Type * SrcTy = src->getType();
2346 if (!isa<llvm::PointerType>(SrcTy)) {
2347 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2348 assert(Size <= 8 && "does not support size > 8");
2349 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2350 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002351 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2352 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002353 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2354 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian58626502008-11-19 00:59:10 +00002355 CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn,
2356 src, dst, "weakassign");
2357 return;
2358}
2359
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002360/// EmitObjCValueForIvar - Code Gen for ivar reference.
2361///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002362LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
2363 QualType ObjectTy,
2364 llvm::Value *BaseValue,
2365 const ObjCIvarDecl *Ivar,
2366 const FieldDecl *Field,
2367 unsigned CVRQualifiers) {
2368 if (Ivar->isBitField())
2369 return CGF.EmitLValueForBitfield(BaseValue, const_cast<FieldDecl *>(Field),
2370 CVRQualifiers);
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002371 // TODO: Add a special case for isa (index 0)
2372 unsigned Index = CGM.getTypes().getLLVMFieldNo(Field);
2373 llvm::Value *V = CGF.Builder.CreateStructGEP(BaseValue, Index, "tmp");
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002374 LValue LV = LValue::MakeAddr(V,
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00002375 Ivar->getType().getCVRQualifiers()|CVRQualifiers,
2376 CGM.getContext().getObjCGCAttrKind(Ivar->getType()));
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002377 LValue::SetObjCIvar(LV, true);
2378 return LV;
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002379}
2380
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002381llvm::Value *CGObjCMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
2382 ObjCInterfaceDecl *Interface,
2383 const ObjCIvarDecl *Ivar) {
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002384 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(Interface);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002385 FieldDecl *Field = Interface->lookupFieldDeclForIvar(CGM.getContext(), Ivar);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00002386 uint64_t Offset = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002387 return llvm::ConstantInt::get(
2388 CGM.getTypes().ConvertType(CGM.getContext().LongTy),
2389 Offset);
2390}
2391
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002392/* *** Private Interface *** */
2393
2394/// EmitImageInfo - Emit the image info marker used to encode some module
2395/// level information.
2396///
2397/// See: <rdr://4810609&4810587&4810587>
2398/// struct IMAGE_INFO {
2399/// unsigned version;
2400/// unsigned flags;
2401/// };
2402enum ImageInfoFlags {
2403 eImageInfo_FixAndContinue = (1 << 0), // FIXME: Not sure what this implies
2404 eImageInfo_GarbageCollected = (1 << 1),
2405 eImageInfo_GCOnly = (1 << 2)
2406};
2407
2408void CGObjCMac::EmitImageInfo() {
2409 unsigned version = 0; // Version is unused?
2410 unsigned flags = 0;
2411
2412 // FIXME: Fix and continue?
2413 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
2414 flags |= eImageInfo_GarbageCollected;
2415 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
2416 flags |= eImageInfo_GCOnly;
2417
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002418 // Emitted as int[2];
2419 llvm::Constant *values[2] = {
2420 llvm::ConstantInt::get(llvm::Type::Int32Ty, version),
2421 llvm::ConstantInt::get(llvm::Type::Int32Ty, flags)
2422 };
2423 llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002424
2425 const char *Section;
2426 if (ObjCABI == 1)
2427 Section = "__OBJC, __image_info,regular";
2428 else
2429 Section = "__DATA, __objc_imageinfo, regular, no_dead_strip";
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002430 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002431 CreateMetadataVar("\01L_OBJC_IMAGE_INFO",
2432 llvm::ConstantArray::get(AT, values, 2),
2433 Section,
2434 0,
2435 true);
2436 GV->setConstant(true);
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002437}
2438
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002439
2440// struct objc_module {
2441// unsigned long version;
2442// unsigned long size;
2443// const char *name;
2444// Symtab symtab;
2445// };
2446
2447// FIXME: Get from somewhere
2448static const int ModuleVersion = 7;
2449
2450void CGObjCMac::EmitModuleInfo() {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00002451 uint64_t Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ModuleTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002452
2453 std::vector<llvm::Constant*> Values(4);
2454 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
2455 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002456 // This used to be the filename, now it is unused. <rdr://4327263>
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002457 Values[2] = GetClassName(&CGM.getContext().Idents.get(""));
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002458 Values[3] = EmitModuleSymbols();
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002459 CreateMetadataVar("\01L_OBJC_MODULES",
2460 llvm::ConstantStruct::get(ObjCTypes.ModuleTy, Values),
2461 "__OBJC,__module_info,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00002462 4, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002463}
2464
2465llvm::Constant *CGObjCMac::EmitModuleSymbols() {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002466 unsigned NumClasses = DefinedClasses.size();
2467 unsigned NumCategories = DefinedCategories.size();
2468
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002469 // Return null if no symbols were defined.
2470 if (!NumClasses && !NumCategories)
2471 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
2472
2473 std::vector<llvm::Constant*> Values(5);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002474 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2475 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
2476 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
2477 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
2478
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002479 // The runtime expects exactly the list of defined classes followed
2480 // by the list of defined categories, in a single array.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002481 std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002482 for (unsigned i=0; i<NumClasses; i++)
2483 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
2484 ObjCTypes.Int8PtrTy);
2485 for (unsigned i=0; i<NumCategories; i++)
2486 Symbols[NumClasses + i] =
2487 llvm::ConstantExpr::getBitCast(DefinedCategories[i],
2488 ObjCTypes.Int8PtrTy);
2489
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002490 Values[4] =
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002491 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002492 NumClasses + NumCategories),
2493 Symbols);
2494
2495 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2496
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002497 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002498 CreateMetadataVar("\01L_OBJC_SYMBOLS", Init,
2499 "__OBJC,__symbols,regular,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002500 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002501 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
2502}
2503
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002504llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002505 const ObjCInterfaceDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002506 LazySymbols.insert(ID->getIdentifier());
2507
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002508 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
2509
2510 if (!Entry) {
2511 llvm::Constant *Casted =
2512 llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()),
2513 ObjCTypes.ClassPtrTy);
2514 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002515 CreateMetadataVar("\01L_OBJC_CLASS_REFERENCES_", Casted,
2516 "__OBJC,__cls_refs,literal_pointers,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002517 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002518 }
2519
2520 return Builder.CreateLoad(Entry, false, "tmp");
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002521}
2522
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002523llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002524 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
2525
2526 if (!Entry) {
2527 llvm::Constant *Casted =
2528 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
2529 ObjCTypes.SelectorPtrTy);
2530 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002531 CreateMetadataVar("\01L_OBJC_SELECTOR_REFERENCES_", Casted,
2532 "__OBJC,__message_refs,literal_pointers,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002533 4, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002534 }
2535
2536 return Builder.CreateLoad(Entry, false, "tmp");
2537}
2538
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00002539llvm::Constant *CGObjCCommonMac::GetClassName(IdentifierInfo *Ident) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002540 llvm::GlobalVariable *&Entry = ClassNames[Ident];
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002541
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002542 if (!Entry)
2543 Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
2544 llvm::ConstantArray::get(Ident->getName()),
2545 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00002546 1, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002547
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002548 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002549}
2550
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002551/// GetInterfaceDeclStructLayout - Get layout for ivars of given
2552/// interface declaration.
2553const llvm::StructLayout *CGObjCCommonMac::GetInterfaceDeclStructLayout(
2554 const ObjCInterfaceDecl *OID) const {
2555 const llvm::Type *InterfaceTy =
2556 CGM.getTypes().ConvertType(
2557 CGM.getContext().getObjCInterfaceType(
2558 const_cast<ObjCInterfaceDecl*>(OID)));
2559 const llvm::StructLayout *Layout =
2560 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceTy));
2561 return Layout;
2562}
2563
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00002564/// GetIvarLayoutName - Returns a unique constant for the given
2565/// ivar layout bitmap.
2566llvm::Constant *CGObjCCommonMac::GetIvarLayoutName(IdentifierInfo *Ident,
2567 const ObjCCommonTypesHelper &ObjCTypes) {
2568 return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2569}
2570
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002571void CGObjCCommonMac::BuildAggrIvarLayout(const ObjCInterfaceDecl *OI,
2572 const llvm::StructLayout *Layout,
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002573 const RecordDecl *RD,
Chris Lattnerf1690852009-03-31 08:48:01 +00002574 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002575 unsigned int BytePos, bool ForStrongLayout,
2576 int &Index, int &SkIndex, bool &HasUnion) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002577 bool IsUnion = (RD && RD->isUnion());
2578 uint64_t MaxUnionIvarSize = 0;
2579 uint64_t MaxSkippedUnionIvarSize = 0;
2580 FieldDecl *MaxField = 0;
2581 FieldDecl *MaxSkippedField = 0;
Chris Lattnerf1690852009-03-31 08:48:01 +00002582 unsigned base = 0;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002583 if (RecFields.empty())
2584 return;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002585 if (IsUnion)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002586 base = BytePos + GetFieldBaseOffset(OI, Layout, RecFields[0]);
Chris Lattnerf1690852009-03-31 08:48:01 +00002587 unsigned WordSizeInBits = CGM.getContext().Target.getPointerWidth(0);
2588 unsigned ByteSizeInBits = CGM.getContext().Target.getCharWidth();
2589
2590 llvm::SmallVector<FieldDecl*, 16> TmpRecFields;
2591
2592 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002593 FieldDecl *Field = RecFields[i];
2594 // Skip over unnamed or bitfields
2595 if (!Field->getIdentifier() || Field->isBitField())
2596 continue;
2597 QualType FQT = Field->getType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002598 if (FQT->isRecordType() || FQT->isUnionType()) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002599 if (FQT->isUnionType())
2600 HasUnion = true;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002601 else
2602 assert(FQT->isRecordType() &&
2603 "only union/record is supported for ivar layout bitmap");
2604
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002605 const RecordType *RT = FQT->getAsRecordType();
2606 const RecordDecl *RD = RT->getDecl();
2607 // FIXME - Find a more efficiant way of passing records down.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002608 TmpRecFields.append(RD->field_begin(CGM.getContext()),
2609 RD->field_end(CGM.getContext()));
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002610 // FIXME - Is Layout correct?
Chris Lattnerf1690852009-03-31 08:48:01 +00002611 BuildAggrIvarLayout(OI, Layout, RD, TmpRecFields,
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002612 BytePos + GetFieldBaseOffset(OI, Layout, Field),
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002613 ForStrongLayout, Index, SkIndex,
2614 HasUnion);
Chris Lattnerf1690852009-03-31 08:48:01 +00002615 TmpRecFields.clear();
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002616 continue;
2617 }
Chris Lattnerf1690852009-03-31 08:48:01 +00002618
2619 if (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002620 const ConstantArrayType *CArray =
2621 dyn_cast_or_null<ConstantArrayType>(Array);
2622 assert(CArray && "only array with know element size is supported");
2623 FQT = CArray->getElementType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002624 while (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
2625 const ConstantArrayType *CArray =
2626 dyn_cast_or_null<ConstantArrayType>(Array);
2627 FQT = CArray->getElementType();
2628 }
2629
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002630 assert(!FQT->isUnionType() &&
2631 "layout for array of unions not supported");
2632 if (FQT->isRecordType()) {
2633 uint64_t ElCount = CArray->getSize().getZExtValue();
2634 int OldIndex = Index;
2635 int OldSkIndex = SkIndex;
2636
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002637 // FIXME - Use a common routine with the above!
2638 const RecordType *RT = FQT->getAsRecordType();
2639 const RecordDecl *RD = RT->getDecl();
2640 // FIXME - Find a more efficiant way of passing records down.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002641 TmpRecFields.append(RD->field_begin(CGM.getContext()),
2642 RD->field_end(CGM.getContext()));
Chris Lattnerf1690852009-03-31 08:48:01 +00002643
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002644 BuildAggrIvarLayout(OI, Layout, RD,
Chris Lattnerf1690852009-03-31 08:48:01 +00002645 TmpRecFields,
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002646 BytePos + GetFieldBaseOffset(OI, Layout, Field),
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002647 ForStrongLayout, Index, SkIndex,
2648 HasUnion);
Chris Lattnerf1690852009-03-31 08:48:01 +00002649 TmpRecFields.clear();
2650
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002651 // Replicate layout information for each array element. Note that
2652 // one element is already done.
2653 uint64_t ElIx = 1;
2654 for (int FirstIndex = Index, FirstSkIndex = SkIndex;
2655 ElIx < ElCount; ElIx++) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002656 uint64_t Size = CGM.getContext().getTypeSize(RT)/ByteSizeInBits;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002657 for (int i = OldIndex+1; i <= FirstIndex; ++i)
2658 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002659 GC_IVAR gcivar;
2660 gcivar.ivar_bytepos = IvarsInfo[i].ivar_bytepos + Size*ElIx;
2661 gcivar.ivar_size = IvarsInfo[i].ivar_size;
2662 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002663 }
2664
Chris Lattnerf1690852009-03-31 08:48:01 +00002665 for (int i = OldSkIndex+1; i <= FirstSkIndex; ++i) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002666 GC_IVAR skivar;
2667 skivar.ivar_bytepos = SkipIvars[i].ivar_bytepos + Size*ElIx;
2668 skivar.ivar_size = SkipIvars[i].ivar_size;
2669 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002670 }
2671 }
2672 continue;
2673 }
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002674 }
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002675 // At this point, we are done with Record/Union and array there of.
2676 // For other arrays we are down to its element type.
2677 QualType::GCAttrTypes GCAttr = QualType::GCNone;
2678 do {
2679 if (FQT.isObjCGCStrong() || FQT.isObjCGCWeak()) {
2680 GCAttr = FQT.isObjCGCStrong() ? QualType::Strong : QualType::Weak;
2681 break;
2682 }
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002683 else if (CGM.getContext().isObjCObjectPointerType(FQT)) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002684 GCAttr = QualType::Strong;
2685 break;
2686 }
2687 else if (const PointerType *PT = FQT->getAsPointerType()) {
2688 FQT = PT->getPointeeType();
2689 }
2690 else {
2691 break;
2692 }
2693 } while (true);
Chris Lattnerf1690852009-03-31 08:48:01 +00002694
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002695 if ((ForStrongLayout && GCAttr == QualType::Strong)
2696 || (!ForStrongLayout && GCAttr == QualType::Weak)) {
2697 if (IsUnion)
2698 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002699 uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType())
2700 / WordSizeInBits;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002701 if (UnionIvarSize > MaxUnionIvarSize)
2702 {
2703 MaxUnionIvarSize = UnionIvarSize;
2704 MaxField = Field;
2705 }
2706 }
2707 else
2708 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002709 GC_IVAR gcivar;
2710 gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field);
2711 gcivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) /
2712 WordSizeInBits;
2713 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002714 }
2715 }
2716 else if ((ForStrongLayout &&
2717 (GCAttr == QualType::GCNone || GCAttr == QualType::Weak))
2718 || (!ForStrongLayout && GCAttr != QualType::Weak)) {
2719 if (IsUnion)
2720 {
2721 uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType());
2722 if (UnionIvarSize > MaxSkippedUnionIvarSize)
2723 {
2724 MaxSkippedUnionIvarSize = UnionIvarSize;
2725 MaxSkippedField = Field;
2726 }
2727 }
2728 else
2729 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002730 GC_IVAR skivar;
2731 skivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field);
2732 skivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) /
2733 WordSizeInBits;
2734 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002735 }
2736 }
2737 }
Chris Lattnerf1690852009-03-31 08:48:01 +00002738 if (MaxField) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002739 GC_IVAR gcivar;
2740 gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, MaxField);
2741 gcivar.ivar_size = MaxUnionIvarSize;
2742 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002743 }
Chris Lattnerf1690852009-03-31 08:48:01 +00002744
2745 if (MaxSkippedField) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002746 GC_IVAR skivar;
2747 skivar.ivar_bytepos = BytePos +
2748 GetFieldBaseOffset(OI, Layout, MaxSkippedField);
2749 skivar.ivar_size = MaxSkippedUnionIvarSize;
2750 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002751 }
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002752}
2753
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002754static int
Chris Lattnerf1690852009-03-31 08:48:01 +00002755IvarBytePosCompare(const void *a, const void *b)
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002756{
2757 unsigned int sa = ((CGObjCCommonMac::GC_IVAR *)a)->ivar_bytepos;
2758 unsigned int sb = ((CGObjCCommonMac::GC_IVAR *)b)->ivar_bytepos;
2759
2760 if (sa < sb)
2761 return -1;
2762 if (sa > sb)
2763 return 1;
2764 return 0;
2765}
2766
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002767/// BuildIvarLayout - Builds ivar layout bitmap for the class
2768/// implementation for the __strong or __weak case.
2769/// The layout map displays which words in ivar list must be skipped
2770/// and which must be scanned by GC (see below). String is built of bytes.
2771/// Each byte is divided up in two nibbles (4-bit each). Left nibble is count
2772/// of words to skip and right nibble is count of words to scan. So, each
2773/// nibble represents up to 15 workds to skip or scan. Skipping the rest is
2774/// represented by a 0x00 byte which also ends the string.
2775/// 1. when ForStrongLayout is true, following ivars are scanned:
2776/// - id, Class
2777/// - object *
2778/// - __strong anything
2779///
2780/// 2. When ForStrongLayout is false, following ivars are scanned:
2781/// - __weak anything
2782///
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002783llvm::Constant *CGObjCCommonMac::BuildIvarLayout(
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002784 const ObjCImplementationDecl *OMD,
2785 bool ForStrongLayout) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002786 int Index = -1;
2787 int SkIndex = -1;
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002788 bool hasUnion = false;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002789 int SkipScan;
2790 unsigned int WordsToScan, WordsToSkip;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002791 const llvm::Type *PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
2792 if (CGM.getLangOptions().getGCMode() == LangOptions::NonGC)
2793 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002794
Chris Lattnerf1690852009-03-31 08:48:01 +00002795 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002796 const ObjCInterfaceDecl *OI = OMD->getClassInterface();
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002797 CGM.getContext().CollectObjCIvars(OI, RecFields);
2798 if (RecFields.empty())
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002799 return llvm::Constant::getNullValue(PtrTy);
Chris Lattnerf1690852009-03-31 08:48:01 +00002800
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002801 SkipIvars.clear();
2802 IvarsInfo.clear();
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002803
2804 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OI);
Chris Lattnerf1690852009-03-31 08:48:01 +00002805 BuildAggrIvarLayout(OI, Layout, 0, RecFields, 0, ForStrongLayout,
2806 Index, SkIndex, hasUnion);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002807 if (Index == -1)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002808 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002809
2810 // Sort on byte position in case we encounterred a union nested in
2811 // the ivar list.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002812 if (hasUnion && !IvarsInfo.empty())
2813 qsort(&IvarsInfo[0], Index+1, sizeof(GC_IVAR), IvarBytePosCompare);
2814 if (hasUnion && !SkipIvars.empty())
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002815 qsort(&SkipIvars[0], Index+1, sizeof(GC_IVAR), IvarBytePosCompare);
2816
2817 // Build the string of skip/scan nibbles
2818 SkipScan = -1;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002819 SkipScanIvars.clear();
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002820 unsigned int WordSize =
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002821 CGM.getTypes().getTargetData().getTypePaddedSize(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002822 if (IvarsInfo[0].ivar_bytepos == 0) {
2823 WordsToSkip = 0;
2824 WordsToScan = IvarsInfo[0].ivar_size;
2825 }
2826 else {
2827 WordsToSkip = IvarsInfo[0].ivar_bytepos/WordSize;
2828 WordsToScan = IvarsInfo[0].ivar_size;
2829 }
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002830 for (unsigned int i=1, Last=IvarsInfo.size(); i != Last; i++)
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002831 {
2832 unsigned int TailPrevGCObjC =
2833 IvarsInfo[i-1].ivar_bytepos + IvarsInfo[i-1].ivar_size * WordSize;
2834 if (IvarsInfo[i].ivar_bytepos == TailPrevGCObjC)
2835 {
2836 // consecutive 'scanned' object pointers.
2837 WordsToScan += IvarsInfo[i].ivar_size;
2838 }
2839 else
2840 {
2841 // Skip over 'gc'able object pointer which lay over each other.
2842 if (TailPrevGCObjC > IvarsInfo[i].ivar_bytepos)
2843 continue;
2844 // Must skip over 1 or more words. We save current skip/scan values
2845 // and start a new pair.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002846 SKIP_SCAN SkScan;
2847 SkScan.skip = WordsToSkip;
2848 SkScan.scan = WordsToScan;
2849 SkipScanIvars.push_back(SkScan); ++SkipScan;
2850
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002851 // Skip the hole.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002852 SkScan.skip = (IvarsInfo[i].ivar_bytepos - TailPrevGCObjC) / WordSize;
2853 SkScan.scan = 0;
2854 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002855 WordsToSkip = 0;
2856 WordsToScan = IvarsInfo[i].ivar_size;
2857 }
2858 }
2859 if (WordsToScan > 0)
2860 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002861 SKIP_SCAN SkScan;
2862 SkScan.skip = WordsToSkip;
2863 SkScan.scan = WordsToScan;
2864 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002865 }
2866
2867 bool BytesSkipped = false;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002868 if (!SkipIvars.empty())
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002869 {
2870 int LastByteSkipped =
2871 SkipIvars[SkIndex].ivar_bytepos + SkipIvars[SkIndex].ivar_size;
2872 int LastByteScanned =
2873 IvarsInfo[Index].ivar_bytepos + IvarsInfo[Index].ivar_size * WordSize;
2874 BytesSkipped = (LastByteSkipped > LastByteScanned);
2875 // Compute number of bytes to skip at the tail end of the last ivar scanned.
2876 if (BytesSkipped)
2877 {
2878 unsigned int TotalWords = (LastByteSkipped + (WordSize -1)) / WordSize;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002879 SKIP_SCAN SkScan;
2880 SkScan.skip = TotalWords - (LastByteScanned/WordSize);
2881 SkScan.scan = 0;
2882 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002883 }
2884 }
2885 // Mini optimization of nibbles such that an 0xM0 followed by 0x0N is produced
2886 // as 0xMN.
2887 for (int i = 0; i <= SkipScan; i++)
2888 {
2889 if ((i < SkipScan) && SkipScanIvars[i].skip && SkipScanIvars[i].scan == 0
2890 && SkipScanIvars[i+1].skip == 0 && SkipScanIvars[i+1].scan) {
2891 // 0xM0 followed by 0x0N detected.
2892 SkipScanIvars[i].scan = SkipScanIvars[i+1].scan;
2893 for (int j = i+1; j < SkipScan; j++)
2894 SkipScanIvars[j] = SkipScanIvars[j+1];
2895 --SkipScan;
2896 }
2897 }
2898
2899 // Generate the string.
2900 std::string BitMap;
2901 for (int i = 0; i <= SkipScan; i++)
2902 {
2903 unsigned char byte;
2904 unsigned int skip_small = SkipScanIvars[i].skip % 0xf;
2905 unsigned int scan_small = SkipScanIvars[i].scan % 0xf;
2906 unsigned int skip_big = SkipScanIvars[i].skip / 0xf;
2907 unsigned int scan_big = SkipScanIvars[i].scan / 0xf;
2908
2909 if (skip_small > 0 || skip_big > 0)
2910 BytesSkipped = true;
2911 // first skip big.
2912 for (unsigned int ix = 0; ix < skip_big; ix++)
2913 BitMap += (unsigned char)(0xf0);
2914
2915 // next (skip small, scan)
2916 if (skip_small)
2917 {
2918 byte = skip_small << 4;
2919 if (scan_big > 0)
2920 {
2921 byte |= 0xf;
2922 --scan_big;
2923 }
2924 else if (scan_small)
2925 {
2926 byte |= scan_small;
2927 scan_small = 0;
2928 }
2929 BitMap += byte;
2930 }
2931 // next scan big
2932 for (unsigned int ix = 0; ix < scan_big; ix++)
2933 BitMap += (unsigned char)(0x0f);
2934 // last scan small
2935 if (scan_small)
2936 {
2937 byte = scan_small;
2938 BitMap += byte;
2939 }
2940 }
2941 // null terminate string.
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002942 unsigned char zero = 0;
2943 BitMap += zero;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002944 // if ivar_layout bitmap is all 1 bits (nothing skipped) then use NULL as
2945 // final layout.
2946 if (ForStrongLayout && !BytesSkipped)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002947 return llvm::Constant::getNullValue(PtrTy);
2948 llvm::GlobalVariable * Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
2949 llvm::ConstantArray::get(BitMap.c_str()),
2950 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00002951 1, true);
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002952 // FIXME. Need a commomand-line option for this eventually.
2953 if (ForStrongLayout)
2954 printf("\nstrong ivar layout: ");
2955 else
2956 printf("\nweak ivar layout: ");
2957 const unsigned char *s = (unsigned char*)BitMap.c_str();
2958 for (unsigned i = 0; i < BitMap.size(); i++)
Fariborz Jahaniandbf15cb2009-03-26 19:10:36 +00002959 if (!(s[i] & 0xf0))
2960 printf("0x0%x%s", s[i], s[i] != 0 ? ", " : "");
2961 else
2962 printf("0x%x%s", s[i], s[i] != 0 ? ", " : "");
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002963 printf("\n");
2964
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002965 return getConstantGEP(Entry, 0, 0);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002966}
2967
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002968llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002969 llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
2970
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002971 // FIXME: Avoid std::string copying.
2972 if (!Entry)
2973 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_NAME_",
2974 llvm::ConstantArray::get(Sel.getAsString()),
2975 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00002976 1, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002977
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002978 return getConstantGEP(Entry, 0, 0);
2979}
2980
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002981// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002982llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002983 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
2984}
2985
2986// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002987llvm::Constant *CGObjCCommonMac::GetMethodVarName(const std::string &Name) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002988 return GetMethodVarName(&CGM.getContext().Idents.get(Name));
2989}
2990
Devang Patel7794bb82009-03-04 18:21:39 +00002991llvm::Constant *CGObjCCommonMac::GetMethodVarType(FieldDecl *Field) {
2992 std::string TypeStr;
2993 CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
2994
2995 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002996
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002997 if (!Entry)
2998 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
2999 llvm::ConstantArray::get(TypeStr),
3000 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003001 1, true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003002
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003003 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003004}
3005
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003006llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003007 std::string TypeStr;
Daniel Dunbarc45ef602008-08-26 21:51:14 +00003008 CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D),
3009 TypeStr);
Devang Patel7794bb82009-03-04 18:21:39 +00003010
3011 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
3012
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003013 if (!Entry)
3014 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3015 llvm::ConstantArray::get(TypeStr),
3016 "__TEXT,__cstring,cstring_literals",
3017 1, true);
Devang Patel7794bb82009-03-04 18:21:39 +00003018
3019 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003020}
3021
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003022// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003023llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003024 llvm::GlobalVariable *&Entry = PropertyNames[Ident];
3025
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003026 if (!Entry)
3027 Entry = CreateMetadataVar("\01L_OBJC_PROP_NAME_ATTR_",
3028 llvm::ConstantArray::get(Ident->getName()),
3029 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003030 1, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003031
3032 return getConstantGEP(Entry, 0, 0);
3033}
3034
3035// FIXME: Merge into a single cstring creation function.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003036// FIXME: This Decl should be more precise.
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003037llvm::Constant *
3038 CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
3039 const Decl *Container) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003040 std::string TypeStr;
3041 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003042 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
3043}
3044
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003045void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D,
3046 const ObjCContainerDecl *CD,
3047 std::string &NameOut) {
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00003048 NameOut = '\01';
3049 NameOut += (D->isInstanceMethod() ? '-' : '+');
Chris Lattner077bf5e2008-11-24 03:33:13 +00003050 NameOut += '[';
Fariborz Jahanian679a5022009-01-10 21:06:09 +00003051 assert (CD && "Missing container decl in GetNameForMethod");
3052 NameOut += CD->getNameAsString();
Fariborz Jahanian1e9aef32009-04-16 18:34:20 +00003053 if (const ObjCCategoryImplDecl *CID =
3054 dyn_cast<ObjCCategoryImplDecl>(D->getDeclContext())) {
3055 NameOut += '(';
3056 NameOut += CID->getNameAsString();
3057 NameOut+= ')';
3058 }
Chris Lattner077bf5e2008-11-24 03:33:13 +00003059 NameOut += ' ';
3060 NameOut += D->getSelector().getAsString();
3061 NameOut += ']';
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00003062}
3063
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00003064/// GetFirstIvarInRecord - This routine returns the record for the
3065/// implementation of the fiven class OID. It also returns field
3066/// corresponding to the first ivar in the class in FIV. It also
3067/// returns the one before the first ivar.
3068///
3069const RecordDecl *CGObjCCommonMac::GetFirstIvarInRecord(
3070 const ObjCInterfaceDecl *OID,
3071 RecordDecl::field_iterator &FIV,
3072 RecordDecl::field_iterator &PIV) {
Douglas Gregor6ab35242009-04-09 21:40:53 +00003073 int countSuperClassIvars = countInheritedIvars(OID->getSuperClass(),
3074 CGM.getContext());
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00003075 const RecordDecl *RD = CGM.getContext().addRecordToClass(OID);
Douglas Gregor6ab35242009-04-09 21:40:53 +00003076 RecordDecl::field_iterator ifield = RD->field_begin(CGM.getContext());
3077 RecordDecl::field_iterator pfield = RD->field_end(CGM.getContext());
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00003078 while (countSuperClassIvars-- > 0) {
3079 pfield = ifield;
3080 ++ifield;
3081 }
3082 FIV = ifield;
3083 PIV = pfield;
3084 return RD;
3085}
3086
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003087void CGObjCMac::FinishModule() {
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003088 EmitModuleInfo();
3089
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003090 // Emit the dummy bodies for any protocols which were referenced but
3091 // never defined.
3092 for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
3093 i = Protocols.begin(), e = Protocols.end(); i != e; ++i) {
3094 if (i->second->hasInitializer())
3095 continue;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003096
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003097 std::vector<llvm::Constant*> Values(5);
3098 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
3099 Values[1] = GetClassName(i->first);
3100 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
3101 Values[3] = Values[4] =
3102 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
3103 i->second->setLinkage(llvm::GlobalValue::InternalLinkage);
3104 i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
3105 Values));
3106 }
3107
3108 std::vector<llvm::Constant*> Used;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003109 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003110 e = UsedGlobals.end(); i != e; ++i) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003111 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003112 }
3113
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003114 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003115 llvm::GlobalValue *GV =
3116 new llvm::GlobalVariable(AT, false,
3117 llvm::GlobalValue::AppendingLinkage,
3118 llvm::ConstantArray::get(AT, Used),
3119 "llvm.used",
3120 &CGM.getModule());
3121
3122 GV->setSection("llvm.metadata");
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003123
3124 // Add assembler directives to add lazy undefined symbol references
3125 // for classes which are referenced but not defined. This is
3126 // important for correct linker interaction.
3127
3128 // FIXME: Uh, this isn't particularly portable.
3129 std::stringstream s;
Anders Carlsson565c99f2008-12-10 02:21:04 +00003130
3131 if (!CGM.getModule().getModuleInlineAsm().empty())
3132 s << "\n";
3133
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003134 for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(),
3135 e = LazySymbols.end(); i != e; ++i) {
3136 s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n";
3137 }
3138 for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(),
3139 e = DefinedSymbols.end(); i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003140 s << "\t.objc_class_name_" << (*i)->getName() << "=0\n"
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003141 << "\t.globl .objc_class_name_" << (*i)->getName() << "\n";
3142 }
Anders Carlsson565c99f2008-12-10 02:21:04 +00003143
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003144 CGM.getModule().appendModuleInlineAsm(s.str());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003145}
3146
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003147CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003148 : CGObjCCommonMac(cgm),
3149 ObjCTypes(cgm)
3150{
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003151 ObjCEmptyCacheVar = ObjCEmptyVtableVar = NULL;
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003152 ObjCABI = 2;
3153}
3154
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003155/* *** */
3156
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003157ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm)
3158: CGM(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003159{
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003160 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3161 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003162
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003163 ShortTy = Types.ConvertType(Ctx.ShortTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003164 IntTy = Types.ConvertType(Ctx.IntTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003165 LongTy = Types.ConvertType(Ctx.LongTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00003166 LongLongTy = Types.ConvertType(Ctx.LongLongTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003167 Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3168
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003169 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00003170 PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003171 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003172
3173 // FIXME: It would be nice to unify this with the opaque type, so
3174 // that the IR comes out a bit cleaner.
3175 const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
3176 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003177
3178 // I'm not sure I like this. The implicit coordination is a bit
3179 // gross. We should solve this in a reasonable fashion because this
3180 // is a pretty common task (match some runtime data structure with
3181 // an LLVM data structure).
3182
3183 // FIXME: This is leaked.
3184 // FIXME: Merge with rewriter code?
3185
3186 // struct _objc_super {
3187 // id self;
3188 // Class cls;
3189 // }
3190 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3191 SourceLocation(),
3192 &Ctx.Idents.get("_objc_super"));
Douglas Gregor6ab35242009-04-09 21:40:53 +00003193 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3194 Ctx.getObjCIdType(), 0, false));
3195 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3196 Ctx.getObjCClassType(), 0, false));
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003197 RD->completeDefinition(Ctx);
3198
3199 SuperCTy = Ctx.getTagDeclType(RD);
3200 SuperPtrCTy = Ctx.getPointerType(SuperCTy);
3201
3202 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003203 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
3204
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003205 // struct _prop_t {
3206 // char *name;
3207 // char *attributes;
3208 // }
3209 PropertyTy = llvm::StructType::get(Int8PtrTy,
3210 Int8PtrTy,
3211 NULL);
3212 CGM.getModule().addTypeName("struct._prop_t",
3213 PropertyTy);
3214
3215 // struct _prop_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003216 // uint32_t entsize; // sizeof(struct _prop_t)
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003217 // uint32_t count_of_properties;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003218 // struct _prop_t prop_list[count_of_properties];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003219 // }
3220 PropertyListTy = llvm::StructType::get(IntTy,
3221 IntTy,
3222 llvm::ArrayType::get(PropertyTy, 0),
3223 NULL);
3224 CGM.getModule().addTypeName("struct._prop_list_t",
3225 PropertyListTy);
3226 // struct _prop_list_t *
3227 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
3228
3229 // struct _objc_method {
3230 // SEL _cmd;
3231 // char *method_type;
3232 // char *_imp;
3233 // }
3234 MethodTy = llvm::StructType::get(SelectorPtrTy,
3235 Int8PtrTy,
3236 Int8PtrTy,
3237 NULL);
3238 CGM.getModule().addTypeName("struct._objc_method", MethodTy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003239
3240 // struct _objc_cache *
3241 CacheTy = llvm::OpaqueType::get();
3242 CGM.getModule().addTypeName("struct._objc_cache", CacheTy);
3243 CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003244
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003245 // Property manipulation functions.
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003246
3247 QualType IdType = Ctx.getObjCIdType();
3248 QualType SelType = Ctx.getObjCSelType();
3249 llvm::SmallVector<QualType,16> Params;
3250 const llvm::FunctionType *FTy;
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003251
3252 // id objc_getProperty (id, SEL, ptrdiff_t, bool)
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003253 Params.push_back(IdType);
3254 Params.push_back(SelType);
3255 Params.push_back(Ctx.LongTy);
3256 Params.push_back(Ctx.BoolTy);
3257 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params),
3258 false);
3259 GetPropertyFn = CGM.CreateRuntimeFunction(FTy, "objc_getProperty");
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003260
3261 // void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool)
3262 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003263 Params.push_back(IdType);
3264 Params.push_back(SelType);
3265 Params.push_back(Ctx.LongTy);
3266 Params.push_back(IdType);
3267 Params.push_back(Ctx.BoolTy);
3268 Params.push_back(Ctx.BoolTy);
3269 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
3270 SetPropertyFn = CGM.CreateRuntimeFunction(FTy, "objc_setProperty");
3271
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003272 // Enumeration mutation.
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003273
3274 // void objc_enumerationMutation (id)
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003275 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003276 Params.push_back(IdType);
3277 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
3278 EnumerationMutationFn = CGM.CreateRuntimeFunction(FTy,
3279 "objc_enumerationMutation");
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003280
3281 // gc's API
3282 // id objc_read_weak (id *)
3283 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003284 Params.push_back(Ctx.getPointerType(IdType));
3285 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
3286 GcReadWeakFn = CGM.CreateRuntimeFunction(FTy, "objc_read_weak");
3287
Chris Lattner96508e12009-04-17 22:12:36 +00003288 // id objc_assign_global (id, id *)
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003289 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003290 Params.push_back(IdType);
3291 Params.push_back(Ctx.getPointerType(IdType));
3292
3293 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003294 GcAssignGlobalFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_global");
3295 GcAssignIvarFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_ivar");
3296 GcAssignStrongCastFn =
3297 CGM.CreateRuntimeFunction(FTy, "objc_assign_strongCast");
Anders Carlssonf57c5b22009-02-16 22:59:18 +00003298
3299 // void objc_exception_throw(id)
3300 Params.clear();
3301 Params.push_back(IdType);
3302
3303 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00003304 ExceptionThrowFn =
3305 CGM.CreateRuntimeFunction(FTy, "objc_exception_throw");
Daniel Dunbar1c566672009-02-24 01:43:46 +00003306
3307 // synchronized APIs
Daniel Dunbar1c566672009-02-24 01:43:46 +00003308 // void objc_sync_exit (id)
3309 Params.clear();
3310 Params.push_back(IdType);
3311
3312 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
Daniel Dunbar1c566672009-02-24 01:43:46 +00003313 SyncExitFn = CGM.CreateRuntimeFunction(FTy, "objc_sync_exit");
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003314}
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003315
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003316ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
3317 : ObjCCommonTypesHelper(cgm)
3318{
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003319 // struct _objc_method_description {
3320 // SEL name;
3321 // char *types;
3322 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003323 MethodDescriptionTy =
3324 llvm::StructType::get(SelectorPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003325 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003326 NULL);
3327 CGM.getModule().addTypeName("struct._objc_method_description",
3328 MethodDescriptionTy);
3329
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003330 // struct _objc_method_description_list {
3331 // int count;
3332 // struct _objc_method_description[1];
3333 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003334 MethodDescriptionListTy =
3335 llvm::StructType::get(IntTy,
3336 llvm::ArrayType::get(MethodDescriptionTy, 0),
3337 NULL);
3338 CGM.getModule().addTypeName("struct._objc_method_description_list",
3339 MethodDescriptionListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003340
3341 // struct _objc_method_description_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003342 MethodDescriptionListPtrTy =
3343 llvm::PointerType::getUnqual(MethodDescriptionListTy);
3344
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003345 // Protocol description structures
3346
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003347 // struct _objc_protocol_extension {
3348 // uint32_t size; // sizeof(struct _objc_protocol_extension)
3349 // struct _objc_method_description_list *optional_instance_methods;
3350 // struct _objc_method_description_list *optional_class_methods;
3351 // struct _objc_property_list *instance_properties;
3352 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003353 ProtocolExtensionTy =
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003354 llvm::StructType::get(IntTy,
3355 MethodDescriptionListPtrTy,
3356 MethodDescriptionListPtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003357 PropertyListPtrTy,
3358 NULL);
3359 CGM.getModule().addTypeName("struct._objc_protocol_extension",
3360 ProtocolExtensionTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003361
3362 // struct _objc_protocol_extension *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003363 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
3364
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003365 // Handle recursive construction of Protocol and ProtocolList types
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003366
3367 llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get();
3368 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3369
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003370 const llvm::Type *T =
3371 llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder),
3372 LongTy,
3373 llvm::ArrayType::get(ProtocolTyHolder, 0),
3374 NULL);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003375 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T);
3376
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003377 // struct _objc_protocol {
3378 // struct _objc_protocol_extension *isa;
3379 // char *protocol_name;
3380 // struct _objc_protocol **_objc_protocol_list;
3381 // struct _objc_method_description_list *instance_methods;
3382 // struct _objc_method_description_list *class_methods;
3383 // }
3384 T = llvm::StructType::get(ProtocolExtensionPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003385 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003386 llvm::PointerType::getUnqual(ProtocolListTyHolder),
3387 MethodDescriptionListPtrTy,
3388 MethodDescriptionListPtrTy,
3389 NULL);
3390 cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T);
3391
3392 ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get());
3393 CGM.getModule().addTypeName("struct._objc_protocol_list",
3394 ProtocolListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003395 // struct _objc_protocol_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003396 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
3397
3398 ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get());
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003399 CGM.getModule().addTypeName("struct._objc_protocol", ProtocolTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003400 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003401
3402 // Class description structures
3403
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003404 // struct _objc_ivar {
3405 // char *ivar_name;
3406 // char *ivar_type;
3407 // int ivar_offset;
3408 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003409 IvarTy = llvm::StructType::get(Int8PtrTy,
3410 Int8PtrTy,
3411 IntTy,
3412 NULL);
3413 CGM.getModule().addTypeName("struct._objc_ivar", IvarTy);
3414
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003415 // struct _objc_ivar_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003416 IvarListTy = llvm::OpaqueType::get();
3417 CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy);
3418 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
3419
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003420 // struct _objc_method_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003421 MethodListTy = llvm::OpaqueType::get();
3422 CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy);
3423 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
3424
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003425 // struct _objc_class_extension *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003426 ClassExtensionTy =
3427 llvm::StructType::get(IntTy,
3428 Int8PtrTy,
3429 PropertyListPtrTy,
3430 NULL);
3431 CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy);
3432 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
3433
3434 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3435
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003436 // struct _objc_class {
3437 // Class isa;
3438 // Class super_class;
3439 // char *name;
3440 // long version;
3441 // long info;
3442 // long instance_size;
3443 // struct _objc_ivar_list *ivars;
3444 // struct _objc_method_list *methods;
3445 // struct _objc_cache *cache;
3446 // struct _objc_protocol_list *protocols;
3447 // char *ivar_layout;
3448 // struct _objc_class_ext *ext;
3449 // };
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003450 T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3451 llvm::PointerType::getUnqual(ClassTyHolder),
3452 Int8PtrTy,
3453 LongTy,
3454 LongTy,
3455 LongTy,
3456 IvarListPtrTy,
3457 MethodListPtrTy,
3458 CachePtrTy,
3459 ProtocolListPtrTy,
3460 Int8PtrTy,
3461 ClassExtensionPtrTy,
3462 NULL);
3463 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T);
3464
3465 ClassTy = cast<llvm::StructType>(ClassTyHolder.get());
3466 CGM.getModule().addTypeName("struct._objc_class", ClassTy);
3467 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
3468
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003469 // struct _objc_category {
3470 // char *category_name;
3471 // char *class_name;
3472 // struct _objc_method_list *instance_method;
3473 // struct _objc_method_list *class_method;
3474 // uint32_t size; // sizeof(struct _objc_category)
3475 // struct _objc_property_list *instance_properties;// category's @property
3476 // }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003477 CategoryTy = llvm::StructType::get(Int8PtrTy,
3478 Int8PtrTy,
3479 MethodListPtrTy,
3480 MethodListPtrTy,
3481 ProtocolListPtrTy,
3482 IntTy,
3483 PropertyListPtrTy,
3484 NULL);
3485 CGM.getModule().addTypeName("struct._objc_category", CategoryTy);
3486
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003487 // Global metadata structures
3488
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003489 // struct _objc_symtab {
3490 // long sel_ref_cnt;
3491 // SEL *refs;
3492 // short cls_def_cnt;
3493 // short cat_def_cnt;
3494 // char *defs[cls_def_cnt + cat_def_cnt];
3495 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003496 SymtabTy = llvm::StructType::get(LongTy,
3497 SelectorPtrTy,
3498 ShortTy,
3499 ShortTy,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003500 llvm::ArrayType::get(Int8PtrTy, 0),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003501 NULL);
3502 CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy);
3503 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
3504
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003505 // struct _objc_module {
3506 // long version;
3507 // long size; // sizeof(struct _objc_module)
3508 // char *name;
3509 // struct _objc_symtab* symtab;
3510 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003511 ModuleTy =
3512 llvm::StructType::get(LongTy,
3513 LongTy,
3514 Int8PtrTy,
3515 SymtabPtrTy,
3516 NULL);
3517 CGM.getModule().addTypeName("struct._objc_module", ModuleTy);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003518
Daniel Dunbar49f66022008-09-24 03:38:44 +00003519 // Message send functions.
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003520
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003521 // id objc_msgSend (id, SEL, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003522 std::vector<const llvm::Type*> Params;
3523 Params.push_back(ObjectPtrTy);
3524 Params.push_back(SelectorPtrTy);
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003525 MessageSendFn =
3526 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3527 Params,
3528 true),
3529 "objc_msgSend");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003530
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003531 // id objc_msgSend_stret (id, SEL, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003532 Params.clear();
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003533 Params.push_back(ObjectPtrTy);
3534 Params.push_back(SelectorPtrTy);
3535 MessageSendStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003536 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3537 Params,
3538 true),
3539 "objc_msgSend_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00003540
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003541 //
Daniel Dunbar5669e572008-10-17 03:24:53 +00003542 Params.clear();
3543 Params.push_back(ObjectPtrTy);
3544 Params.push_back(SelectorPtrTy);
3545 // FIXME: This should be long double on x86_64?
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003546 // [double | long double] objc_msgSend_fpret(id self, SEL op, ...)
Daniel Dunbar5669e572008-10-17 03:24:53 +00003547 MessageSendFpretFn =
3548 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::DoubleTy,
3549 Params,
3550 true),
3551 "objc_msgSend_fpret");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003552
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003553 // id objc_msgSendSuper(struct objc_super *super, SEL op, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003554 Params.clear();
3555 Params.push_back(SuperPtrTy);
3556 Params.push_back(SelectorPtrTy);
3557 MessageSendSuperFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003558 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3559 Params,
3560 true),
3561 "objc_msgSendSuper");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003562
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003563 // void objc_msgSendSuper_stret(void * stretAddr, struct objc_super *super,
3564 // SEL op, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003565 Params.clear();
3566 Params.push_back(Int8PtrTy);
3567 Params.push_back(SuperPtrTy);
3568 Params.push_back(SelectorPtrTy);
3569 MessageSendSuperStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003570 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3571 Params,
3572 true),
3573 "objc_msgSendSuper_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00003574
3575 // There is no objc_msgSendSuper_fpret? How can that work?
3576 MessageSendSuperFpretFn = MessageSendSuperFn;
Anders Carlsson2abd89c2008-08-31 04:05:03 +00003577
Anders Carlsson124526b2008-09-09 10:10:21 +00003578 // FIXME: This is the size of the setjmp buffer and should be
3579 // target specific. 18 is what's used on 32-bit X86.
3580 uint64_t SetJmpBufferSize = 18;
3581
3582 // Exceptions
3583 const llvm::Type *StackPtrTy =
Daniel Dunbar10004912008-09-27 06:32:25 +00003584 llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4);
Anders Carlsson124526b2008-09-09 10:10:21 +00003585
3586 ExceptionDataTy =
3587 llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty,
3588 SetJmpBufferSize),
3589 StackPtrTy, NULL);
3590 CGM.getModule().addTypeName("struct._objc_exception_data",
3591 ExceptionDataTy);
3592
3593 Params.clear();
Anders Carlsson124526b2008-09-09 10:10:21 +00003594 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
3595 ExceptionTryEnterFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003596 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3597 Params,
3598 false),
3599 "objc_exception_try_enter");
Anders Carlsson124526b2008-09-09 10:10:21 +00003600 ExceptionTryExitFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003601 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3602 Params,
3603 false),
3604 "objc_exception_try_exit");
Anders Carlsson124526b2008-09-09 10:10:21 +00003605 ExceptionExtractFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003606 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3607 Params,
3608 false),
3609 "objc_exception_extract");
Anders Carlsson124526b2008-09-09 10:10:21 +00003610
3611 Params.clear();
3612 Params.push_back(ClassPtrTy);
3613 Params.push_back(ObjectPtrTy);
3614 ExceptionMatchFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003615 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
3616 Params,
3617 false),
3618 "objc_exception_match");
Chris Lattner10cac6f2008-11-15 21:26:17 +00003619
Anders Carlsson124526b2008-09-09 10:10:21 +00003620 Params.clear();
3621 Params.push_back(llvm::PointerType::getUnqual(llvm::Type::Int32Ty));
3622 SetJmpFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003623 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
3624 Params,
3625 false),
3626 "_setjmp");
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00003627
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003628}
3629
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003630ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003631: ObjCCommonTypesHelper(cgm)
3632{
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003633 // struct _method_list_t {
3634 // uint32_t entsize; // sizeof(struct _objc_method)
3635 // uint32_t method_count;
3636 // struct _objc_method method_list[method_count];
3637 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003638 MethodListnfABITy = llvm::StructType::get(IntTy,
3639 IntTy,
3640 llvm::ArrayType::get(MethodTy, 0),
3641 NULL);
3642 CGM.getModule().addTypeName("struct.__method_list_t",
3643 MethodListnfABITy);
3644 // struct method_list_t *
3645 MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003646
3647 // struct _protocol_t {
3648 // id isa; // NULL
3649 // const char * const protocol_name;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003650 // const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003651 // const struct method_list_t * const instance_methods;
3652 // const struct method_list_t * const class_methods;
3653 // const struct method_list_t *optionalInstanceMethods;
3654 // const struct method_list_t *optionalClassMethods;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003655 // const struct _prop_list_t * properties;
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003656 // const uint32_t size; // sizeof(struct _protocol_t)
3657 // const uint32_t flags; // = 0
3658 // }
3659
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003660 // Holder for struct _protocol_list_t *
3661 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3662
3663 ProtocolnfABITy = llvm::StructType::get(ObjectPtrTy,
3664 Int8PtrTy,
3665 llvm::PointerType::getUnqual(
3666 ProtocolListTyHolder),
3667 MethodListnfABIPtrTy,
3668 MethodListnfABIPtrTy,
3669 MethodListnfABIPtrTy,
3670 MethodListnfABIPtrTy,
3671 PropertyListPtrTy,
3672 IntTy,
3673 IntTy,
3674 NULL);
3675 CGM.getModule().addTypeName("struct._protocol_t",
3676 ProtocolnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003677
3678 // struct _protocol_t*
3679 ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003680
Fariborz Jahanianda320092009-01-29 19:24:30 +00003681 // struct _protocol_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003682 // long protocol_count; // Note, this is 32/64 bit
Daniel Dunbar948e2582009-02-15 07:36:20 +00003683 // struct _protocol_t *[protocol_count];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003684 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003685 ProtocolListnfABITy = llvm::StructType::get(LongTy,
3686 llvm::ArrayType::get(
Daniel Dunbar948e2582009-02-15 07:36:20 +00003687 ProtocolnfABIPtrTy, 0),
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003688 NULL);
3689 CGM.getModule().addTypeName("struct._objc_protocol_list",
3690 ProtocolListnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003691 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(
3692 ProtocolListnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003693
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003694 // struct _objc_protocol_list*
3695 ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003696
3697 // struct _ivar_t {
3698 // unsigned long int *offset; // pointer to ivar offset location
3699 // char *name;
3700 // char *type;
3701 // uint32_t alignment;
3702 // uint32_t size;
3703 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003704 IvarnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(LongTy),
3705 Int8PtrTy,
3706 Int8PtrTy,
3707 IntTy,
3708 IntTy,
3709 NULL);
3710 CGM.getModule().addTypeName("struct._ivar_t", IvarnfABITy);
3711
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003712 // struct _ivar_list_t {
3713 // uint32 entsize; // sizeof(struct _ivar_t)
3714 // uint32 count;
3715 // struct _iver_t list[count];
3716 // }
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003717 IvarListnfABITy = llvm::StructType::get(IntTy,
3718 IntTy,
3719 llvm::ArrayType::get(
3720 IvarnfABITy, 0),
3721 NULL);
3722 CGM.getModule().addTypeName("struct._ivar_list_t", IvarListnfABITy);
3723
3724 IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003725
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003726 // struct _class_ro_t {
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003727 // uint32_t const flags;
3728 // uint32_t const instanceStart;
3729 // uint32_t const instanceSize;
3730 // uint32_t const reserved; // only when building for 64bit targets
3731 // const uint8_t * const ivarLayout;
3732 // const char *const name;
3733 // const struct _method_list_t * const baseMethods;
3734 // const struct _objc_protocol_list *const baseProtocols;
3735 // const struct _ivar_list_t *const ivars;
3736 // const uint8_t * const weakIvarLayout;
3737 // const struct _prop_list_t * const properties;
3738 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003739
3740 // FIXME. Add 'reserved' field in 64bit abi mode!
3741 ClassRonfABITy = llvm::StructType::get(IntTy,
3742 IntTy,
3743 IntTy,
3744 Int8PtrTy,
3745 Int8PtrTy,
3746 MethodListnfABIPtrTy,
3747 ProtocolListnfABIPtrTy,
3748 IvarListnfABIPtrTy,
3749 Int8PtrTy,
3750 PropertyListPtrTy,
3751 NULL);
3752 CGM.getModule().addTypeName("struct._class_ro_t",
3753 ClassRonfABITy);
3754
3755 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
3756 std::vector<const llvm::Type*> Params;
3757 Params.push_back(ObjectPtrTy);
3758 Params.push_back(SelectorPtrTy);
3759 ImpnfABITy = llvm::PointerType::getUnqual(
3760 llvm::FunctionType::get(ObjectPtrTy, Params, false));
3761
3762 // struct _class_t {
3763 // struct _class_t *isa;
3764 // struct _class_t * const superclass;
3765 // void *cache;
3766 // IMP *vtable;
3767 // struct class_ro_t *ro;
3768 // }
3769
3770 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3771 ClassnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3772 llvm::PointerType::getUnqual(ClassTyHolder),
3773 CachePtrTy,
3774 llvm::PointerType::getUnqual(ImpnfABITy),
3775 llvm::PointerType::getUnqual(
3776 ClassRonfABITy),
3777 NULL);
3778 CGM.getModule().addTypeName("struct._class_t", ClassnfABITy);
3779
3780 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(
3781 ClassnfABITy);
3782
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003783 // LLVM for struct _class_t *
3784 ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy);
3785
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003786 // struct _category_t {
3787 // const char * const name;
3788 // struct _class_t *const cls;
3789 // const struct _method_list_t * const instance_methods;
3790 // const struct _method_list_t * const class_methods;
3791 // const struct _protocol_list_t * const protocols;
3792 // const struct _prop_list_t * const properties;
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003793 // }
3794 CategorynfABITy = llvm::StructType::get(Int8PtrTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003795 ClassnfABIPtrTy,
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003796 MethodListnfABIPtrTy,
3797 MethodListnfABIPtrTy,
3798 ProtocolListnfABIPtrTy,
3799 PropertyListPtrTy,
3800 NULL);
3801 CGM.getModule().addTypeName("struct._category_t", CategorynfABITy);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003802
3803 // New types for nonfragile abi messaging.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003804 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3805 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003806
3807 // MessageRefTy - LLVM for:
3808 // struct _message_ref_t {
3809 // IMP messenger;
3810 // SEL name;
3811 // };
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003812
3813 // First the clang type for struct _message_ref_t
3814 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3815 SourceLocation(),
3816 &Ctx.Idents.get("_message_ref_t"));
Douglas Gregor6ab35242009-04-09 21:40:53 +00003817 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3818 Ctx.VoidPtrTy, 0, false));
3819 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3820 Ctx.getObjCSelType(), 0, false));
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003821 RD->completeDefinition(Ctx);
3822
3823 MessageRefCTy = Ctx.getTagDeclType(RD);
3824 MessageRefCPtrTy = Ctx.getPointerType(MessageRefCTy);
3825 MessageRefTy = cast<llvm::StructType>(Types.ConvertType(MessageRefCTy));
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003826
3827 // MessageRefPtrTy - LLVM for struct _message_ref_t*
3828 MessageRefPtrTy = llvm::PointerType::getUnqual(MessageRefTy);
3829
3830 // SuperMessageRefTy - LLVM for:
3831 // struct _super_message_ref_t {
3832 // SUPER_IMP messenger;
3833 // SEL name;
3834 // };
3835 SuperMessageRefTy = llvm::StructType::get(ImpnfABITy,
3836 SelectorPtrTy,
3837 NULL);
3838 CGM.getModule().addTypeName("struct._super_message_ref_t", SuperMessageRefTy);
3839
3840 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
3841 SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy);
3842
3843 // id objc_msgSend_fixup (id, struct message_ref_t*, ...)
3844 Params.clear();
3845 Params.push_back(ObjectPtrTy);
3846 Params.push_back(MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00003847 MessengerTy = llvm::FunctionType::get(ObjectPtrTy,
3848 Params,
3849 true);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003850 MessageSendFixupFn =
Fariborz Jahanianef163782009-02-05 01:13:09 +00003851 CGM.CreateRuntimeFunction(MessengerTy,
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003852 "objc_msgSend_fixup");
3853
3854 // id objc_msgSend_fpret_fixup (id, struct message_ref_t*, ...)
3855 MessageSendFpretFixupFn =
3856 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3857 Params,
3858 true),
3859 "objc_msgSend_fpret_fixup");
3860
3861 // id objc_msgSend_stret_fixup (id, struct message_ref_t*, ...)
3862 MessageSendStretFixupFn =
3863 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3864 Params,
3865 true),
3866 "objc_msgSend_stret_fixup");
3867
3868 // id objc_msgSendId_fixup (id, struct message_ref_t*, ...)
3869 MessageSendIdFixupFn =
3870 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3871 Params,
3872 true),
3873 "objc_msgSendId_fixup");
3874
3875
3876 // id objc_msgSendId_stret_fixup (id, struct message_ref_t*, ...)
3877 MessageSendIdStretFixupFn =
3878 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3879 Params,
3880 true),
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003881 "objc_msgSendId_stret_fixup");
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003882
3883 // id objc_msgSendSuper2_fixup (struct objc_super *,
3884 // struct _super_message_ref_t*, ...)
3885 Params.clear();
3886 Params.push_back(SuperPtrTy);
3887 Params.push_back(SuperMessageRefPtrTy);
3888 MessageSendSuper2FixupFn =
3889 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3890 Params,
3891 true),
3892 "objc_msgSendSuper2_fixup");
3893
3894
3895 // id objc_msgSendSuper2_stret_fixup (struct objc_super *,
3896 // struct _super_message_ref_t*, ...)
3897 MessageSendSuper2StretFixupFn =
3898 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3899 Params,
3900 true),
3901 "objc_msgSendSuper2_stret_fixup");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00003902
3903 Params.clear();
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00003904 Params.push_back(Int8PtrTy);
3905 UnwindResumeOrRethrowFn =
3906 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3907 Params,
3908 false),
3909 "_Unwind_Resume_or_Rethrow");
Daniel Dunbare588b992009-03-01 04:46:24 +00003910 ObjCBeginCatchFn =
3911 CGM.CreateRuntimeFunction(llvm::FunctionType::get(Int8PtrTy,
3912 Params,
3913 false),
3914 "objc_begin_catch");
3915
3916 Params.clear();
3917 ObjCEndCatchFn =
3918 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3919 Params,
3920 false),
3921 "objc_end_catch");
3922
3923 // struct objc_typeinfo {
3924 // const void** vtable; // objc_ehtype_vtable + 2
3925 // const char* name; // c++ typeinfo string
3926 // Class cls;
3927 // };
3928 EHTypeTy = llvm::StructType::get(llvm::PointerType::getUnqual(Int8PtrTy),
3929 Int8PtrTy,
3930 ClassnfABIPtrTy,
3931 NULL);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00003932 CGM.getModule().addTypeName("struct._objc_typeinfo", EHTypeTy);
Daniel Dunbare588b992009-03-01 04:46:24 +00003933 EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy);
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003934}
3935
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003936llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() {
3937 FinishNonFragileABIModule();
3938
3939 return NULL;
3940}
3941
3942void CGObjCNonFragileABIMac::FinishNonFragileABIModule() {
3943 // nonfragile abi has no module definition.
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003944
3945 // Build list of all implemented classe addresses in array
3946 // L_OBJC_LABEL_CLASS_$.
3947 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CLASS_$
3948 // list of 'nonlazy' implementations (defined as those with a +load{}
3949 // method!!).
3950 unsigned NumClasses = DefinedClasses.size();
3951 if (NumClasses) {
3952 std::vector<llvm::Constant*> Symbols(NumClasses);
3953 for (unsigned i=0; i<NumClasses; i++)
3954 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
3955 ObjCTypes.Int8PtrTy);
3956 llvm::Constant* Init =
3957 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
3958 NumClasses),
3959 Symbols);
3960
3961 llvm::GlobalVariable *GV =
3962 new llvm::GlobalVariable(Init->getType(), false,
3963 llvm::GlobalValue::InternalLinkage,
3964 Init,
3965 "\01L_OBJC_LABEL_CLASS_$",
3966 &CGM.getModule());
Daniel Dunbar58a29122009-03-09 22:18:41 +00003967 GV->setAlignment(8);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003968 GV->setSection("__DATA, __objc_classlist, regular, no_dead_strip");
3969 UsedGlobals.push_back(GV);
3970 }
3971
3972 // Build list of all implemented category addresses in array
3973 // L_OBJC_LABEL_CATEGORY_$.
3974 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CATEGORY_$
3975 // list of 'nonlazy' category implementations (defined as those with a +load{}
3976 // method!!).
3977 unsigned NumCategory = DefinedCategories.size();
3978 if (NumCategory) {
3979 std::vector<llvm::Constant*> Symbols(NumCategory);
3980 for (unsigned i=0; i<NumCategory; i++)
3981 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedCategories[i],
3982 ObjCTypes.Int8PtrTy);
3983 llvm::Constant* Init =
3984 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
3985 NumCategory),
3986 Symbols);
3987
3988 llvm::GlobalVariable *GV =
3989 new llvm::GlobalVariable(Init->getType(), false,
3990 llvm::GlobalValue::InternalLinkage,
3991 Init,
3992 "\01L_OBJC_LABEL_CATEGORY_$",
3993 &CGM.getModule());
Daniel Dunbar58a29122009-03-09 22:18:41 +00003994 GV->setAlignment(8);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003995 GV->setSection("__DATA, __objc_catlist, regular, no_dead_strip");
3996 UsedGlobals.push_back(GV);
3997 }
3998
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00003999 // static int L_OBJC_IMAGE_INFO[2] = { 0, flags };
4000 // FIXME. flags can be 0 | 1 | 2 | 6. For now just use 0
4001 std::vector<llvm::Constant*> Values(2);
4002 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, 0);
Fariborz Jahanian067986e2009-02-24 21:08:09 +00004003 unsigned int flags = 0;
Fariborz Jahanian66a5c2c2009-02-24 23:34:44 +00004004 // FIXME: Fix and continue?
4005 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
4006 flags |= eImageInfo_GarbageCollected;
4007 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
4008 flags |= eImageInfo_GCOnly;
Fariborz Jahanian067986e2009-02-24 21:08:09 +00004009 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004010 llvm::Constant* Init = llvm::ConstantArray::get(
4011 llvm::ArrayType::get(ObjCTypes.IntTy, 2),
4012 Values);
4013 llvm::GlobalVariable *IMGV =
4014 new llvm::GlobalVariable(Init->getType(), false,
4015 llvm::GlobalValue::InternalLinkage,
4016 Init,
4017 "\01L_OBJC_IMAGE_INFO",
4018 &CGM.getModule());
4019 IMGV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
4020 UsedGlobals.push_back(IMGV);
4021
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004022 std::vector<llvm::Constant*> Used;
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004023
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004024 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
4025 e = UsedGlobals.end(); i != e; ++i) {
4026 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
4027 }
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004028
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004029 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
4030 llvm::GlobalValue *GV =
4031 new llvm::GlobalVariable(AT, false,
4032 llvm::GlobalValue::AppendingLinkage,
4033 llvm::ConstantArray::get(AT, Used),
4034 "llvm.used",
4035 &CGM.getModule());
4036
4037 GV->setSection("llvm.metadata");
4038
4039}
4040
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004041// Metadata flags
4042enum MetaDataDlags {
4043 CLS = 0x0,
4044 CLS_META = 0x1,
4045 CLS_ROOT = 0x2,
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004046 OBJC2_CLS_HIDDEN = 0x10,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004047 CLS_EXCEPTION = 0x20
4048};
4049/// BuildClassRoTInitializer - generate meta-data for:
4050/// struct _class_ro_t {
4051/// uint32_t const flags;
4052/// uint32_t const instanceStart;
4053/// uint32_t const instanceSize;
4054/// uint32_t const reserved; // only when building for 64bit targets
4055/// const uint8_t * const ivarLayout;
4056/// const char *const name;
4057/// const struct _method_list_t * const baseMethods;
Fariborz Jahanianda320092009-01-29 19:24:30 +00004058/// const struct _protocol_list_t *const baseProtocols;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004059/// const struct _ivar_list_t *const ivars;
4060/// const uint8_t * const weakIvarLayout;
4061/// const struct _prop_list_t * const properties;
4062/// }
4063///
4064llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer(
4065 unsigned flags,
4066 unsigned InstanceStart,
4067 unsigned InstanceSize,
4068 const ObjCImplementationDecl *ID) {
4069 std::string ClassName = ID->getNameAsString();
4070 std::vector<llvm::Constant*> Values(10); // 11 for 64bit targets!
4071 Values[ 0] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
4072 Values[ 1] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceStart);
4073 Values[ 2] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceSize);
4074 // FIXME. For 64bit targets add 0 here.
Fariborz Jahanianda320092009-01-29 19:24:30 +00004075 // FIXME. ivarLayout is currently null!
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00004076 Values[ 3] = GetIvarLayoutName(0, ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004077 Values[ 4] = GetClassName(ID->getIdentifier());
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004078 // const struct _method_list_t * const baseMethods;
4079 std::vector<llvm::Constant*> Methods;
4080 std::string MethodListName("\01l_OBJC_$_");
4081 if (flags & CLS_META) {
4082 MethodListName += "CLASS_METHODS_" + ID->getNameAsString();
4083 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
4084 e = ID->classmeth_end(); i != e; ++i) {
4085 // Class methods should always be defined.
4086 Methods.push_back(GetMethodConstant(*i));
4087 }
4088 } else {
4089 MethodListName += "INSTANCE_METHODS_" + ID->getNameAsString();
4090 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
4091 e = ID->instmeth_end(); i != e; ++i) {
4092 // Instance methods should always be defined.
4093 Methods.push_back(GetMethodConstant(*i));
4094 }
Fariborz Jahanian939abce2009-01-28 22:46:49 +00004095 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
4096 e = ID->propimpl_end(); i != e; ++i) {
4097 ObjCPropertyImplDecl *PID = *i;
4098
4099 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize){
4100 ObjCPropertyDecl *PD = PID->getPropertyDecl();
4101
4102 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
4103 if (llvm::Constant *C = GetMethodConstant(MD))
4104 Methods.push_back(C);
4105 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
4106 if (llvm::Constant *C = GetMethodConstant(MD))
4107 Methods.push_back(C);
4108 }
4109 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004110 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004111 Values[ 5] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004112 "__DATA, __objc_const", Methods);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004113
4114 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4115 assert(OID && "CGObjCNonFragileABIMac::BuildClassRoTInitializer");
4116 Values[ 6] = EmitProtocolList("\01l_OBJC_CLASS_PROTOCOLS_$_"
4117 + OID->getNameAsString(),
4118 OID->protocol_begin(),
4119 OID->protocol_end());
4120
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004121 if (flags & CLS_META)
4122 Values[ 7] = llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4123 else
4124 Values[ 7] = EmitIvarList(ID);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004125 // FIXME. weakIvarLayout is currently null.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00004126 Values[ 8] = GetIvarLayoutName(0, ObjCTypes);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004127 if (flags & CLS_META)
4128 Values[ 9] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4129 else
4130 Values[ 9] =
4131 EmitPropertyList(
4132 "\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
4133 ID, ID->getClassInterface(), ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004134 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassRonfABITy,
4135 Values);
4136 llvm::GlobalVariable *CLASS_RO_GV =
4137 new llvm::GlobalVariable(ObjCTypes.ClassRonfABITy, false,
4138 llvm::GlobalValue::InternalLinkage,
4139 Init,
4140 (flags & CLS_META) ?
4141 std::string("\01l_OBJC_METACLASS_RO_$_")+ClassName :
4142 std::string("\01l_OBJC_CLASS_RO_$_")+ClassName,
4143 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004144 CLASS_RO_GV->setAlignment(
4145 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassRonfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004146 CLASS_RO_GV->setSection("__DATA, __objc_const");
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004147 return CLASS_RO_GV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004148
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004149}
4150
4151/// BuildClassMetaData - This routine defines that to-level meta-data
4152/// for the given ClassName for:
4153/// struct _class_t {
4154/// struct _class_t *isa;
4155/// struct _class_t * const superclass;
4156/// void *cache;
4157/// IMP *vtable;
4158/// struct class_ro_t *ro;
4159/// }
4160///
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004161llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassMetaData(
4162 std::string &ClassName,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004163 llvm::Constant *IsAGV,
4164 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004165 llvm::Constant *ClassRoGV,
4166 bool HiddenVisibility) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004167 std::vector<llvm::Constant*> Values(5);
4168 Values[0] = IsAGV;
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004169 Values[1] = SuperClassGV
4170 ? SuperClassGV
4171 : llvm::Constant::getNullValue(ObjCTypes.ClassnfABIPtrTy);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004172 Values[2] = ObjCEmptyCacheVar; // &ObjCEmptyCacheVar
4173 Values[3] = ObjCEmptyVtableVar; // &ObjCEmptyVtableVar
4174 Values[4] = ClassRoGV; // &CLASS_RO_GV
4175 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassnfABITy,
4176 Values);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004177 llvm::GlobalVariable *GV = GetClassGlobal(ClassName);
4178 GV->setInitializer(Init);
Fariborz Jahaniandd0db2a2009-01-31 01:07:39 +00004179 GV->setSection("__DATA, __objc_data");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004180 GV->setAlignment(
4181 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassnfABITy));
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004182 if (HiddenVisibility)
4183 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004184 return GV;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004185}
4186
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004187void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) {
4188 std::string ClassName = ID->getNameAsString();
4189 if (!ObjCEmptyCacheVar) {
4190 ObjCEmptyCacheVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004191 ObjCTypes.CacheTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004192 false,
4193 llvm::GlobalValue::ExternalLinkage,
4194 0,
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004195 "_objc_empty_cache",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004196 &CGM.getModule());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004197
4198 ObjCEmptyVtableVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004199 ObjCTypes.ImpnfABITy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004200 false,
4201 llvm::GlobalValue::ExternalLinkage,
4202 0,
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004203 "_objc_empty_vtable",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004204 &CGM.getModule());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004205 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004206 assert(ID->getClassInterface() &&
4207 "CGObjCNonFragileABIMac::GenerateClass - class is 0");
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004208 uint32_t InstanceStart =
4209 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassnfABITy);
4210 uint32_t InstanceSize = InstanceStart;
4211 uint32_t flags = CLS_META;
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004212 std::string ObjCMetaClassName(getMetaclassSymbolPrefix());
4213 std::string ObjCClassName(getClassSymbolPrefix());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004214
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004215 llvm::GlobalVariable *SuperClassGV, *IsAGV;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004216
Daniel Dunbar04d40782009-04-14 06:00:08 +00004217 bool classIsHidden =
4218 CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004219 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004220 flags |= OBJC2_CLS_HIDDEN;
4221 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004222 // class is root
4223 flags |= CLS_ROOT;
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004224 SuperClassGV = GetClassGlobal(ObjCClassName + ClassName);
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004225 IsAGV = GetClassGlobal(ObjCMetaClassName + ClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004226 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004227 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004228 const ObjCInterfaceDecl *Root = ID->getClassInterface();
4229 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
4230 Root = Super;
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004231 IsAGV = GetClassGlobal(ObjCMetaClassName + Root->getNameAsString());
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004232 // work on super class metadata symbol.
4233 std::string SuperClassName =
4234 ObjCMetaClassName + ID->getClassInterface()->getSuperClass()->getNameAsString();
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004235 SuperClassGV = GetClassGlobal(SuperClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004236 }
4237 llvm::GlobalVariable *CLASS_RO_GV = BuildClassRoTInitializer(flags,
4238 InstanceStart,
4239 InstanceSize,ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004240 std::string TClassName = ObjCMetaClassName + ClassName;
4241 llvm::GlobalVariable *MetaTClass =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004242 BuildClassMetaData(TClassName, IsAGV, SuperClassGV, CLASS_RO_GV,
4243 classIsHidden);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004244
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004245 // Metadata for the class
4246 flags = CLS;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004247 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004248 flags |= OBJC2_CLS_HIDDEN;
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004249
4250 if (hasObjCExceptionAttribute(ID->getClassInterface()))
4251 flags |= CLS_EXCEPTION;
4252
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004253 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004254 flags |= CLS_ROOT;
4255 SuperClassGV = 0;
4256 }
4257 else {
4258 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004259 std::string RootClassName =
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004260 ID->getClassInterface()->getSuperClass()->getNameAsString();
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004261 SuperClassGV = GetClassGlobal(ObjCClassName + RootClassName);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004262 }
Fariborz Jahanianebf9ed32009-03-20 20:48:19 +00004263 // FIXME: Gross
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004264 InstanceStart = InstanceSize = 0;
4265 if (ObjCInterfaceDecl *OID =
4266 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface())) {
4267 // FIXME. Share this with the one in EmitIvarList.
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00004268 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID);
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004269
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00004270 RecordDecl::field_iterator firstField, lastField;
4271 const RecordDecl *RD = GetFirstIvarInRecord(OID, firstField, lastField);
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004272
Douglas Gregor6ab35242009-04-09 21:40:53 +00004273 for (RecordDecl::field_iterator e = RD->field_end(CGM.getContext()),
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004274 ifield = firstField; ifield != e; ++ifield)
4275 lastField = ifield;
4276
Douglas Gregor6ab35242009-04-09 21:40:53 +00004277 if (lastField != RD->field_end(CGM.getContext())) {
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004278 FieldDecl *Field = *lastField;
4279 const llvm::Type *FieldTy =
4280 CGM.getTypes().ConvertTypeForMem(Field->getType());
4281 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00004282 InstanceSize = GetIvarBaseOffset(Layout, Field) + Size;
Douglas Gregor6ab35242009-04-09 21:40:53 +00004283 if (firstField == RD->field_end(CGM.getContext()))
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004284 InstanceStart = InstanceSize;
Fariborz Jahanian11894a42009-03-07 19:43:20 +00004285 else {
4286 Field = *firstField;
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00004287 InstanceStart = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanian11894a42009-03-07 19:43:20 +00004288 }
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004289 }
4290 }
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004291 CLASS_RO_GV = BuildClassRoTInitializer(flags,
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004292 InstanceStart,
4293 InstanceSize,
4294 ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004295
4296 TClassName = ObjCClassName + ClassName;
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004297 llvm::GlobalVariable *ClassMD =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004298 BuildClassMetaData(TClassName, MetaTClass, SuperClassGV, CLASS_RO_GV,
4299 classIsHidden);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004300 DefinedClasses.push_back(ClassMD);
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004301
4302 // Force the definition of the EHType if necessary.
4303 if (flags & CLS_EXCEPTION)
4304 GetInterfaceEHType(ID->getClassInterface(), true);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004305}
4306
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004307/// GenerateProtocolRef - This routine is called to generate code for
4308/// a protocol reference expression; as in:
4309/// @code
4310/// @protocol(Proto1);
4311/// @endcode
4312/// It generates a weak reference to l_OBJC_PROTOCOL_REFERENCE_$_Proto1
4313/// which will hold address of the protocol meta-data.
4314///
4315llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CGBuilderTy &Builder,
4316 const ObjCProtocolDecl *PD) {
4317
Fariborz Jahanian960cd062009-04-10 18:47:34 +00004318 // This routine is called for @protocol only. So, we must build definition
4319 // of protocol's meta-data (not a reference to it!)
4320 //
4321 llvm::Constant *Init = llvm::ConstantExpr::getBitCast(GetOrEmitProtocol(PD),
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004322 ObjCTypes.ExternalProtocolPtrTy);
4323
4324 std::string ProtocolName("\01l_OBJC_PROTOCOL_REFERENCE_$_");
4325 ProtocolName += PD->getNameAsCString();
4326
4327 llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName);
4328 if (PTGV)
4329 return Builder.CreateLoad(PTGV, false, "tmp");
4330 PTGV = new llvm::GlobalVariable(
4331 Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00004332 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004333 Init,
4334 ProtocolName,
4335 &CGM.getModule());
4336 PTGV->setSection("__DATA, __objc_protorefs, coalesced, no_dead_strip");
4337 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4338 UsedGlobals.push_back(PTGV);
4339 return Builder.CreateLoad(PTGV, false, "tmp");
4340}
4341
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004342/// GenerateCategory - Build metadata for a category implementation.
4343/// struct _category_t {
4344/// const char * const name;
4345/// struct _class_t *const cls;
4346/// const struct _method_list_t * const instance_methods;
4347/// const struct _method_list_t * const class_methods;
4348/// const struct _protocol_list_t * const protocols;
4349/// const struct _prop_list_t * const properties;
4350/// }
4351///
4352void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD)
4353{
4354 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004355 const char *Prefix = "\01l_OBJC_$_CATEGORY_";
4356 std::string ExtCatName(Prefix + Interface->getNameAsString()+
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004357 "_$_" + OCD->getNameAsString());
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004358 std::string ExtClassName(getClassSymbolPrefix() +
4359 Interface->getNameAsString());
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004360
4361 std::vector<llvm::Constant*> Values(6);
4362 Values[0] = GetClassName(OCD->getIdentifier());
4363 // meta-class entry symbol
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004364 llvm::GlobalVariable *ClassGV = GetClassGlobal(ExtClassName);
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004365 Values[1] = ClassGV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004366 std::vector<llvm::Constant*> Methods;
4367 std::string MethodListName(Prefix);
4368 MethodListName += "INSTANCE_METHODS_" + Interface->getNameAsString() +
4369 "_$_" + OCD->getNameAsString();
4370
4371 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
4372 e = OCD->instmeth_end(); i != e; ++i) {
4373 // Instance methods should always be defined.
4374 Methods.push_back(GetMethodConstant(*i));
4375 }
4376
4377 Values[2] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004378 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004379 Methods);
4380
4381 MethodListName = Prefix;
4382 MethodListName += "CLASS_METHODS_" + Interface->getNameAsString() + "_$_" +
4383 OCD->getNameAsString();
4384 Methods.clear();
4385 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
4386 e = OCD->classmeth_end(); i != e; ++i) {
4387 // Class methods should always be defined.
4388 Methods.push_back(GetMethodConstant(*i));
4389 }
4390
4391 Values[3] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004392 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004393 Methods);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004394 const ObjCCategoryDecl *Category =
4395 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Fariborz Jahanian943ed6f2009-02-13 17:52:22 +00004396 if (Category) {
4397 std::string ExtName(Interface->getNameAsString() + "_$_" +
4398 OCD->getNameAsString());
4399 Values[4] = EmitProtocolList("\01l_OBJC_CATEGORY_PROTOCOLS_$_"
4400 + Interface->getNameAsString() + "_$_"
4401 + Category->getNameAsString(),
4402 Category->protocol_begin(),
4403 Category->protocol_end());
4404 Values[5] =
4405 EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
4406 OCD, Category, ObjCTypes);
4407 }
4408 else {
4409 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4410 Values[5] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4411 }
4412
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004413 llvm::Constant *Init =
4414 llvm::ConstantStruct::get(ObjCTypes.CategorynfABITy,
4415 Values);
4416 llvm::GlobalVariable *GCATV
4417 = new llvm::GlobalVariable(ObjCTypes.CategorynfABITy,
4418 false,
4419 llvm::GlobalValue::InternalLinkage,
4420 Init,
4421 ExtCatName,
4422 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004423 GCATV->setAlignment(
4424 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.CategorynfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004425 GCATV->setSection("__DATA, __objc_const");
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004426 UsedGlobals.push_back(GCATV);
4427 DefinedCategories.push_back(GCATV);
4428}
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004429
4430/// GetMethodConstant - Return a struct objc_method constant for the
4431/// given method if it has been defined. The result is null if the
4432/// method has not been defined. The return value has type MethodPtrTy.
4433llvm::Constant *CGObjCNonFragileABIMac::GetMethodConstant(
4434 const ObjCMethodDecl *MD) {
4435 // FIXME: Use DenseMap::lookup
4436 llvm::Function *Fn = MethodDefinitions[MD];
4437 if (!Fn)
4438 return 0;
4439
4440 std::vector<llvm::Constant*> Method(3);
4441 Method[0] =
4442 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4443 ObjCTypes.SelectorPtrTy);
4444 Method[1] = GetMethodVarType(MD);
4445 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
4446 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
4447}
4448
4449/// EmitMethodList - Build meta-data for method declarations
4450/// struct _method_list_t {
4451/// uint32_t entsize; // sizeof(struct _objc_method)
4452/// uint32_t method_count;
4453/// struct _objc_method method_list[method_count];
4454/// }
4455///
4456llvm::Constant *CGObjCNonFragileABIMac::EmitMethodList(
4457 const std::string &Name,
4458 const char *Section,
4459 const ConstantVector &Methods) {
4460 // Return null for empty list.
4461 if (Methods.empty())
4462 return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy);
4463
4464 std::vector<llvm::Constant*> Values(3);
4465 // sizeof(struct _objc_method)
4466 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.MethodTy);
4467 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4468 // method_count
4469 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
4470 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
4471 Methods.size());
4472 Values[2] = llvm::ConstantArray::get(AT, Methods);
4473 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4474
4475 llvm::GlobalVariable *GV =
4476 new llvm::GlobalVariable(Init->getType(), false,
4477 llvm::GlobalValue::InternalLinkage,
4478 Init,
4479 Name,
4480 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004481 GV->setAlignment(
4482 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004483 GV->setSection(Section);
4484 UsedGlobals.push_back(GV);
4485 return llvm::ConstantExpr::getBitCast(GV,
4486 ObjCTypes.MethodListnfABIPtrTy);
4487}
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004488
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004489/// ObjCIvarOffsetVariable - Returns the ivar offset variable for
4490/// the given ivar.
4491///
4492llvm::GlobalVariable * CGObjCNonFragileABIMac::ObjCIvarOffsetVariable(
4493 std::string &Name,
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004494 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004495 const ObjCIvarDecl *Ivar) {
Daniel Dunbardd131982009-04-14 22:44:26 +00004496 Name += "OBJC_IVAR_$_" +
Douglas Gregor6ab35242009-04-09 21:40:53 +00004497 getInterfaceDeclForIvar(ID, Ivar, CGM.getContext())->getNameAsString() +
4498 '.' + Ivar->getNameAsString();
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004499 llvm::GlobalVariable *IvarOffsetGV =
4500 CGM.getModule().getGlobalVariable(Name);
4501 if (!IvarOffsetGV)
4502 IvarOffsetGV =
4503 new llvm::GlobalVariable(ObjCTypes.LongTy,
4504 false,
4505 llvm::GlobalValue::ExternalLinkage,
4506 0,
4507 Name,
4508 &CGM.getModule());
4509 return IvarOffsetGV;
4510}
4511
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004512llvm::Constant * CGObjCNonFragileABIMac::EmitIvarOffsetVar(
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004513 const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004514 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004515 unsigned long int Offset) {
4516
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004517 assert(ID && "EmitIvarOffsetVar - null interface decl.");
Daniel Dunbar7595fb12009-04-15 19:52:32 +00004518 std::string ExternalName("OBJC_IVAR_$_" + ID->getNameAsString() + '.'
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004519 + Ivar->getNameAsString());
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004520 llvm::Constant *Init = llvm::ConstantInt::get(ObjCTypes.LongTy, Offset);
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004521 llvm::GlobalVariable *IvarOffsetGV =
4522 CGM.getModule().getGlobalVariable(ExternalName);
Fariborz Jahanian77c9fd22009-04-06 18:30:00 +00004523 if (IvarOffsetGV)
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004524 // ivar offset symbol already built due to user code referencing it.
4525 IvarOffsetGV->setInitializer(Init);
Fariborz Jahanian77c9fd22009-04-06 18:30:00 +00004526 else
4527 IvarOffsetGV =
4528 new llvm::GlobalVariable(Init->getType(),
4529 false,
4530 llvm::GlobalValue::ExternalLinkage,
4531 Init,
4532 ExternalName,
4533 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004534 IvarOffsetGV->setAlignment(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004535 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.LongTy));
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004536 // @private and @package have hidden visibility.
4537 bool globalVisibility = (Ivar->getAccessControl() == ObjCIvarDecl::Public ||
Daniel Dunbar04d40782009-04-14 06:00:08 +00004538 Ivar->getAccessControl() == ObjCIvarDecl::Protected);
4539 if (!globalVisibility || CGM.getDeclVisibilityMode(ID) == LangOptions::Hidden)
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004540 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar04d40782009-04-14 06:00:08 +00004541 else
Fariborz Jahanian77c9fd22009-04-06 18:30:00 +00004542 IvarOffsetGV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004543 IvarOffsetGV->setSection("__DATA, __objc_const");
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004544 return IvarOffsetGV;
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004545}
4546
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004547/// EmitIvarList - Emit the ivar list for the given
4548/// implementation. If ForClass is true the list of class ivars
4549/// (i.e. metaclass ivars) is emitted, otherwise the list of
4550/// interface ivars will be emitted. The return value has type
4551/// IvarListnfABIPtrTy.
4552/// struct _ivar_t {
4553/// unsigned long int *offset; // pointer to ivar offset location
4554/// char *name;
4555/// char *type;
4556/// uint32_t alignment;
4557/// uint32_t size;
4558/// }
4559/// struct _ivar_list_t {
4560/// uint32 entsize; // sizeof(struct _ivar_t)
4561/// uint32 count;
4562/// struct _iver_t list[count];
4563/// }
4564///
4565llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList(
4566 const ObjCImplementationDecl *ID) {
4567
4568 std::vector<llvm::Constant*> Ivars, Ivar(5);
4569
4570 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4571 assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface");
4572
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004573 // FIXME. Consolidate this with similar code in GenerateClass.
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00004574 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00004575
4576 RecordDecl::field_iterator i,p;
4577 const RecordDecl *RD = GetFirstIvarInRecord(OID, i,p);
Fariborz Jahanian18191882009-03-31 18:11:23 +00004578 // collect declared and synthesized ivars in a small vector.
4579 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
4580 for (ObjCInterfaceDecl::ivar_iterator I = OID->ivar_begin(),
4581 E = OID->ivar_end(); I != E; ++I)
4582 OIvars.push_back(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +00004583 for (ObjCInterfaceDecl::prop_iterator I = OID->prop_begin(CGM.getContext()),
4584 E = OID->prop_end(CGM.getContext()); I != E; ++I)
Fariborz Jahanian18191882009-03-31 18:11:23 +00004585 if (ObjCIvarDecl *IV = (*I)->getPropertyIvarDecl())
4586 OIvars.push_back(IV);
Fariborz Jahanian99eee362009-04-01 19:37:34 +00004587
Fariborz Jahanian18191882009-03-31 18:11:23 +00004588 unsigned iv = 0;
Douglas Gregor6ab35242009-04-09 21:40:53 +00004589 for (RecordDecl::field_iterator e = RD->field_end(CGM.getContext());
4590 i != e; ++i) {
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004591 FieldDecl *Field = *i;
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00004592 uint64_t offset = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanian18191882009-03-31 18:11:23 +00004593 Ivar[0] = EmitIvarOffsetVar(ID->getClassInterface(), OIvars[iv++], offset);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004594 if (Field->getIdentifier())
4595 Ivar[1] = GetMethodVarName(Field->getIdentifier());
4596 else
4597 Ivar[1] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Devang Patel7794bb82009-03-04 18:21:39 +00004598 Ivar[2] = GetMethodVarType(Field);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004599 const llvm::Type *FieldTy =
4600 CGM.getTypes().ConvertTypeForMem(Field->getType());
4601 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
4602 unsigned Align = CGM.getContext().getPreferredTypeAlign(
4603 Field->getType().getTypePtr()) >> 3;
4604 Align = llvm::Log2_32(Align);
4605 Ivar[3] = llvm::ConstantInt::get(ObjCTypes.IntTy, Align);
Fariborz Jahanian07236ba2009-01-27 22:27:56 +00004606 // NOTE. Size of a bitfield does not match gcc's, because of the way
4607 // bitfields are treated special in each. But I am told that 'size'
4608 // for bitfield ivars is ignored by the runtime so it does not matter.
4609 // (even if it matters, some day, there is enough info. to get the bitfield
4610 // right!
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004611 Ivar[4] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4612 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarnfABITy, Ivar));
4613 }
4614 // Return null for empty list.
4615 if (Ivars.empty())
4616 return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4617 std::vector<llvm::Constant*> Values(3);
4618 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.IvarnfABITy);
4619 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4620 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
4621 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarnfABITy,
4622 Ivars.size());
4623 Values[2] = llvm::ConstantArray::get(AT, Ivars);
4624 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4625 const char *Prefix = "\01l_OBJC_$_INSTANCE_VARIABLES_";
4626 llvm::GlobalVariable *GV =
4627 new llvm::GlobalVariable(Init->getType(), false,
4628 llvm::GlobalValue::InternalLinkage,
4629 Init,
4630 Prefix + OID->getNameAsString(),
4631 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004632 GV->setAlignment(
4633 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004634 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004635
4636 UsedGlobals.push_back(GV);
4637 return llvm::ConstantExpr::getBitCast(GV,
4638 ObjCTypes.IvarListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004639}
4640
4641llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef(
4642 const ObjCProtocolDecl *PD) {
4643 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4644
4645 if (!Entry) {
4646 // We use the initializer as a marker of whether this is a forward
4647 // reference or not. At module finalization we add the empty
4648 // contents for protocols which were referenced but never defined.
4649 Entry =
4650 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
4651 llvm::GlobalValue::ExternalLinkage,
4652 0,
4653 "\01l_OBJC_PROTOCOL_$_" + PD->getNameAsString(),
4654 &CGM.getModule());
4655 Entry->setSection("__DATA,__datacoal_nt,coalesced");
4656 UsedGlobals.push_back(Entry);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004657 }
4658
4659 return Entry;
4660}
4661
4662/// GetOrEmitProtocol - Generate the protocol meta-data:
4663/// @code
4664/// struct _protocol_t {
4665/// id isa; // NULL
4666/// const char * const protocol_name;
4667/// const struct _protocol_list_t * protocol_list; // super protocols
4668/// const struct method_list_t * const instance_methods;
4669/// const struct method_list_t * const class_methods;
4670/// const struct method_list_t *optionalInstanceMethods;
4671/// const struct method_list_t *optionalClassMethods;
4672/// const struct _prop_list_t * properties;
4673/// const uint32_t size; // sizeof(struct _protocol_t)
4674/// const uint32_t flags; // = 0
4675/// }
4676/// @endcode
4677///
4678
4679llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol(
4680 const ObjCProtocolDecl *PD) {
4681 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4682
4683 // Early exit if a defining object has already been generated.
4684 if (Entry && Entry->hasInitializer())
4685 return Entry;
4686
4687 const char *ProtocolName = PD->getNameAsCString();
4688
4689 // Construct method lists.
4690 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
4691 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregor6ab35242009-04-09 21:40:53 +00004692 for (ObjCProtocolDecl::instmeth_iterator
4693 i = PD->instmeth_begin(CGM.getContext()),
4694 e = PD->instmeth_end(CGM.getContext());
4695 i != e; ++i) {
Fariborz Jahanianda320092009-01-29 19:24:30 +00004696 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004697 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004698 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4699 OptInstanceMethods.push_back(C);
4700 } else {
4701 InstanceMethods.push_back(C);
4702 }
4703 }
4704
Douglas Gregor6ab35242009-04-09 21:40:53 +00004705 for (ObjCProtocolDecl::classmeth_iterator
4706 i = PD->classmeth_begin(CGM.getContext()),
4707 e = PD->classmeth_end(CGM.getContext());
4708 i != e; ++i) {
Fariborz Jahanianda320092009-01-29 19:24:30 +00004709 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004710 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004711 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4712 OptClassMethods.push_back(C);
4713 } else {
4714 ClassMethods.push_back(C);
4715 }
4716 }
4717
4718 std::vector<llvm::Constant*> Values(10);
4719 // isa is NULL
4720 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ObjectPtrTy);
4721 Values[1] = GetClassName(PD->getIdentifier());
4722 Values[2] = EmitProtocolList(
4723 "\01l_OBJC_$_PROTOCOL_REFS_" + PD->getNameAsString(),
4724 PD->protocol_begin(),
4725 PD->protocol_end());
4726
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004727 Values[3] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004728 + PD->getNameAsString(),
4729 "__DATA, __objc_const",
4730 InstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004731 Values[4] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004732 + PD->getNameAsString(),
4733 "__DATA, __objc_const",
4734 ClassMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004735 Values[5] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004736 + PD->getNameAsString(),
4737 "__DATA, __objc_const",
4738 OptInstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004739 Values[6] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004740 + PD->getNameAsString(),
4741 "__DATA, __objc_const",
4742 OptClassMethods);
4743 Values[7] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + PD->getNameAsString(),
4744 0, PD, ObjCTypes);
4745 uint32_t Size =
4746 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolnfABITy);
4747 Values[8] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4748 Values[9] = llvm::Constant::getNullValue(ObjCTypes.IntTy);
4749 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolnfABITy,
4750 Values);
4751
4752 if (Entry) {
4753 // Already created, fix the linkage and update the initializer.
Mike Stump286acbd2009-03-07 16:33:28 +00004754 Entry->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004755 Entry->setInitializer(Init);
4756 } else {
4757 Entry =
4758 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004759 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004760 Init,
4761 std::string("\01l_OBJC_PROTOCOL_$_")+ProtocolName,
4762 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004763 Entry->setAlignment(
4764 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABITy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004765 Entry->setSection("__DATA,__datacoal_nt,coalesced");
Fariborz Jahanianda320092009-01-29 19:24:30 +00004766 }
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004767 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
4768
4769 // Use this protocol meta-data to build protocol list table in section
4770 // __DATA, __objc_protolist
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004771 llvm::GlobalVariable *PTGV = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004772 ObjCTypes.ProtocolnfABIPtrTy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004773 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004774 Entry,
4775 std::string("\01l_OBJC_LABEL_PROTOCOL_$_")
4776 +ProtocolName,
4777 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004778 PTGV->setAlignment(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004779 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABIPtrTy));
Daniel Dunbar0bf21992009-04-15 02:56:18 +00004780 PTGV->setSection("__DATA, __objc_protolist, coalesced, no_dead_strip");
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004781 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4782 UsedGlobals.push_back(PTGV);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004783 return Entry;
4784}
4785
4786/// EmitProtocolList - Generate protocol list meta-data:
4787/// @code
4788/// struct _protocol_list_t {
4789/// long protocol_count; // Note, this is 32/64 bit
4790/// struct _protocol_t[protocol_count];
4791/// }
4792/// @endcode
4793///
4794llvm::Constant *
4795CGObjCNonFragileABIMac::EmitProtocolList(const std::string &Name,
4796 ObjCProtocolDecl::protocol_iterator begin,
4797 ObjCProtocolDecl::protocol_iterator end) {
4798 std::vector<llvm::Constant*> ProtocolRefs;
4799
Fariborz Jahanianda320092009-01-29 19:24:30 +00004800 // Just return null for empty protocol lists
Daniel Dunbar948e2582009-02-15 07:36:20 +00004801 if (begin == end)
Fariborz Jahanianda320092009-01-29 19:24:30 +00004802 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4803
Daniel Dunbar948e2582009-02-15 07:36:20 +00004804 // FIXME: We shouldn't need to do this lookup here, should we?
Fariborz Jahanianda320092009-01-29 19:24:30 +00004805 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
4806 if (GV)
Daniel Dunbar948e2582009-02-15 07:36:20 +00004807 return llvm::ConstantExpr::getBitCast(GV,
4808 ObjCTypes.ProtocolListnfABIPtrTy);
4809
4810 for (; begin != end; ++begin)
4811 ProtocolRefs.push_back(GetProtocolRef(*begin)); // Implemented???
4812
Fariborz Jahanianda320092009-01-29 19:24:30 +00004813 // This list is null terminated.
4814 ProtocolRefs.push_back(llvm::Constant::getNullValue(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004815 ObjCTypes.ProtocolnfABIPtrTy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004816
4817 std::vector<llvm::Constant*> Values(2);
4818 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
4819 Values[1] =
Daniel Dunbar948e2582009-02-15 07:36:20 +00004820 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolnfABIPtrTy,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004821 ProtocolRefs.size()),
4822 ProtocolRefs);
4823
4824 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4825 GV = new llvm::GlobalVariable(Init->getType(), false,
4826 llvm::GlobalValue::InternalLinkage,
4827 Init,
4828 Name,
4829 &CGM.getModule());
4830 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004831 GV->setAlignment(
4832 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004833 UsedGlobals.push_back(GV);
Daniel Dunbar948e2582009-02-15 07:36:20 +00004834 return llvm::ConstantExpr::getBitCast(GV,
4835 ObjCTypes.ProtocolListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004836}
4837
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004838/// GetMethodDescriptionConstant - This routine build following meta-data:
4839/// struct _objc_method {
4840/// SEL _cmd;
4841/// char *method_type;
4842/// char *_imp;
4843/// }
4844
4845llvm::Constant *
4846CGObjCNonFragileABIMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
4847 std::vector<llvm::Constant*> Desc(3);
4848 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4849 ObjCTypes.SelectorPtrTy);
4850 Desc[1] = GetMethodVarType(MD);
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004851 // Protocol methods have no implementation. So, this entry is always NULL.
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004852 Desc[2] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
4853 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Desc);
4854}
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004855
4856/// EmitObjCValueForIvar - Code Gen for nonfragile ivar reference.
4857/// This code gen. amounts to generating code for:
4858/// @code
4859/// (type *)((char *)base + _OBJC_IVAR_$_.ivar;
4860/// @encode
4861///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004862LValue CGObjCNonFragileABIMac::EmitObjCValueForIvar(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004863 CodeGen::CodeGenFunction &CGF,
4864 QualType ObjectTy,
4865 llvm::Value *BaseValue,
4866 const ObjCIvarDecl *Ivar,
4867 const FieldDecl *Field,
4868 unsigned CVRQualifiers) {
4869 assert(ObjectTy->isObjCInterfaceType() &&
4870 "CGObjCNonFragileABIMac::EmitObjCValueForIvar");
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004871 ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004872 std::string ExternalName;
4873 llvm::GlobalVariable *IvarOffsetGV =
4874 ObjCIvarOffsetVariable(ExternalName, ID, Ivar);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004875
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004876 // (char *) BaseValue
Chris Lattner51123fe2009-04-17 17:46:19 +00004877 llvm::Value *V = CGF.Builder.CreateBitCast(BaseValue, ObjCTypes.Int8PtrTy);
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004878 llvm::Value *Offset = CGF.Builder.CreateLoad(IvarOffsetGV);
4879 // (char*)BaseValue + Offset_symbol
4880 V = CGF.Builder.CreateGEP(V, Offset, "add.ptr");
4881 // (type *)((char*)BaseValue + Offset_symbol)
4882 const llvm::Type *IvarTy =
Chris Lattner51123fe2009-04-17 17:46:19 +00004883 CGM.getTypes().ConvertTypeForMem(Ivar->getType());
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004884 llvm::Type *ptrIvarTy = llvm::PointerType::getUnqual(IvarTy);
4885 V = CGF.Builder.CreateBitCast(V, ptrIvarTy);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004886
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00004887 if (Ivar->isBitField()) {
Chris Lattner51123fe2009-04-17 17:46:19 +00004888 QualType FieldTy = Field->getType();
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00004889 CodeGenTypes::BitFieldInfo bitFieldInfo =
4890 CGM.getTypes().getBitFieldInfo(Field);
4891 return LValue::MakeBitfield(V, bitFieldInfo.Begin, bitFieldInfo.Size,
Chris Lattner51123fe2009-04-17 17:46:19 +00004892 FieldTy->isSignedIntegerType(),
4893 FieldTy.getCVRQualifiers()|CVRQualifiers);
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00004894 }
4895
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004896 LValue LV = LValue::MakeAddr(V,
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004897 Ivar->getType().getCVRQualifiers()|CVRQualifiers,
4898 CGM.getContext().getObjCGCAttrKind(Ivar->getType()));
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004899 LValue::SetObjCIvar(LV, true);
4900 return LV;
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004901}
4902
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004903llvm::Value *CGObjCNonFragileABIMac::EmitIvarOffset(
4904 CodeGen::CodeGenFunction &CGF,
4905 ObjCInterfaceDecl *Interface,
4906 const ObjCIvarDecl *Ivar) {
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004907 std::string ExternalName;
4908 llvm::GlobalVariable *IvarOffsetGV =
4909 ObjCIvarOffsetVariable(ExternalName, Interface, Ivar);
4910
4911 return CGF.Builder.CreateLoad(IvarOffsetGV, false, "ivar");
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004912}
4913
Fariborz Jahanian46551122009-02-04 00:22:57 +00004914CodeGen::RValue CGObjCNonFragileABIMac::EmitMessageSend(
4915 CodeGen::CodeGenFunction &CGF,
4916 QualType ResultType,
4917 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004918 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +00004919 QualType Arg0Ty,
4920 bool IsSuper,
4921 const CallArgList &CallArgs) {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004922 // FIXME. Even though IsSuper is passes. This function doese not
4923 // handle calls to 'super' receivers.
4924 CodeGenTypes &Types = CGM.getTypes();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004925 llvm::Value *Arg0 = Receiver;
4926 if (!IsSuper)
4927 Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy, "tmp");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004928
4929 // Find the message function name.
Fariborz Jahanianef163782009-02-05 01:13:09 +00004930 // FIXME. This is too much work to get the ABI-specific result type
4931 // needed to find the message name.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004932 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType,
4933 llvm::SmallVector<QualType, 16>());
4934 llvm::Constant *Fn;
4935 std::string Name("\01l_");
4936 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004937#if 0
4938 // unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004939 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
4940 Fn = ObjCTypes.MessageSendIdStretFixupFn;
4941 // FIXME. Is there a better way of getting these names.
4942 // They are available in RuntimeFunctions vector pair.
4943 Name += "objc_msgSendId_stret_fixup";
4944 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004945 else
4946#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004947 if (IsSuper) {
4948 Fn = ObjCTypes.MessageSendSuper2StretFixupFn;
4949 Name += "objc_msgSendSuper2_stret_fixup";
4950 }
4951 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004952 {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004953 Fn = ObjCTypes.MessageSendStretFixupFn;
4954 Name += "objc_msgSend_stret_fixup";
4955 }
4956 }
Fariborz Jahanian1a6b3682009-02-05 19:35:43 +00004957 else if (ResultType->isFloatingType() &&
4958 // Selection of frret API only happens in 32bit nonfragile ABI.
4959 CGM.getTargetData().getTypePaddedSize(ObjCTypes.LongTy) == 4) {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004960 Fn = ObjCTypes.MessageSendFpretFixupFn;
4961 Name += "objc_msgSend_fpret_fixup";
4962 }
4963 else {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004964#if 0
4965// unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004966 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
4967 Fn = ObjCTypes.MessageSendIdFixupFn;
4968 Name += "objc_msgSendId_fixup";
4969 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004970 else
4971#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004972 if (IsSuper) {
4973 Fn = ObjCTypes.MessageSendSuper2FixupFn;
4974 Name += "objc_msgSendSuper2_fixup";
4975 }
4976 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004977 {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004978 Fn = ObjCTypes.MessageSendFixupFn;
4979 Name += "objc_msgSend_fixup";
4980 }
4981 }
4982 Name += '_';
4983 std::string SelName(Sel.getAsString());
4984 // Replace all ':' in selector name with '_' ouch!
4985 for(unsigned i = 0; i < SelName.size(); i++)
4986 if (SelName[i] == ':')
4987 SelName[i] = '_';
4988 Name += SelName;
4989 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
4990 if (!GV) {
Daniel Dunbar33af70f2009-04-15 19:03:14 +00004991 // Build message ref table entry.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004992 std::vector<llvm::Constant*> Values(2);
4993 Values[0] = Fn;
4994 Values[1] = GetMethodVarName(Sel);
4995 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4996 GV = new llvm::GlobalVariable(Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00004997 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004998 Init,
4999 Name,
5000 &CGM.getModule());
5001 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbarf59c1a62009-04-15 19:04:46 +00005002 GV->setAlignment(16);
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005003 GV->setSection("__DATA, __objc_msgrefs, coalesced");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005004 }
5005 llvm::Value *Arg1 = CGF.Builder.CreateBitCast(GV, ObjCTypes.MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00005006
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005007 CallArgList ActualArgs;
5008 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
5009 ActualArgs.push_back(std::make_pair(RValue::get(Arg1),
5010 ObjCTypes.MessageRefCPtrTy));
5011 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Fariborz Jahanianef163782009-02-05 01:13:09 +00005012 const CGFunctionInfo &FnInfo1 = Types.getFunctionInfo(ResultType, ActualArgs);
5013 llvm::Value *Callee = CGF.Builder.CreateStructGEP(Arg1, 0);
5014 Callee = CGF.Builder.CreateLoad(Callee);
Fariborz Jahanian3ab75bd2009-02-14 21:25:36 +00005015 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo1, true);
Fariborz Jahanianef163782009-02-05 01:13:09 +00005016 Callee = CGF.Builder.CreateBitCast(Callee,
5017 llvm::PointerType::getUnqual(FTy));
5018 return CGF.EmitCall(FnInfo1, Callee, ActualArgs);
Fariborz Jahanian46551122009-02-04 00:22:57 +00005019}
5020
5021/// Generate code for a message send expression in the nonfragile abi.
5022CodeGen::RValue CGObjCNonFragileABIMac::GenerateMessageSend(
5023 CodeGen::CodeGenFunction &CGF,
5024 QualType ResultType,
5025 Selector Sel,
5026 llvm::Value *Receiver,
5027 bool IsClassMessage,
5028 const CallArgList &CallArgs) {
Fariborz Jahanian46551122009-02-04 00:22:57 +00005029 return EmitMessageSend(CGF, ResultType, Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005030 Receiver, CGF.getContext().getObjCIdType(),
Fariborz Jahanian46551122009-02-04 00:22:57 +00005031 false, CallArgs);
5032}
5033
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005034llvm::GlobalVariable *
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005035CGObjCNonFragileABIMac::GetClassGlobal(const std::string &Name) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005036 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5037
Daniel Dunbardfff2302009-03-02 05:18:14 +00005038 if (!GV) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005039 GV = new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
5040 llvm::GlobalValue::ExternalLinkage,
5041 0, Name, &CGM.getModule());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005042 }
5043
5044 return GV;
5045}
5046
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005047llvm::Value *CGObjCNonFragileABIMac::EmitClassRef(CGBuilderTy &Builder,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005048 const ObjCInterfaceDecl *ID,
5049 bool IsSuper) {
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005050
5051 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
5052
5053 if (!Entry) {
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005054 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005055 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005056 Entry =
5057 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5058 llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005059 ClassGV,
5060 IsSuper ? "\01L_OBJC_CLASSLIST_SUP_REFS_$_"
5061 : "\01L_OBJC_CLASSLIST_REFERENCES_$_",
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005062 &CGM.getModule());
5063 Entry->setAlignment(
5064 CGM.getTargetData().getPrefTypeAlignment(
5065 ObjCTypes.ClassnfABIPtrTy));
5066
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005067 if (IsSuper)
Daniel Dunbar0bf21992009-04-15 02:56:18 +00005068 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005069 else
Daniel Dunbar0bf21992009-04-15 02:56:18 +00005070 Entry->setSection("__DATA, __objc_classrefs, regular, no_dead_strip");
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005071 UsedGlobals.push_back(Entry);
5072 }
5073
5074 return Builder.CreateLoad(Entry, false, "tmp");
5075}
5076
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005077/// EmitMetaClassRef - Return a Value * of the address of _class_t
5078/// meta-data
5079///
5080llvm::Value *CGObjCNonFragileABIMac::EmitMetaClassRef(CGBuilderTy &Builder,
5081 const ObjCInterfaceDecl *ID) {
5082 llvm::GlobalVariable * &Entry = MetaClassReferences[ID->getIdentifier()];
5083 if (Entry)
5084 return Builder.CreateLoad(Entry, false, "tmp");
5085
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005086 std::string MetaClassName(getMetaclassSymbolPrefix() + ID->getNameAsString());
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005087 llvm::GlobalVariable *MetaClassGV = GetClassGlobal(MetaClassName);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005088 Entry =
5089 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5090 llvm::GlobalValue::InternalLinkage,
5091 MetaClassGV,
5092 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5093 &CGM.getModule());
5094 Entry->setAlignment(
5095 CGM.getTargetData().getPrefTypeAlignment(
5096 ObjCTypes.ClassnfABIPtrTy));
5097
Daniel Dunbar33af70f2009-04-15 19:03:14 +00005098 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005099 UsedGlobals.push_back(Entry);
5100
5101 return Builder.CreateLoad(Entry, false, "tmp");
5102}
5103
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005104/// GetClass - Return a reference to the class for the given interface
5105/// decl.
5106llvm::Value *CGObjCNonFragileABIMac::GetClass(CGBuilderTy &Builder,
5107 const ObjCInterfaceDecl *ID) {
5108 return EmitClassRef(Builder, ID);
5109}
5110
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005111/// Generates a message send where the super is the receiver. This is
5112/// a message send to self with special delivery semantics indicating
5113/// which class's method should be called.
5114CodeGen::RValue
5115CGObjCNonFragileABIMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
5116 QualType ResultType,
5117 Selector Sel,
5118 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005119 bool isCategoryImpl,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005120 llvm::Value *Receiver,
5121 bool IsClassMessage,
5122 const CodeGen::CallArgList &CallArgs) {
5123 // ...
5124 // Create and init a super structure; this is a (receiver, class)
5125 // pair we will pass to objc_msgSendSuper.
5126 llvm::Value *ObjCSuper =
5127 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
5128
5129 llvm::Value *ReceiverAsObject =
5130 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
5131 CGF.Builder.CreateStore(ReceiverAsObject,
5132 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
5133
5134 // If this is a class message the metaclass is passed as the target.
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005135 llvm::Value *Target;
5136 if (IsClassMessage) {
5137 if (isCategoryImpl) {
5138 // Message sent to "super' in a class method defined in
5139 // a category implementation.
5140 Target = EmitClassRef(CGF.Builder, Class, false);
5141 Target = CGF.Builder.CreateStructGEP(Target, 0);
5142 Target = CGF.Builder.CreateLoad(Target);
5143 }
5144 else
5145 Target = EmitMetaClassRef(CGF.Builder, Class);
5146 }
5147 else
5148 Target = EmitClassRef(CGF.Builder, Class, true);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005149
5150 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
5151 // and ObjCTypes types.
5152 const llvm::Type *ClassTy =
5153 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
5154 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
5155 CGF.Builder.CreateStore(Target,
5156 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
5157
5158 return EmitMessageSend(CGF, ResultType, Sel,
5159 ObjCSuper, ObjCTypes.SuperPtrCTy,
5160 true, CallArgs);
5161}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005162
5163llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CGBuilderTy &Builder,
5164 Selector Sel) {
5165 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
5166
5167 if (!Entry) {
5168 llvm::Constant *Casted =
5169 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
5170 ObjCTypes.SelectorPtrTy);
5171 Entry =
5172 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
5173 llvm::GlobalValue::InternalLinkage,
5174 Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
5175 &CGM.getModule());
5176 Entry->setSection("__DATA,__objc_selrefs,literal_pointers,no_dead_strip");
5177 UsedGlobals.push_back(Entry);
5178 }
5179
5180 return Builder.CreateLoad(Entry, false, "tmp");
5181}
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005182/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
5183/// objc_assign_ivar (id src, id *dst)
5184///
5185void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
5186 llvm::Value *src, llvm::Value *dst)
5187{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005188 const llvm::Type * SrcTy = src->getType();
5189 if (!isa<llvm::PointerType>(SrcTy)) {
5190 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5191 assert(Size <= 8 && "does not support size > 8");
5192 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5193 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005194 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5195 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005196 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5197 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5198 CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn,
5199 src, dst, "assignivar");
5200 return;
5201}
5202
5203/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
5204/// objc_assign_strongCast (id src, id *dst)
5205///
5206void CGObjCNonFragileABIMac::EmitObjCStrongCastAssign(
5207 CodeGen::CodeGenFunction &CGF,
5208 llvm::Value *src, llvm::Value *dst)
5209{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005210 const llvm::Type * SrcTy = src->getType();
5211 if (!isa<llvm::PointerType>(SrcTy)) {
5212 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5213 assert(Size <= 8 && "does not support size > 8");
5214 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5215 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005216 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5217 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005218 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5219 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5220 CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn,
5221 src, dst, "weakassign");
5222 return;
5223}
5224
5225/// EmitObjCWeakRead - Code gen for loading value of a __weak
5226/// object: objc_read_weak (id *src)
5227///
5228llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead(
5229 CodeGen::CodeGenFunction &CGF,
5230 llvm::Value *AddrWeakObj)
5231{
Eli Friedman8339b352009-03-07 03:57:15 +00005232 const llvm::Type* DestTy =
5233 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005234 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
5235 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
5236 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00005237 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005238 return read_weak;
5239}
5240
5241/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
5242/// objc_assign_weak (id src, id *dst)
5243///
5244void CGObjCNonFragileABIMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
5245 llvm::Value *src, llvm::Value *dst)
5246{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005247 const llvm::Type * SrcTy = src->getType();
5248 if (!isa<llvm::PointerType>(SrcTy)) {
5249 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5250 assert(Size <= 8 && "does not support size > 8");
5251 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5252 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005253 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5254 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005255 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5256 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattner96508e12009-04-17 22:12:36 +00005257 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005258 src, dst, "weakassign");
5259 return;
5260}
5261
5262/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
5263/// objc_assign_global (id src, id *dst)
5264///
5265void CGObjCNonFragileABIMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
5266 llvm::Value *src, llvm::Value *dst)
5267{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005268 const llvm::Type * SrcTy = src->getType();
5269 if (!isa<llvm::PointerType>(SrcTy)) {
5270 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5271 assert(Size <= 8 && "does not support size > 8");
5272 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5273 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005274 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5275 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005276 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5277 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5278 CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn,
5279 src, dst, "globalassign");
5280 return;
5281}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005282
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005283void
5284CGObjCNonFragileABIMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
5285 const Stmt &S) {
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005286 bool isTry = isa<ObjCAtTryStmt>(S);
5287 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
5288 llvm::BasicBlock *PrevLandingPad = CGF.getInvokeDest();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005289 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005290 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005291 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005292 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
5293
5294 // For @synchronized, call objc_sync_enter(sync.expr). The
5295 // evaluation of the expression must occur before we enter the
5296 // @synchronized. We can safely avoid a temp here because jumps into
5297 // @synchronized are illegal & this will dominate uses.
5298 llvm::Value *SyncArg = 0;
5299 if (!isTry) {
5300 SyncArg =
5301 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
5302 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005303 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005304 }
5305
5306 // Push an EH context entry, used for handling rethrows and jumps
5307 // through finally.
5308 CGF.PushCleanupBlock(FinallyBlock);
5309
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005310 CGF.setInvokeDest(TryHandler);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005311
5312 CGF.EmitBlock(TryBlock);
5313 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
5314 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
5315 CGF.EmitBranchThroughCleanup(FinallyEnd);
5316
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005317 // Emit the exception handler.
5318
5319 CGF.EmitBlock(TryHandler);
5320
5321 llvm::Value *llvm_eh_exception =
5322 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_exception);
5323 llvm::Value *llvm_eh_selector_i64 =
5324 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector_i64);
5325 llvm::Value *llvm_eh_typeid_for_i64 =
5326 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for_i64);
5327 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5328 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(Exc->getType(), "_rethrow");
5329
5330 llvm::SmallVector<llvm::Value*, 8> SelectorArgs;
5331 SelectorArgs.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005332 SelectorArgs.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005333
5334 // Construct the lists of (type, catch body) to handle.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005335 llvm::SmallVector<std::pair<const ParmVarDecl*, const Stmt*>, 8> Handlers;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005336 bool HasCatchAll = false;
5337 if (isTry) {
5338 if (const ObjCAtCatchStmt* CatchStmt =
5339 cast<ObjCAtTryStmt>(S).getCatchStmts()) {
5340 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005341 const ParmVarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
Steve Naroff7ba138a2009-03-03 19:52:17 +00005342 Handlers.push_back(std::make_pair(CatchDecl, CatchStmt->getCatchBody()));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005343
5344 // catch(...) always matches.
Steve Naroff7ba138a2009-03-03 19:52:17 +00005345 if (!CatchDecl) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005346 // Use i8* null here to signal this is a catch all, not a cleanup.
5347 llvm::Value *Null = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
5348 SelectorArgs.push_back(Null);
5349 HasCatchAll = true;
5350 break;
5351 }
5352
Daniel Dunbarede8de92009-03-06 00:01:21 +00005353 if (CGF.getContext().isObjCIdType(CatchDecl->getType()) ||
5354 CatchDecl->getType()->isObjCQualifiedIdType()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005355 llvm::Value *IDEHType =
5356 CGM.getModule().getGlobalVariable("OBJC_EHTYPE_id");
5357 if (!IDEHType)
5358 IDEHType =
5359 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5360 llvm::GlobalValue::ExternalLinkage,
5361 0, "OBJC_EHTYPE_id", &CGM.getModule());
5362 SelectorArgs.push_back(IDEHType);
5363 HasCatchAll = true;
5364 break;
5365 }
5366
5367 // All other types should be Objective-C interface pointer types.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005368 const PointerType *PT = CatchDecl->getType()->getAsPointerType();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005369 assert(PT && "Invalid @catch type.");
5370 const ObjCInterfaceType *IT =
5371 PT->getPointeeType()->getAsObjCInterfaceType();
5372 assert(IT && "Invalid @catch type.");
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005373 llvm::Value *EHType = GetInterfaceEHType(IT->getDecl(), false);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005374 SelectorArgs.push_back(EHType);
5375 }
5376 }
5377 }
5378
5379 // We use a cleanup unless there was already a catch all.
5380 if (!HasCatchAll) {
5381 SelectorArgs.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
Daniel Dunbarede8de92009-03-06 00:01:21 +00005382 Handlers.push_back(std::make_pair((const ParmVarDecl*) 0, (const Stmt*) 0));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005383 }
5384
5385 llvm::Value *Selector =
5386 CGF.Builder.CreateCall(llvm_eh_selector_i64,
5387 SelectorArgs.begin(), SelectorArgs.end(),
5388 "selector");
5389 for (unsigned i = 0, e = Handlers.size(); i != e; ++i) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005390 const ParmVarDecl *CatchParam = Handlers[i].first;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005391 const Stmt *CatchBody = Handlers[i].second;
5392
5393 llvm::BasicBlock *Next = 0;
5394
5395 // The last handler always matches.
5396 if (i + 1 != e) {
5397 assert(CatchParam && "Only last handler can be a catch all.");
5398
5399 llvm::BasicBlock *Match = CGF.createBasicBlock("match");
5400 Next = CGF.createBasicBlock("catch.next");
5401 llvm::Value *Id =
5402 CGF.Builder.CreateCall(llvm_eh_typeid_for_i64,
5403 CGF.Builder.CreateBitCast(SelectorArgs[i+2],
5404 ObjCTypes.Int8PtrTy));
5405 CGF.Builder.CreateCondBr(CGF.Builder.CreateICmpEQ(Selector, Id),
5406 Match, Next);
5407
5408 CGF.EmitBlock(Match);
5409 }
5410
5411 if (CatchBody) {
5412 llvm::BasicBlock *MatchEnd = CGF.createBasicBlock("match.end");
5413 llvm::BasicBlock *MatchHandler = CGF.createBasicBlock("match.handler");
5414
5415 // Cleanups must call objc_end_catch.
5416 //
5417 // FIXME: It seems incorrect for objc_begin_catch to be inside
5418 // this context, but this matches gcc.
5419 CGF.PushCleanupBlock(MatchEnd);
5420 CGF.setInvokeDest(MatchHandler);
5421
5422 llvm::Value *ExcObject =
5423 CGF.Builder.CreateCall(ObjCTypes.ObjCBeginCatchFn, Exc);
5424
5425 // Bind the catch parameter if it exists.
5426 if (CatchParam) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005427 ExcObject =
5428 CGF.Builder.CreateBitCast(ExcObject,
5429 CGF.ConvertType(CatchParam->getType()));
5430 // CatchParam is a ParmVarDecl because of the grammar
5431 // construction used to handle this, but for codegen purposes
5432 // we treat this as a local decl.
5433 CGF.EmitLocalBlockVarDecl(*CatchParam);
5434 CGF.Builder.CreateStore(ExcObject, CGF.GetAddrOfLocalVar(CatchParam));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005435 }
5436
5437 CGF.ObjCEHValueStack.push_back(ExcObject);
5438 CGF.EmitStmt(CatchBody);
5439 CGF.ObjCEHValueStack.pop_back();
5440
5441 CGF.EmitBranchThroughCleanup(FinallyEnd);
5442
5443 CGF.EmitBlock(MatchHandler);
5444
5445 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5446 // We are required to emit this call to satisfy LLVM, even
5447 // though we don't use the result.
5448 llvm::SmallVector<llvm::Value*, 8> Args;
5449 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005450 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005451 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5452 0));
5453 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5454 CGF.Builder.CreateStore(Exc, RethrowPtr);
5455 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5456
5457 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5458
5459 CGF.EmitBlock(MatchEnd);
5460
5461 // Unfortunately, we also have to generate another EH frame here
5462 // in case this throws.
5463 llvm::BasicBlock *MatchEndHandler =
5464 CGF.createBasicBlock("match.end.handler");
5465 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
5466 CGF.Builder.CreateInvoke(ObjCTypes.ObjCEndCatchFn,
5467 Cont, MatchEndHandler,
5468 Args.begin(), Args.begin());
5469
5470 CGF.EmitBlock(Cont);
5471 if (Info.SwitchBlock)
5472 CGF.EmitBlock(Info.SwitchBlock);
5473 if (Info.EndBlock)
5474 CGF.EmitBlock(Info.EndBlock);
5475
5476 CGF.EmitBlock(MatchEndHandler);
5477 Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5478 // We are required to emit this call to satisfy LLVM, even
5479 // though we don't use the result.
5480 Args.clear();
5481 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005482 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005483 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5484 0));
5485 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5486 CGF.Builder.CreateStore(Exc, RethrowPtr);
5487 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5488
5489 if (Next)
5490 CGF.EmitBlock(Next);
5491 } else {
5492 assert(!Next && "catchup should be last handler.");
5493
5494 CGF.Builder.CreateStore(Exc, RethrowPtr);
5495 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5496 }
5497 }
5498
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005499 // Pop the cleanup entry, the @finally is outside this cleanup
5500 // scope.
5501 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5502 CGF.setInvokeDest(PrevLandingPad);
5503
5504 CGF.EmitBlock(FinallyBlock);
5505
5506 if (isTry) {
5507 if (const ObjCAtFinallyStmt* FinallyStmt =
5508 cast<ObjCAtTryStmt>(S).getFinallyStmt())
5509 CGF.EmitStmt(FinallyStmt->getFinallyBody());
5510 } else {
5511 // Emit 'objc_sync_exit(expr)' as finally's sole statement for
5512 // @synchronized.
5513 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, SyncArg);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005514 }
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005515
5516 if (Info.SwitchBlock)
5517 CGF.EmitBlock(Info.SwitchBlock);
5518 if (Info.EndBlock)
5519 CGF.EmitBlock(Info.EndBlock);
5520
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005521 // Branch around the rethrow code.
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005522 CGF.EmitBranch(FinallyEnd);
5523
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005524 CGF.EmitBlock(FinallyRethrow);
5525 CGF.Builder.CreateCall(ObjCTypes.UnwindResumeOrRethrowFn,
5526 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005527 CGF.Builder.CreateUnreachable();
5528
5529 CGF.EmitBlock(FinallyEnd);
5530}
5531
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005532/// EmitThrowStmt - Generate code for a throw statement.
5533void CGObjCNonFragileABIMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
5534 const ObjCAtThrowStmt &S) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005535 llvm::Value *Exception;
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005536 if (const Expr *ThrowExpr = S.getThrowExpr()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005537 Exception = CGF.EmitScalarExpr(ThrowExpr);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005538 } else {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005539 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
5540 "Unexpected rethrow outside @catch block.");
5541 Exception = CGF.ObjCEHValueStack.back();
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005542 }
5543
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005544 llvm::Value *ExceptionAsObject =
5545 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
5546 llvm::BasicBlock *InvokeDest = CGF.getInvokeDest();
5547 if (InvokeDest) {
5548 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
5549 CGF.Builder.CreateInvoke(ObjCTypes.ExceptionThrowFn,
5550 Cont, InvokeDest,
5551 &ExceptionAsObject, &ExceptionAsObject + 1);
5552 CGF.EmitBlock(Cont);
5553 } else
5554 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
5555 CGF.Builder.CreateUnreachable();
5556
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005557 // Clear the insertion point to indicate we are in unreachable code.
5558 CGF.Builder.ClearInsertionPoint();
5559}
Daniel Dunbare588b992009-03-01 04:46:24 +00005560
5561llvm::Value *
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005562CGObjCNonFragileABIMac::GetInterfaceEHType(const ObjCInterfaceDecl *ID,
5563 bool ForDefinition) {
Daniel Dunbare588b992009-03-01 04:46:24 +00005564 llvm::GlobalVariable * &Entry = EHTypeReferences[ID->getIdentifier()];
Daniel Dunbare588b992009-03-01 04:46:24 +00005565
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005566 // If we don't need a definition, return the entry if found or check
5567 // if we use an external reference.
5568 if (!ForDefinition) {
5569 if (Entry)
5570 return Entry;
Daniel Dunbar7e075cb2009-04-07 06:43:45 +00005571
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005572 // If this type (or a super class) has the __objc_exception__
5573 // attribute, emit an external reference.
5574 if (hasObjCExceptionAttribute(ID))
5575 return Entry =
5576 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5577 llvm::GlobalValue::ExternalLinkage,
5578 0,
5579 (std::string("OBJC_EHTYPE_$_") +
5580 ID->getIdentifier()->getName()),
5581 &CGM.getModule());
5582 }
5583
5584 // Otherwise we need to either make a new entry or fill in the
5585 // initializer.
5586 assert((!Entry || !Entry->hasInitializer()) && "Duplicate EHType definition");
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005587 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbare588b992009-03-01 04:46:24 +00005588 std::string VTableName = "objc_ehtype_vtable";
5589 llvm::GlobalVariable *VTableGV =
5590 CGM.getModule().getGlobalVariable(VTableName);
5591 if (!VTableGV)
5592 VTableGV = new llvm::GlobalVariable(ObjCTypes.Int8PtrTy, false,
5593 llvm::GlobalValue::ExternalLinkage,
5594 0, VTableName, &CGM.getModule());
5595
5596 llvm::Value *VTableIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, 2);
5597
5598 std::vector<llvm::Constant*> Values(3);
5599 Values[0] = llvm::ConstantExpr::getGetElementPtr(VTableGV, &VTableIdx, 1);
5600 Values[1] = GetClassName(ID->getIdentifier());
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005601 Values[2] = GetClassGlobal(ClassName);
Daniel Dunbare588b992009-03-01 04:46:24 +00005602 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.EHTypeTy, Values);
5603
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005604 if (Entry) {
5605 Entry->setInitializer(Init);
5606 } else {
5607 Entry = new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5608 llvm::GlobalValue::WeakAnyLinkage,
5609 Init,
5610 (std::string("OBJC_EHTYPE_$_") +
5611 ID->getIdentifier()->getName()),
5612 &CGM.getModule());
5613 }
5614
Daniel Dunbar04d40782009-04-14 06:00:08 +00005615 if (CGM.getLangOptions().getVisibilityMode() == LangOptions::Hidden)
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005616 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005617 Entry->setAlignment(8);
5618
5619 if (ForDefinition) {
5620 Entry->setSection("__DATA,__objc_const");
5621 Entry->setLinkage(llvm::GlobalValue::ExternalLinkage);
5622 } else {
5623 Entry->setSection("__DATA,__datacoal_nt,coalesced");
5624 }
Daniel Dunbare588b992009-03-01 04:46:24 +00005625
5626 return Entry;
5627}
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005628
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00005629/* *** */
5630
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00005631CodeGen::CGObjCRuntime *
5632CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00005633 return new CGObjCMac(CGM);
5634}
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005635
5636CodeGen::CGObjCRuntime *
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00005637CodeGen::CreateMacNonFragileABIObjCRuntime(CodeGen::CodeGenModule &CGM) {
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00005638 return new CGObjCNonFragileABIMac(CGM);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005639}