blob: 3b5e0c55047d67596f1b93e935be550ca28faa61 [file] [log] [blame]
Daniel Dunbar8c85fac2008-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 Dunbar1be1df32008-08-11 21:35:06 +000015
16#include "CodeGenModule.h"
Daniel Dunbarace33292008-08-16 03:19:19 +000017#include "CodeGenFunction.h"
Daniel Dunbardaf4ad42008-08-12 00:12:39 +000018#include "clang/AST/ASTContext.h"
Daniel Dunbarde300732008-08-11 04:54:23 +000019#include "clang/AST/Decl.h"
Daniel Dunbarcffcdac2008-08-13 03:21:16 +000020#include "clang/AST/DeclObjC.h"
Daniel Dunbar1be1df32008-08-11 21:35:06 +000021#include "clang/Basic/LangOptions.h"
22
Daniel Dunbar75de89f2009-02-24 07:47:38 +000023#include "llvm/Intrinsics.h"
Daniel Dunbardaf4ad42008-08-12 00:12:39 +000024#include "llvm/Module.h"
Daniel Dunbar35b777f2008-10-29 22:36:39 +000025#include "llvm/ADT/DenseSet.h"
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +000026#include "llvm/Target/TargetData.h"
Daniel Dunbarace33292008-08-16 03:19:19 +000027#include <sstream>
Daniel Dunbar8c85fac2008-08-11 02:45:11 +000028
29using namespace clang;
Daniel Dunbar0a2da0f2008-09-09 01:06:48 +000030using namespace CodeGen;
Daniel Dunbar8c85fac2008-08-11 02:45:11 +000031
32namespace {
Daniel Dunbardaf4ad42008-08-12 00:12:39 +000033
Daniel Dunbarfe131f02008-08-27 02:31:56 +000034 typedef std::vector<llvm::Constant*> ConstantVector;
35
Daniel Dunbarcffcdac2008-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 Jahanian48543f52009-01-21 22:04:16 +000039class ObjCCommonTypesHelper {
40protected:
41 CodeGen::CodeGenModule &CGM;
Daniel Dunbardaf4ad42008-08-12 00:12:39 +000042
Daniel Dunbardaf4ad42008-08-12 00:12:39 +000043public:
Fariborz Jahanianad51ca02009-03-23 19:10:40 +000044 const llvm::Type *ShortTy, *IntTy, *LongTy, *LongLongTy;
Daniel Dunbarb050fa62008-08-21 04:36:09 +000045 const llvm::Type *Int8PtrTy;
Fariborz Jahanian48543f52009-01-21 22:04:16 +000046
Daniel Dunbar6fa3daf2008-08-12 05:28:47 +000047 /// ObjectPtrTy - LLVM type for object handles (typeof(id))
48 const llvm::Type *ObjectPtrTy;
Fariborz Jahanianc192d4d2008-11-18 20:18:11 +000049
50 /// PtrObjectPtrTy - LLVM type for id *
51 const llvm::Type *PtrObjectPtrTy;
52
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +000053 /// SelectorPtrTy - LLVM type for selector handles (typeof(SEL))
Daniel Dunbar6fa3daf2008-08-12 05:28:47 +000054 const llvm::Type *SelectorPtrTy;
Daniel Dunbarcffcdac2008-08-13 03:21:16 +000055 /// ProtocolPtrTy - LLVM type for external protocol handles
56 /// (typeof(Protocol))
57 const llvm::Type *ExternalProtocolPtrTy;
Fariborz Jahanian48543f52009-01-21 22:04:16 +000058
Daniel Dunbar0ed60b02008-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 Jahanian48543f52009-01-21 22:04:16 +000063
Daniel Dunbar15245e52008-08-23 04:28:29 +000064 /// SuperTy - LLVM type for struct objc_super.
65 const llvm::StructType *SuperTy;
Daniel Dunbar87062ff2008-08-23 09:25:55 +000066 /// SuperPtrTy - LLVM type for struct objc_super *.
67 const llvm::Type *SuperPtrTy;
Fariborz Jahanian48543f52009-01-21 22:04:16 +000068
Fariborz Jahaniand0374812009-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 Jahanian781f2732009-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 Lattneraea1aee2009-03-22 21:03:39 +000087 llvm::Constant *GetPropertyFn, *SetPropertyFn;
Fariborz Jahanian4b161702009-01-22 00:37:21 +000088
Chris Lattneraea1aee2009-03-22 21:03:39 +000089 llvm::Constant *EnumerationMutationFn;
Fariborz Jahanian4b161702009-01-22 00:37:21 +000090
91 /// GcReadWeakFn -- LLVM objc_read_weak (id *src) function.
Chris Lattneraea1aee2009-03-22 21:03:39 +000092 llvm::Constant *GcReadWeakFn;
Fariborz Jahanian4b161702009-01-22 00:37:21 +000093
94 /// GcAssignWeakFn -- LLVM objc_assign_weak function.
Chris Lattner293c1d32009-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 Jahanian4b161702009-01-22 00:37:21 +0000103
104 /// GcAssignGlobalFn -- LLVM objc_assign_global function.
Chris Lattneraea1aee2009-03-22 21:03:39 +0000105 llvm::Constant *GcAssignGlobalFn;
Fariborz Jahanian4b161702009-01-22 00:37:21 +0000106
107 /// GcAssignIvarFn -- LLVM objc_assign_ivar function.
Chris Lattneraea1aee2009-03-22 21:03:39 +0000108 llvm::Constant *GcAssignIvarFn;
Fariborz Jahanian4b161702009-01-22 00:37:21 +0000109
110 /// GcAssignStrongCastFn -- LLVM objc_assign_strongCast function.
Chris Lattneraea1aee2009-03-22 21:03:39 +0000111 llvm::Constant *GcAssignStrongCastFn;
Anders Carlsson1cf75362009-02-16 22:59:18 +0000112
113 /// ExceptionThrowFn - LLVM objc_exception_throw function.
Chris Lattneraea1aee2009-03-22 21:03:39 +0000114 llvm::Constant *ExceptionThrowFn;
Anders Carlsson1cf75362009-02-16 22:59:18 +0000115
Daniel Dunbar34416d62009-02-24 01:43:46 +0000116 /// SyncEnterFn - LLVM object_sync_enter function.
Chris Lattner23e24652009-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 Dunbar34416d62009-02-24 01:43:46 +0000124
125 /// SyncExitFn - LLVM object_sync_exit function.
Chris Lattneraea1aee2009-03-22 21:03:39 +0000126 llvm::Constant *SyncExitFn;
Daniel Dunbar34416d62009-02-24 01:43:46 +0000127
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000128 ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm);
129 ~ObjCCommonTypesHelper(){}
130};
Daniel Dunbar15245e52008-08-23 04:28:29 +0000131
Fariborz Jahanian48543f52009-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 Lattneraea1aee2009-03-22 21:03:39 +0000137 llvm::Constant *MessageSendFn, *MessageSendStretFn, *MessageSendFpretFn;
138 llvm::Constant *MessageSendSuperFn, *MessageSendSuperStretFn,
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000139 *MessageSendSuperFpretFn;
140
141public:
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +0000142 /// SymtabTy - LLVM type for struct objc_symtab.
143 const llvm::StructType *SymtabTy;
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000144 /// SymtabPtrTy - LLVM type for struct objc_symtab *.
145 const llvm::Type *SymtabPtrTy;
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +0000146 /// ModuleTy - LLVM type for struct objc_module.
147 const llvm::StructType *ModuleTy;
Daniel Dunbar5eec6142008-08-12 03:39:23 +0000148
Daniel Dunbarcffcdac2008-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 Dunbarcffcdac2008-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 Dunbar4246a8b2008-08-22 20:34:54 +0000172 /// CategoryTy - LLVM type for struct objc_category.
173 const llvm::StructType *CategoryTy;
Daniel Dunbarb050fa62008-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 Dunbarb050fa62008-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 Dunbarb050fa62008-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 Carlsson9acb0a42008-09-09 10:10:21 +0000192
193 /// ExceptionDataTy - LLVM type for struct _objc_exception_data.
194 const llvm::Type *ExceptionDataTy;
195
Anders Carlsson9acb0a42008-09-09 10:10:21 +0000196 /// ExceptionTryEnterFn - LLVM objc_exception_try_enter function.
Chris Lattneraea1aee2009-03-22 21:03:39 +0000197 llvm::Constant *ExceptionTryEnterFn;
Anders Carlsson9acb0a42008-09-09 10:10:21 +0000198
199 /// ExceptionTryExitFn - LLVM objc_exception_try_exit function.
Chris Lattneraea1aee2009-03-22 21:03:39 +0000200 llvm::Constant *ExceptionTryExitFn;
Anders Carlsson9acb0a42008-09-09 10:10:21 +0000201
202 /// ExceptionExtractFn - LLVM objc_exception_extract function.
Chris Lattneraea1aee2009-03-22 21:03:39 +0000203 llvm::Constant *ExceptionExtractFn;
Anders Carlsson9acb0a42008-09-09 10:10:21 +0000204
205 /// ExceptionMatchFn - LLVM objc_exception_match function.
Chris Lattneraea1aee2009-03-22 21:03:39 +0000206 llvm::Constant *ExceptionMatchFn;
Anders Carlsson9acb0a42008-09-09 10:10:21 +0000207
208 /// SetJmpFn - LLVM _setjmp function.
Chris Lattneraea1aee2009-03-22 21:03:39 +0000209 llvm::Constant *SetJmpFn;
Chris Lattnerdd978702008-11-15 21:26:17 +0000210
Daniel Dunbardaf4ad42008-08-12 00:12:39 +0000211public:
212 ObjCTypesHelper(CodeGen::CodeGenModule &cgm);
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000213 ~ObjCTypesHelper() {}
Daniel Dunbaraecef4c2008-10-17 03:24:53 +0000214
215
Chris Lattneraea1aee2009-03-22 21:03:39 +0000216 llvm::Constant *getSendFn(bool IsSuper) {
Daniel Dunbaraecef4c2008-10-17 03:24:53 +0000217 return IsSuper ? MessageSendSuperFn : MessageSendFn;
218 }
219
Chris Lattneraea1aee2009-03-22 21:03:39 +0000220 llvm::Constant *getSendStretFn(bool IsSuper) {
Daniel Dunbaraecef4c2008-10-17 03:24:53 +0000221 return IsSuper ? MessageSendSuperStretFn : MessageSendStretFn;
222 }
223
Chris Lattneraea1aee2009-03-22 21:03:39 +0000224 llvm::Constant *getSendFpretFn(bool IsSuper) {
Daniel Dunbaraecef4c2008-10-17 03:24:53 +0000225 return IsSuper ? MessageSendSuperFpretFn : MessageSendFpretFn;
226 }
Daniel Dunbardaf4ad42008-08-12 00:12:39 +0000227};
228
Fariborz Jahaniand0374812009-01-22 23:02:58 +0000229/// ObjCNonFragileABITypesHelper - will have all types needed by objective-c's
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000230/// modern abi
Fariborz Jahaniand0374812009-01-22 23:02:58 +0000231class ObjCNonFragileABITypesHelper : public ObjCCommonTypesHelper {
Fariborz Jahanianf52110f2009-02-04 20:42:28 +0000232public:
Chris Lattneraea1aee2009-03-22 21:03:39 +0000233 llvm::Constant *MessageSendFixupFn, *MessageSendFpretFixupFn,
Fariborz Jahanian711e8dd2009-02-03 23:49:23 +0000234 *MessageSendStretFixupFn, *MessageSendIdFixupFn,
235 *MessageSendIdStretFixupFn, *MessageSendSuper2FixupFn,
236 *MessageSendSuper2StretFixupFn;
237
Fariborz Jahanian781f2732009-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 Dunbar1f42bb02009-02-15 07:36:20 +0000247 // ProtocolnfABIPtrTy = LLVM for struct _protocol_t*
248 const llvm::Type *ProtocolnfABIPtrTy;
249
Fariborz Jahanian781f2732009-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 Jahanianc2a1c3e2009-01-23 23:53:38 +0000259 // ClassnfABIPtrTy - LLVM for struct _class_t*
260 const llvm::Type *ClassnfABIPtrTy;
261
Fariborz Jahanian781f2732009-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 Jahanian711e8dd2009-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 Jahanianf52110f2009-02-04 20:42:28 +0000288 // MessageRefCTy - clang type for struct _message_ref_t
289 QualType MessageRefCTy;
Fariborz Jahanian711e8dd2009-02-03 23:49:23 +0000290
291 // MessageRefPtrTy - LLVM for struct _message_ref_t*
292 const llvm::Type *MessageRefPtrTy;
Fariborz Jahanianf52110f2009-02-04 20:42:28 +0000293 // MessageRefCPtrTy - clang type for struct _message_ref_t*
294 QualType MessageRefCPtrTy;
Fariborz Jahanian711e8dd2009-02-03 23:49:23 +0000295
Fariborz Jahanian10d69ea2009-02-05 01:13:09 +0000296 // MessengerTy - Type of the messenger (shown as IMP above)
297 const llvm::FunctionType *MessengerTy;
298
Fariborz Jahanian711e8dd2009-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 Dunbar75de89f2009-02-24 07:47:38 +0000308
309 /// EHPersonalityPtr - LLVM value for an i8* to the Objective-C
310 /// exception personality function.
Chris Lattner23e24652009-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 Dunbar75de89f2009-02-24 07:47:38 +0000319
Chris Lattneraea1aee2009-03-22 21:03:39 +0000320 llvm::Constant *UnwindResumeOrRethrowFn, *ObjCBeginCatchFn, *ObjCEndCatchFn;
Daniel Dunbar9c285e72009-03-01 04:46:24 +0000321
322 const llvm::StructType *EHTypeTy;
323 const llvm::Type *EHTypePtrTy;
Daniel Dunbar75de89f2009-02-24 07:47:38 +0000324
Fariborz Jahaniand0374812009-01-22 23:02:58 +0000325 ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm);
326 ~ObjCNonFragileABITypesHelper(){}
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000327};
328
329class CGObjCCommonMac : public CodeGen::CGObjCRuntime {
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +0000330public:
331 // FIXME - accessibility
Fariborz Jahanian37931062009-03-10 16:22:08 +0000332 class GC_IVAR {
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +0000333 public:
Fariborz Jahanian37931062009-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 Jahaniandf1d9032009-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 Jahanian48543f52009-01-21 22:04:16 +0000346protected:
347 CodeGen::CodeGenModule &CGM;
348 // FIXME! May not be needing this after all.
Daniel Dunbardaf4ad42008-08-12 00:12:39 +0000349 unsigned ObjCABI;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000350
Fariborz Jahaniandf1d9032009-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 Jahanian37931062009-03-10 16:22:08 +0000355
Daniel Dunbar8ede0052008-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 Jahanian48543f52009-01-21 22:04:16 +0000365
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +0000366 /// ClassNames - uniqued class names.
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000367 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassNames;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000368
Daniel Dunbar5eec6142008-08-12 03:39:23 +0000369 /// MethodVarNames - uniqued method variable names.
370 llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000371
Daniel Dunbarcffcdac2008-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 Jahanian48543f52009-01-21 22:04:16 +0000375
Daniel Dunbar12996f52008-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 Jahanian48543f52009-01-21 22:04:16 +0000379
Daniel Dunbara6eb6b72008-08-23 00:19:03 +0000380 /// PropertyNames - uniqued method variable names.
381 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000382
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000383 /// ClassReferences - uniqued class references.
384 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000385
Daniel Dunbar5eec6142008-08-12 03:39:23 +0000386 /// SelectorReferences - uniqued selector references.
387 llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000388
Daniel Dunbarcffcdac2008-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 Jahanian48543f52009-01-21 22:04:16 +0000393
Daniel Dunbar35b777f2008-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 Jahanian48543f52009-01-21 22:04:16 +0000397
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000398 /// DefinedClasses - List of defined classes.
399 std::vector<llvm::GlobalValue*> DefinedClasses;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000400
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000401 /// DefinedCategories - List of defined categories.
402 std::vector<llvm::GlobalValue*> DefinedCategories;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000403
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000404 /// UsedGlobals - List of globals to pack into the llvm.used metadata
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000405 /// to prevent them from being clobbered.
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +0000406 std::vector<llvm::GlobalVariable*> UsedGlobals;
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000407
Fariborz Jahanian32b5ea22009-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);
Daniel Dunbar356f0742009-04-20 06:54:31 +0000425 llvm::Constant *GetMethodVarType(const FieldDecl *D);
Fariborz Jahanian32b5ea22009-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 Jahanian4c1e4612009-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 Jahanian6d49ab62009-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 Jahanian01b3e342009-03-05 22:39:55 +0000444 /// BuildIvarLayout - Builds ivar layout bitmap for the class
445 /// implementation for the __strong or __weak case.
446 ///
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +0000447 llvm::Constant *BuildIvarLayout(const ObjCImplementationDecl *OI,
448 bool ForStrongLayout);
Fariborz Jahanian01b3e342009-03-05 22:39:55 +0000449
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +0000450 void BuildAggrIvarLayout(const ObjCInterfaceDecl *OI,
451 const llvm::StructLayout *Layout,
Fariborz Jahanian37931062009-03-10 16:22:08 +0000452 const RecordDecl *RD,
Chris Lattner9329cf52009-03-31 08:48:01 +0000453 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahanian01b3e342009-03-05 22:39:55 +0000454 unsigned int BytePos, bool ForStrongLayout,
455 int &Index, int &SkIndex, bool &HasUnion);
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +0000456
Fariborz Jahanian7345eba2009-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 Jahanian7b709bb2009-01-28 22:18:42 +0000462 /// EmitPropertyList - Emit the given property list. The return
463 /// value has type PropertyListPtrTy.
464 llvm::Constant *EmitPropertyList(const std::string &Name,
465 const Decl *Container,
466 const ObjCContainerDecl *OCD,
467 const ObjCCommonTypesHelper &ObjCTypes);
468
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +0000469 /// GetProtocolRef - Return a reference to the internal protocol
470 /// description, creating an empty one if it has not been
471 /// defined. The return value has type ProtocolPtrTy.
472 llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD);
Fariborz Jahaniand65949b2009-03-08 20:18:37 +0000473
474 /// GetIvarBaseOffset - returns ivars byte offset.
475 uint64_t GetIvarBaseOffset(const llvm::StructLayout *Layout,
Chris Lattnerd391dab2009-03-31 08:33:16 +0000476 const FieldDecl *Field);
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +0000477
Chris Lattnerd391dab2009-03-31 08:33:16 +0000478 /// GetFieldBaseOffset - return's field byte offset.
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +0000479 uint64_t GetFieldBaseOffset(const ObjCInterfaceDecl *OI,
480 const llvm::StructLayout *Layout,
Chris Lattnerd391dab2009-03-31 08:33:16 +0000481 const FieldDecl *Field);
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +0000482
Daniel Dunbarc4594f22009-03-09 20:09:19 +0000483 /// CreateMetadataVar - Create a global variable with internal
484 /// linkage for use by the Objective-C runtime.
485 ///
486 /// This is a convenience wrapper which not only creates the
487 /// variable, but also sets the section and alignment and adds the
488 /// global to the UsedGlobals list.
Daniel Dunbareddddd22009-03-09 20:50:13 +0000489 ///
490 /// \param Name - The variable name.
491 /// \param Init - The variable initializer; this is also used to
492 /// define the type of the variable.
493 /// \param Section - The section the variable should go into, or 0.
494 /// \param Align - The alignment for the variable, or 0.
495 /// \param AddToUsed - Whether the variable should be added to
Daniel Dunbar6b343692009-04-14 17:42:51 +0000496 /// "llvm.used".
Daniel Dunbarc4594f22009-03-09 20:09:19 +0000497 llvm::GlobalVariable *CreateMetadataVar(const std::string &Name,
498 llvm::Constant *Init,
499 const char *Section,
Daniel Dunbareddddd22009-03-09 20:50:13 +0000500 unsigned Align,
501 bool AddToUsed);
Daniel Dunbarc4594f22009-03-09 20:09:19 +0000502
Daniel Dunbar356f0742009-04-20 06:54:31 +0000503 /// GetNamedIvarList - Return the list of ivars in the interface
504 /// itself (not including super classes and not including unnamed
505 /// bitfields).
506 ///
507 /// For the non-fragile ABI, this also includes synthesized property
508 /// ivars.
509 void GetNamedIvarList(const ObjCInterfaceDecl *OID,
510 llvm::SmallVector<ObjCIvarDecl*, 16> &Res) const;
511
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000512public:
513 CGObjCCommonMac(CodeGen::CodeGenModule &cgm) : CGM(cgm)
514 { }
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +0000515
Steve Naroff2c8a08e2009-03-31 16:53:37 +0000516 virtual llvm::Constant *GenerateConstantString(const ObjCStringLiteral *SL);
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +0000517
518 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
519 const ObjCContainerDecl *CD=0);
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +0000520
521 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
522
523 /// GetOrEmitProtocol - Get the protocol object for the given
524 /// declaration, emitting it if necessary. The return value has type
525 /// ProtocolPtrTy.
526 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD)=0;
527
528 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
529 /// object for the given declaration, emitting it if needed. These
530 /// forward references will be filled in with empty bodies if no
531 /// definition is seen. The return value has type ProtocolPtrTy.
532 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD)=0;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000533};
534
535class CGObjCMac : public CGObjCCommonMac {
536private:
537 ObjCTypesHelper ObjCTypes;
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000538 /// EmitImageInfo - Emit the image info marker used to encode some module
539 /// level information.
540 void EmitImageInfo();
541
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +0000542 /// EmitModuleInfo - Another marker encoding module level
543 /// information.
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +0000544 void EmitModuleInfo();
545
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000546 /// EmitModuleSymols - Emit module symbols, the list of defined
547 /// classes and categories. The result has type SymtabPtrTy.
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +0000548 llvm::Constant *EmitModuleSymbols();
549
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000550 /// FinishModule - Write out global data structures at the end of
551 /// processing a translation unit.
552 void FinishModule();
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000553
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000554 /// EmitClassExtension - Generate the class extension structure used
555 /// to store the weak ivar layout and properties. The return value
556 /// has type ClassExtensionPtrTy.
557 llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID);
558
559 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
560 /// for the given class.
Daniel Dunbard916e6e2008-11-01 01:53:16 +0000561 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000562 const ObjCInterfaceDecl *ID);
563
Daniel Dunbar87062ff2008-08-23 09:25:55 +0000564 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbardd851282008-08-30 05:35:15 +0000565 QualType ResultType,
566 Selector Sel,
Daniel Dunbar87062ff2008-08-23 09:25:55 +0000567 llvm::Value *Arg0,
Daniel Dunbar0ed60b02008-08-30 03:02:31 +0000568 QualType Arg0Ty,
569 bool IsSuper,
570 const CallArgList &CallArgs);
Daniel Dunbar87062ff2008-08-23 09:25:55 +0000571
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000572 /// EmitIvarList - Emit the ivar list for the given
573 /// implementation. If ForClass is true the list of class ivars
574 /// (i.e. metaclass ivars) is emitted, otherwise the list of
575 /// interface ivars will be emitted. The return value has type
576 /// IvarListPtrTy.
577 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanianf2a94cd2009-01-28 19:12:34 +0000578 bool ForClass);
579
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +0000580 /// EmitMetaClass - Emit a forward reference to the class structure
581 /// for the metaclass of the given interface. The return value has
582 /// type ClassPtrTy.
583 llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
584
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000585 /// EmitMetaClass - Emit a class structure for the metaclass of the
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +0000586 /// given implementation. The return value has type ClassPtrTy.
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000587 llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
588 llvm::Constant *Protocols,
Daniel Dunbar12996f52008-08-26 21:51:14 +0000589 const llvm::Type *InterfaceTy,
Daniel Dunbarfe131f02008-08-27 02:31:56 +0000590 const ConstantVector &Methods);
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +0000591
Daniel Dunbarfe131f02008-08-27 02:31:56 +0000592 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +0000593
Daniel Dunbarfe131f02008-08-27 02:31:56 +0000594 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000595
596 /// EmitMethodList - Emit the method list for the given
Daniel Dunbar6b57d432008-08-26 08:29:31 +0000597 /// implementation. The return value has type MethodListPtrTy.
Daniel Dunbar4246a8b2008-08-22 20:34:54 +0000598 llvm::Constant *EmitMethodList(const std::string &Name,
599 const char *Section,
Daniel Dunbarfe131f02008-08-27 02:31:56 +0000600 const ConstantVector &Methods);
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000601
602 /// EmitMethodDescList - Emit a method description list for a list of
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000603 /// method declarations.
604 /// - TypeName: The name for the type containing the methods.
605 /// - IsProtocol: True iff these methods are for a protocol.
606 /// - ClassMethds: True iff these are class methods.
607 /// - Required: When true, only "required" methods are
608 /// listed. Similarly, when false only "optional" methods are
609 /// listed. For classes this should always be true.
610 /// - begin, end: The method list to output.
611 ///
612 /// The return value has type MethodDescriptionListPtrTy.
Daniel Dunbarfe131f02008-08-27 02:31:56 +0000613 llvm::Constant *EmitMethodDescList(const std::string &Name,
614 const char *Section,
615 const ConstantVector &Methods);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000616
Daniel Dunbar35b777f2008-10-29 22:36:39 +0000617 /// GetOrEmitProtocol - Get the protocol object for the given
618 /// declaration, emitting it if necessary. The return value has type
619 /// ProtocolPtrTy.
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +0000620 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
Daniel Dunbar35b777f2008-10-29 22:36:39 +0000621
622 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
623 /// object for the given declaration, emitting it if needed. These
624 /// forward references will be filled in with empty bodies if no
625 /// definition is seen. The return value has type ProtocolPtrTy.
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +0000626 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
Daniel Dunbar35b777f2008-10-29 22:36:39 +0000627
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000628 /// EmitProtocolExtension - Generate the protocol extension
629 /// structure used to store optional instance and class methods, and
630 /// protocol properties. The return value has type
631 /// ProtocolExtensionPtrTy.
Daniel Dunbarfe131f02008-08-27 02:31:56 +0000632 llvm::Constant *
633 EmitProtocolExtension(const ObjCProtocolDecl *PD,
634 const ConstantVector &OptInstanceMethods,
635 const ConstantVector &OptClassMethods);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000636
637 /// EmitProtocolList - Generate the list of referenced
638 /// protocols. The return value has type ProtocolListPtrTy.
Daniel Dunbar67e778b2008-08-21 21:57:41 +0000639 llvm::Constant *EmitProtocolList(const std::string &Name,
640 ObjCProtocolDecl::protocol_iterator begin,
641 ObjCProtocolDecl::protocol_iterator end);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000642
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000643 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
644 /// for the given selector.
Daniel Dunbard916e6e2008-11-01 01:53:16 +0000645 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +0000646
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +0000647 public:
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000648 CGObjCMac(CodeGen::CodeGenModule &cgm);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000649
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +0000650 virtual llvm::Function *ModuleInitFunction();
651
Daniel Dunbara04840b2008-08-23 03:46:30 +0000652 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbardd851282008-08-30 05:35:15 +0000653 QualType ResultType,
654 Selector Sel,
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +0000655 llvm::Value *Receiver,
Daniel Dunbar0ed60b02008-08-30 03:02:31 +0000656 bool IsClassMessage,
657 const CallArgList &CallArgs);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000658
Daniel Dunbara04840b2008-08-23 03:46:30 +0000659 virtual CodeGen::RValue
660 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbardd851282008-08-30 05:35:15 +0000661 QualType ResultType,
662 Selector Sel,
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +0000663 const ObjCInterfaceDecl *Class,
Fariborz Jahanian17636fa2009-02-28 20:07:56 +0000664 bool isCategoryImpl,
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +0000665 llvm::Value *Receiver,
Daniel Dunbar0ed60b02008-08-30 03:02:31 +0000666 bool IsClassMessage,
667 const CallArgList &CallArgs);
Daniel Dunbar434627a2008-08-16 00:25:02 +0000668
Daniel Dunbard916e6e2008-11-01 01:53:16 +0000669 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000670 const ObjCInterfaceDecl *ID);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000671
Daniel Dunbard916e6e2008-11-01 01:53:16 +0000672 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000673
Daniel Dunbarac93e472008-08-15 22:20:32 +0000674 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000675
Daniel Dunbarac93e472008-08-15 22:20:32 +0000676 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000677
Daniel Dunbard916e6e2008-11-01 01:53:16 +0000678 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbar84bb85f2008-08-13 00:59:25 +0000679 const ObjCProtocolDecl *PD);
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +0000680
Chris Lattneraea1aee2009-03-22 21:03:39 +0000681 virtual llvm::Constant *GetPropertyGetFunction();
682 virtual llvm::Constant *GetPropertySetFunction();
683 virtual llvm::Constant *EnumerationMutationFunction();
Anders Carlssonb01a2112008-09-09 10:04:29 +0000684
Fariborz Jahanianfbeda7b2008-11-21 00:49:24 +0000685 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
686 const Stmt &S);
Anders Carlssonb01a2112008-09-09 10:04:29 +0000687 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
688 const ObjCAtThrowStmt &S);
Fariborz Jahanian252d87f2008-11-18 22:37:34 +0000689 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian3305ad32008-11-18 21:45:40 +0000690 llvm::Value *AddrWeakObj);
Fariborz Jahanian252d87f2008-11-18 22:37:34 +0000691 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
692 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanian17958902008-11-19 00:59:10 +0000693 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
694 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianf310b592008-11-20 19:23:36 +0000695 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
696 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian17958902008-11-19 00:59:10 +0000697 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
698 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian4337afe2009-02-02 20:02:29 +0000699
Fariborz Jahanianc912eb72009-02-03 19:03:09 +0000700 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
701 QualType ObjectTy,
702 llvm::Value *BaseValue,
703 const ObjCIvarDecl *Ivar,
704 const FieldDecl *Field,
705 unsigned CVRQualifiers);
Fariborz Jahanian27cc6662009-02-10 19:02:04 +0000706 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
707 ObjCInterfaceDecl *Interface,
708 const ObjCIvarDecl *Ivar);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000709};
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000710
Fariborz Jahaniand0374812009-01-22 23:02:58 +0000711class CGObjCNonFragileABIMac : public CGObjCCommonMac {
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000712private:
Fariborz Jahaniand0374812009-01-22 23:02:58 +0000713 ObjCNonFragileABITypesHelper ObjCTypes;
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +0000714 llvm::GlobalVariable* ObjCEmptyCacheVar;
715 llvm::GlobalVariable* ObjCEmptyVtableVar;
Daniel Dunbarc0318b22009-03-02 06:08:11 +0000716
Daniel Dunbar3c190812009-04-18 08:51:00 +0000717 /// SuperClassReferences - uniqued super class references.
718 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> SuperClassReferences;
719
Fariborz Jahanianf3a44012009-02-06 20:09:23 +0000720 /// MetaClassReferences - uniqued meta class references.
721 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> MetaClassReferences;
Daniel Dunbar9c285e72009-03-01 04:46:24 +0000722
723 /// EHTypeReferences - uniqued class ehtype references.
724 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> EHTypeReferences;
Daniel Dunbarc0318b22009-03-02 06:08:11 +0000725
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +0000726 /// FinishNonFragileABIModule - Write out global data structures at the end of
727 /// processing a translation unit.
728 void FinishNonFragileABIModule();
Daniel Dunbarc2129532009-04-08 04:21:03 +0000729
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +0000730 llvm::GlobalVariable * BuildClassRoTInitializer(unsigned flags,
731 unsigned InstanceStart,
732 unsigned InstanceSize,
733 const ObjCImplementationDecl *ID);
Fariborz Jahanian06726462009-01-24 21:21:53 +0000734 llvm::GlobalVariable * BuildClassMetaData(std::string &ClassName,
735 llvm::Constant *IsAGV,
736 llvm::Constant *SuperClassGV,
Fariborz Jahanian51dcacb2009-01-31 00:59:10 +0000737 llvm::Constant *ClassRoGV,
738 bool HiddenVisibility);
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +0000739
740 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
741
Fariborz Jahanian151747b2009-01-30 00:46:37 +0000742 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
743
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +0000744 /// EmitMethodList - Emit the method list for the given
745 /// implementation. The return value has type MethodListnfABITy.
746 llvm::Constant *EmitMethodList(const std::string &Name,
747 const char *Section,
Fariborz Jahanian3f1cc562009-01-27 19:38:51 +0000748 const ConstantVector &Methods);
749 /// EmitIvarList - Emit the ivar list for the given
750 /// implementation. If ForClass is true the list of class ivars
751 /// (i.e. metaclass ivars) is emitted, otherwise the list of
752 /// interface ivars will be emitted. The return value has type
753 /// IvarListnfABIPtrTy.
754 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID);
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +0000755
Fariborz Jahaniancc00f922009-02-10 20:21:06 +0000756 llvm::Constant *EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,
Fariborz Jahanian150f7732009-01-28 01:36:42 +0000757 const ObjCIvarDecl *Ivar,
Fariborz Jahanian3175ddd2009-01-28 01:05:23 +0000758 unsigned long int offset);
759
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +0000760 /// GetOrEmitProtocol - Get the protocol object for the given
761 /// declaration, emitting it if necessary. The return value has type
762 /// ProtocolPtrTy.
763 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
764
765 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
766 /// object for the given declaration, emitting it if needed. These
767 /// forward references will be filled in with empty bodies if no
768 /// definition is seen. The return value has type ProtocolPtrTy.
769 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
770
771 /// EmitProtocolList - Generate the list of referenced
772 /// protocols. The return value has type ProtocolListPtrTy.
773 llvm::Constant *EmitProtocolList(const std::string &Name,
774 ObjCProtocolDecl::protocol_iterator begin,
Fariborz Jahanian7e881162009-02-04 00:22:57 +0000775 ObjCProtocolDecl::protocol_iterator end);
776
777 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
778 QualType ResultType,
779 Selector Sel,
Fariborz Jahanianf52110f2009-02-04 20:42:28 +0000780 llvm::Value *Receiver,
Fariborz Jahanian7e881162009-02-04 00:22:57 +0000781 QualType Arg0Ty,
782 bool IsSuper,
783 const CallArgList &CallArgs);
Daniel Dunbarabbda222009-03-01 04:40:10 +0000784
785 /// GetClassGlobal - Return the global variable for the Objective-C
786 /// class of the given name.
Fariborz Jahanianab438842009-04-14 18:41:56 +0000787 llvm::GlobalVariable *GetClassGlobal(const std::string &Name);
788
Fariborz Jahanian917c0402009-02-05 20:41:40 +0000789 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
Daniel Dunbar3c190812009-04-18 08:51:00 +0000790 /// for the given class reference.
Fariborz Jahanian917c0402009-02-05 20:41:40 +0000791 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar3c190812009-04-18 08:51:00 +0000792 const ObjCInterfaceDecl *ID);
793
794 /// EmitSuperClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
795 /// for the given super class reference.
796 llvm::Value *EmitSuperClassRef(CGBuilderTy &Builder,
797 const ObjCInterfaceDecl *ID);
Fariborz Jahanianf3a44012009-02-06 20:09:23 +0000798
799 /// EmitMetaClassRef - Return a Value * of the address of _class_t
800 /// meta-data
801 llvm::Value *EmitMetaClassRef(CGBuilderTy &Builder,
802 const ObjCInterfaceDecl *ID);
803
Fariborz Jahaniancc00f922009-02-10 20:21:06 +0000804 /// ObjCIvarOffsetVariable - Returns the ivar offset variable for
805 /// the given ivar.
806 ///
Daniel Dunbar07d204a2009-04-19 00:31:15 +0000807 llvm::GlobalVariable * ObjCIvarOffsetVariable(
Fariborz Jahaniana09a5142009-02-12 18:51:23 +0000808 const ObjCInterfaceDecl *ID,
Fariborz Jahaniancc00f922009-02-10 20:21:06 +0000809 const ObjCIvarDecl *Ivar);
Fariborz Jahanian917c0402009-02-05 20:41:40 +0000810
Fariborz Jahanianebb82c62009-02-11 20:51:17 +0000811 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
812 /// for the given selector.
813 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbar9c285e72009-03-01 04:46:24 +0000814
Daniel Dunbarc2129532009-04-08 04:21:03 +0000815 /// GetInterfaceEHType - Get the cached ehtype for the given Objective-C
Daniel Dunbar9c285e72009-03-01 04:46:24 +0000816 /// interface. The return value has type EHTypePtrTy.
Daniel Dunbarc2129532009-04-08 04:21:03 +0000817 llvm::Value *GetInterfaceEHType(const ObjCInterfaceDecl *ID,
818 bool ForDefinition);
Daniel Dunbara2d275d2009-04-07 05:48:37 +0000819
820 const char *getMetaclassSymbolPrefix() const {
821 return "OBJC_METACLASS_$_";
822 }
Daniel Dunbarc0318b22009-03-02 06:08:11 +0000823
Daniel Dunbara2d275d2009-04-07 05:48:37 +0000824 const char *getClassSymbolPrefix() const {
825 return "OBJC_CLASS_$_";
826 }
827
Daniel Dunbarecb5d402009-04-19 23:41:48 +0000828 void GetClassSizeInfo(const ObjCInterfaceDecl *OID,
829 uint32_t &InstanceStart,
830 uint32_t &InstanceSize);
831
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000832public:
Fariborz Jahaniand0374812009-01-22 23:02:58 +0000833 CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +0000834 // FIXME. All stubs for now!
835 virtual llvm::Function *ModuleInitFunction();
836
837 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
838 QualType ResultType,
839 Selector Sel,
840 llvm::Value *Receiver,
841 bool IsClassMessage,
Fariborz Jahanian7e881162009-02-04 00:22:57 +0000842 const CallArgList &CallArgs);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +0000843
844 virtual CodeGen::RValue
845 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
846 QualType ResultType,
847 Selector Sel,
848 const ObjCInterfaceDecl *Class,
Fariborz Jahanian17636fa2009-02-28 20:07:56 +0000849 bool isCategoryImpl,
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +0000850 llvm::Value *Receiver,
851 bool IsClassMessage,
Fariborz Jahanianf3a44012009-02-06 20:09:23 +0000852 const CallArgList &CallArgs);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +0000853
854 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Fariborz Jahanian917c0402009-02-05 20:41:40 +0000855 const ObjCInterfaceDecl *ID);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +0000856
857 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel)
Fariborz Jahanianebb82c62009-02-11 20:51:17 +0000858 { return EmitSelector(Builder, Sel); }
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +0000859
Fariborz Jahanianfe49a092009-01-26 18:32:24 +0000860 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +0000861
862 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +0000863 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Fariborz Jahanian5d13ab12009-01-30 18:58:59 +0000864 const ObjCProtocolDecl *PD);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +0000865
Chris Lattneraea1aee2009-03-22 21:03:39 +0000866 virtual llvm::Constant *GetPropertyGetFunction() {
Fariborz Jahanian27cc6662009-02-10 19:02:04 +0000867 return ObjCTypes.GetPropertyFn;
868 }
Chris Lattneraea1aee2009-03-22 21:03:39 +0000869 virtual llvm::Constant *GetPropertySetFunction() {
Fariborz Jahanian27cc6662009-02-10 19:02:04 +0000870 return ObjCTypes.SetPropertyFn;
871 }
Chris Lattneraea1aee2009-03-22 21:03:39 +0000872 virtual llvm::Constant *EnumerationMutationFunction() {
Daniel Dunbar978d2be2009-02-16 18:48:45 +0000873 return ObjCTypes.EnumerationMutationFn;
874 }
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +0000875
876 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar75de89f2009-02-24 07:47:38 +0000877 const Stmt &S);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +0000878 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Anders Carlsson1cf75362009-02-16 22:59:18 +0000879 const ObjCAtThrowStmt &S);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +0000880 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian5eefb432009-02-16 22:52:32 +0000881 llvm::Value *AddrWeakObj);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +0000882 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian5eefb432009-02-16 22:52:32 +0000883 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +0000884 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian5eefb432009-02-16 22:52:32 +0000885 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +0000886 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian5eefb432009-02-16 22:52:32 +0000887 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +0000888 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian5eefb432009-02-16 22:52:32 +0000889 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianc912eb72009-02-03 19:03:09 +0000890 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
891 QualType ObjectTy,
892 llvm::Value *BaseValue,
893 const ObjCIvarDecl *Ivar,
894 const FieldDecl *Field,
895 unsigned CVRQualifiers);
Fariborz Jahanian27cc6662009-02-10 19:02:04 +0000896 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
897 ObjCInterfaceDecl *Interface,
898 const ObjCIvarDecl *Ivar);
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000899};
900
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000901} // end anonymous namespace
Daniel Dunbardaf4ad42008-08-12 00:12:39 +0000902
903/* *** Helper Functions *** */
904
905/// getConstantGEP() - Help routine to construct simple GEPs.
906static llvm::Constant *getConstantGEP(llvm::Constant *C,
907 unsigned idx0,
908 unsigned idx1) {
909 llvm::Value *Idxs[] = {
910 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx0),
911 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx1)
912 };
913 return llvm::ConstantExpr::getGetElementPtr(C, Idxs, 2);
914}
915
Daniel Dunbarc2129532009-04-08 04:21:03 +0000916/// hasObjCExceptionAttribute - Return true if this class or any super
917/// class has the __objc_exception__ attribute.
918static bool hasObjCExceptionAttribute(const ObjCInterfaceDecl *OID) {
Daniel Dunbar78582862009-04-13 21:08:27 +0000919 if (OID->hasAttr<ObjCExceptionAttr>())
Daniel Dunbarc2129532009-04-08 04:21:03 +0000920 return true;
921 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
922 return hasObjCExceptionAttribute(Super);
923 return false;
924}
925
Daniel Dunbardaf4ad42008-08-12 00:12:39 +0000926/* *** CGObjCMac Public Interface *** */
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000927
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000928CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm),
929 ObjCTypes(cgm)
Daniel Dunbardaf4ad42008-08-12 00:12:39 +0000930{
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000931 ObjCABI = 1;
Daniel Dunbardaf4ad42008-08-12 00:12:39 +0000932 EmitImageInfo();
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000933}
934
Daniel Dunbar434627a2008-08-16 00:25:02 +0000935/// GetClass - Return a reference to the class for the given interface
936/// decl.
Daniel Dunbard916e6e2008-11-01 01:53:16 +0000937llvm::Value *CGObjCMac::GetClass(CGBuilderTy &Builder,
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000938 const ObjCInterfaceDecl *ID) {
939 return EmitClassRef(Builder, ID);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000940}
941
942/// GetSelector - Return the pointer to the unique'd string for this selector.
Daniel Dunbard916e6e2008-11-01 01:53:16 +0000943llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar5eec6142008-08-12 03:39:23 +0000944 return EmitSelector(Builder, Sel);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000945}
946
Daniel Dunbardaf4ad42008-08-12 00:12:39 +0000947/// Generate a constant CFString object.
948/*
949 struct __builtin_CFString {
950 const int *isa; // point to __CFConstantStringClassReference
951 int flags;
952 const char *str;
953 long length;
954 };
955*/
956
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +0000957llvm::Constant *CGObjCCommonMac::GenerateConstantString(
Steve Naroff2c8a08e2009-03-31 16:53:37 +0000958 const ObjCStringLiteral *SL) {
Steve Naroff9a744e52009-04-01 13:55:36 +0000959 return CGM.GetAddrOfConstantCFString(SL->getString());
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000960}
961
962/// Generates a message send where the super is the receiver. This is
963/// a message send to self with special delivery semantics indicating
964/// which class's method should be called.
Daniel Dunbara04840b2008-08-23 03:46:30 +0000965CodeGen::RValue
966CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbardd851282008-08-30 05:35:15 +0000967 QualType ResultType,
968 Selector Sel,
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +0000969 const ObjCInterfaceDecl *Class,
Fariborz Jahanian17636fa2009-02-28 20:07:56 +0000970 bool isCategoryImpl,
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +0000971 llvm::Value *Receiver,
Daniel Dunbar0ed60b02008-08-30 03:02:31 +0000972 bool IsClassMessage,
Daniel Dunbar0a2da0f2008-09-09 01:06:48 +0000973 const CodeGen::CallArgList &CallArgs) {
Daniel Dunbar15245e52008-08-23 04:28:29 +0000974 // Create and init a super structure; this is a (receiver, class)
975 // pair we will pass to objc_msgSendSuper.
976 llvm::Value *ObjCSuper =
977 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
978 llvm::Value *ReceiverAsObject =
979 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
980 CGF.Builder.CreateStore(ReceiverAsObject,
981 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
Daniel Dunbar15245e52008-08-23 04:28:29 +0000982
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +0000983 // If this is a class message the metaclass is passed as the target.
984 llvm::Value *Target;
985 if (IsClassMessage) {
Fariborz Jahanian17636fa2009-02-28 20:07:56 +0000986 if (isCategoryImpl) {
987 // Message sent to 'super' in a class method defined in a category
988 // implementation requires an odd treatment.
989 // If we are in a class method, we must retrieve the
990 // _metaclass_ for the current class, pointed at by
991 // the class's "isa" pointer. The following assumes that
992 // isa" is the first ivar in a class (which it must be).
993 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
994 Target = CGF.Builder.CreateStructGEP(Target, 0);
995 Target = CGF.Builder.CreateLoad(Target);
996 }
997 else {
998 llvm::Value *MetaClassPtr = EmitMetaClassRef(Class);
999 llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1);
1000 llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr);
1001 Target = Super;
1002 }
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +00001003 } else {
1004 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
1005 }
Daniel Dunbar0ed60b02008-08-30 03:02:31 +00001006 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
1007 // and ObjCTypes types.
1008 const llvm::Type *ClassTy =
1009 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
Daniel Dunbar35b777f2008-10-29 22:36:39 +00001010 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +00001011 CGF.Builder.CreateStore(Target,
1012 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
1013
Daniel Dunbardd851282008-08-30 05:35:15 +00001014 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar0ed60b02008-08-30 03:02:31 +00001015 ObjCSuper, ObjCTypes.SuperPtrCTy,
1016 true, CallArgs);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001017}
Daniel Dunbar87062ff2008-08-23 09:25:55 +00001018
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001019/// Generate code for a message send expression.
Daniel Dunbara04840b2008-08-23 03:46:30 +00001020CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbardd851282008-08-30 05:35:15 +00001021 QualType ResultType,
1022 Selector Sel,
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +00001023 llvm::Value *Receiver,
Daniel Dunbar0ed60b02008-08-30 03:02:31 +00001024 bool IsClassMessage,
1025 const CallArgList &CallArgs) {
Daniel Dunbar87062ff2008-08-23 09:25:55 +00001026 llvm::Value *Arg0 =
1027 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy, "tmp");
Daniel Dunbardd851282008-08-30 05:35:15 +00001028 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar0ed60b02008-08-30 03:02:31 +00001029 Arg0, CGF.getContext().getObjCIdType(),
1030 false, CallArgs);
Daniel Dunbar87062ff2008-08-23 09:25:55 +00001031}
1032
1033CodeGen::RValue CGObjCMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbardd851282008-08-30 05:35:15 +00001034 QualType ResultType,
1035 Selector Sel,
Daniel Dunbar87062ff2008-08-23 09:25:55 +00001036 llvm::Value *Arg0,
Daniel Dunbar0ed60b02008-08-30 03:02:31 +00001037 QualType Arg0Ty,
1038 bool IsSuper,
1039 const CallArgList &CallArgs) {
1040 CallArgList ActualArgs;
Daniel Dunbar0a2da0f2008-09-09 01:06:48 +00001041 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
1042 ActualArgs.push_back(std::make_pair(RValue::get(EmitSelector(CGF.Builder,
1043 Sel)),
Daniel Dunbar0ed60b02008-08-30 03:02:31 +00001044 CGF.getContext().getObjCSelType()));
1045 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Daniel Dunbarac93e472008-08-15 22:20:32 +00001046
Daniel Dunbar34bda882009-02-02 23:23:47 +00001047 CodeGenTypes &Types = CGM.getTypes();
1048 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs);
1049 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo, false);
Daniel Dunbaraecef4c2008-10-17 03:24:53 +00001050
1051 llvm::Constant *Fn;
Daniel Dunbar6ee022b2009-02-02 22:03:45 +00001052 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Daniel Dunbaraecef4c2008-10-17 03:24:53 +00001053 Fn = ObjCTypes.getSendStretFn(IsSuper);
1054 } else if (ResultType->isFloatingType()) {
1055 // FIXME: Sadly, this is wrong. This actually depends on the
1056 // architecture. This happens to be right for x86-32 though.
1057 Fn = ObjCTypes.getSendFpretFn(IsSuper);
1058 } else {
1059 Fn = ObjCTypes.getSendFn(IsSuper);
1060 }
Daniel Dunbara9976a22008-09-10 07:00:50 +00001061 Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy));
Daniel Dunbar6ee022b2009-02-02 22:03:45 +00001062 return CGF.EmitCall(FnInfo, Fn, ActualArgs);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001063}
1064
Daniel Dunbard916e6e2008-11-01 01:53:16 +00001065llvm::Value *CGObjCMac::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbar84bb85f2008-08-13 00:59:25 +00001066 const ObjCProtocolDecl *PD) {
Daniel Dunbarb3518152008-09-04 04:33:15 +00001067 // FIXME: I don't understand why gcc generates this, or where it is
1068 // resolved. Investigate. Its also wasteful to look this up over and
1069 // over.
1070 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1071
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001072 return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
1073 ObjCTypes.ExternalProtocolPtrTy);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001074}
1075
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00001076void CGObjCCommonMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
Daniel Dunbar35b777f2008-10-29 22:36:39 +00001077 // FIXME: We shouldn't need this, the protocol decl should contain
1078 // enough information to tell us whether this was a declaration or a
1079 // definition.
1080 DefinedProtocols.insert(PD->getIdentifier());
1081
1082 // If we have generated a forward reference to this protocol, emit
1083 // it now. Otherwise do nothing, the protocol objects are lazily
1084 // emitted.
1085 if (Protocols.count(PD->getIdentifier()))
1086 GetOrEmitProtocol(PD);
1087}
1088
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00001089llvm::Constant *CGObjCCommonMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar35b777f2008-10-29 22:36:39 +00001090 if (DefinedProtocols.count(PD->getIdentifier()))
1091 return GetOrEmitProtocol(PD);
1092 return GetOrEmitProtocolRef(PD);
1093}
1094
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001095/*
1096 // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions
1097 struct _objc_protocol {
1098 struct _objc_protocol_extension *isa;
1099 char *protocol_name;
1100 struct _objc_protocol_list *protocol_list;
1101 struct _objc__method_prototype_list *instance_methods;
1102 struct _objc__method_prototype_list *class_methods
1103 };
1104
1105 See EmitProtocolExtension().
1106*/
Daniel Dunbar35b777f2008-10-29 22:36:39 +00001107llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
1108 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1109
1110 // Early exit if a defining object has already been generated.
1111 if (Entry && Entry->hasInitializer())
1112 return Entry;
1113
Daniel Dunbar8ede0052008-08-25 06:02:07 +00001114 // FIXME: I don't understand why gcc generates this, or where it is
1115 // resolved. Investigate. Its also wasteful to look this up over and
1116 // over.
1117 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1118
Chris Lattnerd120b9e2008-11-24 03:54:41 +00001119 const char *ProtocolName = PD->getNameAsCString();
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001120
1121 // Construct method lists.
1122 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1123 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001124 for (ObjCProtocolDecl::instmeth_iterator
1125 i = PD->instmeth_begin(CGM.getContext()),
1126 e = PD->instmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001127 ObjCMethodDecl *MD = *i;
1128 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1129 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1130 OptInstanceMethods.push_back(C);
1131 } else {
1132 InstanceMethods.push_back(C);
1133 }
1134 }
1135
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001136 for (ObjCProtocolDecl::classmeth_iterator
1137 i = PD->classmeth_begin(CGM.getContext()),
1138 e = PD->classmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001139 ObjCMethodDecl *MD = *i;
1140 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1141 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1142 OptClassMethods.push_back(C);
1143 } else {
1144 ClassMethods.push_back(C);
1145 }
1146 }
1147
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001148 std::vector<llvm::Constant*> Values(5);
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001149 Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001150 Values[1] = GetClassName(PD->getIdentifier());
Daniel Dunbar67e778b2008-08-21 21:57:41 +00001151 Values[2] =
Chris Lattner271d4c22008-11-24 05:29:24 +00001152 EmitProtocolList("\01L_OBJC_PROTOCOL_REFS_" + PD->getNameAsString(),
Daniel Dunbar67e778b2008-08-21 21:57:41 +00001153 PD->protocol_begin(),
1154 PD->protocol_end());
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001155 Values[3] =
Chris Lattner271d4c22008-11-24 05:29:24 +00001156 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_"
1157 + PD->getNameAsString(),
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001158 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1159 InstanceMethods);
1160 Values[4] =
Chris Lattner271d4c22008-11-24 05:29:24 +00001161 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_"
1162 + PD->getNameAsString(),
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001163 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1164 ClassMethods);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001165 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
1166 Values);
1167
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001168 if (Entry) {
Daniel Dunbar35b777f2008-10-29 22:36:39 +00001169 // Already created, fix the linkage and update the initializer.
1170 Entry->setLinkage(llvm::GlobalValue::InternalLinkage);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001171 Entry->setInitializer(Init);
1172 } else {
1173 Entry =
1174 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
1175 llvm::GlobalValue::InternalLinkage,
1176 Init,
1177 std::string("\01L_OBJC_PROTOCOL_")+ProtocolName,
1178 &CGM.getModule());
1179 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar56756c32009-03-09 22:18:41 +00001180 Entry->setAlignment(4);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001181 UsedGlobals.push_back(Entry);
1182 // FIXME: Is this necessary? Why only for protocol?
1183 Entry->setAlignment(4);
1184 }
Daniel Dunbar35b777f2008-10-29 22:36:39 +00001185
1186 return Entry;
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001187}
1188
Daniel Dunbar35b777f2008-10-29 22:36:39 +00001189llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001190 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1191
1192 if (!Entry) {
Daniel Dunbar35b777f2008-10-29 22:36:39 +00001193 // We use the initializer as a marker of whether this is a forward
1194 // reference or not. At module finalization we add the empty
1195 // contents for protocols which were referenced but never defined.
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001196 Entry =
1197 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
Daniel Dunbar35b777f2008-10-29 22:36:39 +00001198 llvm::GlobalValue::ExternalLinkage,
1199 0,
Chris Lattner271d4c22008-11-24 05:29:24 +00001200 "\01L_OBJC_PROTOCOL_" + PD->getNameAsString(),
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001201 &CGM.getModule());
1202 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar56756c32009-03-09 22:18:41 +00001203 Entry->setAlignment(4);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001204 UsedGlobals.push_back(Entry);
1205 // FIXME: Is this necessary? Why only for protocol?
1206 Entry->setAlignment(4);
1207 }
1208
1209 return Entry;
1210}
1211
1212/*
1213 struct _objc_protocol_extension {
1214 uint32_t size;
1215 struct objc_method_description_list *optional_instance_methods;
1216 struct objc_method_description_list *optional_class_methods;
1217 struct objc_property_list *instance_properties;
1218 };
1219*/
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001220llvm::Constant *
1221CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
1222 const ConstantVector &OptInstanceMethods,
1223 const ConstantVector &OptClassMethods) {
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001224 uint64_t Size =
Daniel Dunbard8439f22009-01-12 21:08:18 +00001225 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolExtensionTy);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001226 std::vector<llvm::Constant*> Values(4);
1227 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001228 Values[1] =
Chris Lattner271d4c22008-11-24 05:29:24 +00001229 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_"
1230 + PD->getNameAsString(),
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001231 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1232 OptInstanceMethods);
1233 Values[2] =
Chris Lattner271d4c22008-11-24 05:29:24 +00001234 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_"
1235 + PD->getNameAsString(),
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001236 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1237 OptClassMethods);
Chris Lattner271d4c22008-11-24 05:29:24 +00001238 Values[3] = EmitPropertyList("\01L_OBJC_$_PROP_PROTO_LIST_" +
1239 PD->getNameAsString(),
Fariborz Jahanian7b709bb2009-01-28 22:18:42 +00001240 0, PD, ObjCTypes);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001241
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001242 // Return null if no extension bits are used.
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001243 if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
1244 Values[3]->isNullValue())
1245 return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
1246
1247 llvm::Constant *Init =
1248 llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001249
Daniel Dunbar90d88f92009-03-09 21:49:58 +00001250 // No special section, but goes in llvm.used
1251 return CreateMetadataVar("\01L_OBJC_PROTOCOLEXT_" + PD->getNameAsString(),
1252 Init,
1253 0, 0, true);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001254}
1255
1256/*
1257 struct objc_protocol_list {
1258 struct objc_protocol_list *next;
1259 long count;
1260 Protocol *list[];
1261 };
1262*/
Daniel Dunbar67e778b2008-08-21 21:57:41 +00001263llvm::Constant *
1264CGObjCMac::EmitProtocolList(const std::string &Name,
1265 ObjCProtocolDecl::protocol_iterator begin,
1266 ObjCProtocolDecl::protocol_iterator end) {
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001267 std::vector<llvm::Constant*> ProtocolRefs;
1268
Daniel Dunbar67e778b2008-08-21 21:57:41 +00001269 for (; begin != end; ++begin)
1270 ProtocolRefs.push_back(GetProtocolRef(*begin));
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001271
1272 // Just return null for empty protocol lists
1273 if (ProtocolRefs.empty())
1274 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1275
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001276 // This list is null terminated.
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001277 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
1278
1279 std::vector<llvm::Constant*> Values(3);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001280 // This field is only used by the runtime.
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001281 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1282 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
1283 Values[2] =
1284 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
1285 ProtocolRefs.size()),
1286 ProtocolRefs);
1287
1288 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1289 llvm::GlobalVariable *GV =
Daniel Dunbar90d88f92009-03-09 21:49:58 +00001290 CreateMetadataVar(Name, Init, "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbar56756c32009-03-09 22:18:41 +00001291 4, false);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001292 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
1293}
1294
1295/*
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00001296 struct _objc_property {
1297 const char * const name;
1298 const char * const attributes;
1299 };
1300
1301 struct _objc_property_list {
1302 uint32_t entsize; // sizeof (struct _objc_property)
1303 uint32_t prop_count;
1304 struct _objc_property[prop_count];
1305 };
1306*/
Fariborz Jahanian7b709bb2009-01-28 22:18:42 +00001307llvm::Constant *CGObjCCommonMac::EmitPropertyList(const std::string &Name,
1308 const Decl *Container,
1309 const ObjCContainerDecl *OCD,
1310 const ObjCCommonTypesHelper &ObjCTypes) {
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00001311 std::vector<llvm::Constant*> Properties, Prop(2);
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001312 for (ObjCContainerDecl::prop_iterator I = OCD->prop_begin(CGM.getContext()),
1313 E = OCD->prop_end(CGM.getContext()); I != E; ++I) {
Steve Naroffdcf1e842009-01-11 12:47:58 +00001314 const ObjCPropertyDecl *PD = *I;
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00001315 Prop[0] = GetPropertyName(PD->getIdentifier());
Daniel Dunbar698d6f32008-08-28 04:38:10 +00001316 Prop[1] = GetPropertyTypeString(PD, Container);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00001317 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
1318 Prop));
1319 }
1320
1321 // Return null for empty list.
1322 if (Properties.empty())
1323 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1324
1325 unsigned PropertySize =
Daniel Dunbard8439f22009-01-12 21:08:18 +00001326 CGM.getTargetData().getTypePaddedSize(ObjCTypes.PropertyTy);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00001327 std::vector<llvm::Constant*> Values(3);
1328 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
1329 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
1330 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
1331 Properties.size());
1332 Values[2] = llvm::ConstantArray::get(AT, Properties);
1333 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1334
Daniel Dunbar90d88f92009-03-09 21:49:58 +00001335 llvm::GlobalVariable *GV =
Daniel Dunbar9dfd3a72009-04-15 02:56:18 +00001336 CreateMetadataVar(Name, Init,
1337 (ObjCABI == 2) ? "__DATA, __objc_const" :
1338 "__OBJC,__property,regular,no_dead_strip",
1339 (ObjCABI == 2) ? 8 : 4,
1340 true);
Daniel Dunbar90d88f92009-03-09 21:49:58 +00001341 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.PropertyListPtrTy);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00001342}
1343
1344/*
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001345 struct objc_method_description_list {
1346 int count;
1347 struct objc_method_description list[];
1348 };
1349*/
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001350llvm::Constant *
1351CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
1352 std::vector<llvm::Constant*> Desc(2);
1353 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1354 ObjCTypes.SelectorPtrTy);
1355 Desc[1] = GetMethodVarType(MD);
1356 return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
1357 Desc);
1358}
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001359
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001360llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name,
1361 const char *Section,
1362 const ConstantVector &Methods) {
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001363 // Return null for empty list.
1364 if (Methods.empty())
1365 return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
1366
1367 std::vector<llvm::Constant*> Values(2);
1368 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1369 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
1370 Methods.size());
1371 Values[1] = llvm::ConstantArray::get(AT, Methods);
1372 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1373
Daniel Dunbar9dfd3a72009-04-15 02:56:18 +00001374 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001375 return llvm::ConstantExpr::getBitCast(GV,
1376 ObjCTypes.MethodDescriptionListPtrTy);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001377}
1378
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001379/*
1380 struct _objc_category {
1381 char *category_name;
1382 char *class_name;
1383 struct _objc_method_list *instance_methods;
1384 struct _objc_method_list *class_methods;
1385 struct _objc_protocol_list *protocols;
1386 uint32_t size; // <rdar://4585769>
1387 struct _objc_property_list *instance_properties;
1388 };
1389 */
Daniel Dunbarac93e472008-08-15 22:20:32 +00001390void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Daniel Dunbard8439f22009-01-12 21:08:18 +00001391 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.CategoryTy);
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001392
Daniel Dunbar0cd49032008-08-26 23:03:11 +00001393 // FIXME: This is poor design, the OCD should have a pointer to the
1394 // category decl. Additionally, note that Category can be null for
1395 // the @implementation w/o an @interface case. Sema should just
1396 // create one for us as it does for @implementation so everyone else
1397 // can live life under a clear blue sky.
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001398 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Daniel Dunbar0cd49032008-08-26 23:03:11 +00001399 const ObjCCategoryDecl *Category =
1400 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Chris Lattner271d4c22008-11-24 05:29:24 +00001401 std::string ExtName(Interface->getNameAsString() + "_" +
1402 OCD->getNameAsString());
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001403
Daniel Dunbar12996f52008-08-26 21:51:14 +00001404 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1405 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
1406 e = OCD->instmeth_end(); i != e; ++i) {
1407 // Instance methods should always be defined.
1408 InstanceMethods.push_back(GetMethodConstant(*i));
1409 }
1410 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
1411 e = OCD->classmeth_end(); i != e; ++i) {
1412 // Class methods should always be defined.
1413 ClassMethods.push_back(GetMethodConstant(*i));
1414 }
1415
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001416 std::vector<llvm::Constant*> Values(7);
1417 Values[0] = GetClassName(OCD->getIdentifier());
1418 Values[1] = GetClassName(Interface->getIdentifier());
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00001419 Values[2] =
1420 EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") +
1421 ExtName,
1422 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
Daniel Dunbar12996f52008-08-26 21:51:14 +00001423 InstanceMethods);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00001424 Values[3] =
1425 EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName,
Daniel Dunbar9dfd3a72009-04-15 02:56:18 +00001426 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbar12996f52008-08-26 21:51:14 +00001427 ClassMethods);
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001428 if (Category) {
1429 Values[4] =
1430 EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName,
1431 Category->protocol_begin(),
1432 Category->protocol_end());
1433 } else {
1434 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1435 }
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001436 Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar0cd49032008-08-26 23:03:11 +00001437
1438 // If there is no category @interface then there can be no properties.
1439 if (Category) {
Daniel Dunbar9dfd3a72009-04-15 02:56:18 +00001440 Values[6] = EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
Fariborz Jahanian7b709bb2009-01-28 22:18:42 +00001441 OCD, Category, ObjCTypes);
Daniel Dunbar0cd49032008-08-26 23:03:11 +00001442 } else {
1443 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1444 }
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001445
1446 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
1447 Values);
1448
1449 llvm::GlobalVariable *GV =
Daniel Dunbar90d88f92009-03-09 21:49:58 +00001450 CreateMetadataVar(std::string("\01L_OBJC_CATEGORY_")+ExtName, Init,
1451 "__OBJC,__category,regular,no_dead_strip",
Daniel Dunbar56756c32009-03-09 22:18:41 +00001452 4, true);
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001453 DefinedCategories.push_back(GV);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001454}
1455
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001456// FIXME: Get from somewhere?
1457enum ClassFlags {
1458 eClassFlags_Factory = 0x00001,
1459 eClassFlags_Meta = 0x00002,
1460 // <rdr://5142207>
1461 eClassFlags_HasCXXStructors = 0x02000,
1462 eClassFlags_Hidden = 0x20000,
1463 eClassFlags_ABI2_Hidden = 0x00010,
1464 eClassFlags_ABI2_HasCXXStructors = 0x00004 // <rdr://4923634>
1465};
1466
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001467/*
1468 struct _objc_class {
1469 Class isa;
1470 Class super_class;
1471 const char *name;
1472 long version;
1473 long info;
1474 long instance_size;
1475 struct _objc_ivar_list *ivars;
1476 struct _objc_method_list *methods;
1477 struct _objc_cache *cache;
1478 struct _objc_protocol_list *protocols;
1479 // Objective-C 1.0 extensions (<rdr://4585769>)
1480 const char *ivar_layout;
1481 struct _objc_class_ext *ext;
1482 };
1483
1484 See EmitClassExtension();
1485 */
1486void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
Daniel Dunbar8ede0052008-08-25 06:02:07 +00001487 DefinedSymbols.insert(ID->getIdentifier());
1488
Chris Lattnerd120b9e2008-11-24 03:54:41 +00001489 std::string ClassName = ID->getNameAsString();
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001490 // FIXME: Gross
1491 ObjCInterfaceDecl *Interface =
1492 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Daniel Dunbar67e778b2008-08-21 21:57:41 +00001493 llvm::Constant *Protocols =
Chris Lattner271d4c22008-11-24 05:29:24 +00001494 EmitProtocolList("\01L_OBJC_CLASS_PROTOCOLS_" + ID->getNameAsString(),
Daniel Dunbar67e778b2008-08-21 21:57:41 +00001495 Interface->protocol_begin(),
1496 Interface->protocol_end());
Chris Lattner9fe470d2009-04-19 06:02:28 +00001497 const llvm::Type *InterfaceTy;
1498 if (Interface->isForwardDecl())
1499 InterfaceTy = llvm::StructType::get(NULL, NULL);
1500 else
1501 InterfaceTy =
Chris Lattner46ee0f32009-04-01 06:23:52 +00001502 CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(Interface));
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001503 unsigned Flags = eClassFlags_Factory;
Daniel Dunbard8439f22009-01-12 21:08:18 +00001504 unsigned Size = CGM.getTargetData().getTypePaddedSize(InterfaceTy);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001505
1506 // FIXME: Set CXX-structors flag.
Daniel Dunbar8394fda2009-04-14 06:00:08 +00001507 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001508 Flags |= eClassFlags_Hidden;
1509
Daniel Dunbar12996f52008-08-26 21:51:14 +00001510 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1511 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
1512 e = ID->instmeth_end(); i != e; ++i) {
1513 // Instance methods should always be defined.
1514 InstanceMethods.push_back(GetMethodConstant(*i));
1515 }
1516 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
1517 e = ID->classmeth_end(); i != e; ++i) {
1518 // Class methods should always be defined.
1519 ClassMethods.push_back(GetMethodConstant(*i));
1520 }
1521
1522 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
1523 e = ID->propimpl_end(); i != e; ++i) {
1524 ObjCPropertyImplDecl *PID = *i;
1525
1526 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1527 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1528
1529 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
1530 if (llvm::Constant *C = GetMethodConstant(MD))
1531 InstanceMethods.push_back(C);
1532 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
1533 if (llvm::Constant *C = GetMethodConstant(MD))
1534 InstanceMethods.push_back(C);
1535 }
1536 }
1537
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001538 std::vector<llvm::Constant*> Values(12);
Daniel Dunbar12996f52008-08-26 21:51:14 +00001539 Values[ 0] = EmitMetaClass(ID, Protocols, InterfaceTy, ClassMethods);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001540 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
Daniel Dunbar8ede0052008-08-25 06:02:07 +00001541 // Record a reference to the super class.
1542 LazySymbols.insert(Super->getIdentifier());
1543
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001544 Values[ 1] =
1545 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1546 ObjCTypes.ClassPtrTy);
1547 } else {
1548 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1549 }
1550 Values[ 2] = GetClassName(ID->getIdentifier());
1551 // Version is always 0.
1552 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1553 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1554 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanianf2a94cd2009-01-28 19:12:34 +00001555 Values[ 6] = EmitIvarList(ID, false);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00001556 Values[ 7] =
Chris Lattner271d4c22008-11-24 05:29:24 +00001557 EmitMethodList("\01L_OBJC_INSTANCE_METHODS_" + ID->getNameAsString(),
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00001558 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbar12996f52008-08-26 21:51:14 +00001559 InstanceMethods);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001560 // cache is always NULL.
1561 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1562 Values[ 9] = Protocols;
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001563 // FIXME: Set ivar_layout
Fariborz Jahanian738ee712009-03-25 22:36:49 +00001564 // Values[10] = BuildIvarLayout(ID, true);
1565 Values[10] = GetIvarLayoutName(0, ObjCTypes);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001566 Values[11] = EmitClassExtension(ID);
1567 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1568 Values);
1569
1570 llvm::GlobalVariable *GV =
Daniel Dunbar90d88f92009-03-09 21:49:58 +00001571 CreateMetadataVar(std::string("\01L_OBJC_CLASS_")+ClassName, Init,
1572 "__OBJC,__class,regular,no_dead_strip",
Daniel Dunbar56756c32009-03-09 22:18:41 +00001573 4, true);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001574 DefinedClasses.push_back(GV);
1575}
1576
1577llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
1578 llvm::Constant *Protocols,
Daniel Dunbar12996f52008-08-26 21:51:14 +00001579 const llvm::Type *InterfaceTy,
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001580 const ConstantVector &Methods) {
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001581 unsigned Flags = eClassFlags_Meta;
Daniel Dunbard8439f22009-01-12 21:08:18 +00001582 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassTy);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001583
Daniel Dunbar8394fda2009-04-14 06:00:08 +00001584 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001585 Flags |= eClassFlags_Hidden;
1586
1587 std::vector<llvm::Constant*> Values(12);
1588 // The isa for the metaclass is the root of the hierarchy.
1589 const ObjCInterfaceDecl *Root = ID->getClassInterface();
1590 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
1591 Root = Super;
1592 Values[ 0] =
1593 llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
1594 ObjCTypes.ClassPtrTy);
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001595 // The super class for the metaclass is emitted as the name of the
1596 // super class. The runtime fixes this up to point to the
1597 // *metaclass* for the super class.
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001598 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
1599 Values[ 1] =
1600 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1601 ObjCTypes.ClassPtrTy);
1602 } else {
1603 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1604 }
1605 Values[ 2] = GetClassName(ID->getIdentifier());
1606 // Version is always 0.
1607 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1608 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1609 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanianf2a94cd2009-01-28 19:12:34 +00001610 Values[ 6] = EmitIvarList(ID, true);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00001611 Values[ 7] =
Chris Lattner271d4c22008-11-24 05:29:24 +00001612 EmitMethodList("\01L_OBJC_CLASS_METHODS_" + ID->getNameAsString(),
Daniel Dunbar9dfd3a72009-04-15 02:56:18 +00001613 "__OBJC,__cls_meth,regular,no_dead_strip",
Daniel Dunbar12996f52008-08-26 21:51:14 +00001614 Methods);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001615 // cache is always NULL.
1616 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1617 Values[ 9] = Protocols;
1618 // ivar_layout for metaclass is always NULL.
1619 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1620 // The class extension is always unused for metaclasses.
1621 Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1622 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1623 Values);
1624
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +00001625 std::string Name("\01L_OBJC_METACLASS_");
Chris Lattnerd120b9e2008-11-24 03:54:41 +00001626 Name += ID->getNameAsCString();
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +00001627
1628 // Check for a forward reference.
1629 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
1630 if (GV) {
1631 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1632 "Forward metaclass reference has incorrect type.");
1633 GV->setLinkage(llvm::GlobalValue::InternalLinkage);
1634 GV->setInitializer(Init);
1635 } else {
1636 GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1637 llvm::GlobalValue::InternalLinkage,
1638 Init, Name,
1639 &CGM.getModule());
1640 }
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001641 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
Daniel Dunbar56756c32009-03-09 22:18:41 +00001642 GV->setAlignment(4);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001643 UsedGlobals.push_back(GV);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001644
1645 return GV;
1646}
1647
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +00001648llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
Chris Lattner271d4c22008-11-24 05:29:24 +00001649 std::string Name = "\01L_OBJC_METACLASS_" + ID->getNameAsString();
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +00001650
1651 // FIXME: Should we look these up somewhere other than the
1652 // module. Its a bit silly since we only generate these while
1653 // processing an implementation, so exactly one pointer would work
1654 // if know when we entered/exitted an implementation block.
1655
1656 // Check for an existing forward reference.
Fariborz Jahanian5fe09f72009-01-07 20:11:22 +00001657 // Previously, metaclass with internal linkage may have been defined.
1658 // pass 'true' as 2nd argument so it is returned.
1659 if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true)) {
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +00001660 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1661 "Forward metaclass reference has incorrect type.");
1662 return GV;
1663 } else {
1664 // Generate as an external reference to keep a consistent
1665 // module. This will be patched up when we emit the metaclass.
1666 return new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1667 llvm::GlobalValue::ExternalLinkage,
1668 0,
1669 Name,
1670 &CGM.getModule());
1671 }
1672}
1673
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001674/*
1675 struct objc_class_ext {
1676 uint32_t size;
1677 const char *weak_ivar_layout;
1678 struct _objc_property_list *properties;
1679 };
1680*/
1681llvm::Constant *
1682CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
1683 uint64_t Size =
Daniel Dunbard8439f22009-01-12 21:08:18 +00001684 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassExtensionTy);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001685
1686 std::vector<llvm::Constant*> Values(3);
1687 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001688 // FIXME: Output weak_ivar_layout string.
Fariborz Jahanian738ee712009-03-25 22:36:49 +00001689 // Values[1] = BuildIvarLayout(ID, false);
Fariborz Jahanian7345eba2009-03-05 19:17:31 +00001690 Values[1] = GetIvarLayoutName(0, ObjCTypes);
Daniel Dunbar9dfd3a72009-04-15 02:56:18 +00001691 Values[2] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
Fariborz Jahanian7b709bb2009-01-28 22:18:42 +00001692 ID, ID->getClassInterface(), ObjCTypes);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001693
1694 // Return null if no extension bits are used.
1695 if (Values[1]->isNullValue() && Values[2]->isNullValue())
1696 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1697
1698 llvm::Constant *Init =
1699 llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
Daniel Dunbar90d88f92009-03-09 21:49:58 +00001700 return CreateMetadataVar("\01L_OBJC_CLASSEXT_" + ID->getNameAsString(),
Daniel Dunbar9dfd3a72009-04-15 02:56:18 +00001701 Init, "__OBJC,__class_ext,regular,no_dead_strip",
1702 4, true);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001703}
1704
Fariborz Jahaniana09a5142009-02-12 18:51:23 +00001705/// getInterfaceDeclForIvar - Get the interface declaration node where
1706/// this ivar is declared in.
1707/// FIXME. Ideally, this info should be in the ivar node. But currently
1708/// it is not and prevailing wisdom is that ASTs should not have more
1709/// info than is absolutely needed, even though this info reflects the
1710/// source language.
1711///
1712static const ObjCInterfaceDecl *getInterfaceDeclForIvar(
1713 const ObjCInterfaceDecl *OI,
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001714 const ObjCIvarDecl *IVD,
1715 ASTContext &Context) {
Fariborz Jahaniana09a5142009-02-12 18:51:23 +00001716 if (!OI)
1717 return 0;
1718 assert(isa<ObjCInterfaceDecl>(OI) && "OI is not an interface");
1719 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1720 E = OI->ivar_end(); I != E; ++I)
1721 if ((*I)->getIdentifier() == IVD->getIdentifier())
1722 return OI;
Fariborz Jahanian13c22d72009-03-31 17:00:52 +00001723 // look into properties.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001724 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(Context),
1725 E = OI->prop_end(Context); I != E; ++I) {
Fariborz Jahanian13c22d72009-03-31 17:00:52 +00001726 ObjCPropertyDecl *PDecl = (*I);
1727 if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl())
1728 if (IV->getIdentifier() == IVD->getIdentifier())
1729 return OI;
1730 }
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001731 return getInterfaceDeclForIvar(OI->getSuperClass(), IVD, Context);
Fariborz Jahaniana09a5142009-02-12 18:51:23 +00001732}
1733
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001734/*
1735 struct objc_ivar {
1736 char *ivar_name;
1737 char *ivar_type;
1738 int ivar_offset;
1739 };
1740
1741 struct objc_ivar_list {
1742 int ivar_count;
1743 struct objc_ivar list[count];
1744 };
1745 */
1746llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanianf2a94cd2009-01-28 19:12:34 +00001747 bool ForClass) {
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001748 std::vector<llvm::Constant*> Ivars, Ivar(3);
1749
1750 // When emitting the root class GCC emits ivar entries for the
1751 // actual class structure. It is not clear if we need to follow this
1752 // behavior; for now lets try and get away with not doing it. If so,
1753 // the cleanest solution would be to make up an ObjCInterfaceDecl
1754 // for the class.
1755 if (ForClass)
1756 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
Fariborz Jahanianf2a94cd2009-01-28 19:12:34 +00001757
1758 ObjCInterfaceDecl *OID =
1759 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Fariborz Jahanian6d49ab62009-03-11 21:42:00 +00001760 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID);
Fariborz Jahanianf2a94cd2009-01-28 19:12:34 +00001761
Daniel Dunbar356f0742009-04-20 06:54:31 +00001762 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
1763 GetNamedIvarList(OID, OIvars);
1764
1765 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
1766 ObjCIvarDecl *IVD = OIvars[i];
1767 const FieldDecl *Field = OID->lookupFieldDeclForIvar(CGM.getContext(), IVD);
Daniel Dunbar356f0742009-04-20 06:54:31 +00001768 Ivar[0] = GetMethodVarName(Field->getIdentifier());
Devang Patel593a07a2009-03-04 18:21:39 +00001769 Ivar[1] = GetMethodVarType(Field);
Daniel Dunbar72878722009-04-20 20:18:54 +00001770 Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy,
1771 GetIvarBaseOffset(Layout, Field));
Daniel Dunbarc9197cd2008-10-17 20:21:44 +00001772 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001773 }
1774
1775 // Return null for empty list.
1776 if (Ivars.empty())
1777 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
1778
1779 std::vector<llvm::Constant*> Values(2);
1780 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
1781 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
1782 Ivars.size());
1783 Values[1] = llvm::ConstantArray::get(AT, Ivars);
1784 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1785
Daniel Dunbar90d88f92009-03-09 21:49:58 +00001786 llvm::GlobalVariable *GV;
1787 if (ForClass)
1788 GV = CreateMetadataVar("\01L_OBJC_CLASS_VARIABLES_" + ID->getNameAsString(),
Daniel Dunbar56756c32009-03-09 22:18:41 +00001789 Init, "__OBJC,__class_vars,regular,no_dead_strip",
1790 4, true);
Daniel Dunbar90d88f92009-03-09 21:49:58 +00001791 else
1792 GV = CreateMetadataVar("\01L_OBJC_INSTANCE_VARIABLES_"
1793 + ID->getNameAsString(),
1794 Init, "__OBJC,__instance_vars,regular,no_dead_strip",
Daniel Dunbar9dfd3a72009-04-15 02:56:18 +00001795 4, true);
1796 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.IvarListPtrTy);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001797}
1798
1799/*
1800 struct objc_method {
1801 SEL method_name;
1802 char *method_types;
1803 void *method;
1804 };
1805
1806 struct objc_method_list {
1807 struct objc_method_list *obsolete;
1808 int count;
1809 struct objc_method methods_list[count];
1810 };
1811*/
Daniel Dunbar12996f52008-08-26 21:51:14 +00001812
1813/// GetMethodConstant - Return a struct objc_method constant for the
1814/// given method if it has been defined. The result is null if the
1815/// method has not been defined. The return value has type MethodPtrTy.
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001816llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
Daniel Dunbar12996f52008-08-26 21:51:14 +00001817 // FIXME: Use DenseMap::lookup
1818 llvm::Function *Fn = MethodDefinitions[MD];
1819 if (!Fn)
1820 return 0;
1821
1822 std::vector<llvm::Constant*> Method(3);
1823 Method[0] =
1824 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1825 ObjCTypes.SelectorPtrTy);
1826 Method[1] = GetMethodVarType(MD);
1827 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
1828 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
1829}
1830
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001831llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name,
1832 const char *Section,
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001833 const ConstantVector &Methods) {
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001834 // Return null for empty list.
1835 if (Methods.empty())
1836 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
1837
1838 std::vector<llvm::Constant*> Values(3);
1839 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1840 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1841 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
1842 Methods.size());
1843 Values[2] = llvm::ConstantArray::get(AT, Methods);
1844 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1845
Daniel Dunbar9dfd3a72009-04-15 02:56:18 +00001846 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001847 return llvm::ConstantExpr::getBitCast(GV,
1848 ObjCTypes.MethodListPtrTy);
Daniel Dunbarace33292008-08-16 03:19:19 +00001849}
1850
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00001851llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD,
Daniel Dunbar9fc15a82009-02-02 21:43:58 +00001852 const ObjCContainerDecl *CD) {
Daniel Dunbarace33292008-08-16 03:19:19 +00001853 std::string Name;
Fariborz Jahanian0adaa8a2009-01-10 21:06:09 +00001854 GetNameForMethod(OMD, CD, Name);
Daniel Dunbarace33292008-08-16 03:19:19 +00001855
Daniel Dunbar34bda882009-02-02 23:23:47 +00001856 CodeGenTypes &Types = CGM.getTypes();
Daniel Dunbar3ad1f072008-09-10 04:01:49 +00001857 const llvm::FunctionType *MethodTy =
Daniel Dunbar34bda882009-02-02 23:23:47 +00001858 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Daniel Dunbarace33292008-08-16 03:19:19 +00001859 llvm::Function *Method =
Daniel Dunbar3ad1f072008-09-10 04:01:49 +00001860 llvm::Function::Create(MethodTy,
Daniel Dunbarace33292008-08-16 03:19:19 +00001861 llvm::GlobalValue::InternalLinkage,
1862 Name,
1863 &CGM.getModule());
Daniel Dunbar12996f52008-08-26 21:51:14 +00001864 MethodDefinitions.insert(std::make_pair(OMD, Method));
Daniel Dunbarace33292008-08-16 03:19:19 +00001865
Daniel Dunbarace33292008-08-16 03:19:19 +00001866 return Method;
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001867}
1868
Fariborz Jahaniand65949b2009-03-08 20:18:37 +00001869uint64_t CGObjCCommonMac::GetIvarBaseOffset(const llvm::StructLayout *Layout,
Chris Lattnerd391dab2009-03-31 08:33:16 +00001870 const FieldDecl *Field) {
Fariborz Jahanian40a94a92009-03-09 20:44:22 +00001871 if (!Field->isBitField())
Daniel Dunbar1cfb5192009-04-19 02:03:42 +00001872 return Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(Field));
1873
Fariborz Jahanian40a94a92009-03-09 20:44:22 +00001874 // FIXME. Must be a better way of getting a bitfield base offset.
Daniel Dunbar1cfb5192009-04-19 02:03:42 +00001875 CodeGenTypes::BitFieldInfo BFI = CGM.getTypes().getBitFieldInfo(Field);
1876 // FIXME: The "field no" for bitfields is something completely
1877 // different; it is the offset in multiples of the base type size!
1878 uint64_t Offset = CGM.getTypes().getLLVMFieldNo(Field);
1879 const llvm::Type *Ty =
1880 CGM.getTypes().ConvertTypeForMemRecursive(Field->getType());
1881 Offset *= CGM.getTypes().getTargetData().getTypePaddedSizeInBits(Ty);
1882 return (Offset + BFI.Begin) / 8;
Fariborz Jahaniand65949b2009-03-08 20:18:37 +00001883}
1884
Daniel Dunbar1cfb5192009-04-19 02:03:42 +00001885/// GetFieldBaseOffset - return the field's byte offset.
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00001886uint64_t CGObjCCommonMac::GetFieldBaseOffset(const ObjCInterfaceDecl *OI,
1887 const llvm::StructLayout *Layout,
Chris Lattnerd391dab2009-03-31 08:33:16 +00001888 const FieldDecl *Field) {
Fariborz Jahanian31614742009-04-20 22:03:45 +00001889 // Is this a c struct?
1890 if (!OI)
1891 return Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(Field));
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00001892 const ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
Chris Lattnerd391dab2009-03-31 08:33:16 +00001893 const FieldDecl *FD = OI->lookupFieldDeclForIvar(CGM.getContext(), Ivar);
1894 return GetIvarBaseOffset(Layout, FD);
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00001895}
1896
Daniel Dunbarc4594f22009-03-09 20:09:19 +00001897llvm::GlobalVariable *
1898CGObjCCommonMac::CreateMetadataVar(const std::string &Name,
1899 llvm::Constant *Init,
1900 const char *Section,
Daniel Dunbareddddd22009-03-09 20:50:13 +00001901 unsigned Align,
1902 bool AddToUsed) {
Daniel Dunbarc4594f22009-03-09 20:09:19 +00001903 const llvm::Type *Ty = Init->getType();
1904 llvm::GlobalVariable *GV =
1905 new llvm::GlobalVariable(Ty, false,
1906 llvm::GlobalValue::InternalLinkage,
1907 Init,
1908 Name,
1909 &CGM.getModule());
1910 if (Section)
1911 GV->setSection(Section);
Daniel Dunbareddddd22009-03-09 20:50:13 +00001912 if (Align)
1913 GV->setAlignment(Align);
1914 if (AddToUsed)
Daniel Dunbarc4594f22009-03-09 20:09:19 +00001915 UsedGlobals.push_back(GV);
1916 return GV;
1917}
1918
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001919llvm::Function *CGObjCMac::ModuleInitFunction() {
Daniel Dunbar1be1df32008-08-11 21:35:06 +00001920 // Abuse this interface function as a place to finalize.
1921 FinishModule();
1922
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001923 return NULL;
1924}
1925
Chris Lattneraea1aee2009-03-22 21:03:39 +00001926llvm::Constant *CGObjCMac::GetPropertyGetFunction() {
Daniel Dunbarf7103722008-09-24 03:38:44 +00001927 return ObjCTypes.GetPropertyFn;
1928}
1929
Chris Lattneraea1aee2009-03-22 21:03:39 +00001930llvm::Constant *CGObjCMac::GetPropertySetFunction() {
Daniel Dunbarf7103722008-09-24 03:38:44 +00001931 return ObjCTypes.SetPropertyFn;
1932}
1933
Chris Lattneraea1aee2009-03-22 21:03:39 +00001934llvm::Constant *CGObjCMac::EnumerationMutationFunction() {
Anders Carlsson58d16242008-08-31 04:05:03 +00001935 return ObjCTypes.EnumerationMutationFn;
1936}
1937
Daniel Dunbar83544842008-09-28 01:03:14 +00001938/*
1939
1940Objective-C setjmp-longjmp (sjlj) Exception Handling
1941--
1942
1943The basic framework for a @try-catch-finally is as follows:
1944{
1945 objc_exception_data d;
1946 id _rethrow = null;
Anders Carlsson8559de12009-02-07 21:26:04 +00001947 bool _call_try_exit = true;
1948
Daniel Dunbar83544842008-09-28 01:03:14 +00001949 objc_exception_try_enter(&d);
1950 if (!setjmp(d.jmp_buf)) {
1951 ... try body ...
1952 } else {
1953 // exception path
1954 id _caught = objc_exception_extract(&d);
1955
1956 // enter new try scope for handlers
1957 if (!setjmp(d.jmp_buf)) {
1958 ... match exception and execute catch blocks ...
1959
1960 // fell off end, rethrow.
1961 _rethrow = _caught;
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001962 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar83544842008-09-28 01:03:14 +00001963 } else {
1964 // exception in catch block
1965 _rethrow = objc_exception_extract(&d);
Anders Carlsson8559de12009-02-07 21:26:04 +00001966 _call_try_exit = false;
1967 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar83544842008-09-28 01:03:14 +00001968 }
1969 }
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001970 ... jump-through-finally to finally_end ...
Daniel Dunbar83544842008-09-28 01:03:14 +00001971
1972finally:
Anders Carlsson8559de12009-02-07 21:26:04 +00001973 if (_call_try_exit)
1974 objc_exception_try_exit(&d);
1975
Daniel Dunbar83544842008-09-28 01:03:14 +00001976 ... finally block ....
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001977 ... dispatch to finally destination ...
1978
1979finally_rethrow:
1980 objc_exception_throw(_rethrow);
1981
1982finally_end:
Daniel Dunbar83544842008-09-28 01:03:14 +00001983}
1984
1985This framework differs slightly from the one gcc uses, in that gcc
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001986uses _rethrow to determine if objc_exception_try_exit should be called
1987and if the object should be rethrown. This breaks in the face of
1988throwing nil and introduces unnecessary branches.
Daniel Dunbar83544842008-09-28 01:03:14 +00001989
1990We specialize this framework for a few particular circumstances:
1991
1992 - If there are no catch blocks, then we avoid emitting the second
1993 exception handling context.
1994
1995 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
1996 e)) we avoid emitting the code to rethrow an uncaught exception.
1997
1998 - FIXME: If there is no @finally block we can do a few more
1999 simplifications.
2000
2001Rethrows and Jumps-Through-Finally
2002--
2003
2004Support for implicit rethrows and jumping through the finally block is
2005handled by storing the current exception-handling context in
2006ObjCEHStack.
2007
Daniel Dunbare9900eb2008-09-30 01:06:03 +00002008In order to implement proper @finally semantics, we support one basic
2009mechanism for jumping through the finally block to an arbitrary
2010destination. Constructs which generate exits from a @try or @catch
2011block use this mechanism to implement the proper semantics by chaining
2012jumps, as necessary.
2013
2014This mechanism works like the one used for indirect goto: we
2015arbitrarily assign an ID to each destination and store the ID for the
2016destination in a variable prior to entering the finally block. At the
2017end of the finally block we simply create a switch to the proper
2018destination.
Fariborz Jahanianfbeda7b2008-11-21 00:49:24 +00002019
2020Code gen for @synchronized(expr) stmt;
2021Effectively generating code for:
2022objc_sync_enter(expr);
2023@try stmt @finally { objc_sync_exit(expr); }
Daniel Dunbar83544842008-09-28 01:03:14 +00002024*/
2025
Fariborz Jahanianfbeda7b2008-11-21 00:49:24 +00002026void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
2027 const Stmt &S) {
2028 bool isTry = isa<ObjCAtTryStmt>(S);
Daniel Dunbare9900eb2008-09-30 01:06:03 +00002029 // Create various blocks we refer to for handling @finally.
Daniel Dunbar72f96552008-11-11 02:29:29 +00002030 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Anders Carlsson8559de12009-02-07 21:26:04 +00002031 llvm::BasicBlock *FinallyExit = CGF.createBasicBlock("finally.exit");
Daniel Dunbar72f96552008-11-11 02:29:29 +00002032 llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
2033 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
2034 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
Daniel Dunbar34416d62009-02-24 01:43:46 +00002035
2036 // For @synchronized, call objc_sync_enter(sync.expr). The
2037 // evaluation of the expression must occur before we enter the
2038 // @synchronized. We can safely avoid a temp here because jumps into
2039 // @synchronized are illegal & this will dominate uses.
2040 llvm::Value *SyncArg = 0;
2041 if (!isTry) {
2042 SyncArg =
2043 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
2044 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattner23e24652009-04-06 16:53:45 +00002045 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar34416d62009-02-24 01:43:46 +00002046 }
Daniel Dunbare9900eb2008-09-30 01:06:03 +00002047
2048 // Push an EH context entry, used for handling rethrows and jumps
2049 // through finally.
Anders Carlsson00ffb962009-02-09 20:38:58 +00002050 CGF.PushCleanupBlock(FinallyBlock);
2051
Anders Carlssonecd81832009-02-07 21:37:21 +00002052 CGF.ObjCEHValueStack.push_back(0);
2053
Daniel Dunbare9900eb2008-09-30 01:06:03 +00002054 // Allocate memory for the exception data and rethrow pointer.
Anders Carlssonfca6c292008-09-09 17:59:25 +00002055 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
2056 "exceptiondata.ptr");
Daniel Dunbar35b777f2008-10-29 22:36:39 +00002057 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
2058 "_rethrow");
Anders Carlsson8559de12009-02-07 21:26:04 +00002059 llvm::Value *CallTryExitPtr = CGF.CreateTempAlloca(llvm::Type::Int1Ty,
2060 "_call_try_exit");
2061 CGF.Builder.CreateStore(llvm::ConstantInt::getTrue(), CallTryExitPtr);
2062
Anders Carlssonfca6c292008-09-09 17:59:25 +00002063 // Enter a new try block and call setjmp.
2064 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
2065 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
2066 "jmpbufarray");
2067 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
2068 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
2069 JmpBufPtr, "result");
Daniel Dunbare9900eb2008-09-30 01:06:03 +00002070
Daniel Dunbar72f96552008-11-11 02:29:29 +00002071 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
2072 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbarbe56f012008-10-02 17:05:36 +00002073 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
Daniel Dunbar0ac66f72008-09-27 23:30:04 +00002074 TryHandler, TryBlock);
Anders Carlssonfca6c292008-09-09 17:59:25 +00002075
2076 // Emit the @try block.
2077 CGF.EmitBlock(TryBlock);
Fariborz Jahanianfbeda7b2008-11-21 00:49:24 +00002078 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
2079 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
Anders Carlsson00ffb962009-02-09 20:38:58 +00002080 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlssonfca6c292008-09-09 17:59:25 +00002081
2082 // Emit the "exception in @try" block.
Daniel Dunbar0ac66f72008-09-27 23:30:04 +00002083 CGF.EmitBlock(TryHandler);
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00002084
2085 // Retrieve the exception object. We may emit multiple blocks but
2086 // nothing can cross this so the value is already in SSA form.
2087 llvm::Value *Caught = CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
2088 ExceptionData,
2089 "caught");
Anders Carlssonecd81832009-02-07 21:37:21 +00002090 CGF.ObjCEHValueStack.back() = Caught;
Fariborz Jahanianfbeda7b2008-11-21 00:49:24 +00002091 if (!isTry)
2092 {
2093 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson8559de12009-02-07 21:26:04 +00002094 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlsson00ffb962009-02-09 20:38:58 +00002095 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Fariborz Jahanianfbeda7b2008-11-21 00:49:24 +00002096 }
2097 else if (const ObjCAtCatchStmt* CatchStmt =
2098 cast<ObjCAtTryStmt>(S).getCatchStmts())
2099 {
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00002100 // Enter a new exception try block (in case a @catch block throws
2101 // an exception).
Anders Carlssonfca6c292008-09-09 17:59:25 +00002102 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00002103
Anders Carlssonfca6c292008-09-09 17:59:25 +00002104 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
2105 JmpBufPtr, "result");
Daniel Dunbarbe56f012008-10-02 17:05:36 +00002106 llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw");
Anders Carlssonfca6c292008-09-09 17:59:25 +00002107
Daniel Dunbar72f96552008-11-11 02:29:29 +00002108 llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch");
2109 llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler");
Daniel Dunbar0ac66f72008-09-27 23:30:04 +00002110 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
Anders Carlssonfca6c292008-09-09 17:59:25 +00002111
2112 CGF.EmitBlock(CatchBlock);
2113
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00002114 // Handle catch list. As a special case we check if everything is
2115 // matched and avoid generating code for falling off the end if
2116 // so.
2117 bool AllMatched = false;
Anders Carlssonfca6c292008-09-09 17:59:25 +00002118 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbar72f96552008-11-11 02:29:29 +00002119 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch");
Anders Carlssonfca6c292008-09-09 17:59:25 +00002120
Steve Naroff0e8b96a2009-03-03 19:52:17 +00002121 const ParmVarDecl *CatchParam = CatchStmt->getCatchParamDecl();
Daniel Dunbar7a68b452008-09-27 07:36:24 +00002122 const PointerType *PT = 0;
2123
Anders Carlssonfca6c292008-09-09 17:59:25 +00002124 // catch(...) always matches.
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00002125 if (!CatchParam) {
2126 AllMatched = true;
2127 } else {
Steve Naroff0e8b96a2009-03-03 19:52:17 +00002128 PT = CatchParam->getType()->getAsPointerType();
Anders Carlssonfca6c292008-09-09 17:59:25 +00002129
Daniel Dunbard04c9352008-09-27 22:21:14 +00002130 // catch(id e) always matches.
2131 // FIXME: For the time being we also match id<X>; this should
2132 // be rejected by Sema instead.
Steve Naroff17c03822009-02-12 17:52:19 +00002133 if ((PT && CGF.getContext().isObjCIdStructType(PT->getPointeeType())) ||
Steve Naroff0e8b96a2009-03-03 19:52:17 +00002134 CatchParam->getType()->isObjCQualifiedIdType())
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00002135 AllMatched = true;
Anders Carlssonfca6c292008-09-09 17:59:25 +00002136 }
2137
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00002138 if (AllMatched) {
Anders Carlsson75d86732008-09-11 09:15:33 +00002139 if (CatchParam) {
Steve Naroff0e8b96a2009-03-03 19:52:17 +00002140 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbar5aa22bc2008-11-11 23:11:34 +00002141 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Steve Naroff0e8b96a2009-03-03 19:52:17 +00002142 CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlsson75d86732008-09-11 09:15:33 +00002143 }
Anders Carlsson1f4acc32008-09-11 08:21:54 +00002144
Anders Carlsson75d86732008-09-11 09:15:33 +00002145 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlsson00ffb962009-02-09 20:38:58 +00002146 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlssonfca6c292008-09-09 17:59:25 +00002147 break;
2148 }
2149
Daniel Dunbar7a68b452008-09-27 07:36:24 +00002150 assert(PT && "Unexpected non-pointer type in @catch");
2151 QualType T = PT->getPointeeType();
Anders Carlssona4519172008-09-11 06:35:14 +00002152 const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType();
Anders Carlssonfca6c292008-09-09 17:59:25 +00002153 assert(ObjCType && "Catch parameter must have Objective-C type!");
2154
2155 // Check if the @catch block matches the exception object.
2156 llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl());
2157
Anders Carlssonfca6c292008-09-09 17:59:25 +00002158 llvm::Value *Match = CGF.Builder.CreateCall2(ObjCTypes.ExceptionMatchFn,
2159 Class, Caught, "match");
Anders Carlssonfca6c292008-09-09 17:59:25 +00002160
Daniel Dunbar72f96552008-11-11 02:29:29 +00002161 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched");
Anders Carlssonfca6c292008-09-09 17:59:25 +00002162
Daniel Dunbarbe56f012008-10-02 17:05:36 +00002163 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
Daniel Dunbar0ac66f72008-09-27 23:30:04 +00002164 MatchedBlock, NextCatchBlock);
Anders Carlssonfca6c292008-09-09 17:59:25 +00002165
2166 // Emit the @catch block.
2167 CGF.EmitBlock(MatchedBlock);
Steve Naroff0e8b96a2009-03-03 19:52:17 +00002168 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbar5aa22bc2008-11-11 23:11:34 +00002169 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar83544842008-09-28 01:03:14 +00002170
2171 llvm::Value *Tmp =
Steve Naroff0e8b96a2009-03-03 19:52:17 +00002172 CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(CatchParam->getType()),
Daniel Dunbar83544842008-09-28 01:03:14 +00002173 "tmp");
Steve Naroff0e8b96a2009-03-03 19:52:17 +00002174 CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlsson75d86732008-09-11 09:15:33 +00002175
2176 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlsson00ffb962009-02-09 20:38:58 +00002177 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlssonfca6c292008-09-09 17:59:25 +00002178
2179 CGF.EmitBlock(NextCatchBlock);
2180 }
2181
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00002182 if (!AllMatched) {
2183 // None of the handlers caught the exception, so store it to be
2184 // rethrown at the end of the @finally block.
2185 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson00ffb962009-02-09 20:38:58 +00002186 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00002187 }
2188
2189 // Emit the exception handler for the @catch blocks.
Daniel Dunbar0ac66f72008-09-27 23:30:04 +00002190 CGF.EmitBlock(CatchHandler);
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00002191 CGF.Builder.CreateStore(CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
2192 ExceptionData),
2193 RethrowPtr);
Anders Carlsson8559de12009-02-07 21:26:04 +00002194 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlsson00ffb962009-02-09 20:38:58 +00002195 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00002196 } else {
Anders Carlssonfca6c292008-09-09 17:59:25 +00002197 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson8559de12009-02-07 21:26:04 +00002198 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlsson00ffb962009-02-09 20:38:58 +00002199 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Anders Carlssonfca6c292008-09-09 17:59:25 +00002200 }
2201
Daniel Dunbare9900eb2008-09-30 01:06:03 +00002202 // Pop the exception-handling stack entry. It is important to do
2203 // this now, because the code in the @finally block is not in this
2204 // context.
Anders Carlsson00ffb962009-02-09 20:38:58 +00002205 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
2206
Anders Carlssonecd81832009-02-07 21:37:21 +00002207 CGF.ObjCEHValueStack.pop_back();
2208
Anders Carlssonfca6c292008-09-09 17:59:25 +00002209 // Emit the @finally block.
2210 CGF.EmitBlock(FinallyBlock);
Anders Carlsson8559de12009-02-07 21:26:04 +00002211 llvm::Value* CallTryExit = CGF.Builder.CreateLoad(CallTryExitPtr, "tmp");
2212
2213 CGF.Builder.CreateCondBr(CallTryExit, FinallyExit, FinallyNoExit);
2214
2215 CGF.EmitBlock(FinallyExit);
Anders Carlssonfca6c292008-09-09 17:59:25 +00002216 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryExitFn, ExceptionData);
Daniel Dunbar7a68b452008-09-27 07:36:24 +00002217
2218 CGF.EmitBlock(FinallyNoExit);
Fariborz Jahanianfbeda7b2008-11-21 00:49:24 +00002219 if (isTry) {
2220 if (const ObjCAtFinallyStmt* FinallyStmt =
2221 cast<ObjCAtTryStmt>(S).getFinallyStmt())
2222 CGF.EmitStmt(FinallyStmt->getFinallyBody());
Daniel Dunbar34416d62009-02-24 01:43:46 +00002223 } else {
2224 // Emit objc_sync_exit(expr); as finally's sole statement for
2225 // @synchronized.
2226 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, SyncArg);
Fariborz Jahanian3895d922008-11-21 19:21:53 +00002227 }
Anders Carlssonfca6c292008-09-09 17:59:25 +00002228
Anders Carlsson00ffb962009-02-09 20:38:58 +00002229 // Emit the switch block
2230 if (Info.SwitchBlock)
2231 CGF.EmitBlock(Info.SwitchBlock);
2232 if (Info.EndBlock)
2233 CGF.EmitBlock(Info.EndBlock);
2234
Daniel Dunbare9900eb2008-09-30 01:06:03 +00002235 CGF.EmitBlock(FinallyRethrow);
2236 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn,
2237 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbar0ac66f72008-09-27 23:30:04 +00002238 CGF.Builder.CreateUnreachable();
Daniel Dunbare9900eb2008-09-30 01:06:03 +00002239
2240 CGF.EmitBlock(FinallyEnd);
Anders Carlssonb01a2112008-09-09 10:04:29 +00002241}
2242
2243void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbare9900eb2008-09-30 01:06:03 +00002244 const ObjCAtThrowStmt &S) {
Anders Carlsson05d7be72008-09-09 16:16:55 +00002245 llvm::Value *ExceptionAsObject;
2246
2247 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2248 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
2249 ExceptionAsObject =
2250 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
2251 } else {
Anders Carlssonecd81832009-02-07 21:37:21 +00002252 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Daniel Dunbar83544842008-09-28 01:03:14 +00002253 "Unexpected rethrow outside @catch block.");
Anders Carlssonecd81832009-02-07 21:37:21 +00002254 ExceptionAsObject = CGF.ObjCEHValueStack.back();
Anders Carlsson05d7be72008-09-09 16:16:55 +00002255 }
2256
2257 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
Anders Carlssonfca6c292008-09-09 17:59:25 +00002258 CGF.Builder.CreateUnreachable();
Daniel Dunbar5aa22bc2008-11-11 23:11:34 +00002259
2260 // Clear the insertion point to indicate we are in unreachable code.
2261 CGF.Builder.ClearInsertionPoint();
Anders Carlssonb01a2112008-09-09 10:04:29 +00002262}
2263
Fariborz Jahanian252d87f2008-11-18 22:37:34 +00002264/// EmitObjCWeakRead - Code gen for loading value of a __weak
Fariborz Jahanian3305ad32008-11-18 21:45:40 +00002265/// object: objc_read_weak (id *src)
2266///
Fariborz Jahanian252d87f2008-11-18 22:37:34 +00002267llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian3305ad32008-11-18 21:45:40 +00002268 llvm::Value *AddrWeakObj)
2269{
Eli Friedmanf8466232009-03-07 03:57:15 +00002270 const llvm::Type* DestTy =
2271 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahaniand2f661a2008-11-19 17:34:06 +00002272 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian3305ad32008-11-18 21:45:40 +00002273 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
Fariborz Jahanian252d87f2008-11-18 22:37:34 +00002274 AddrWeakObj, "weakread");
Eli Friedmanf8466232009-03-07 03:57:15 +00002275 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian3305ad32008-11-18 21:45:40 +00002276 return read_weak;
2277}
2278
Fariborz Jahanian252d87f2008-11-18 22:37:34 +00002279/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
2280/// objc_assign_weak (id src, id *dst)
2281///
2282void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
2283 llvm::Value *src, llvm::Value *dst)
2284{
Fariborz Jahanianad51ca02009-03-23 19:10:40 +00002285 const llvm::Type * SrcTy = src->getType();
2286 if (!isa<llvm::PointerType>(SrcTy)) {
2287 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2288 assert(Size <= 8 && "does not support size > 8");
2289 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2290 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian664da982009-03-13 00:42:52 +00002291 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2292 }
Fariborz Jahaniand2f661a2008-11-19 17:34:06 +00002293 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2294 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattner293c1d32009-04-17 22:12:36 +00002295 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
Fariborz Jahanian252d87f2008-11-18 22:37:34 +00002296 src, dst, "weakassign");
2297 return;
2298}
2299
Fariborz Jahanian17958902008-11-19 00:59:10 +00002300/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
2301/// objc_assign_global (id src, id *dst)
2302///
2303void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
2304 llvm::Value *src, llvm::Value *dst)
2305{
Fariborz Jahanianad51ca02009-03-23 19:10:40 +00002306 const llvm::Type * SrcTy = src->getType();
2307 if (!isa<llvm::PointerType>(SrcTy)) {
2308 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2309 assert(Size <= 8 && "does not support size > 8");
2310 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2311 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian664da982009-03-13 00:42:52 +00002312 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2313 }
Fariborz Jahaniand2f661a2008-11-19 17:34:06 +00002314 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2315 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian17958902008-11-19 00:59:10 +00002316 CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn,
2317 src, dst, "globalassign");
2318 return;
2319}
2320
Fariborz Jahanianf310b592008-11-20 19:23:36 +00002321/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
2322/// objc_assign_ivar (id src, id *dst)
2323///
2324void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
2325 llvm::Value *src, llvm::Value *dst)
2326{
Fariborz Jahanianad51ca02009-03-23 19:10:40 +00002327 const llvm::Type * SrcTy = src->getType();
2328 if (!isa<llvm::PointerType>(SrcTy)) {
2329 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2330 assert(Size <= 8 && "does not support size > 8");
2331 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2332 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian664da982009-03-13 00:42:52 +00002333 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2334 }
Fariborz Jahanianf310b592008-11-20 19:23:36 +00002335 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2336 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
2337 CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn,
2338 src, dst, "assignivar");
2339 return;
2340}
2341
Fariborz Jahanian17958902008-11-19 00:59:10 +00002342/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
2343/// objc_assign_strongCast (id src, id *dst)
2344///
2345void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
2346 llvm::Value *src, llvm::Value *dst)
2347{
Fariborz Jahanianad51ca02009-03-23 19:10:40 +00002348 const llvm::Type * SrcTy = src->getType();
2349 if (!isa<llvm::PointerType>(SrcTy)) {
2350 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2351 assert(Size <= 8 && "does not support size > 8");
2352 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2353 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian664da982009-03-13 00:42:52 +00002354 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2355 }
Fariborz Jahaniand2f661a2008-11-19 17:34:06 +00002356 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2357 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian17958902008-11-19 00:59:10 +00002358 CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn,
2359 src, dst, "weakassign");
2360 return;
2361}
2362
Fariborz Jahanian4337afe2009-02-02 20:02:29 +00002363/// EmitObjCValueForIvar - Code Gen for ivar reference.
2364///
Fariborz Jahanianc912eb72009-02-03 19:03:09 +00002365LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
2366 QualType ObjectTy,
2367 llvm::Value *BaseValue,
2368 const ObjCIvarDecl *Ivar,
2369 const FieldDecl *Field,
2370 unsigned CVRQualifiers) {
Daniel Dunbar0ac5bbc2009-04-21 00:41:40 +00002371 assert(Field == ObjectTy->getAsObjCInterfaceType()->getDecl()->lookupFieldDeclForIvar(CGM.getContext(), Ivar));
Fariborz Jahanianc912eb72009-02-03 19:03:09 +00002372 if (Ivar->isBitField())
2373 return CGF.EmitLValueForBitfield(BaseValue, const_cast<FieldDecl *>(Field),
2374 CVRQualifiers);
Fariborz Jahanian4337afe2009-02-02 20:02:29 +00002375 // TODO: Add a special case for isa (index 0)
2376 unsigned Index = CGM.getTypes().getLLVMFieldNo(Field);
2377 llvm::Value *V = CGF.Builder.CreateStructGEP(BaseValue, Index, "tmp");
Fariborz Jahanianc912eb72009-02-03 19:03:09 +00002378 LValue LV = LValue::MakeAddr(V,
Fariborz Jahanianbbd4ca92009-02-19 23:36:06 +00002379 Ivar->getType().getCVRQualifiers()|CVRQualifiers,
2380 CGM.getContext().getObjCGCAttrKind(Ivar->getType()));
Fariborz Jahanianc912eb72009-02-03 19:03:09 +00002381 LValue::SetObjCIvar(LV, true);
2382 return LV;
Fariborz Jahanian4337afe2009-02-02 20:02:29 +00002383}
2384
Fariborz Jahanian27cc6662009-02-10 19:02:04 +00002385llvm::Value *CGObjCMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
2386 ObjCInterfaceDecl *Interface,
2387 const ObjCIvarDecl *Ivar) {
Fariborz Jahanian6d49ab62009-03-11 21:42:00 +00002388 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(Interface);
Daniel Dunbarf0587c62009-04-20 00:37:55 +00002389 const FieldDecl *Field =
2390 Interface->lookupFieldDeclForIvar(CGM.getContext(), Ivar);
Fariborz Jahaniand65949b2009-03-08 20:18:37 +00002391 uint64_t Offset = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanian27cc6662009-02-10 19:02:04 +00002392 return llvm::ConstantInt::get(
2393 CGM.getTypes().ConvertType(CGM.getContext().LongTy),
2394 Offset);
2395}
2396
Daniel Dunbar1be1df32008-08-11 21:35:06 +00002397/* *** Private Interface *** */
2398
2399/// EmitImageInfo - Emit the image info marker used to encode some module
2400/// level information.
2401///
2402/// See: <rdr://4810609&4810587&4810587>
2403/// struct IMAGE_INFO {
2404/// unsigned version;
2405/// unsigned flags;
2406/// };
2407enum ImageInfoFlags {
Daniel Dunbarb79f5a92009-04-20 07:11:47 +00002408 eImageInfo_FixAndContinue = (1 << 0), // FIXME: Not sure what
2409 // this implies.
2410 eImageInfo_GarbageCollected = (1 << 1),
2411 eImageInfo_GCOnly = (1 << 2),
2412 eImageInfo_OptimizedByDyld = (1 << 3), // FIXME: When is this set.
2413
2414 // A flag indicating that the module has no instances of an
2415 // @synthesize of a superclass variable. <rdar://problem/6803242>
2416 eImageInfo_CorrectedSynthesize = (1 << 4)
Daniel Dunbar1be1df32008-08-11 21:35:06 +00002417};
2418
2419void CGObjCMac::EmitImageInfo() {
2420 unsigned version = 0; // Version is unused?
2421 unsigned flags = 0;
2422
2423 // FIXME: Fix and continue?
2424 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
2425 flags |= eImageInfo_GarbageCollected;
2426 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
2427 flags |= eImageInfo_GCOnly;
Daniel Dunbarb79f5a92009-04-20 07:11:47 +00002428
2429 // We never allow @synthesize of a superclass property.
2430 flags |= eImageInfo_CorrectedSynthesize;
Daniel Dunbar1be1df32008-08-11 21:35:06 +00002431
Daniel Dunbar1be1df32008-08-11 21:35:06 +00002432 // Emitted as int[2];
2433 llvm::Constant *values[2] = {
2434 llvm::ConstantInt::get(llvm::Type::Int32Ty, version),
2435 llvm::ConstantInt::get(llvm::Type::Int32Ty, flags)
2436 };
2437 llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2);
Daniel Dunbar90d88f92009-03-09 21:49:58 +00002438
2439 const char *Section;
2440 if (ObjCABI == 1)
2441 Section = "__OBJC, __image_info,regular";
2442 else
2443 Section = "__DATA, __objc_imageinfo, regular, no_dead_strip";
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002444 llvm::GlobalVariable *GV =
Daniel Dunbar90d88f92009-03-09 21:49:58 +00002445 CreateMetadataVar("\01L_OBJC_IMAGE_INFO",
2446 llvm::ConstantArray::get(AT, values, 2),
2447 Section,
2448 0,
2449 true);
2450 GV->setConstant(true);
Daniel Dunbar1be1df32008-08-11 21:35:06 +00002451}
2452
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002453
2454// struct objc_module {
2455// unsigned long version;
2456// unsigned long size;
2457// const char *name;
2458// Symtab symtab;
2459// };
2460
2461// FIXME: Get from somewhere
2462static const int ModuleVersion = 7;
2463
2464void CGObjCMac::EmitModuleInfo() {
Daniel Dunbard8439f22009-01-12 21:08:18 +00002465 uint64_t Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ModuleTy);
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002466
2467 std::vector<llvm::Constant*> Values(4);
2468 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
2469 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Daniel Dunbarac93e472008-08-15 22:20:32 +00002470 // This used to be the filename, now it is unused. <rdr://4327263>
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00002471 Values[2] = GetClassName(&CGM.getContext().Idents.get(""));
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002472 Values[3] = EmitModuleSymbols();
Daniel Dunbar90d88f92009-03-09 21:49:58 +00002473 CreateMetadataVar("\01L_OBJC_MODULES",
2474 llvm::ConstantStruct::get(ObjCTypes.ModuleTy, Values),
2475 "__OBJC,__module_info,regular,no_dead_strip",
Daniel Dunbar56756c32009-03-09 22:18:41 +00002476 4, true);
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002477}
2478
2479llvm::Constant *CGObjCMac::EmitModuleSymbols() {
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002480 unsigned NumClasses = DefinedClasses.size();
2481 unsigned NumCategories = DefinedCategories.size();
2482
Daniel Dunbar8ede0052008-08-25 06:02:07 +00002483 // Return null if no symbols were defined.
2484 if (!NumClasses && !NumCategories)
2485 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
2486
2487 std::vector<llvm::Constant*> Values(5);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002488 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2489 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
2490 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
2491 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
2492
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00002493 // The runtime expects exactly the list of defined classes followed
2494 // by the list of defined categories, in a single array.
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002495 std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00002496 for (unsigned i=0; i<NumClasses; i++)
2497 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
2498 ObjCTypes.Int8PtrTy);
2499 for (unsigned i=0; i<NumCategories; i++)
2500 Symbols[NumClasses + i] =
2501 llvm::ConstantExpr::getBitCast(DefinedCategories[i],
2502 ObjCTypes.Int8PtrTy);
2503
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002504 Values[4] =
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00002505 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002506 NumClasses + NumCategories),
2507 Symbols);
2508
2509 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2510
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002511 llvm::GlobalVariable *GV =
Daniel Dunbar90d88f92009-03-09 21:49:58 +00002512 CreateMetadataVar("\01L_OBJC_SYMBOLS", Init,
2513 "__OBJC,__symbols,regular,no_dead_strip",
Daniel Dunbar9dfd3a72009-04-15 02:56:18 +00002514 4, true);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002515 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
2516}
2517
Daniel Dunbard916e6e2008-11-01 01:53:16 +00002518llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002519 const ObjCInterfaceDecl *ID) {
Daniel Dunbar8ede0052008-08-25 06:02:07 +00002520 LazySymbols.insert(ID->getIdentifier());
2521
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002522 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
2523
2524 if (!Entry) {
2525 llvm::Constant *Casted =
2526 llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()),
2527 ObjCTypes.ClassPtrTy);
2528 Entry =
Daniel Dunbar90d88f92009-03-09 21:49:58 +00002529 CreateMetadataVar("\01L_OBJC_CLASS_REFERENCES_", Casted,
2530 "__OBJC,__cls_refs,literal_pointers,no_dead_strip",
Daniel Dunbar9dfd3a72009-04-15 02:56:18 +00002531 4, true);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002532 }
2533
2534 return Builder.CreateLoad(Entry, false, "tmp");
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002535}
2536
Daniel Dunbard916e6e2008-11-01 01:53:16 +00002537llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar5eec6142008-08-12 03:39:23 +00002538 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
2539
2540 if (!Entry) {
2541 llvm::Constant *Casted =
2542 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
2543 ObjCTypes.SelectorPtrTy);
2544 Entry =
Daniel Dunbar90d88f92009-03-09 21:49:58 +00002545 CreateMetadataVar("\01L_OBJC_SELECTOR_REFERENCES_", Casted,
2546 "__OBJC,__message_refs,literal_pointers,no_dead_strip",
Daniel Dunbar9dfd3a72009-04-15 02:56:18 +00002547 4, true);
Daniel Dunbar5eec6142008-08-12 03:39:23 +00002548 }
2549
2550 return Builder.CreateLoad(Entry, false, "tmp");
2551}
2552
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00002553llvm::Constant *CGObjCCommonMac::GetClassName(IdentifierInfo *Ident) {
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00002554 llvm::GlobalVariable *&Entry = ClassNames[Ident];
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002555
Daniel Dunbar90d88f92009-03-09 21:49:58 +00002556 if (!Entry)
2557 Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
2558 llvm::ConstantArray::get(Ident->getName()),
2559 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarfbfd92a2009-04-14 23:14:47 +00002560 1, true);
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002561
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00002562 return getConstantGEP(Entry, 0, 0);
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002563}
2564
Fariborz Jahanian6d49ab62009-03-11 21:42:00 +00002565/// GetInterfaceDeclStructLayout - Get layout for ivars of given
2566/// interface declaration.
2567const llvm::StructLayout *CGObjCCommonMac::GetInterfaceDeclStructLayout(
2568 const ObjCInterfaceDecl *OID) const {
Daniel Dunbarecb5d402009-04-19 23:41:48 +00002569 // FIXME: When does this happen? It seems pretty bad to do this...
Daniel Dunbar72878722009-04-20 20:18:54 +00002570 if (OID->isForwardDecl())
2571 return CGM.getTargetData().getStructLayout(llvm::StructType::get(NULL,
2572 NULL));
2573
2574 QualType T =
2575 CGM.getContext().getObjCInterfaceType(const_cast<ObjCInterfaceDecl*>(OID));
2576 const llvm::StructType *InterfaceTy =
2577 cast<llvm::StructType>(CGM.getTypes().ConvertType(T));
2578 return CGM.getTargetData().getStructLayout(InterfaceTy);
Fariborz Jahanian6d49ab62009-03-11 21:42:00 +00002579}
2580
Fariborz Jahanian7345eba2009-03-05 19:17:31 +00002581/// GetIvarLayoutName - Returns a unique constant for the given
2582/// ivar layout bitmap.
2583llvm::Constant *CGObjCCommonMac::GetIvarLayoutName(IdentifierInfo *Ident,
2584 const ObjCCommonTypesHelper &ObjCTypes) {
2585 return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2586}
2587
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002588void CGObjCCommonMac::BuildAggrIvarLayout(const ObjCInterfaceDecl *OI,
2589 const llvm::StructLayout *Layout,
Fariborz Jahanian37931062009-03-10 16:22:08 +00002590 const RecordDecl *RD,
Chris Lattner9329cf52009-03-31 08:48:01 +00002591 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahanian01b3e342009-03-05 22:39:55 +00002592 unsigned int BytePos, bool ForStrongLayout,
2593 int &Index, int &SkIndex, bool &HasUnion) {
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00002594 bool IsUnion = (RD && RD->isUnion());
2595 uint64_t MaxUnionIvarSize = 0;
2596 uint64_t MaxSkippedUnionIvarSize = 0;
2597 FieldDecl *MaxField = 0;
2598 FieldDecl *MaxSkippedField = 0;
Chris Lattner9329cf52009-03-31 08:48:01 +00002599 unsigned base = 0;
Fariborz Jahanian37931062009-03-10 16:22:08 +00002600 if (RecFields.empty())
2601 return;
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00002602 if (IsUnion)
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002603 base = BytePos + GetFieldBaseOffset(OI, Layout, RecFields[0]);
Chris Lattner9329cf52009-03-31 08:48:01 +00002604 unsigned WordSizeInBits = CGM.getContext().Target.getPointerWidth(0);
2605 unsigned ByteSizeInBits = CGM.getContext().Target.getCharWidth();
2606
2607 llvm::SmallVector<FieldDecl*, 16> TmpRecFields;
2608
2609 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian37931062009-03-10 16:22:08 +00002610 FieldDecl *Field = RecFields[i];
2611 // Skip over unnamed or bitfields
2612 if (!Field->getIdentifier() || Field->isBitField())
2613 continue;
2614 QualType FQT = Field->getType();
Fariborz Jahanian738ee712009-03-25 22:36:49 +00002615 if (FQT->isRecordType() || FQT->isUnionType()) {
Fariborz Jahanian37931062009-03-10 16:22:08 +00002616 if (FQT->isUnionType())
2617 HasUnion = true;
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00002618 else
2619 assert(FQT->isRecordType() &&
2620 "only union/record is supported for ivar layout bitmap");
2621
Fariborz Jahanian37931062009-03-10 16:22:08 +00002622 const RecordType *RT = FQT->getAsRecordType();
2623 const RecordDecl *RD = RT->getDecl();
Daniel Dunbarecb5d402009-04-19 23:41:48 +00002624 // FIXME - Find a more efficient way of passing records down.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002625 TmpRecFields.append(RD->field_begin(CGM.getContext()),
2626 RD->field_end(CGM.getContext()));
Fariborz Jahanian31614742009-04-20 22:03:45 +00002627 const llvm::Type *Ty = CGM.getTypes().ConvertType(FQT);
2628 const llvm::StructLayout *RecLayout =
2629 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(Ty));
2630
2631 BuildAggrIvarLayout(0, RecLayout, RD, TmpRecFields,
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002632 BytePos + GetFieldBaseOffset(OI, Layout, Field),
Fariborz Jahanian37931062009-03-10 16:22:08 +00002633 ForStrongLayout, Index, SkIndex,
2634 HasUnion);
Chris Lattner9329cf52009-03-31 08:48:01 +00002635 TmpRecFields.clear();
Fariborz Jahanian37931062009-03-10 16:22:08 +00002636 continue;
2637 }
Chris Lattner9329cf52009-03-31 08:48:01 +00002638
2639 if (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00002640 const ConstantArrayType *CArray =
2641 dyn_cast_or_null<ConstantArrayType>(Array);
2642 assert(CArray && "only array with know element size is supported");
2643 FQT = CArray->getElementType();
Fariborz Jahanian738ee712009-03-25 22:36:49 +00002644 while (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
2645 const ConstantArrayType *CArray =
2646 dyn_cast_or_null<ConstantArrayType>(Array);
2647 FQT = CArray->getElementType();
2648 }
2649
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00002650 assert(!FQT->isUnionType() &&
2651 "layout for array of unions not supported");
2652 if (FQT->isRecordType()) {
2653 uint64_t ElCount = CArray->getSize().getZExtValue();
2654 int OldIndex = Index;
2655 int OldSkIndex = SkIndex;
2656
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00002657 // FIXME - Use a common routine with the above!
2658 const RecordType *RT = FQT->getAsRecordType();
2659 const RecordDecl *RD = RT->getDecl();
2660 // FIXME - Find a more efficiant way of passing records down.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002661 TmpRecFields.append(RD->field_begin(CGM.getContext()),
2662 RD->field_end(CGM.getContext()));
Fariborz Jahanian31614742009-04-20 22:03:45 +00002663 const llvm::Type *Ty = CGM.getTypes().ConvertType(FQT);
2664 const llvm::StructLayout *RecLayout =
2665 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(Ty));
Chris Lattner9329cf52009-03-31 08:48:01 +00002666
Fariborz Jahanian31614742009-04-20 22:03:45 +00002667 BuildAggrIvarLayout(0, RecLayout, RD,
Chris Lattner9329cf52009-03-31 08:48:01 +00002668 TmpRecFields,
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002669 BytePos + GetFieldBaseOffset(OI, Layout, Field),
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00002670 ForStrongLayout, Index, SkIndex,
2671 HasUnion);
Chris Lattner9329cf52009-03-31 08:48:01 +00002672 TmpRecFields.clear();
2673
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00002674 // Replicate layout information for each array element. Note that
2675 // one element is already done.
2676 uint64_t ElIx = 1;
2677 for (int FirstIndex = Index, FirstSkIndex = SkIndex;
2678 ElIx < ElCount; ElIx++) {
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002679 uint64_t Size = CGM.getContext().getTypeSize(RT)/ByteSizeInBits;
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00002680 for (int i = OldIndex+1; i <= FirstIndex; ++i)
2681 {
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002682 GC_IVAR gcivar;
2683 gcivar.ivar_bytepos = IvarsInfo[i].ivar_bytepos + Size*ElIx;
2684 gcivar.ivar_size = IvarsInfo[i].ivar_size;
2685 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00002686 }
2687
Chris Lattner9329cf52009-03-31 08:48:01 +00002688 for (int i = OldSkIndex+1; i <= FirstSkIndex; ++i) {
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002689 GC_IVAR skivar;
2690 skivar.ivar_bytepos = SkipIvars[i].ivar_bytepos + Size*ElIx;
2691 skivar.ivar_size = SkipIvars[i].ivar_size;
2692 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00002693 }
2694 }
2695 continue;
2696 }
Fariborz Jahanian37931062009-03-10 16:22:08 +00002697 }
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00002698 // At this point, we are done with Record/Union and array there of.
2699 // For other arrays we are down to its element type.
2700 QualType::GCAttrTypes GCAttr = QualType::GCNone;
2701 do {
2702 if (FQT.isObjCGCStrong() || FQT.isObjCGCWeak()) {
2703 GCAttr = FQT.isObjCGCStrong() ? QualType::Strong : QualType::Weak;
2704 break;
2705 }
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002706 else if (CGM.getContext().isObjCObjectPointerType(FQT)) {
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00002707 GCAttr = QualType::Strong;
2708 break;
2709 }
2710 else if (const PointerType *PT = FQT->getAsPointerType()) {
2711 FQT = PT->getPointeeType();
2712 }
2713 else {
2714 break;
2715 }
2716 } while (true);
Chris Lattner9329cf52009-03-31 08:48:01 +00002717
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00002718 if ((ForStrongLayout && GCAttr == QualType::Strong)
2719 || (!ForStrongLayout && GCAttr == QualType::Weak)) {
2720 if (IsUnion)
2721 {
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002722 uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType())
2723 / WordSizeInBits;
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00002724 if (UnionIvarSize > MaxUnionIvarSize)
2725 {
2726 MaxUnionIvarSize = UnionIvarSize;
2727 MaxField = Field;
2728 }
2729 }
2730 else
2731 {
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002732 GC_IVAR gcivar;
2733 gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field);
2734 gcivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) /
2735 WordSizeInBits;
2736 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00002737 }
2738 }
2739 else if ((ForStrongLayout &&
2740 (GCAttr == QualType::GCNone || GCAttr == QualType::Weak))
2741 || (!ForStrongLayout && GCAttr != QualType::Weak)) {
2742 if (IsUnion)
2743 {
2744 uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType());
2745 if (UnionIvarSize > MaxSkippedUnionIvarSize)
2746 {
2747 MaxSkippedUnionIvarSize = UnionIvarSize;
2748 MaxSkippedField = Field;
2749 }
2750 }
2751 else
2752 {
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002753 GC_IVAR skivar;
2754 skivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field);
2755 skivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) /
2756 WordSizeInBits;
2757 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00002758 }
2759 }
2760 }
Chris Lattner9329cf52009-03-31 08:48:01 +00002761 if (MaxField) {
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002762 GC_IVAR gcivar;
2763 gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, MaxField);
2764 gcivar.ivar_size = MaxUnionIvarSize;
2765 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00002766 }
Chris Lattner9329cf52009-03-31 08:48:01 +00002767
2768 if (MaxSkippedField) {
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002769 GC_IVAR skivar;
2770 skivar.ivar_bytepos = BytePos +
2771 GetFieldBaseOffset(OI, Layout, MaxSkippedField);
2772 skivar.ivar_size = MaxSkippedUnionIvarSize;
2773 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahanian37931062009-03-10 16:22:08 +00002774 }
Fariborz Jahanian01b3e342009-03-05 22:39:55 +00002775}
2776
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00002777static int
Chris Lattner9329cf52009-03-31 08:48:01 +00002778IvarBytePosCompare(const void *a, const void *b)
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00002779{
2780 unsigned int sa = ((CGObjCCommonMac::GC_IVAR *)a)->ivar_bytepos;
2781 unsigned int sb = ((CGObjCCommonMac::GC_IVAR *)b)->ivar_bytepos;
2782
2783 if (sa < sb)
2784 return -1;
2785 if (sa > sb)
2786 return 1;
2787 return 0;
2788}
2789
Fariborz Jahanian01b3e342009-03-05 22:39:55 +00002790/// BuildIvarLayout - Builds ivar layout bitmap for the class
2791/// implementation for the __strong or __weak case.
2792/// The layout map displays which words in ivar list must be skipped
2793/// and which must be scanned by GC (see below). String is built of bytes.
2794/// Each byte is divided up in two nibbles (4-bit each). Left nibble is count
2795/// of words to skip and right nibble is count of words to scan. So, each
2796/// nibble represents up to 15 workds to skip or scan. Skipping the rest is
2797/// represented by a 0x00 byte which also ends the string.
2798/// 1. when ForStrongLayout is true, following ivars are scanned:
2799/// - id, Class
2800/// - object *
2801/// - __strong anything
2802///
2803/// 2. When ForStrongLayout is false, following ivars are scanned:
2804/// - __weak anything
2805///
Fariborz Jahanian37931062009-03-10 16:22:08 +00002806llvm::Constant *CGObjCCommonMac::BuildIvarLayout(
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002807 const ObjCImplementationDecl *OMD,
2808 bool ForStrongLayout) {
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00002809 int Index = -1;
2810 int SkIndex = -1;
Fariborz Jahanian01b3e342009-03-05 22:39:55 +00002811 bool hasUnion = false;
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00002812 int SkipScan;
2813 unsigned int WordsToScan, WordsToSkip;
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002814 const llvm::Type *PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
2815 if (CGM.getLangOptions().getGCMode() == LangOptions::NonGC)
2816 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahanian01b3e342009-03-05 22:39:55 +00002817
Chris Lattner9329cf52009-03-31 08:48:01 +00002818 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002819 const ObjCInterfaceDecl *OI = OMD->getClassInterface();
Fariborz Jahanian01b3e342009-03-05 22:39:55 +00002820 CGM.getContext().CollectObjCIvars(OI, RecFields);
2821 if (RecFields.empty())
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002822 return llvm::Constant::getNullValue(PtrTy);
Chris Lattner9329cf52009-03-31 08:48:01 +00002823
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002824 SkipIvars.clear();
2825 IvarsInfo.clear();
Fariborz Jahanian6d49ab62009-03-11 21:42:00 +00002826
2827 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OI);
Chris Lattner9329cf52009-03-31 08:48:01 +00002828 BuildAggrIvarLayout(OI, Layout, 0, RecFields, 0, ForStrongLayout,
2829 Index, SkIndex, hasUnion);
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00002830 if (Index == -1)
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002831 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00002832
2833 // Sort on byte position in case we encounterred a union nested in
2834 // the ivar list.
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002835 if (hasUnion && !IvarsInfo.empty())
2836 qsort(&IvarsInfo[0], Index+1, sizeof(GC_IVAR), IvarBytePosCompare);
2837 if (hasUnion && !SkipIvars.empty())
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00002838 qsort(&SkipIvars[0], Index+1, sizeof(GC_IVAR), IvarBytePosCompare);
2839
2840 // Build the string of skip/scan nibbles
2841 SkipScan = -1;
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002842 SkipScanIvars.clear();
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00002843 unsigned int WordSize =
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002844 CGM.getTypes().getTargetData().getTypePaddedSize(PtrTy);
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00002845 if (IvarsInfo[0].ivar_bytepos == 0) {
2846 WordsToSkip = 0;
2847 WordsToScan = IvarsInfo[0].ivar_size;
2848 }
2849 else {
2850 WordsToSkip = IvarsInfo[0].ivar_bytepos/WordSize;
2851 WordsToScan = IvarsInfo[0].ivar_size;
2852 }
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002853 for (unsigned int i=1, Last=IvarsInfo.size(); i != Last; i++)
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00002854 {
2855 unsigned int TailPrevGCObjC =
2856 IvarsInfo[i-1].ivar_bytepos + IvarsInfo[i-1].ivar_size * WordSize;
2857 if (IvarsInfo[i].ivar_bytepos == TailPrevGCObjC)
2858 {
2859 // consecutive 'scanned' object pointers.
2860 WordsToScan += IvarsInfo[i].ivar_size;
2861 }
2862 else
2863 {
2864 // Skip over 'gc'able object pointer which lay over each other.
2865 if (TailPrevGCObjC > IvarsInfo[i].ivar_bytepos)
2866 continue;
2867 // Must skip over 1 or more words. We save current skip/scan values
2868 // and start a new pair.
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002869 SKIP_SCAN SkScan;
2870 SkScan.skip = WordsToSkip;
2871 SkScan.scan = WordsToScan;
2872 SkipScanIvars.push_back(SkScan); ++SkipScan;
2873
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00002874 // Skip the hole.
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002875 SkScan.skip = (IvarsInfo[i].ivar_bytepos - TailPrevGCObjC) / WordSize;
2876 SkScan.scan = 0;
2877 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00002878 WordsToSkip = 0;
2879 WordsToScan = IvarsInfo[i].ivar_size;
2880 }
2881 }
2882 if (WordsToScan > 0)
2883 {
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002884 SKIP_SCAN SkScan;
2885 SkScan.skip = WordsToSkip;
2886 SkScan.scan = WordsToScan;
2887 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00002888 }
2889
2890 bool BytesSkipped = false;
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002891 if (!SkipIvars.empty())
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00002892 {
2893 int LastByteSkipped =
2894 SkipIvars[SkIndex].ivar_bytepos + SkipIvars[SkIndex].ivar_size;
2895 int LastByteScanned =
2896 IvarsInfo[Index].ivar_bytepos + IvarsInfo[Index].ivar_size * WordSize;
2897 BytesSkipped = (LastByteSkipped > LastByteScanned);
2898 // Compute number of bytes to skip at the tail end of the last ivar scanned.
2899 if (BytesSkipped)
2900 {
2901 unsigned int TotalWords = (LastByteSkipped + (WordSize -1)) / WordSize;
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002902 SKIP_SCAN SkScan;
2903 SkScan.skip = TotalWords - (LastByteScanned/WordSize);
2904 SkScan.scan = 0;
2905 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00002906 }
2907 }
2908 // Mini optimization of nibbles such that an 0xM0 followed by 0x0N is produced
2909 // as 0xMN.
2910 for (int i = 0; i <= SkipScan; i++)
2911 {
2912 if ((i < SkipScan) && SkipScanIvars[i].skip && SkipScanIvars[i].scan == 0
2913 && SkipScanIvars[i+1].skip == 0 && SkipScanIvars[i+1].scan) {
2914 // 0xM0 followed by 0x0N detected.
2915 SkipScanIvars[i].scan = SkipScanIvars[i+1].scan;
2916 for (int j = i+1; j < SkipScan; j++)
2917 SkipScanIvars[j] = SkipScanIvars[j+1];
2918 --SkipScan;
2919 }
2920 }
2921
2922 // Generate the string.
2923 std::string BitMap;
2924 for (int i = 0; i <= SkipScan; i++)
2925 {
2926 unsigned char byte;
2927 unsigned int skip_small = SkipScanIvars[i].skip % 0xf;
2928 unsigned int scan_small = SkipScanIvars[i].scan % 0xf;
2929 unsigned int skip_big = SkipScanIvars[i].skip / 0xf;
2930 unsigned int scan_big = SkipScanIvars[i].scan / 0xf;
2931
2932 if (skip_small > 0 || skip_big > 0)
2933 BytesSkipped = true;
2934 // first skip big.
2935 for (unsigned int ix = 0; ix < skip_big; ix++)
2936 BitMap += (unsigned char)(0xf0);
2937
2938 // next (skip small, scan)
2939 if (skip_small)
2940 {
2941 byte = skip_small << 4;
2942 if (scan_big > 0)
2943 {
2944 byte |= 0xf;
2945 --scan_big;
2946 }
2947 else if (scan_small)
2948 {
2949 byte |= scan_small;
2950 scan_small = 0;
2951 }
2952 BitMap += byte;
2953 }
2954 // next scan big
2955 for (unsigned int ix = 0; ix < scan_big; ix++)
2956 BitMap += (unsigned char)(0x0f);
2957 // last scan small
2958 if (scan_small)
2959 {
2960 byte = scan_small;
2961 BitMap += byte;
2962 }
2963 }
2964 // null terminate string.
Fariborz Jahanian738ee712009-03-25 22:36:49 +00002965 unsigned char zero = 0;
2966 BitMap += zero;
Fariborz Jahanian31614742009-04-20 22:03:45 +00002967
2968 if (CGM.getLangOptions().ObjCGCBitmapPrint) {
2969 printf("\n%s ivar layout for class '%s': ",
2970 ForStrongLayout ? "strong" : "weak",
2971 OMD->getClassInterface()->getNameAsCString());
2972 const unsigned char *s = (unsigned char*)BitMap.c_str();
2973 for (unsigned i = 0; i < BitMap.size(); i++)
2974 if (!(s[i] & 0xf0))
2975 printf("0x0%x%s", s[i], s[i] != 0 ? ", " : "");
2976 else
2977 printf("0x%x%s", s[i], s[i] != 0 ? ", " : "");
2978 printf("\n");
2979 }
2980
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00002981 // if ivar_layout bitmap is all 1 bits (nothing skipped) then use NULL as
2982 // final layout.
2983 if (ForStrongLayout && !BytesSkipped)
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002984 return llvm::Constant::getNullValue(PtrTy);
2985 llvm::GlobalVariable * Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
2986 llvm::ConstantArray::get(BitMap.c_str()),
2987 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarfbfd92a2009-04-14 23:14:47 +00002988 1, true);
Fariborz Jahanian31614742009-04-20 22:03:45 +00002989 return getConstantGEP(Entry, 0, 0);
Fariborz Jahanian01b3e342009-03-05 22:39:55 +00002990}
2991
Fariborz Jahanian32b5ea22009-01-21 23:34:32 +00002992llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) {
Daniel Dunbar5eec6142008-08-12 03:39:23 +00002993 llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
2994
Daniel Dunbar90d88f92009-03-09 21:49:58 +00002995 // FIXME: Avoid std::string copying.
2996 if (!Entry)
2997 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_NAME_",
2998 llvm::ConstantArray::get(Sel.getAsString()),
2999 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarfbfd92a2009-04-14 23:14:47 +00003000 1, true);
Daniel Dunbar5eec6142008-08-12 03:39:23 +00003001
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003002 return getConstantGEP(Entry, 0, 0);
3003}
3004
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003005// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian32b5ea22009-01-21 23:34:32 +00003006llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) {
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003007 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
3008}
3009
3010// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian32b5ea22009-01-21 23:34:32 +00003011llvm::Constant *CGObjCCommonMac::GetMethodVarName(const std::string &Name) {
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003012 return GetMethodVarName(&CGM.getContext().Idents.get(Name));
3013}
3014
Daniel Dunbar356f0742009-04-20 06:54:31 +00003015llvm::Constant *CGObjCCommonMac::GetMethodVarType(const FieldDecl *Field) {
Devang Patel593a07a2009-03-04 18:21:39 +00003016 std::string TypeStr;
3017 CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
3018
3019 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003020
Daniel Dunbar90d88f92009-03-09 21:49:58 +00003021 if (!Entry)
3022 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3023 llvm::ConstantArray::get(TypeStr),
3024 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarfbfd92a2009-04-14 23:14:47 +00003025 1, true);
Daniel Dunbar90d88f92009-03-09 21:49:58 +00003026
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003027 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar5eec6142008-08-12 03:39:23 +00003028}
3029
Fariborz Jahanian32b5ea22009-01-21 23:34:32 +00003030llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D) {
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003031 std::string TypeStr;
Daniel Dunbar12996f52008-08-26 21:51:14 +00003032 CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D),
3033 TypeStr);
Devang Patel593a07a2009-03-04 18:21:39 +00003034
3035 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
3036
Daniel Dunbarfbfd92a2009-04-14 23:14:47 +00003037 if (!Entry)
3038 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3039 llvm::ConstantArray::get(TypeStr),
3040 "__TEXT,__cstring,cstring_literals",
3041 1, true);
Devang Patel593a07a2009-03-04 18:21:39 +00003042
3043 return getConstantGEP(Entry, 0, 0);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003044}
3045
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00003046// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian32b5ea22009-01-21 23:34:32 +00003047llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) {
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00003048 llvm::GlobalVariable *&Entry = PropertyNames[Ident];
3049
Daniel Dunbar90d88f92009-03-09 21:49:58 +00003050 if (!Entry)
3051 Entry = CreateMetadataVar("\01L_OBJC_PROP_NAME_ATTR_",
3052 llvm::ConstantArray::get(Ident->getName()),
3053 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarfbfd92a2009-04-14 23:14:47 +00003054 1, true);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00003055
3056 return getConstantGEP(Entry, 0, 0);
3057}
3058
3059// FIXME: Merge into a single cstring creation function.
Daniel Dunbar698d6f32008-08-28 04:38:10 +00003060// FIXME: This Decl should be more precise.
Daniel Dunbar90d88f92009-03-09 21:49:58 +00003061llvm::Constant *
3062 CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
3063 const Decl *Container) {
Daniel Dunbar698d6f32008-08-28 04:38:10 +00003064 std::string TypeStr;
3065 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00003066 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
3067}
3068
Fariborz Jahanian32b5ea22009-01-21 23:34:32 +00003069void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D,
3070 const ObjCContainerDecl *CD,
3071 std::string &NameOut) {
Daniel Dunbara2d275d2009-04-07 05:48:37 +00003072 NameOut = '\01';
3073 NameOut += (D->isInstanceMethod() ? '-' : '+');
Chris Lattner3a8f2942008-11-24 03:33:13 +00003074 NameOut += '[';
Fariborz Jahanian0adaa8a2009-01-10 21:06:09 +00003075 assert (CD && "Missing container decl in GetNameForMethod");
3076 NameOut += CD->getNameAsString();
Fariborz Jahanian6e4b7372009-04-16 18:34:20 +00003077 if (const ObjCCategoryImplDecl *CID =
3078 dyn_cast<ObjCCategoryImplDecl>(D->getDeclContext())) {
3079 NameOut += '(';
3080 NameOut += CID->getNameAsString();
3081 NameOut+= ')';
3082 }
Chris Lattner3a8f2942008-11-24 03:33:13 +00003083 NameOut += ' ';
3084 NameOut += D->getSelector().getAsString();
3085 NameOut += ']';
Daniel Dunbarace33292008-08-16 03:19:19 +00003086}
3087
Daniel Dunbar1be1df32008-08-11 21:35:06 +00003088void CGObjCMac::FinishModule() {
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00003089 EmitModuleInfo();
3090
Daniel Dunbar35b777f2008-10-29 22:36:39 +00003091 // Emit the dummy bodies for any protocols which were referenced but
3092 // never defined.
3093 for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
3094 i = Protocols.begin(), e = Protocols.end(); i != e; ++i) {
3095 if (i->second->hasInitializer())
3096 continue;
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00003097
Daniel Dunbar35b777f2008-10-29 22:36:39 +00003098 std::vector<llvm::Constant*> Values(5);
3099 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
3100 Values[1] = GetClassName(i->first);
3101 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
3102 Values[3] = Values[4] =
3103 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
3104 i->second->setLinkage(llvm::GlobalValue::InternalLinkage);
3105 i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
3106 Values));
3107 }
3108
3109 std::vector<llvm::Constant*> Used;
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00003110 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
Daniel Dunbar1be1df32008-08-11 21:35:06 +00003111 e = UsedGlobals.end(); i != e; ++i) {
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003112 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
Daniel Dunbar1be1df32008-08-11 21:35:06 +00003113 }
3114
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003115 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
Daniel Dunbar1be1df32008-08-11 21:35:06 +00003116 llvm::GlobalValue *GV =
3117 new llvm::GlobalVariable(AT, false,
3118 llvm::GlobalValue::AppendingLinkage,
3119 llvm::ConstantArray::get(AT, Used),
3120 "llvm.used",
3121 &CGM.getModule());
3122
3123 GV->setSection("llvm.metadata");
Daniel Dunbar8ede0052008-08-25 06:02:07 +00003124
3125 // Add assembler directives to add lazy undefined symbol references
3126 // for classes which are referenced but not defined. This is
3127 // important for correct linker interaction.
3128
3129 // FIXME: Uh, this isn't particularly portable.
3130 std::stringstream s;
Anders Carlsson63f98352008-12-10 02:21:04 +00003131
3132 if (!CGM.getModule().getModuleInlineAsm().empty())
3133 s << "\n";
3134
Daniel Dunbar8ede0052008-08-25 06:02:07 +00003135 for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(),
3136 e = LazySymbols.end(); i != e; ++i) {
3137 s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n";
3138 }
3139 for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(),
3140 e = DefinedSymbols.end(); i != e; ++i) {
Daniel Dunbar698d6f32008-08-28 04:38:10 +00003141 s << "\t.objc_class_name_" << (*i)->getName() << "=0\n"
Daniel Dunbar8ede0052008-08-25 06:02:07 +00003142 << "\t.globl .objc_class_name_" << (*i)->getName() << "\n";
3143 }
Anders Carlsson63f98352008-12-10 02:21:04 +00003144
Daniel Dunbar8ede0052008-08-25 06:02:07 +00003145 CGM.getModule().appendModuleInlineAsm(s.str());
Daniel Dunbar1be1df32008-08-11 21:35:06 +00003146}
3147
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003148CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm)
Fariborz Jahanian48543f52009-01-21 22:04:16 +00003149 : CGObjCCommonMac(cgm),
3150 ObjCTypes(cgm)
3151{
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00003152 ObjCEmptyCacheVar = ObjCEmptyVtableVar = NULL;
Fariborz Jahanian48543f52009-01-21 22:04:16 +00003153 ObjCABI = 2;
3154}
3155
Daniel Dunbar1be1df32008-08-11 21:35:06 +00003156/* *** */
3157
Fariborz Jahanian48543f52009-01-21 22:04:16 +00003158ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm)
3159: CGM(cgm)
Daniel Dunbardaf4ad42008-08-12 00:12:39 +00003160{
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00003161 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3162 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanian48543f52009-01-21 22:04:16 +00003163
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003164 ShortTy = Types.ConvertType(Ctx.ShortTy);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003165 IntTy = Types.ConvertType(Ctx.IntTy);
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00003166 LongTy = Types.ConvertType(Ctx.LongTy);
Fariborz Jahanianad51ca02009-03-23 19:10:40 +00003167 LongLongTy = Types.ConvertType(Ctx.LongLongTy);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003168 Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3169
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00003170 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
Fariborz Jahanianc192d4d2008-11-18 20:18:11 +00003171 PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00003172 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003173
3174 // FIXME: It would be nice to unify this with the opaque type, so
3175 // that the IR comes out a bit cleaner.
3176 const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
3177 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
Fariborz Jahanian48543f52009-01-21 22:04:16 +00003178
3179 // I'm not sure I like this. The implicit coordination is a bit
3180 // gross. We should solve this in a reasonable fashion because this
3181 // is a pretty common task (match some runtime data structure with
3182 // an LLVM data structure).
3183
3184 // FIXME: This is leaked.
3185 // FIXME: Merge with rewriter code?
3186
3187 // struct _objc_super {
3188 // id self;
3189 // Class cls;
3190 // }
3191 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3192 SourceLocation(),
3193 &Ctx.Idents.get("_objc_super"));
Douglas Gregorc55b0b02009-04-09 21:40:53 +00003194 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3195 Ctx.getObjCIdType(), 0, false));
3196 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3197 Ctx.getObjCClassType(), 0, false));
Fariborz Jahanian48543f52009-01-21 22:04:16 +00003198 RD->completeDefinition(Ctx);
3199
3200 SuperCTy = Ctx.getTagDeclType(RD);
3201 SuperPtrCTy = Ctx.getPointerType(SuperCTy);
3202
3203 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
Fariborz Jahanian4b161702009-01-22 00:37:21 +00003204 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
3205
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003206 // struct _prop_t {
3207 // char *name;
3208 // char *attributes;
3209 // }
3210 PropertyTy = llvm::StructType::get(Int8PtrTy,
3211 Int8PtrTy,
3212 NULL);
3213 CGM.getModule().addTypeName("struct._prop_t",
3214 PropertyTy);
3215
3216 // struct _prop_list_t {
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003217 // uint32_t entsize; // sizeof(struct _prop_t)
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003218 // uint32_t count_of_properties;
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003219 // struct _prop_t prop_list[count_of_properties];
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003220 // }
3221 PropertyListTy = llvm::StructType::get(IntTy,
3222 IntTy,
3223 llvm::ArrayType::get(PropertyTy, 0),
3224 NULL);
3225 CGM.getModule().addTypeName("struct._prop_list_t",
3226 PropertyListTy);
3227 // struct _prop_list_t *
3228 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
3229
3230 // struct _objc_method {
3231 // SEL _cmd;
3232 // char *method_type;
3233 // char *_imp;
3234 // }
3235 MethodTy = llvm::StructType::get(SelectorPtrTy,
3236 Int8PtrTy,
3237 Int8PtrTy,
3238 NULL);
3239 CGM.getModule().addTypeName("struct._objc_method", MethodTy);
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003240
3241 // struct _objc_cache *
3242 CacheTy = llvm::OpaqueType::get();
3243 CGM.getModule().addTypeName("struct._objc_cache", CacheTy);
3244 CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003245
Fariborz Jahanian4b161702009-01-22 00:37:21 +00003246 // Property manipulation functions.
Daniel Dunbardac29922009-02-04 00:44:42 +00003247
3248 QualType IdType = Ctx.getObjCIdType();
3249 QualType SelType = Ctx.getObjCSelType();
3250 llvm::SmallVector<QualType,16> Params;
3251 const llvm::FunctionType *FTy;
Fariborz Jahanian4b161702009-01-22 00:37:21 +00003252
3253 // id objc_getProperty (id, SEL, ptrdiff_t, bool)
Daniel Dunbardac29922009-02-04 00:44:42 +00003254 Params.push_back(IdType);
3255 Params.push_back(SelType);
3256 Params.push_back(Ctx.LongTy);
3257 Params.push_back(Ctx.BoolTy);
3258 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params),
3259 false);
3260 GetPropertyFn = CGM.CreateRuntimeFunction(FTy, "objc_getProperty");
Fariborz Jahanian4b161702009-01-22 00:37:21 +00003261
3262 // void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool)
3263 Params.clear();
Daniel Dunbardac29922009-02-04 00:44:42 +00003264 Params.push_back(IdType);
3265 Params.push_back(SelType);
3266 Params.push_back(Ctx.LongTy);
3267 Params.push_back(IdType);
3268 Params.push_back(Ctx.BoolTy);
3269 Params.push_back(Ctx.BoolTy);
3270 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
3271 SetPropertyFn = CGM.CreateRuntimeFunction(FTy, "objc_setProperty");
3272
Fariborz Jahanian4b161702009-01-22 00:37:21 +00003273 // Enumeration mutation.
Daniel Dunbardac29922009-02-04 00:44:42 +00003274
3275 // void objc_enumerationMutation (id)
Fariborz Jahanian4b161702009-01-22 00:37:21 +00003276 Params.clear();
Daniel Dunbardac29922009-02-04 00:44:42 +00003277 Params.push_back(IdType);
3278 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
3279 EnumerationMutationFn = CGM.CreateRuntimeFunction(FTy,
3280 "objc_enumerationMutation");
Fariborz Jahanian4b161702009-01-22 00:37:21 +00003281
3282 // gc's API
3283 // id objc_read_weak (id *)
3284 Params.clear();
Daniel Dunbardac29922009-02-04 00:44:42 +00003285 Params.push_back(Ctx.getPointerType(IdType));
3286 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
3287 GcReadWeakFn = CGM.CreateRuntimeFunction(FTy, "objc_read_weak");
3288
Chris Lattner293c1d32009-04-17 22:12:36 +00003289 // id objc_assign_global (id, id *)
Fariborz Jahanian4b161702009-01-22 00:37:21 +00003290 Params.clear();
Daniel Dunbardac29922009-02-04 00:44:42 +00003291 Params.push_back(IdType);
3292 Params.push_back(Ctx.getPointerType(IdType));
3293
3294 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
Daniel Dunbardac29922009-02-04 00:44:42 +00003295 GcAssignGlobalFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_global");
3296 GcAssignIvarFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_ivar");
3297 GcAssignStrongCastFn =
3298 CGM.CreateRuntimeFunction(FTy, "objc_assign_strongCast");
Anders Carlsson1cf75362009-02-16 22:59:18 +00003299
3300 // void objc_exception_throw(id)
3301 Params.clear();
3302 Params.push_back(IdType);
3303
3304 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
Anders Carlsson1cf75362009-02-16 22:59:18 +00003305 ExceptionThrowFn =
3306 CGM.CreateRuntimeFunction(FTy, "objc_exception_throw");
Daniel Dunbar34416d62009-02-24 01:43:46 +00003307
3308 // synchronized APIs
Daniel Dunbar34416d62009-02-24 01:43:46 +00003309 // void objc_sync_exit (id)
3310 Params.clear();
3311 Params.push_back(IdType);
3312
3313 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
Daniel Dunbar34416d62009-02-24 01:43:46 +00003314 SyncExitFn = CGM.CreateRuntimeFunction(FTy, "objc_sync_exit");
Fariborz Jahanian48543f52009-01-21 22:04:16 +00003315}
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00003316
Fariborz Jahanian48543f52009-01-21 22:04:16 +00003317ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
3318 : ObjCCommonTypesHelper(cgm)
3319{
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003320 // struct _objc_method_description {
3321 // SEL name;
3322 // char *types;
3323 // }
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003324 MethodDescriptionTy =
3325 llvm::StructType::get(SelectorPtrTy,
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003326 Int8PtrTy,
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003327 NULL);
3328 CGM.getModule().addTypeName("struct._objc_method_description",
3329 MethodDescriptionTy);
3330
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003331 // struct _objc_method_description_list {
3332 // int count;
3333 // struct _objc_method_description[1];
3334 // }
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003335 MethodDescriptionListTy =
3336 llvm::StructType::get(IntTy,
3337 llvm::ArrayType::get(MethodDescriptionTy, 0),
3338 NULL);
3339 CGM.getModule().addTypeName("struct._objc_method_description_list",
3340 MethodDescriptionListTy);
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003341
3342 // struct _objc_method_description_list *
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003343 MethodDescriptionListPtrTy =
3344 llvm::PointerType::getUnqual(MethodDescriptionListTy);
3345
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003346 // Protocol description structures
3347
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003348 // struct _objc_protocol_extension {
3349 // uint32_t size; // sizeof(struct _objc_protocol_extension)
3350 // struct _objc_method_description_list *optional_instance_methods;
3351 // struct _objc_method_description_list *optional_class_methods;
3352 // struct _objc_property_list *instance_properties;
3353 // }
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003354 ProtocolExtensionTy =
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003355 llvm::StructType::get(IntTy,
3356 MethodDescriptionListPtrTy,
3357 MethodDescriptionListPtrTy,
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003358 PropertyListPtrTy,
3359 NULL);
3360 CGM.getModule().addTypeName("struct._objc_protocol_extension",
3361 ProtocolExtensionTy);
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003362
3363 // struct _objc_protocol_extension *
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003364 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
3365
Daniel Dunbar35b777f2008-10-29 22:36:39 +00003366 // Handle recursive construction of Protocol and ProtocolList types
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003367
3368 llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get();
3369 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3370
Fariborz Jahanian48543f52009-01-21 22:04:16 +00003371 const llvm::Type *T =
3372 llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder),
3373 LongTy,
3374 llvm::ArrayType::get(ProtocolTyHolder, 0),
3375 NULL);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003376 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T);
3377
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003378 // struct _objc_protocol {
3379 // struct _objc_protocol_extension *isa;
3380 // char *protocol_name;
3381 // struct _objc_protocol **_objc_protocol_list;
3382 // struct _objc_method_description_list *instance_methods;
3383 // struct _objc_method_description_list *class_methods;
3384 // }
3385 T = llvm::StructType::get(ProtocolExtensionPtrTy,
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003386 Int8PtrTy,
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003387 llvm::PointerType::getUnqual(ProtocolListTyHolder),
3388 MethodDescriptionListPtrTy,
3389 MethodDescriptionListPtrTy,
3390 NULL);
3391 cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T);
3392
3393 ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get());
3394 CGM.getModule().addTypeName("struct._objc_protocol_list",
3395 ProtocolListTy);
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003396 // struct _objc_protocol_list *
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003397 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
3398
3399 ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get());
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003400 CGM.getModule().addTypeName("struct._objc_protocol", ProtocolTy);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003401 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003402
3403 // Class description structures
3404
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003405 // struct _objc_ivar {
3406 // char *ivar_name;
3407 // char *ivar_type;
3408 // int ivar_offset;
3409 // }
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003410 IvarTy = llvm::StructType::get(Int8PtrTy,
3411 Int8PtrTy,
3412 IntTy,
3413 NULL);
3414 CGM.getModule().addTypeName("struct._objc_ivar", IvarTy);
3415
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003416 // struct _objc_ivar_list *
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003417 IvarListTy = llvm::OpaqueType::get();
3418 CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy);
3419 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
3420
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003421 // struct _objc_method_list *
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003422 MethodListTy = llvm::OpaqueType::get();
3423 CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy);
3424 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
3425
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003426 // struct _objc_class_extension *
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003427 ClassExtensionTy =
3428 llvm::StructType::get(IntTy,
3429 Int8PtrTy,
3430 PropertyListPtrTy,
3431 NULL);
3432 CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy);
3433 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
3434
3435 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3436
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003437 // struct _objc_class {
3438 // Class isa;
3439 // Class super_class;
3440 // char *name;
3441 // long version;
3442 // long info;
3443 // long instance_size;
3444 // struct _objc_ivar_list *ivars;
3445 // struct _objc_method_list *methods;
3446 // struct _objc_cache *cache;
3447 // struct _objc_protocol_list *protocols;
3448 // char *ivar_layout;
3449 // struct _objc_class_ext *ext;
3450 // };
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003451 T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3452 llvm::PointerType::getUnqual(ClassTyHolder),
3453 Int8PtrTy,
3454 LongTy,
3455 LongTy,
3456 LongTy,
3457 IvarListPtrTy,
3458 MethodListPtrTy,
3459 CachePtrTy,
3460 ProtocolListPtrTy,
3461 Int8PtrTy,
3462 ClassExtensionPtrTy,
3463 NULL);
3464 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T);
3465
3466 ClassTy = cast<llvm::StructType>(ClassTyHolder.get());
3467 CGM.getModule().addTypeName("struct._objc_class", ClassTy);
3468 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
3469
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003470 // struct _objc_category {
3471 // char *category_name;
3472 // char *class_name;
3473 // struct _objc_method_list *instance_method;
3474 // struct _objc_method_list *class_method;
3475 // uint32_t size; // sizeof(struct _objc_category)
3476 // struct _objc_property_list *instance_properties;// category's @property
3477 // }
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00003478 CategoryTy = llvm::StructType::get(Int8PtrTy,
3479 Int8PtrTy,
3480 MethodListPtrTy,
3481 MethodListPtrTy,
3482 ProtocolListPtrTy,
3483 IntTy,
3484 PropertyListPtrTy,
3485 NULL);
3486 CGM.getModule().addTypeName("struct._objc_category", CategoryTy);
3487
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003488 // Global metadata structures
3489
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003490 // struct _objc_symtab {
3491 // long sel_ref_cnt;
3492 // SEL *refs;
3493 // short cls_def_cnt;
3494 // short cat_def_cnt;
3495 // char *defs[cls_def_cnt + cat_def_cnt];
3496 // }
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003497 SymtabTy = llvm::StructType::get(LongTy,
3498 SelectorPtrTy,
3499 ShortTy,
3500 ShortTy,
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00003501 llvm::ArrayType::get(Int8PtrTy, 0),
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003502 NULL);
3503 CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy);
3504 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
3505
Fariborz Jahanian4b161702009-01-22 00:37:21 +00003506 // struct _objc_module {
3507 // long version;
3508 // long size; // sizeof(struct _objc_module)
3509 // char *name;
3510 // struct _objc_symtab* symtab;
3511 // }
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003512 ModuleTy =
3513 llvm::StructType::get(LongTy,
3514 LongTy,
3515 Int8PtrTy,
3516 SymtabPtrTy,
3517 NULL);
3518 CGM.getModule().addTypeName("struct._objc_module", ModuleTy);
Daniel Dunbar87062ff2008-08-23 09:25:55 +00003519
Daniel Dunbarf7103722008-09-24 03:38:44 +00003520 // Message send functions.
Daniel Dunbar87062ff2008-08-23 09:25:55 +00003521
Fariborz Jahanian4b161702009-01-22 00:37:21 +00003522 // id objc_msgSend (id, SEL, ...)
Daniel Dunbar87062ff2008-08-23 09:25:55 +00003523 std::vector<const llvm::Type*> Params;
3524 Params.push_back(ObjectPtrTy);
3525 Params.push_back(SelectorPtrTy);
Daniel Dunbar4e19f4e2008-10-01 01:06:06 +00003526 MessageSendFn =
3527 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3528 Params,
3529 true),
3530 "objc_msgSend");
Daniel Dunbar87062ff2008-08-23 09:25:55 +00003531
Fariborz Jahanian4b161702009-01-22 00:37:21 +00003532 // id objc_msgSend_stret (id, SEL, ...)
Daniel Dunbar87062ff2008-08-23 09:25:55 +00003533 Params.clear();
Daniel Dunbar87062ff2008-08-23 09:25:55 +00003534 Params.push_back(ObjectPtrTy);
3535 Params.push_back(SelectorPtrTy);
3536 MessageSendStretFn =
Daniel Dunbar4e19f4e2008-10-01 01:06:06 +00003537 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3538 Params,
3539 true),
3540 "objc_msgSend_stret");
Daniel Dunbaraecef4c2008-10-17 03:24:53 +00003541
Fariborz Jahanian4b161702009-01-22 00:37:21 +00003542 //
Daniel Dunbaraecef4c2008-10-17 03:24:53 +00003543 Params.clear();
3544 Params.push_back(ObjectPtrTy);
3545 Params.push_back(SelectorPtrTy);
3546 // FIXME: This should be long double on x86_64?
Fariborz Jahanian4b161702009-01-22 00:37:21 +00003547 // [double | long double] objc_msgSend_fpret(id self, SEL op, ...)
Daniel Dunbaraecef4c2008-10-17 03:24:53 +00003548 MessageSendFpretFn =
3549 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::DoubleTy,
3550 Params,
3551 true),
3552 "objc_msgSend_fpret");
Daniel Dunbar87062ff2008-08-23 09:25:55 +00003553
Fariborz Jahanian4b161702009-01-22 00:37:21 +00003554 // id objc_msgSendSuper(struct objc_super *super, SEL op, ...)
Daniel Dunbar87062ff2008-08-23 09:25:55 +00003555 Params.clear();
3556 Params.push_back(SuperPtrTy);
3557 Params.push_back(SelectorPtrTy);
3558 MessageSendSuperFn =
Daniel Dunbar4e19f4e2008-10-01 01:06:06 +00003559 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3560 Params,
3561 true),
3562 "objc_msgSendSuper");
Daniel Dunbar87062ff2008-08-23 09:25:55 +00003563
Fariborz Jahanian4b161702009-01-22 00:37:21 +00003564 // void objc_msgSendSuper_stret(void * stretAddr, struct objc_super *super,
3565 // SEL op, ...)
Daniel Dunbar87062ff2008-08-23 09:25:55 +00003566 Params.clear();
3567 Params.push_back(Int8PtrTy);
3568 Params.push_back(SuperPtrTy);
3569 Params.push_back(SelectorPtrTy);
3570 MessageSendSuperStretFn =
Daniel Dunbar4e19f4e2008-10-01 01:06:06 +00003571 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3572 Params,
3573 true),
3574 "objc_msgSendSuper_stret");
Daniel Dunbaraecef4c2008-10-17 03:24:53 +00003575
3576 // There is no objc_msgSendSuper_fpret? How can that work?
3577 MessageSendSuperFpretFn = MessageSendSuperFn;
Anders Carlsson58d16242008-08-31 04:05:03 +00003578
Anders Carlsson9acb0a42008-09-09 10:10:21 +00003579 // FIXME: This is the size of the setjmp buffer and should be
3580 // target specific. 18 is what's used on 32-bit X86.
3581 uint64_t SetJmpBufferSize = 18;
3582
3583 // Exceptions
3584 const llvm::Type *StackPtrTy =
Daniel Dunbar1c5e4632008-09-27 06:32:25 +00003585 llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4);
Anders Carlsson9acb0a42008-09-09 10:10:21 +00003586
3587 ExceptionDataTy =
3588 llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty,
3589 SetJmpBufferSize),
3590 StackPtrTy, NULL);
3591 CGM.getModule().addTypeName("struct._objc_exception_data",
3592 ExceptionDataTy);
3593
3594 Params.clear();
Anders Carlsson9acb0a42008-09-09 10:10:21 +00003595 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
3596 ExceptionTryEnterFn =
Daniel Dunbar4e19f4e2008-10-01 01:06:06 +00003597 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3598 Params,
3599 false),
3600 "objc_exception_try_enter");
Anders Carlsson9acb0a42008-09-09 10:10:21 +00003601 ExceptionTryExitFn =
Daniel Dunbar4e19f4e2008-10-01 01:06:06 +00003602 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3603 Params,
3604 false),
3605 "objc_exception_try_exit");
Anders Carlsson9acb0a42008-09-09 10:10:21 +00003606 ExceptionExtractFn =
Daniel Dunbar4e19f4e2008-10-01 01:06:06 +00003607 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3608 Params,
3609 false),
3610 "objc_exception_extract");
Anders Carlsson9acb0a42008-09-09 10:10:21 +00003611
3612 Params.clear();
3613 Params.push_back(ClassPtrTy);
3614 Params.push_back(ObjectPtrTy);
3615 ExceptionMatchFn =
Daniel Dunbar4e19f4e2008-10-01 01:06:06 +00003616 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
3617 Params,
3618 false),
3619 "objc_exception_match");
Chris Lattnerdd978702008-11-15 21:26:17 +00003620
Anders Carlsson9acb0a42008-09-09 10:10:21 +00003621 Params.clear();
3622 Params.push_back(llvm::PointerType::getUnqual(llvm::Type::Int32Ty));
3623 SetJmpFn =
Daniel Dunbar4e19f4e2008-10-01 01:06:06 +00003624 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
3625 Params,
3626 false),
3627 "_setjmp");
Fariborz Jahanianc192d4d2008-11-18 20:18:11 +00003628
Daniel Dunbardaf4ad42008-08-12 00:12:39 +00003629}
3630
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003631ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm)
Fariborz Jahanian48543f52009-01-21 22:04:16 +00003632: ObjCCommonTypesHelper(cgm)
3633{
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003634 // struct _method_list_t {
3635 // uint32_t entsize; // sizeof(struct _objc_method)
3636 // uint32_t method_count;
3637 // struct _objc_method method_list[method_count];
3638 // }
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003639 MethodListnfABITy = llvm::StructType::get(IntTy,
3640 IntTy,
3641 llvm::ArrayType::get(MethodTy, 0),
3642 NULL);
3643 CGM.getModule().addTypeName("struct.__method_list_t",
3644 MethodListnfABITy);
3645 // struct method_list_t *
3646 MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy);
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003647
3648 // struct _protocol_t {
3649 // id isa; // NULL
3650 // const char * const protocol_name;
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003651 // const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003652 // const struct method_list_t * const instance_methods;
3653 // const struct method_list_t * const class_methods;
3654 // const struct method_list_t *optionalInstanceMethods;
3655 // const struct method_list_t *optionalClassMethods;
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003656 // const struct _prop_list_t * properties;
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003657 // const uint32_t size; // sizeof(struct _protocol_t)
3658 // const uint32_t flags; // = 0
3659 // }
3660
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003661 // Holder for struct _protocol_list_t *
3662 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3663
3664 ProtocolnfABITy = llvm::StructType::get(ObjectPtrTy,
3665 Int8PtrTy,
3666 llvm::PointerType::getUnqual(
3667 ProtocolListTyHolder),
3668 MethodListnfABIPtrTy,
3669 MethodListnfABIPtrTy,
3670 MethodListnfABIPtrTy,
3671 MethodListnfABIPtrTy,
3672 PropertyListPtrTy,
3673 IntTy,
3674 IntTy,
3675 NULL);
3676 CGM.getModule().addTypeName("struct._protocol_t",
3677 ProtocolnfABITy);
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00003678
3679 // struct _protocol_t*
3680 ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy);
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003681
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00003682 // struct _protocol_list_t {
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003683 // long protocol_count; // Note, this is 32/64 bit
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00003684 // struct _protocol_t *[protocol_count];
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003685 // }
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003686 ProtocolListnfABITy = llvm::StructType::get(LongTy,
3687 llvm::ArrayType::get(
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00003688 ProtocolnfABIPtrTy, 0),
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003689 NULL);
3690 CGM.getModule().addTypeName("struct._objc_protocol_list",
3691 ProtocolListnfABITy);
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00003692 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(
3693 ProtocolListnfABITy);
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003694
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003695 // struct _objc_protocol_list*
3696 ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy);
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003697
3698 // struct _ivar_t {
3699 // unsigned long int *offset; // pointer to ivar offset location
3700 // char *name;
3701 // char *type;
3702 // uint32_t alignment;
3703 // uint32_t size;
3704 // }
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003705 IvarnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(LongTy),
3706 Int8PtrTy,
3707 Int8PtrTy,
3708 IntTy,
3709 IntTy,
3710 NULL);
3711 CGM.getModule().addTypeName("struct._ivar_t", IvarnfABITy);
3712
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003713 // struct _ivar_list_t {
3714 // uint32 entsize; // sizeof(struct _ivar_t)
3715 // uint32 count;
3716 // struct _iver_t list[count];
3717 // }
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00003718 IvarListnfABITy = llvm::StructType::get(IntTy,
3719 IntTy,
3720 llvm::ArrayType::get(
3721 IvarnfABITy, 0),
3722 NULL);
3723 CGM.getModule().addTypeName("struct._ivar_list_t", IvarListnfABITy);
3724
3725 IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy);
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003726
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003727 // struct _class_ro_t {
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003728 // uint32_t const flags;
3729 // uint32_t const instanceStart;
3730 // uint32_t const instanceSize;
3731 // uint32_t const reserved; // only when building for 64bit targets
3732 // const uint8_t * const ivarLayout;
3733 // const char *const name;
3734 // const struct _method_list_t * const baseMethods;
3735 // const struct _objc_protocol_list *const baseProtocols;
3736 // const struct _ivar_list_t *const ivars;
3737 // const uint8_t * const weakIvarLayout;
3738 // const struct _prop_list_t * const properties;
3739 // }
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003740
3741 // FIXME. Add 'reserved' field in 64bit abi mode!
3742 ClassRonfABITy = llvm::StructType::get(IntTy,
3743 IntTy,
3744 IntTy,
3745 Int8PtrTy,
3746 Int8PtrTy,
3747 MethodListnfABIPtrTy,
3748 ProtocolListnfABIPtrTy,
3749 IvarListnfABIPtrTy,
3750 Int8PtrTy,
3751 PropertyListPtrTy,
3752 NULL);
3753 CGM.getModule().addTypeName("struct._class_ro_t",
3754 ClassRonfABITy);
3755
3756 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
3757 std::vector<const llvm::Type*> Params;
3758 Params.push_back(ObjectPtrTy);
3759 Params.push_back(SelectorPtrTy);
3760 ImpnfABITy = llvm::PointerType::getUnqual(
3761 llvm::FunctionType::get(ObjectPtrTy, Params, false));
3762
3763 // struct _class_t {
3764 // struct _class_t *isa;
3765 // struct _class_t * const superclass;
3766 // void *cache;
3767 // IMP *vtable;
3768 // struct class_ro_t *ro;
3769 // }
3770
3771 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3772 ClassnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3773 llvm::PointerType::getUnqual(ClassTyHolder),
3774 CachePtrTy,
3775 llvm::PointerType::getUnqual(ImpnfABITy),
3776 llvm::PointerType::getUnqual(
3777 ClassRonfABITy),
3778 NULL);
3779 CGM.getModule().addTypeName("struct._class_t", ClassnfABITy);
3780
3781 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(
3782 ClassnfABITy);
3783
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00003784 // LLVM for struct _class_t *
3785 ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy);
3786
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003787 // struct _category_t {
3788 // const char * const name;
3789 // struct _class_t *const cls;
3790 // const struct _method_list_t * const instance_methods;
3791 // const struct _method_list_t * const class_methods;
3792 // const struct _protocol_list_t * const protocols;
3793 // const struct _prop_list_t * const properties;
Fariborz Jahanianb9459b72009-01-23 17:41:22 +00003794 // }
3795 CategorynfABITy = llvm::StructType::get(Int8PtrTy,
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00003796 ClassnfABIPtrTy,
Fariborz Jahanianb9459b72009-01-23 17:41:22 +00003797 MethodListnfABIPtrTy,
3798 MethodListnfABIPtrTy,
3799 ProtocolListnfABIPtrTy,
3800 PropertyListPtrTy,
3801 NULL);
3802 CGM.getModule().addTypeName("struct._category_t", CategorynfABITy);
Fariborz Jahanian711e8dd2009-02-03 23:49:23 +00003803
3804 // New types for nonfragile abi messaging.
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00003805 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3806 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanian711e8dd2009-02-03 23:49:23 +00003807
3808 // MessageRefTy - LLVM for:
3809 // struct _message_ref_t {
3810 // IMP messenger;
3811 // SEL name;
3812 // };
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00003813
3814 // First the clang type for struct _message_ref_t
3815 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3816 SourceLocation(),
3817 &Ctx.Idents.get("_message_ref_t"));
Douglas Gregorc55b0b02009-04-09 21:40:53 +00003818 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3819 Ctx.VoidPtrTy, 0, false));
3820 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3821 Ctx.getObjCSelType(), 0, false));
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00003822 RD->completeDefinition(Ctx);
3823
3824 MessageRefCTy = Ctx.getTagDeclType(RD);
3825 MessageRefCPtrTy = Ctx.getPointerType(MessageRefCTy);
3826 MessageRefTy = cast<llvm::StructType>(Types.ConvertType(MessageRefCTy));
Fariborz Jahanian711e8dd2009-02-03 23:49:23 +00003827
3828 // MessageRefPtrTy - LLVM for struct _message_ref_t*
3829 MessageRefPtrTy = llvm::PointerType::getUnqual(MessageRefTy);
3830
3831 // SuperMessageRefTy - LLVM for:
3832 // struct _super_message_ref_t {
3833 // SUPER_IMP messenger;
3834 // SEL name;
3835 // };
3836 SuperMessageRefTy = llvm::StructType::get(ImpnfABITy,
3837 SelectorPtrTy,
3838 NULL);
3839 CGM.getModule().addTypeName("struct._super_message_ref_t", SuperMessageRefTy);
3840
3841 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
3842 SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy);
3843
3844 // id objc_msgSend_fixup (id, struct message_ref_t*, ...)
3845 Params.clear();
3846 Params.push_back(ObjectPtrTy);
3847 Params.push_back(MessageRefPtrTy);
Fariborz Jahanian10d69ea2009-02-05 01:13:09 +00003848 MessengerTy = llvm::FunctionType::get(ObjectPtrTy,
3849 Params,
3850 true);
Fariborz Jahanian711e8dd2009-02-03 23:49:23 +00003851 MessageSendFixupFn =
Fariborz Jahanian10d69ea2009-02-05 01:13:09 +00003852 CGM.CreateRuntimeFunction(MessengerTy,
Fariborz Jahanian711e8dd2009-02-03 23:49:23 +00003853 "objc_msgSend_fixup");
3854
3855 // id objc_msgSend_fpret_fixup (id, struct message_ref_t*, ...)
3856 MessageSendFpretFixupFn =
3857 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3858 Params,
3859 true),
3860 "objc_msgSend_fpret_fixup");
3861
3862 // id objc_msgSend_stret_fixup (id, struct message_ref_t*, ...)
3863 MessageSendStretFixupFn =
3864 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3865 Params,
3866 true),
3867 "objc_msgSend_stret_fixup");
3868
3869 // id objc_msgSendId_fixup (id, struct message_ref_t*, ...)
3870 MessageSendIdFixupFn =
3871 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3872 Params,
3873 true),
3874 "objc_msgSendId_fixup");
3875
3876
3877 // id objc_msgSendId_stret_fixup (id, struct message_ref_t*, ...)
3878 MessageSendIdStretFixupFn =
3879 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3880 Params,
3881 true),
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00003882 "objc_msgSendId_stret_fixup");
Fariborz Jahanian711e8dd2009-02-03 23:49:23 +00003883
3884 // id objc_msgSendSuper2_fixup (struct objc_super *,
3885 // struct _super_message_ref_t*, ...)
3886 Params.clear();
3887 Params.push_back(SuperPtrTy);
3888 Params.push_back(SuperMessageRefPtrTy);
3889 MessageSendSuper2FixupFn =
3890 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3891 Params,
3892 true),
3893 "objc_msgSendSuper2_fixup");
3894
3895
3896 // id objc_msgSendSuper2_stret_fixup (struct objc_super *,
3897 // struct _super_message_ref_t*, ...)
3898 MessageSendSuper2StretFixupFn =
3899 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3900 Params,
3901 true),
3902 "objc_msgSendSuper2_stret_fixup");
Daniel Dunbar75de89f2009-02-24 07:47:38 +00003903
3904 Params.clear();
Daniel Dunbar75de89f2009-02-24 07:47:38 +00003905 Params.push_back(Int8PtrTy);
3906 UnwindResumeOrRethrowFn =
3907 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3908 Params,
3909 false),
3910 "_Unwind_Resume_or_Rethrow");
Daniel Dunbar9c285e72009-03-01 04:46:24 +00003911 ObjCBeginCatchFn =
3912 CGM.CreateRuntimeFunction(llvm::FunctionType::get(Int8PtrTy,
3913 Params,
3914 false),
3915 "objc_begin_catch");
3916
3917 Params.clear();
3918 ObjCEndCatchFn =
3919 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3920 Params,
3921 false),
3922 "objc_end_catch");
3923
3924 // struct objc_typeinfo {
3925 // const void** vtable; // objc_ehtype_vtable + 2
3926 // const char* name; // c++ typeinfo string
3927 // Class cls;
3928 // };
3929 EHTypeTy = llvm::StructType::get(llvm::PointerType::getUnqual(Int8PtrTy),
3930 Int8PtrTy,
3931 ClassnfABIPtrTy,
3932 NULL);
Daniel Dunbarc0318b22009-03-02 06:08:11 +00003933 CGM.getModule().addTypeName("struct._objc_typeinfo", EHTypeTy);
Daniel Dunbar9c285e72009-03-01 04:46:24 +00003934 EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy);
Daniel Dunbardaf4ad42008-08-12 00:12:39 +00003935}
3936
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00003937llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() {
3938 FinishNonFragileABIModule();
3939
3940 return NULL;
3941}
3942
3943void CGObjCNonFragileABIMac::FinishNonFragileABIModule() {
3944 // nonfragile abi has no module definition.
Fariborz Jahanian11c93dd2009-01-30 20:55:31 +00003945
3946 // Build list of all implemented classe addresses in array
3947 // L_OBJC_LABEL_CLASS_$.
3948 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CLASS_$
3949 // list of 'nonlazy' implementations (defined as those with a +load{}
3950 // method!!).
3951 unsigned NumClasses = DefinedClasses.size();
3952 if (NumClasses) {
3953 std::vector<llvm::Constant*> Symbols(NumClasses);
3954 for (unsigned i=0; i<NumClasses; i++)
3955 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
3956 ObjCTypes.Int8PtrTy);
3957 llvm::Constant* Init =
3958 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
3959 NumClasses),
3960 Symbols);
3961
3962 llvm::GlobalVariable *GV =
3963 new llvm::GlobalVariable(Init->getType(), false,
3964 llvm::GlobalValue::InternalLinkage,
3965 Init,
3966 "\01L_OBJC_LABEL_CLASS_$",
3967 &CGM.getModule());
Daniel Dunbar56756c32009-03-09 22:18:41 +00003968 GV->setAlignment(8);
Fariborz Jahanian11c93dd2009-01-30 20:55:31 +00003969 GV->setSection("__DATA, __objc_classlist, regular, no_dead_strip");
3970 UsedGlobals.push_back(GV);
3971 }
3972
3973 // Build list of all implemented category addresses in array
3974 // L_OBJC_LABEL_CATEGORY_$.
3975 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CATEGORY_$
3976 // list of 'nonlazy' category implementations (defined as those with a +load{}
3977 // method!!).
3978 unsigned NumCategory = DefinedCategories.size();
3979 if (NumCategory) {
3980 std::vector<llvm::Constant*> Symbols(NumCategory);
3981 for (unsigned i=0; i<NumCategory; i++)
3982 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedCategories[i],
3983 ObjCTypes.Int8PtrTy);
3984 llvm::Constant* Init =
3985 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
3986 NumCategory),
3987 Symbols);
3988
3989 llvm::GlobalVariable *GV =
3990 new llvm::GlobalVariable(Init->getType(), false,
3991 llvm::GlobalValue::InternalLinkage,
3992 Init,
3993 "\01L_OBJC_LABEL_CATEGORY_$",
3994 &CGM.getModule());
Daniel Dunbar56756c32009-03-09 22:18:41 +00003995 GV->setAlignment(8);
Fariborz Jahanian11c93dd2009-01-30 20:55:31 +00003996 GV->setSection("__DATA, __objc_catlist, regular, no_dead_strip");
3997 UsedGlobals.push_back(GV);
3998 }
3999
Fariborz Jahanian5b2f5502009-01-30 22:07:48 +00004000 // static int L_OBJC_IMAGE_INFO[2] = { 0, flags };
4001 // FIXME. flags can be 0 | 1 | 2 | 6. For now just use 0
4002 std::vector<llvm::Constant*> Values(2);
4003 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, 0);
Fariborz Jahanian4d7933a2009-02-24 21:08:09 +00004004 unsigned int flags = 0;
Fariborz Jahanian27f58962009-02-24 23:34:44 +00004005 // FIXME: Fix and continue?
4006 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
4007 flags |= eImageInfo_GarbageCollected;
4008 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
4009 flags |= eImageInfo_GCOnly;
Fariborz Jahanian4d7933a2009-02-24 21:08:09 +00004010 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
Fariborz Jahanian5b2f5502009-01-30 22:07:48 +00004011 llvm::Constant* Init = llvm::ConstantArray::get(
4012 llvm::ArrayType::get(ObjCTypes.IntTy, 2),
4013 Values);
4014 llvm::GlobalVariable *IMGV =
4015 new llvm::GlobalVariable(Init->getType(), false,
4016 llvm::GlobalValue::InternalLinkage,
4017 Init,
4018 "\01L_OBJC_IMAGE_INFO",
4019 &CGM.getModule());
4020 IMGV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
4021 UsedGlobals.push_back(IMGV);
4022
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00004023 std::vector<llvm::Constant*> Used;
Fariborz Jahanianab438842009-04-14 18:41:56 +00004024
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00004025 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
4026 e = UsedGlobals.end(); i != e; ++i) {
4027 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
4028 }
Fariborz Jahanianab438842009-04-14 18:41:56 +00004029
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00004030 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
4031 llvm::GlobalValue *GV =
4032 new llvm::GlobalVariable(AT, false,
4033 llvm::GlobalValue::AppendingLinkage,
4034 llvm::ConstantArray::get(AT, Used),
4035 "llvm.used",
4036 &CGM.getModule());
4037
4038 GV->setSection("llvm.metadata");
4039
4040}
4041
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004042// Metadata flags
4043enum MetaDataDlags {
4044 CLS = 0x0,
4045 CLS_META = 0x1,
4046 CLS_ROOT = 0x2,
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00004047 OBJC2_CLS_HIDDEN = 0x10,
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004048 CLS_EXCEPTION = 0x20
4049};
4050/// BuildClassRoTInitializer - generate meta-data for:
4051/// struct _class_ro_t {
4052/// uint32_t const flags;
4053/// uint32_t const instanceStart;
4054/// uint32_t const instanceSize;
4055/// uint32_t const reserved; // only when building for 64bit targets
4056/// const uint8_t * const ivarLayout;
4057/// const char *const name;
4058/// const struct _method_list_t * const baseMethods;
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004059/// const struct _protocol_list_t *const baseProtocols;
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004060/// const struct _ivar_list_t *const ivars;
4061/// const uint8_t * const weakIvarLayout;
4062/// const struct _prop_list_t * const properties;
4063/// }
4064///
4065llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer(
4066 unsigned flags,
4067 unsigned InstanceStart,
4068 unsigned InstanceSize,
4069 const ObjCImplementationDecl *ID) {
4070 std::string ClassName = ID->getNameAsString();
4071 std::vector<llvm::Constant*> Values(10); // 11 for 64bit targets!
4072 Values[ 0] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
4073 Values[ 1] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceStart);
4074 Values[ 2] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceSize);
4075 // FIXME. For 64bit targets add 0 here.
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004076 // FIXME. ivarLayout is currently null!
Fariborz Jahanian31614742009-04-20 22:03:45 +00004077 // Values[ 3] = BuildIvarLayout(ID, true);
Fariborz Jahanian7345eba2009-03-05 19:17:31 +00004078 Values[ 3] = GetIvarLayoutName(0, ObjCTypes);
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004079 Values[ 4] = GetClassName(ID->getIdentifier());
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00004080 // const struct _method_list_t * const baseMethods;
4081 std::vector<llvm::Constant*> Methods;
4082 std::string MethodListName("\01l_OBJC_$_");
4083 if (flags & CLS_META) {
4084 MethodListName += "CLASS_METHODS_" + ID->getNameAsString();
4085 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
4086 e = ID->classmeth_end(); i != e; ++i) {
4087 // Class methods should always be defined.
4088 Methods.push_back(GetMethodConstant(*i));
4089 }
4090 } else {
4091 MethodListName += "INSTANCE_METHODS_" + ID->getNameAsString();
4092 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
4093 e = ID->instmeth_end(); i != e; ++i) {
4094 // Instance methods should always be defined.
4095 Methods.push_back(GetMethodConstant(*i));
4096 }
Fariborz Jahanian78355ec2009-01-28 22:46:49 +00004097 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
4098 e = ID->propimpl_end(); i != e; ++i) {
4099 ObjCPropertyImplDecl *PID = *i;
4100
4101 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize){
4102 ObjCPropertyDecl *PD = PID->getPropertyDecl();
4103
4104 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
4105 if (llvm::Constant *C = GetMethodConstant(MD))
4106 Methods.push_back(C);
4107 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
4108 if (llvm::Constant *C = GetMethodConstant(MD))
4109 Methods.push_back(C);
4110 }
4111 }
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00004112 }
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00004113 Values[ 5] = EmitMethodList(MethodListName,
Fariborz Jahanian3175ddd2009-01-28 01:05:23 +00004114 "__DATA, __objc_const", Methods);
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004115
4116 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4117 assert(OID && "CGObjCNonFragileABIMac::BuildClassRoTInitializer");
4118 Values[ 6] = EmitProtocolList("\01l_OBJC_CLASS_PROTOCOLS_$_"
4119 + OID->getNameAsString(),
4120 OID->protocol_begin(),
4121 OID->protocol_end());
4122
Fariborz Jahanian3f1cc562009-01-27 19:38:51 +00004123 if (flags & CLS_META)
4124 Values[ 7] = llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4125 else
4126 Values[ 7] = EmitIvarList(ID);
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004127 // FIXME. weakIvarLayout is currently null.
Fariborz Jahanian31614742009-04-20 22:03:45 +00004128 // Values[ 8] = BuildIvarLayout(ID, false);
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00004129 Values[ 8] = GetIvarLayoutName(0, ObjCTypes);
Fariborz Jahanian7b709bb2009-01-28 22:18:42 +00004130 if (flags & CLS_META)
4131 Values[ 9] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4132 else
4133 Values[ 9] =
4134 EmitPropertyList(
4135 "\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
4136 ID, ID->getClassInterface(), ObjCTypes);
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004137 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassRonfABITy,
4138 Values);
4139 llvm::GlobalVariable *CLASS_RO_GV =
4140 new llvm::GlobalVariable(ObjCTypes.ClassRonfABITy, false,
4141 llvm::GlobalValue::InternalLinkage,
4142 Init,
4143 (flags & CLS_META) ?
4144 std::string("\01l_OBJC_METACLASS_RO_$_")+ClassName :
4145 std::string("\01l_OBJC_CLASS_RO_$_")+ClassName,
4146 &CGM.getModule());
Fariborz Jahanian2d6ecb22009-01-31 02:43:27 +00004147 CLASS_RO_GV->setAlignment(
4148 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassRonfABITy));
Fariborz Jahanian3175ddd2009-01-28 01:05:23 +00004149 CLASS_RO_GV->setSection("__DATA, __objc_const");
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004150 return CLASS_RO_GV;
Fariborz Jahanianc98c87b2009-01-26 22:58:07 +00004151
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004152}
4153
4154/// BuildClassMetaData - This routine defines that to-level meta-data
4155/// for the given ClassName for:
4156/// struct _class_t {
4157/// struct _class_t *isa;
4158/// struct _class_t * const superclass;
4159/// void *cache;
4160/// IMP *vtable;
4161/// struct class_ro_t *ro;
4162/// }
4163///
Fariborz Jahanian06726462009-01-24 21:21:53 +00004164llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassMetaData(
4165 std::string &ClassName,
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004166 llvm::Constant *IsAGV,
4167 llvm::Constant *SuperClassGV,
Fariborz Jahanian51dcacb2009-01-31 00:59:10 +00004168 llvm::Constant *ClassRoGV,
4169 bool HiddenVisibility) {
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004170 std::vector<llvm::Constant*> Values(5);
4171 Values[0] = IsAGV;
Fariborz Jahanian06726462009-01-24 21:21:53 +00004172 Values[1] = SuperClassGV
4173 ? SuperClassGV
4174 : llvm::Constant::getNullValue(ObjCTypes.ClassnfABIPtrTy);
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004175 Values[2] = ObjCEmptyCacheVar; // &ObjCEmptyCacheVar
4176 Values[3] = ObjCEmptyVtableVar; // &ObjCEmptyVtableVar
4177 Values[4] = ClassRoGV; // &CLASS_RO_GV
4178 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassnfABITy,
4179 Values);
Daniel Dunbarabbda222009-03-01 04:40:10 +00004180 llvm::GlobalVariable *GV = GetClassGlobal(ClassName);
4181 GV->setInitializer(Init);
Fariborz Jahanian7c891592009-01-31 01:07:39 +00004182 GV->setSection("__DATA, __objc_data");
Fariborz Jahanian2d6ecb22009-01-31 02:43:27 +00004183 GV->setAlignment(
4184 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassnfABITy));
Fariborz Jahanian51dcacb2009-01-31 00:59:10 +00004185 if (HiddenVisibility)
4186 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahanian06726462009-01-24 21:21:53 +00004187 return GV;
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004188}
4189
Daniel Dunbar72878722009-04-20 20:18:54 +00004190/// countInheritedIvars - count number of ivars in class and its super class(s)
4191///
4192static int countInheritedIvars(const ObjCInterfaceDecl *OI,
4193 ASTContext &Context) {
4194 int count = 0;
4195 if (!OI)
4196 return 0;
4197 const ObjCInterfaceDecl *SuperClass = OI->getSuperClass();
4198 if (SuperClass)
4199 count += countInheritedIvars(SuperClass, Context);
4200 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
4201 E = OI->ivar_end(); I != E; ++I)
4202 ++count;
4203 // look into properties.
4204 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(Context),
4205 E = OI->prop_end(Context); I != E; ++I) {
4206 if ((*I)->getPropertyIvarDecl())
4207 ++count;
4208 }
4209 return count;
4210}
4211
Daniel Dunbarecb5d402009-04-19 23:41:48 +00004212void CGObjCNonFragileABIMac::GetClassSizeInfo(const ObjCInterfaceDecl *OID,
4213 uint32_t &InstanceStart,
4214 uint32_t &InstanceSize) {
Daniel Dunbarecb5d402009-04-19 23:41:48 +00004215 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID);
4216
Daniel Dunbarde585722009-04-20 07:18:49 +00004217 int countSuperClassIvars = countInheritedIvars(OID->getSuperClass(),
4218 CGM.getContext());
4219 const RecordDecl *RD = CGM.getContext().addRecordToClass(OID);
4220 RecordDecl::field_iterator firstField = RD->field_begin(CGM.getContext());
4221 RecordDecl::field_iterator lastField = RD->field_end(CGM.getContext());
4222 while (countSuperClassIvars-- > 0) {
4223 lastField = firstField;
4224 ++firstField;
4225 }
Daniel Dunbarecb5d402009-04-19 23:41:48 +00004226
4227 for (RecordDecl::field_iterator e = RD->field_end(CGM.getContext()),
4228 ifield = firstField; ifield != e; ++ifield)
4229 lastField = ifield;
4230
4231 InstanceStart = InstanceSize = 0;
4232 if (lastField != RD->field_end(CGM.getContext())) {
4233 FieldDecl *Field = *lastField;
4234 const llvm::Type *FieldTy =
4235 CGM.getTypes().ConvertTypeForMem(Field->getType());
4236 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
4237 InstanceSize = GetIvarBaseOffset(Layout, Field) + Size;
4238 if (firstField == RD->field_end(CGM.getContext()))
4239 InstanceStart = InstanceSize;
4240 else {
4241 Field = *firstField;
4242 InstanceStart = GetIvarBaseOffset(Layout, Field);
4243 }
4244 }
4245}
4246
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00004247void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) {
4248 std::string ClassName = ID->getNameAsString();
4249 if (!ObjCEmptyCacheVar) {
4250 ObjCEmptyCacheVar = new llvm::GlobalVariable(
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00004251 ObjCTypes.CacheTy,
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00004252 false,
4253 llvm::GlobalValue::ExternalLinkage,
4254 0,
Daniel Dunbara2d275d2009-04-07 05:48:37 +00004255 "_objc_empty_cache",
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00004256 &CGM.getModule());
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00004257
4258 ObjCEmptyVtableVar = new llvm::GlobalVariable(
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00004259 ObjCTypes.ImpnfABITy,
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00004260 false,
4261 llvm::GlobalValue::ExternalLinkage,
4262 0,
Daniel Dunbara2d275d2009-04-07 05:48:37 +00004263 "_objc_empty_vtable",
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00004264 &CGM.getModule());
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00004265 }
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00004266 assert(ID->getClassInterface() &&
4267 "CGObjCNonFragileABIMac::GenerateClass - class is 0");
Daniel Dunbar72878722009-04-20 20:18:54 +00004268 // FIXME: Is this correct (that meta class size is never computed)?
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004269 uint32_t InstanceStart =
4270 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassnfABITy);
4271 uint32_t InstanceSize = InstanceStart;
4272 uint32_t flags = CLS_META;
Daniel Dunbara2d275d2009-04-07 05:48:37 +00004273 std::string ObjCMetaClassName(getMetaclassSymbolPrefix());
4274 std::string ObjCClassName(getClassSymbolPrefix());
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00004275
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004276 llvm::GlobalVariable *SuperClassGV, *IsAGV;
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00004277
Daniel Dunbar8394fda2009-04-14 06:00:08 +00004278 bool classIsHidden =
4279 CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden;
Fariborz Jahanian51dcacb2009-01-31 00:59:10 +00004280 if (classIsHidden)
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00004281 flags |= OBJC2_CLS_HIDDEN;
4282 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004283 // class is root
4284 flags |= CLS_ROOT;
Daniel Dunbarabbda222009-03-01 04:40:10 +00004285 SuperClassGV = GetClassGlobal(ObjCClassName + ClassName);
Fariborz Jahanianab438842009-04-14 18:41:56 +00004286 IsAGV = GetClassGlobal(ObjCMetaClassName + ClassName);
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004287 } else {
Fariborz Jahanian06726462009-01-24 21:21:53 +00004288 // Has a root. Current class is not a root.
Fariborz Jahanian514c63b2009-02-26 18:23:47 +00004289 const ObjCInterfaceDecl *Root = ID->getClassInterface();
4290 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
4291 Root = Super;
Fariborz Jahanianab438842009-04-14 18:41:56 +00004292 IsAGV = GetClassGlobal(ObjCMetaClassName + Root->getNameAsString());
Fariborz Jahanian514c63b2009-02-26 18:23:47 +00004293 // work on super class metadata symbol.
4294 std::string SuperClassName =
4295 ObjCMetaClassName + ID->getClassInterface()->getSuperClass()->getNameAsString();
Fariborz Jahanianab438842009-04-14 18:41:56 +00004296 SuperClassGV = GetClassGlobal(SuperClassName);
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004297 }
4298 llvm::GlobalVariable *CLASS_RO_GV = BuildClassRoTInitializer(flags,
4299 InstanceStart,
4300 InstanceSize,ID);
Fariborz Jahanian06726462009-01-24 21:21:53 +00004301 std::string TClassName = ObjCMetaClassName + ClassName;
4302 llvm::GlobalVariable *MetaTClass =
Fariborz Jahanian51dcacb2009-01-31 00:59:10 +00004303 BuildClassMetaData(TClassName, IsAGV, SuperClassGV, CLASS_RO_GV,
4304 classIsHidden);
Daniel Dunbara2d275d2009-04-07 05:48:37 +00004305
Fariborz Jahanian06726462009-01-24 21:21:53 +00004306 // Metadata for the class
4307 flags = CLS;
Fariborz Jahanian51dcacb2009-01-31 00:59:10 +00004308 if (classIsHidden)
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00004309 flags |= OBJC2_CLS_HIDDEN;
Daniel Dunbarc2129532009-04-08 04:21:03 +00004310
4311 if (hasObjCExceptionAttribute(ID->getClassInterface()))
4312 flags |= CLS_EXCEPTION;
4313
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00004314 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian06726462009-01-24 21:21:53 +00004315 flags |= CLS_ROOT;
4316 SuperClassGV = 0;
Chris Lattner9fe470d2009-04-19 06:02:28 +00004317 } else {
Fariborz Jahanian06726462009-01-24 21:21:53 +00004318 // Has a root. Current class is not a root.
Fariborz Jahanian514c63b2009-02-26 18:23:47 +00004319 std::string RootClassName =
Fariborz Jahanian06726462009-01-24 21:21:53 +00004320 ID->getClassInterface()->getSuperClass()->getNameAsString();
Daniel Dunbarabbda222009-03-01 04:40:10 +00004321 SuperClassGV = GetClassGlobal(ObjCClassName + RootClassName);
Fariborz Jahanian06726462009-01-24 21:21:53 +00004322 }
Daniel Dunbarecb5d402009-04-19 23:41:48 +00004323 GetClassSizeInfo(ID->getClassInterface(), InstanceStart, InstanceSize);
Fariborz Jahanian06726462009-01-24 21:21:53 +00004324 CLASS_RO_GV = BuildClassRoTInitializer(flags,
Fariborz Jahanianddd2fdd2009-01-24 23:43:01 +00004325 InstanceStart,
4326 InstanceSize,
4327 ID);
Fariborz Jahanian06726462009-01-24 21:21:53 +00004328
4329 TClassName = ObjCClassName + ClassName;
Fariborz Jahanian11c93dd2009-01-30 20:55:31 +00004330 llvm::GlobalVariable *ClassMD =
Fariborz Jahanian51dcacb2009-01-31 00:59:10 +00004331 BuildClassMetaData(TClassName, MetaTClass, SuperClassGV, CLASS_RO_GV,
4332 classIsHidden);
Fariborz Jahanian11c93dd2009-01-30 20:55:31 +00004333 DefinedClasses.push_back(ClassMD);
Daniel Dunbarc2129532009-04-08 04:21:03 +00004334
4335 // Force the definition of the EHType if necessary.
4336 if (flags & CLS_EXCEPTION)
4337 GetInterfaceEHType(ID->getClassInterface(), true);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00004338}
4339
Fariborz Jahanian5d13ab12009-01-30 18:58:59 +00004340/// GenerateProtocolRef - This routine is called to generate code for
4341/// a protocol reference expression; as in:
4342/// @code
4343/// @protocol(Proto1);
4344/// @endcode
4345/// It generates a weak reference to l_OBJC_PROTOCOL_REFERENCE_$_Proto1
4346/// which will hold address of the protocol meta-data.
4347///
4348llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CGBuilderTy &Builder,
4349 const ObjCProtocolDecl *PD) {
4350
Fariborz Jahaniand3243322009-04-10 18:47:34 +00004351 // This routine is called for @protocol only. So, we must build definition
4352 // of protocol's meta-data (not a reference to it!)
4353 //
4354 llvm::Constant *Init = llvm::ConstantExpr::getBitCast(GetOrEmitProtocol(PD),
Fariborz Jahanian5d13ab12009-01-30 18:58:59 +00004355 ObjCTypes.ExternalProtocolPtrTy);
4356
4357 std::string ProtocolName("\01l_OBJC_PROTOCOL_REFERENCE_$_");
4358 ProtocolName += PD->getNameAsCString();
4359
4360 llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName);
4361 if (PTGV)
4362 return Builder.CreateLoad(PTGV, false, "tmp");
4363 PTGV = new llvm::GlobalVariable(
4364 Init->getType(), false,
Mike Stump36dbf222009-03-07 16:33:28 +00004365 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian5d13ab12009-01-30 18:58:59 +00004366 Init,
4367 ProtocolName,
4368 &CGM.getModule());
4369 PTGV->setSection("__DATA, __objc_protorefs, coalesced, no_dead_strip");
4370 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4371 UsedGlobals.push_back(PTGV);
4372 return Builder.CreateLoad(PTGV, false, "tmp");
4373}
4374
Fariborz Jahanianfe49a092009-01-26 18:32:24 +00004375/// GenerateCategory - Build metadata for a category implementation.
4376/// struct _category_t {
4377/// const char * const name;
4378/// struct _class_t *const cls;
4379/// const struct _method_list_t * const instance_methods;
4380/// const struct _method_list_t * const class_methods;
4381/// const struct _protocol_list_t * const protocols;
4382/// const struct _prop_list_t * const properties;
4383/// }
4384///
4385void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD)
4386{
4387 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Fariborz Jahanianc98c87b2009-01-26 22:58:07 +00004388 const char *Prefix = "\01l_OBJC_$_CATEGORY_";
4389 std::string ExtCatName(Prefix + Interface->getNameAsString()+
Fariborz Jahanianfe49a092009-01-26 18:32:24 +00004390 "_$_" + OCD->getNameAsString());
Daniel Dunbara2d275d2009-04-07 05:48:37 +00004391 std::string ExtClassName(getClassSymbolPrefix() +
4392 Interface->getNameAsString());
Fariborz Jahanianfe49a092009-01-26 18:32:24 +00004393
4394 std::vector<llvm::Constant*> Values(6);
4395 Values[0] = GetClassName(OCD->getIdentifier());
4396 // meta-class entry symbol
Daniel Dunbarabbda222009-03-01 04:40:10 +00004397 llvm::GlobalVariable *ClassGV = GetClassGlobal(ExtClassName);
Fariborz Jahanianfe49a092009-01-26 18:32:24 +00004398 Values[1] = ClassGV;
Fariborz Jahanianc98c87b2009-01-26 22:58:07 +00004399 std::vector<llvm::Constant*> Methods;
4400 std::string MethodListName(Prefix);
4401 MethodListName += "INSTANCE_METHODS_" + Interface->getNameAsString() +
4402 "_$_" + OCD->getNameAsString();
4403
4404 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
4405 e = OCD->instmeth_end(); i != e; ++i) {
4406 // Instance methods should always be defined.
4407 Methods.push_back(GetMethodConstant(*i));
4408 }
4409
4410 Values[2] = EmitMethodList(MethodListName,
Fariborz Jahanian3175ddd2009-01-28 01:05:23 +00004411 "__DATA, __objc_const",
Fariborz Jahanianc98c87b2009-01-26 22:58:07 +00004412 Methods);
4413
4414 MethodListName = Prefix;
4415 MethodListName += "CLASS_METHODS_" + Interface->getNameAsString() + "_$_" +
4416 OCD->getNameAsString();
4417 Methods.clear();
4418 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
4419 e = OCD->classmeth_end(); i != e; ++i) {
4420 // Class methods should always be defined.
4421 Methods.push_back(GetMethodConstant(*i));
4422 }
4423
4424 Values[3] = EmitMethodList(MethodListName,
Fariborz Jahanian3175ddd2009-01-28 01:05:23 +00004425 "__DATA, __objc_const",
Fariborz Jahanianc98c87b2009-01-26 22:58:07 +00004426 Methods);
Fariborz Jahanian7b709bb2009-01-28 22:18:42 +00004427 const ObjCCategoryDecl *Category =
4428 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Fariborz Jahanian8c7904b2009-02-13 17:52:22 +00004429 if (Category) {
4430 std::string ExtName(Interface->getNameAsString() + "_$_" +
4431 OCD->getNameAsString());
4432 Values[4] = EmitProtocolList("\01l_OBJC_CATEGORY_PROTOCOLS_$_"
4433 + Interface->getNameAsString() + "_$_"
4434 + Category->getNameAsString(),
4435 Category->protocol_begin(),
4436 Category->protocol_end());
4437 Values[5] =
4438 EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
4439 OCD, Category, ObjCTypes);
4440 }
4441 else {
4442 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4443 Values[5] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4444 }
4445
Fariborz Jahanianfe49a092009-01-26 18:32:24 +00004446 llvm::Constant *Init =
4447 llvm::ConstantStruct::get(ObjCTypes.CategorynfABITy,
4448 Values);
4449 llvm::GlobalVariable *GCATV
4450 = new llvm::GlobalVariable(ObjCTypes.CategorynfABITy,
4451 false,
4452 llvm::GlobalValue::InternalLinkage,
4453 Init,
4454 ExtCatName,
4455 &CGM.getModule());
Fariborz Jahanian2d6ecb22009-01-31 02:43:27 +00004456 GCATV->setAlignment(
4457 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.CategorynfABITy));
Fariborz Jahanian3175ddd2009-01-28 01:05:23 +00004458 GCATV->setSection("__DATA, __objc_const");
Fariborz Jahanianfe49a092009-01-26 18:32:24 +00004459 UsedGlobals.push_back(GCATV);
4460 DefinedCategories.push_back(GCATV);
4461}
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00004462
4463/// GetMethodConstant - Return a struct objc_method constant for the
4464/// given method if it has been defined. The result is null if the
4465/// method has not been defined. The return value has type MethodPtrTy.
4466llvm::Constant *CGObjCNonFragileABIMac::GetMethodConstant(
4467 const ObjCMethodDecl *MD) {
4468 // FIXME: Use DenseMap::lookup
4469 llvm::Function *Fn = MethodDefinitions[MD];
4470 if (!Fn)
4471 return 0;
4472
4473 std::vector<llvm::Constant*> Method(3);
4474 Method[0] =
4475 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4476 ObjCTypes.SelectorPtrTy);
4477 Method[1] = GetMethodVarType(MD);
4478 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
4479 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
4480}
4481
4482/// EmitMethodList - Build meta-data for method declarations
4483/// struct _method_list_t {
4484/// uint32_t entsize; // sizeof(struct _objc_method)
4485/// uint32_t method_count;
4486/// struct _objc_method method_list[method_count];
4487/// }
4488///
4489llvm::Constant *CGObjCNonFragileABIMac::EmitMethodList(
4490 const std::string &Name,
4491 const char *Section,
4492 const ConstantVector &Methods) {
4493 // Return null for empty list.
4494 if (Methods.empty())
4495 return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy);
4496
4497 std::vector<llvm::Constant*> Values(3);
4498 // sizeof(struct _objc_method)
4499 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.MethodTy);
4500 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4501 // method_count
4502 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
4503 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
4504 Methods.size());
4505 Values[2] = llvm::ConstantArray::get(AT, Methods);
4506 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4507
4508 llvm::GlobalVariable *GV =
4509 new llvm::GlobalVariable(Init->getType(), false,
4510 llvm::GlobalValue::InternalLinkage,
4511 Init,
4512 Name,
4513 &CGM.getModule());
Fariborz Jahanian2d6ecb22009-01-31 02:43:27 +00004514 GV->setAlignment(
4515 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00004516 GV->setSection(Section);
4517 UsedGlobals.push_back(GV);
4518 return llvm::ConstantExpr::getBitCast(GV,
4519 ObjCTypes.MethodListnfABIPtrTy);
4520}
Fariborz Jahanian3f1cc562009-01-27 19:38:51 +00004521
Fariborz Jahaniancc00f922009-02-10 20:21:06 +00004522/// ObjCIvarOffsetVariable - Returns the ivar offset variable for
4523/// the given ivar.
4524///
4525llvm::GlobalVariable * CGObjCNonFragileABIMac::ObjCIvarOffsetVariable(
Fariborz Jahaniana09a5142009-02-12 18:51:23 +00004526 const ObjCInterfaceDecl *ID,
Fariborz Jahaniancc00f922009-02-10 20:21:06 +00004527 const ObjCIvarDecl *Ivar) {
Daniel Dunbar07d204a2009-04-19 00:31:15 +00004528 std::string Name = "OBJC_IVAR_$_" +
Douglas Gregorc55b0b02009-04-09 21:40:53 +00004529 getInterfaceDeclForIvar(ID, Ivar, CGM.getContext())->getNameAsString() +
4530 '.' + Ivar->getNameAsString();
Fariborz Jahaniancc00f922009-02-10 20:21:06 +00004531 llvm::GlobalVariable *IvarOffsetGV =
4532 CGM.getModule().getGlobalVariable(Name);
4533 if (!IvarOffsetGV)
4534 IvarOffsetGV =
4535 new llvm::GlobalVariable(ObjCTypes.LongTy,
4536 false,
4537 llvm::GlobalValue::ExternalLinkage,
4538 0,
4539 Name,
4540 &CGM.getModule());
4541 return IvarOffsetGV;
4542}
4543
Fariborz Jahanian3175ddd2009-01-28 01:05:23 +00004544llvm::Constant * CGObjCNonFragileABIMac::EmitIvarOffsetVar(
Fariborz Jahaniancc00f922009-02-10 20:21:06 +00004545 const ObjCInterfaceDecl *ID,
Fariborz Jahanian150f7732009-01-28 01:36:42 +00004546 const ObjCIvarDecl *Ivar,
Fariborz Jahanian3175ddd2009-01-28 01:05:23 +00004547 unsigned long int Offset) {
Daniel Dunbar0438ff42009-04-19 00:44:02 +00004548 llvm::GlobalVariable *IvarOffsetGV = ObjCIvarOffsetVariable(ID, Ivar);
4549 IvarOffsetGV->setInitializer(llvm::ConstantInt::get(ObjCTypes.LongTy,
4550 Offset));
Fariborz Jahanian2d6ecb22009-01-31 02:43:27 +00004551 IvarOffsetGV->setAlignment(
Fariborz Jahanian55343922009-02-03 00:09:52 +00004552 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.LongTy));
Daniel Dunbar0438ff42009-04-19 00:44:02 +00004553
4554 // FIXME: This matches gcc, but shouldn't the visibility be set on
4555 // the use as well (i.e., in ObjCIvarOffsetVariable).
4556 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
4557 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
4558 CGM.getDeclVisibilityMode(ID) == LangOptions::Hidden)
Fariborz Jahanian150f7732009-01-28 01:36:42 +00004559 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar8394fda2009-04-14 06:00:08 +00004560 else
Fariborz Jahanian745fd892009-04-06 18:30:00 +00004561 IvarOffsetGV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Fariborz Jahanian3175ddd2009-01-28 01:05:23 +00004562 IvarOffsetGV->setSection("__DATA, __objc_const");
Fariborz Jahanian55343922009-02-03 00:09:52 +00004563 return IvarOffsetGV;
Fariborz Jahanian3175ddd2009-01-28 01:05:23 +00004564}
4565
Fariborz Jahanian3f1cc562009-01-27 19:38:51 +00004566/// EmitIvarList - Emit the ivar list for the given
Daniel Dunbar3c190812009-04-18 08:51:00 +00004567/// implementation. The return value has type
Fariborz Jahanian3f1cc562009-01-27 19:38:51 +00004568/// IvarListnfABIPtrTy.
4569/// struct _ivar_t {
4570/// unsigned long int *offset; // pointer to ivar offset location
4571/// char *name;
4572/// char *type;
4573/// uint32_t alignment;
4574/// uint32_t size;
4575/// }
4576/// struct _ivar_list_t {
4577/// uint32 entsize; // sizeof(struct _ivar_t)
4578/// uint32 count;
4579/// struct _iver_t list[count];
4580/// }
4581///
Daniel Dunbar356f0742009-04-20 06:54:31 +00004582
4583void CGObjCCommonMac::GetNamedIvarList(const ObjCInterfaceDecl *OID,
4584 llvm::SmallVector<ObjCIvarDecl*, 16> &Res) const {
4585 for (ObjCInterfaceDecl::ivar_iterator I = OID->ivar_begin(),
4586 E = OID->ivar_end(); I != E; ++I) {
4587 // Ignore unnamed bit-fields.
4588 if (!(*I)->getDeclName())
4589 continue;
4590
4591 Res.push_back(*I);
4592 }
4593
4594 for (ObjCInterfaceDecl::prop_iterator I = OID->prop_begin(CGM.getContext()),
4595 E = OID->prop_end(CGM.getContext()); I != E; ++I)
4596 if (ObjCIvarDecl *IV = (*I)->getPropertyIvarDecl())
4597 Res.push_back(IV);
4598}
4599
Fariborz Jahanian3f1cc562009-01-27 19:38:51 +00004600llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList(
4601 const ObjCImplementationDecl *ID) {
4602
4603 std::vector<llvm::Constant*> Ivars, Ivar(5);
4604
4605 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4606 assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface");
4607
Fariborz Jahanian3175ddd2009-01-28 01:05:23 +00004608 // FIXME. Consolidate this with similar code in GenerateClass.
Fariborz Jahanian6d49ab62009-03-11 21:42:00 +00004609 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID);
Fariborz Jahanianf2a94cd2009-01-28 19:12:34 +00004610
Daniel Dunbar1748ac32009-04-20 00:33:43 +00004611 // Collect declared and synthesized ivars in a small vector.
Fariborz Jahanianfbf44642009-03-31 18:11:23 +00004612 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
Daniel Dunbar356f0742009-04-20 06:54:31 +00004613 GetNamedIvarList(OID, OIvars);
Fariborz Jahanian84c45692009-04-01 19:37:34 +00004614
Daniel Dunbar356f0742009-04-20 06:54:31 +00004615 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
4616 ObjCIvarDecl *IVD = OIvars[i];
4617 const FieldDecl *Field = OID->lookupFieldDeclForIvar(CGM.getContext(), IVD);
Daniel Dunbard73f5f22009-04-20 05:53:40 +00004618 Ivar[0] = EmitIvarOffsetVar(ID->getClassInterface(), IVD,
Daniel Dunbar1cfb5192009-04-19 02:03:42 +00004619 GetIvarBaseOffset(Layout, Field));
Daniel Dunbard73f5f22009-04-20 05:53:40 +00004620 Ivar[1] = GetMethodVarName(Field->getIdentifier());
Devang Patel593a07a2009-03-04 18:21:39 +00004621 Ivar[2] = GetMethodVarType(Field);
Fariborz Jahanian3f1cc562009-01-27 19:38:51 +00004622 const llvm::Type *FieldTy =
4623 CGM.getTypes().ConvertTypeForMem(Field->getType());
4624 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
4625 unsigned Align = CGM.getContext().getPreferredTypeAlign(
4626 Field->getType().getTypePtr()) >> 3;
4627 Align = llvm::Log2_32(Align);
4628 Ivar[3] = llvm::ConstantInt::get(ObjCTypes.IntTy, Align);
Daniel Dunbar1748ac32009-04-20 00:33:43 +00004629 // NOTE. Size of a bitfield does not match gcc's, because of the
4630 // way bitfields are treated special in each. But I am told that
4631 // 'size' for bitfield ivars is ignored by the runtime so it does
4632 // not matter. If it matters, there is enough info to get the
4633 // bitfield right!
Fariborz Jahanian3f1cc562009-01-27 19:38:51 +00004634 Ivar[4] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4635 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarnfABITy, Ivar));
4636 }
4637 // Return null for empty list.
4638 if (Ivars.empty())
4639 return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4640 std::vector<llvm::Constant*> Values(3);
4641 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.IvarnfABITy);
4642 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4643 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
4644 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarnfABITy,
4645 Ivars.size());
4646 Values[2] = llvm::ConstantArray::get(AT, Ivars);
4647 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4648 const char *Prefix = "\01l_OBJC_$_INSTANCE_VARIABLES_";
4649 llvm::GlobalVariable *GV =
4650 new llvm::GlobalVariable(Init->getType(), false,
4651 llvm::GlobalValue::InternalLinkage,
4652 Init,
4653 Prefix + OID->getNameAsString(),
4654 &CGM.getModule());
Fariborz Jahanian2d6ecb22009-01-31 02:43:27 +00004655 GV->setAlignment(
4656 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian3175ddd2009-01-28 01:05:23 +00004657 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian3f1cc562009-01-27 19:38:51 +00004658
4659 UsedGlobals.push_back(GV);
4660 return llvm::ConstantExpr::getBitCast(GV,
4661 ObjCTypes.IvarListnfABIPtrTy);
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004662}
4663
4664llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef(
4665 const ObjCProtocolDecl *PD) {
4666 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4667
4668 if (!Entry) {
4669 // We use the initializer as a marker of whether this is a forward
4670 // reference or not. At module finalization we add the empty
4671 // contents for protocols which were referenced but never defined.
4672 Entry =
4673 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
4674 llvm::GlobalValue::ExternalLinkage,
4675 0,
4676 "\01l_OBJC_PROTOCOL_$_" + PD->getNameAsString(),
4677 &CGM.getModule());
4678 Entry->setSection("__DATA,__datacoal_nt,coalesced");
4679 UsedGlobals.push_back(Entry);
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004680 }
4681
4682 return Entry;
4683}
4684
4685/// GetOrEmitProtocol - Generate the protocol meta-data:
4686/// @code
4687/// struct _protocol_t {
4688/// id isa; // NULL
4689/// const char * const protocol_name;
4690/// const struct _protocol_list_t * protocol_list; // super protocols
4691/// const struct method_list_t * const instance_methods;
4692/// const struct method_list_t * const class_methods;
4693/// const struct method_list_t *optionalInstanceMethods;
4694/// const struct method_list_t *optionalClassMethods;
4695/// const struct _prop_list_t * properties;
4696/// const uint32_t size; // sizeof(struct _protocol_t)
4697/// const uint32_t flags; // = 0
4698/// }
4699/// @endcode
4700///
4701
4702llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol(
4703 const ObjCProtocolDecl *PD) {
4704 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4705
4706 // Early exit if a defining object has already been generated.
4707 if (Entry && Entry->hasInitializer())
4708 return Entry;
4709
4710 const char *ProtocolName = PD->getNameAsCString();
4711
4712 // Construct method lists.
4713 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
4714 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00004715 for (ObjCProtocolDecl::instmeth_iterator
4716 i = PD->instmeth_begin(CGM.getContext()),
4717 e = PD->instmeth_end(CGM.getContext());
4718 i != e; ++i) {
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004719 ObjCMethodDecl *MD = *i;
Fariborz Jahanian151747b2009-01-30 00:46:37 +00004720 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004721 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4722 OptInstanceMethods.push_back(C);
4723 } else {
4724 InstanceMethods.push_back(C);
4725 }
4726 }
4727
Douglas Gregorc55b0b02009-04-09 21:40:53 +00004728 for (ObjCProtocolDecl::classmeth_iterator
4729 i = PD->classmeth_begin(CGM.getContext()),
4730 e = PD->classmeth_end(CGM.getContext());
4731 i != e; ++i) {
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004732 ObjCMethodDecl *MD = *i;
Fariborz Jahanian151747b2009-01-30 00:46:37 +00004733 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004734 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4735 OptClassMethods.push_back(C);
4736 } else {
4737 ClassMethods.push_back(C);
4738 }
4739 }
4740
4741 std::vector<llvm::Constant*> Values(10);
4742 // isa is NULL
4743 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ObjectPtrTy);
4744 Values[1] = GetClassName(PD->getIdentifier());
4745 Values[2] = EmitProtocolList(
4746 "\01l_OBJC_$_PROTOCOL_REFS_" + PD->getNameAsString(),
4747 PD->protocol_begin(),
4748 PD->protocol_end());
4749
Fariborz Jahanian151747b2009-01-30 00:46:37 +00004750 Values[3] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_"
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004751 + PD->getNameAsString(),
4752 "__DATA, __objc_const",
4753 InstanceMethods);
Fariborz Jahanian151747b2009-01-30 00:46:37 +00004754 Values[4] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_"
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004755 + PD->getNameAsString(),
4756 "__DATA, __objc_const",
4757 ClassMethods);
Fariborz Jahanian151747b2009-01-30 00:46:37 +00004758 Values[5] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_"
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004759 + PD->getNameAsString(),
4760 "__DATA, __objc_const",
4761 OptInstanceMethods);
Fariborz Jahanian151747b2009-01-30 00:46:37 +00004762 Values[6] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_"
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004763 + PD->getNameAsString(),
4764 "__DATA, __objc_const",
4765 OptClassMethods);
4766 Values[7] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + PD->getNameAsString(),
4767 0, PD, ObjCTypes);
4768 uint32_t Size =
4769 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolnfABITy);
4770 Values[8] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4771 Values[9] = llvm::Constant::getNullValue(ObjCTypes.IntTy);
4772 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolnfABITy,
4773 Values);
4774
4775 if (Entry) {
4776 // Already created, fix the linkage and update the initializer.
Mike Stump36dbf222009-03-07 16:33:28 +00004777 Entry->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004778 Entry->setInitializer(Init);
4779 } else {
4780 Entry =
4781 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
Mike Stump36dbf222009-03-07 16:33:28 +00004782 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004783 Init,
4784 std::string("\01l_OBJC_PROTOCOL_$_")+ProtocolName,
4785 &CGM.getModule());
Fariborz Jahanian2d6ecb22009-01-31 02:43:27 +00004786 Entry->setAlignment(
4787 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABITy));
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004788 Entry->setSection("__DATA,__datacoal_nt,coalesced");
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004789 }
Fariborz Jahanianfd02a662009-01-29 20:10:59 +00004790 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
4791
4792 // Use this protocol meta-data to build protocol list table in section
4793 // __DATA, __objc_protolist
Fariborz Jahanianfd02a662009-01-29 20:10:59 +00004794 llvm::GlobalVariable *PTGV = new llvm::GlobalVariable(
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00004795 ObjCTypes.ProtocolnfABIPtrTy, false,
Mike Stump36dbf222009-03-07 16:33:28 +00004796 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanianfd02a662009-01-29 20:10:59 +00004797 Entry,
4798 std::string("\01l_OBJC_LABEL_PROTOCOL_$_")
4799 +ProtocolName,
4800 &CGM.getModule());
Fariborz Jahanian2d6ecb22009-01-31 02:43:27 +00004801 PTGV->setAlignment(
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00004802 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABIPtrTy));
Daniel Dunbar9dfd3a72009-04-15 02:56:18 +00004803 PTGV->setSection("__DATA, __objc_protolist, coalesced, no_dead_strip");
Fariborz Jahanianfd02a662009-01-29 20:10:59 +00004804 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4805 UsedGlobals.push_back(PTGV);
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004806 return Entry;
4807}
4808
4809/// EmitProtocolList - Generate protocol list meta-data:
4810/// @code
4811/// struct _protocol_list_t {
4812/// long protocol_count; // Note, this is 32/64 bit
4813/// struct _protocol_t[protocol_count];
4814/// }
4815/// @endcode
4816///
4817llvm::Constant *
4818CGObjCNonFragileABIMac::EmitProtocolList(const std::string &Name,
4819 ObjCProtocolDecl::protocol_iterator begin,
4820 ObjCProtocolDecl::protocol_iterator end) {
4821 std::vector<llvm::Constant*> ProtocolRefs;
4822
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004823 // Just return null for empty protocol lists
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00004824 if (begin == end)
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004825 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4826
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00004827 // FIXME: We shouldn't need to do this lookup here, should we?
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004828 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
4829 if (GV)
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00004830 return llvm::ConstantExpr::getBitCast(GV,
4831 ObjCTypes.ProtocolListnfABIPtrTy);
4832
4833 for (; begin != end; ++begin)
4834 ProtocolRefs.push_back(GetProtocolRef(*begin)); // Implemented???
4835
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004836 // This list is null terminated.
4837 ProtocolRefs.push_back(llvm::Constant::getNullValue(
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00004838 ObjCTypes.ProtocolnfABIPtrTy));
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004839
4840 std::vector<llvm::Constant*> Values(2);
4841 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
4842 Values[1] =
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00004843 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolnfABIPtrTy,
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004844 ProtocolRefs.size()),
4845 ProtocolRefs);
4846
4847 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4848 GV = new llvm::GlobalVariable(Init->getType(), false,
4849 llvm::GlobalValue::InternalLinkage,
4850 Init,
4851 Name,
4852 &CGM.getModule());
4853 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian2d6ecb22009-01-31 02:43:27 +00004854 GV->setAlignment(
4855 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004856 UsedGlobals.push_back(GV);
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00004857 return llvm::ConstantExpr::getBitCast(GV,
4858 ObjCTypes.ProtocolListnfABIPtrTy);
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004859}
4860
Fariborz Jahanian151747b2009-01-30 00:46:37 +00004861/// GetMethodDescriptionConstant - This routine build following meta-data:
4862/// struct _objc_method {
4863/// SEL _cmd;
4864/// char *method_type;
4865/// char *_imp;
4866/// }
4867
4868llvm::Constant *
4869CGObjCNonFragileABIMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
4870 std::vector<llvm::Constant*> Desc(3);
4871 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4872 ObjCTypes.SelectorPtrTy);
4873 Desc[1] = GetMethodVarType(MD);
Fariborz Jahanian5d13ab12009-01-30 18:58:59 +00004874 // Protocol methods have no implementation. So, this entry is always NULL.
Fariborz Jahanian151747b2009-01-30 00:46:37 +00004875 Desc[2] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
4876 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Desc);
4877}
Fariborz Jahanian55343922009-02-03 00:09:52 +00004878
4879/// EmitObjCValueForIvar - Code Gen for nonfragile ivar reference.
4880/// This code gen. amounts to generating code for:
4881/// @code
4882/// (type *)((char *)base + _OBJC_IVAR_$_.ivar;
4883/// @encode
4884///
Fariborz Jahanianc912eb72009-02-03 19:03:09 +00004885LValue CGObjCNonFragileABIMac::EmitObjCValueForIvar(
Fariborz Jahanian55343922009-02-03 00:09:52 +00004886 CodeGen::CodeGenFunction &CGF,
4887 QualType ObjectTy,
4888 llvm::Value *BaseValue,
4889 const ObjCIvarDecl *Ivar,
4890 const FieldDecl *Field,
4891 unsigned CVRQualifiers) {
Daniel Dunbar0ac5bbc2009-04-21 00:41:40 +00004892 assert(Field == ObjectTy->getAsObjCInterfaceType()->getDecl()->lookupFieldDeclForIvar(CGM.getContext(), Ivar));
Fariborz Jahanian55343922009-02-03 00:09:52 +00004893 assert(ObjectTy->isObjCInterfaceType() &&
4894 "CGObjCNonFragileABIMac::EmitObjCValueForIvar");
Fariborz Jahaniana09a5142009-02-12 18:51:23 +00004895 ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
Daniel Dunbar07d204a2009-04-19 00:31:15 +00004896 llvm::GlobalVariable *IvarOffsetGV = ObjCIvarOffsetVariable(ID, Ivar);
Fariborz Jahanianc912eb72009-02-03 19:03:09 +00004897
Fariborz Jahanian55343922009-02-03 00:09:52 +00004898 // (char *) BaseValue
Chris Lattnerbb87be22009-04-17 17:46:19 +00004899 llvm::Value *V = CGF.Builder.CreateBitCast(BaseValue, ObjCTypes.Int8PtrTy);
Fariborz Jahanian55343922009-02-03 00:09:52 +00004900 llvm::Value *Offset = CGF.Builder.CreateLoad(IvarOffsetGV);
4901 // (char*)BaseValue + Offset_symbol
4902 V = CGF.Builder.CreateGEP(V, Offset, "add.ptr");
4903 // (type *)((char*)BaseValue + Offset_symbol)
4904 const llvm::Type *IvarTy =
Chris Lattnerbb87be22009-04-17 17:46:19 +00004905 CGM.getTypes().ConvertTypeForMem(Ivar->getType());
Fariborz Jahanian55343922009-02-03 00:09:52 +00004906 llvm::Type *ptrIvarTy = llvm::PointerType::getUnqual(IvarTy);
4907 V = CGF.Builder.CreateBitCast(V, ptrIvarTy);
Fariborz Jahanianc912eb72009-02-03 19:03:09 +00004908
Fariborz Jahanian40a94a92009-03-09 20:44:22 +00004909 if (Ivar->isBitField()) {
Chris Lattnerbb87be22009-04-17 17:46:19 +00004910 QualType FieldTy = Field->getType();
Fariborz Jahanian40a94a92009-03-09 20:44:22 +00004911 CodeGenTypes::BitFieldInfo bitFieldInfo =
4912 CGM.getTypes().getBitFieldInfo(Field);
4913 return LValue::MakeBitfield(V, bitFieldInfo.Begin, bitFieldInfo.Size,
Chris Lattnerbb87be22009-04-17 17:46:19 +00004914 FieldTy->isSignedIntegerType(),
4915 FieldTy.getCVRQualifiers()|CVRQualifiers);
Fariborz Jahanian40a94a92009-03-09 20:44:22 +00004916 }
4917
Fariborz Jahanianc912eb72009-02-03 19:03:09 +00004918 LValue LV = LValue::MakeAddr(V,
Fariborz Jahanianbbd4ca92009-02-19 23:36:06 +00004919 Ivar->getType().getCVRQualifiers()|CVRQualifiers,
4920 CGM.getContext().getObjCGCAttrKind(Ivar->getType()));
Fariborz Jahanianc912eb72009-02-03 19:03:09 +00004921 LValue::SetObjCIvar(LV, true);
4922 return LV;
Fariborz Jahanian55343922009-02-03 00:09:52 +00004923}
4924
Fariborz Jahanian27cc6662009-02-10 19:02:04 +00004925llvm::Value *CGObjCNonFragileABIMac::EmitIvarOffset(
4926 CodeGen::CodeGenFunction &CGF,
4927 ObjCInterfaceDecl *Interface,
4928 const ObjCIvarDecl *Ivar) {
Daniel Dunbar07d204a2009-04-19 00:31:15 +00004929 return CGF.Builder.CreateLoad(ObjCIvarOffsetVariable(Interface, Ivar),
4930 false, "ivar");
Fariborz Jahanian27cc6662009-02-10 19:02:04 +00004931}
4932
Fariborz Jahanian7e881162009-02-04 00:22:57 +00004933CodeGen::RValue CGObjCNonFragileABIMac::EmitMessageSend(
4934 CodeGen::CodeGenFunction &CGF,
4935 QualType ResultType,
4936 Selector Sel,
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00004937 llvm::Value *Receiver,
Fariborz Jahanian7e881162009-02-04 00:22:57 +00004938 QualType Arg0Ty,
4939 bool IsSuper,
4940 const CallArgList &CallArgs) {
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00004941 // FIXME. Even though IsSuper is passes. This function doese not
4942 // handle calls to 'super' receivers.
4943 CodeGenTypes &Types = CGM.getTypes();
Fariborz Jahanianf3a44012009-02-06 20:09:23 +00004944 llvm::Value *Arg0 = Receiver;
4945 if (!IsSuper)
4946 Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy, "tmp");
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00004947
4948 // Find the message function name.
Fariborz Jahanian10d69ea2009-02-05 01:13:09 +00004949 // FIXME. This is too much work to get the ABI-specific result type
4950 // needed to find the message name.
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00004951 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType,
4952 llvm::SmallVector<QualType, 16>());
4953 llvm::Constant *Fn;
4954 std::string Name("\01l_");
4955 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Fariborz Jahanian13ab25e2009-02-05 18:00:27 +00004956#if 0
4957 // unlike what is documented. gcc never generates this API!!
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00004958 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
4959 Fn = ObjCTypes.MessageSendIdStretFixupFn;
4960 // FIXME. Is there a better way of getting these names.
4961 // They are available in RuntimeFunctions vector pair.
4962 Name += "objc_msgSendId_stret_fixup";
4963 }
Fariborz Jahanian13ab25e2009-02-05 18:00:27 +00004964 else
4965#endif
Fariborz Jahanianf3a44012009-02-06 20:09:23 +00004966 if (IsSuper) {
4967 Fn = ObjCTypes.MessageSendSuper2StretFixupFn;
4968 Name += "objc_msgSendSuper2_stret_fixup";
4969 }
4970 else
Fariborz Jahanian13ab25e2009-02-05 18:00:27 +00004971 {
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00004972 Fn = ObjCTypes.MessageSendStretFixupFn;
4973 Name += "objc_msgSend_stret_fixup";
4974 }
4975 }
Fariborz Jahanianbea03192009-02-05 19:35:43 +00004976 else if (ResultType->isFloatingType() &&
4977 // Selection of frret API only happens in 32bit nonfragile ABI.
4978 CGM.getTargetData().getTypePaddedSize(ObjCTypes.LongTy) == 4) {
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00004979 Fn = ObjCTypes.MessageSendFpretFixupFn;
4980 Name += "objc_msgSend_fpret_fixup";
4981 }
4982 else {
Fariborz Jahanian13ab25e2009-02-05 18:00:27 +00004983#if 0
4984// unlike what is documented. gcc never generates this API!!
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00004985 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
4986 Fn = ObjCTypes.MessageSendIdFixupFn;
4987 Name += "objc_msgSendId_fixup";
4988 }
Fariborz Jahanian13ab25e2009-02-05 18:00:27 +00004989 else
4990#endif
Fariborz Jahanianf3a44012009-02-06 20:09:23 +00004991 if (IsSuper) {
4992 Fn = ObjCTypes.MessageSendSuper2FixupFn;
4993 Name += "objc_msgSendSuper2_fixup";
4994 }
4995 else
Fariborz Jahanian13ab25e2009-02-05 18:00:27 +00004996 {
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00004997 Fn = ObjCTypes.MessageSendFixupFn;
4998 Name += "objc_msgSend_fixup";
4999 }
5000 }
5001 Name += '_';
5002 std::string SelName(Sel.getAsString());
5003 // Replace all ':' in selector name with '_' ouch!
5004 for(unsigned i = 0; i < SelName.size(); i++)
5005 if (SelName[i] == ':')
5006 SelName[i] = '_';
5007 Name += SelName;
5008 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5009 if (!GV) {
Daniel Dunbar4993e292009-04-15 19:03:14 +00005010 // Build message ref table entry.
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00005011 std::vector<llvm::Constant*> Values(2);
5012 Values[0] = Fn;
5013 Values[1] = GetMethodVarName(Sel);
5014 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
5015 GV = new llvm::GlobalVariable(Init->getType(), false,
Mike Stump36dbf222009-03-07 16:33:28 +00005016 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00005017 Init,
5018 Name,
5019 &CGM.getModule());
5020 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbara405f782009-04-15 19:04:46 +00005021 GV->setAlignment(16);
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00005022 GV->setSection("__DATA, __objc_msgrefs, coalesced");
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00005023 }
5024 llvm::Value *Arg1 = CGF.Builder.CreateBitCast(GV, ObjCTypes.MessageRefPtrTy);
Fariborz Jahanian10d69ea2009-02-05 01:13:09 +00005025
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00005026 CallArgList ActualArgs;
5027 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
5028 ActualArgs.push_back(std::make_pair(RValue::get(Arg1),
5029 ObjCTypes.MessageRefCPtrTy));
5030 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Fariborz Jahanian10d69ea2009-02-05 01:13:09 +00005031 const CGFunctionInfo &FnInfo1 = Types.getFunctionInfo(ResultType, ActualArgs);
5032 llvm::Value *Callee = CGF.Builder.CreateStructGEP(Arg1, 0);
5033 Callee = CGF.Builder.CreateLoad(Callee);
Fariborz Jahanianf3c17752009-02-14 21:25:36 +00005034 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo1, true);
Fariborz Jahanian10d69ea2009-02-05 01:13:09 +00005035 Callee = CGF.Builder.CreateBitCast(Callee,
5036 llvm::PointerType::getUnqual(FTy));
5037 return CGF.EmitCall(FnInfo1, Callee, ActualArgs);
Fariborz Jahanian7e881162009-02-04 00:22:57 +00005038}
5039
5040/// Generate code for a message send expression in the nonfragile abi.
5041CodeGen::RValue CGObjCNonFragileABIMac::GenerateMessageSend(
5042 CodeGen::CodeGenFunction &CGF,
5043 QualType ResultType,
5044 Selector Sel,
5045 llvm::Value *Receiver,
5046 bool IsClassMessage,
5047 const CallArgList &CallArgs) {
Fariborz Jahanian7e881162009-02-04 00:22:57 +00005048 return EmitMessageSend(CGF, ResultType, Sel,
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00005049 Receiver, CGF.getContext().getObjCIdType(),
Fariborz Jahanian7e881162009-02-04 00:22:57 +00005050 false, CallArgs);
5051}
5052
Daniel Dunbarabbda222009-03-01 04:40:10 +00005053llvm::GlobalVariable *
Fariborz Jahanianab438842009-04-14 18:41:56 +00005054CGObjCNonFragileABIMac::GetClassGlobal(const std::string &Name) {
Daniel Dunbarabbda222009-03-01 04:40:10 +00005055 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5056
Daniel Dunbar66b47512009-03-02 05:18:14 +00005057 if (!GV) {
Daniel Dunbarabbda222009-03-01 04:40:10 +00005058 GV = new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
5059 llvm::GlobalValue::ExternalLinkage,
5060 0, Name, &CGM.getModule());
Daniel Dunbarabbda222009-03-01 04:40:10 +00005061 }
5062
5063 return GV;
5064}
5065
Fariborz Jahanian917c0402009-02-05 20:41:40 +00005066llvm::Value *CGObjCNonFragileABIMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar3c190812009-04-18 08:51:00 +00005067 const ObjCInterfaceDecl *ID) {
Fariborz Jahanian917c0402009-02-05 20:41:40 +00005068 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
5069
5070 if (!Entry) {
Daniel Dunbara2d275d2009-04-07 05:48:37 +00005071 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbarabbda222009-03-01 04:40:10 +00005072 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
Fariborz Jahanian917c0402009-02-05 20:41:40 +00005073 Entry =
5074 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5075 llvm::GlobalValue::InternalLinkage,
Fariborz Jahanianf3a44012009-02-06 20:09:23 +00005076 ClassGV,
Daniel Dunbar3c190812009-04-18 08:51:00 +00005077 "\01L_OBJC_CLASSLIST_REFERENCES_$_",
Fariborz Jahanian917c0402009-02-05 20:41:40 +00005078 &CGM.getModule());
5079 Entry->setAlignment(
5080 CGM.getTargetData().getPrefTypeAlignment(
5081 ObjCTypes.ClassnfABIPtrTy));
Daniel Dunbar3c190812009-04-18 08:51:00 +00005082 Entry->setSection("__DATA, __objc_classrefs, regular, no_dead_strip");
5083 UsedGlobals.push_back(Entry);
5084 }
5085
5086 return Builder.CreateLoad(Entry, false, "tmp");
5087}
Fariborz Jahanian917c0402009-02-05 20:41:40 +00005088
Daniel Dunbar3c190812009-04-18 08:51:00 +00005089llvm::Value *
5090CGObjCNonFragileABIMac::EmitSuperClassRef(CGBuilderTy &Builder,
5091 const ObjCInterfaceDecl *ID) {
5092 llvm::GlobalVariable *&Entry = SuperClassReferences[ID->getIdentifier()];
5093
5094 if (!Entry) {
5095 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
5096 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
5097 Entry =
5098 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5099 llvm::GlobalValue::InternalLinkage,
5100 ClassGV,
5101 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5102 &CGM.getModule());
5103 Entry->setAlignment(
5104 CGM.getTargetData().getPrefTypeAlignment(
5105 ObjCTypes.ClassnfABIPtrTy));
5106 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanian917c0402009-02-05 20:41:40 +00005107 UsedGlobals.push_back(Entry);
5108 }
5109
5110 return Builder.CreateLoad(Entry, false, "tmp");
5111}
5112
Fariborz Jahanianf3a44012009-02-06 20:09:23 +00005113/// EmitMetaClassRef - Return a Value * of the address of _class_t
5114/// meta-data
5115///
5116llvm::Value *CGObjCNonFragileABIMac::EmitMetaClassRef(CGBuilderTy &Builder,
5117 const ObjCInterfaceDecl *ID) {
5118 llvm::GlobalVariable * &Entry = MetaClassReferences[ID->getIdentifier()];
5119 if (Entry)
5120 return Builder.CreateLoad(Entry, false, "tmp");
5121
Daniel Dunbara2d275d2009-04-07 05:48:37 +00005122 std::string MetaClassName(getMetaclassSymbolPrefix() + ID->getNameAsString());
Fariborz Jahanianab438842009-04-14 18:41:56 +00005123 llvm::GlobalVariable *MetaClassGV = GetClassGlobal(MetaClassName);
Fariborz Jahanianf3a44012009-02-06 20:09:23 +00005124 Entry =
5125 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5126 llvm::GlobalValue::InternalLinkage,
5127 MetaClassGV,
5128 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5129 &CGM.getModule());
5130 Entry->setAlignment(
5131 CGM.getTargetData().getPrefTypeAlignment(
5132 ObjCTypes.ClassnfABIPtrTy));
5133
Daniel Dunbar4993e292009-04-15 19:03:14 +00005134 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanianf3a44012009-02-06 20:09:23 +00005135 UsedGlobals.push_back(Entry);
5136
5137 return Builder.CreateLoad(Entry, false, "tmp");
5138}
5139
Fariborz Jahanian917c0402009-02-05 20:41:40 +00005140/// GetClass - Return a reference to the class for the given interface
5141/// decl.
5142llvm::Value *CGObjCNonFragileABIMac::GetClass(CGBuilderTy &Builder,
5143 const ObjCInterfaceDecl *ID) {
5144 return EmitClassRef(Builder, ID);
5145}
5146
Fariborz Jahanianf3a44012009-02-06 20:09:23 +00005147/// Generates a message send where the super is the receiver. This is
5148/// a message send to self with special delivery semantics indicating
5149/// which class's method should be called.
5150CodeGen::RValue
5151CGObjCNonFragileABIMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
5152 QualType ResultType,
5153 Selector Sel,
5154 const ObjCInterfaceDecl *Class,
Fariborz Jahanian17636fa2009-02-28 20:07:56 +00005155 bool isCategoryImpl,
Fariborz Jahanianf3a44012009-02-06 20:09:23 +00005156 llvm::Value *Receiver,
5157 bool IsClassMessage,
5158 const CodeGen::CallArgList &CallArgs) {
5159 // ...
5160 // Create and init a super structure; this is a (receiver, class)
5161 // pair we will pass to objc_msgSendSuper.
5162 llvm::Value *ObjCSuper =
5163 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
5164
5165 llvm::Value *ReceiverAsObject =
5166 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
5167 CGF.Builder.CreateStore(ReceiverAsObject,
5168 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
5169
5170 // If this is a class message the metaclass is passed as the target.
Fariborz Jahanian17636fa2009-02-28 20:07:56 +00005171 llvm::Value *Target;
5172 if (IsClassMessage) {
5173 if (isCategoryImpl) {
5174 // Message sent to "super' in a class method defined in
5175 // a category implementation.
Daniel Dunbar3c190812009-04-18 08:51:00 +00005176 Target = EmitClassRef(CGF.Builder, Class);
Fariborz Jahanian17636fa2009-02-28 20:07:56 +00005177 Target = CGF.Builder.CreateStructGEP(Target, 0);
5178 Target = CGF.Builder.CreateLoad(Target);
5179 }
5180 else
5181 Target = EmitMetaClassRef(CGF.Builder, Class);
5182 }
5183 else
Daniel Dunbar3c190812009-04-18 08:51:00 +00005184 Target = EmitSuperClassRef(CGF.Builder, Class);
Fariborz Jahanianf3a44012009-02-06 20:09:23 +00005185
5186 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
5187 // and ObjCTypes types.
5188 const llvm::Type *ClassTy =
5189 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
5190 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
5191 CGF.Builder.CreateStore(Target,
5192 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
5193
5194 return EmitMessageSend(CGF, ResultType, Sel,
5195 ObjCSuper, ObjCTypes.SuperPtrCTy,
5196 true, CallArgs);
5197}
Fariborz Jahanianebb82c62009-02-11 20:51:17 +00005198
5199llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CGBuilderTy &Builder,
5200 Selector Sel) {
5201 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
5202
5203 if (!Entry) {
5204 llvm::Constant *Casted =
5205 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
5206 ObjCTypes.SelectorPtrTy);
5207 Entry =
5208 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
5209 llvm::GlobalValue::InternalLinkage,
5210 Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
5211 &CGM.getModule());
5212 Entry->setSection("__DATA,__objc_selrefs,literal_pointers,no_dead_strip");
5213 UsedGlobals.push_back(Entry);
5214 }
5215
5216 return Builder.CreateLoad(Entry, false, "tmp");
5217}
Fariborz Jahanian5eefb432009-02-16 22:52:32 +00005218/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
5219/// objc_assign_ivar (id src, id *dst)
5220///
5221void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
5222 llvm::Value *src, llvm::Value *dst)
5223{
Fariborz Jahanianad51ca02009-03-23 19:10:40 +00005224 const llvm::Type * SrcTy = src->getType();
5225 if (!isa<llvm::PointerType>(SrcTy)) {
5226 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5227 assert(Size <= 8 && "does not support size > 8");
5228 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5229 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian664da982009-03-13 00:42:52 +00005230 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5231 }
Fariborz Jahanian5eefb432009-02-16 22:52:32 +00005232 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5233 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5234 CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn,
5235 src, dst, "assignivar");
5236 return;
5237}
5238
5239/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
5240/// objc_assign_strongCast (id src, id *dst)
5241///
5242void CGObjCNonFragileABIMac::EmitObjCStrongCastAssign(
5243 CodeGen::CodeGenFunction &CGF,
5244 llvm::Value *src, llvm::Value *dst)
5245{
Fariborz Jahanianad51ca02009-03-23 19:10:40 +00005246 const llvm::Type * SrcTy = src->getType();
5247 if (!isa<llvm::PointerType>(SrcTy)) {
5248 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5249 assert(Size <= 8 && "does not support size > 8");
5250 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5251 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian664da982009-03-13 00:42:52 +00005252 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5253 }
Fariborz Jahanian5eefb432009-02-16 22:52:32 +00005254 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5255 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5256 CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn,
5257 src, dst, "weakassign");
5258 return;
5259}
5260
5261/// EmitObjCWeakRead - Code gen for loading value of a __weak
5262/// object: objc_read_weak (id *src)
5263///
5264llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead(
5265 CodeGen::CodeGenFunction &CGF,
5266 llvm::Value *AddrWeakObj)
5267{
Eli Friedmanf8466232009-03-07 03:57:15 +00005268 const llvm::Type* DestTy =
5269 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahanian5eefb432009-02-16 22:52:32 +00005270 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
5271 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
5272 AddrWeakObj, "weakread");
Eli Friedmanf8466232009-03-07 03:57:15 +00005273 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian5eefb432009-02-16 22:52:32 +00005274 return read_weak;
5275}
5276
5277/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
5278/// objc_assign_weak (id src, id *dst)
5279///
5280void CGObjCNonFragileABIMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
5281 llvm::Value *src, llvm::Value *dst)
5282{
Fariborz Jahanianad51ca02009-03-23 19:10:40 +00005283 const llvm::Type * SrcTy = src->getType();
5284 if (!isa<llvm::PointerType>(SrcTy)) {
5285 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5286 assert(Size <= 8 && "does not support size > 8");
5287 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5288 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian664da982009-03-13 00:42:52 +00005289 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5290 }
Fariborz Jahanian5eefb432009-02-16 22:52:32 +00005291 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5292 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattner293c1d32009-04-17 22:12:36 +00005293 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
Fariborz Jahanian5eefb432009-02-16 22:52:32 +00005294 src, dst, "weakassign");
5295 return;
5296}
5297
5298/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
5299/// objc_assign_global (id src, id *dst)
5300///
5301void CGObjCNonFragileABIMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
5302 llvm::Value *src, llvm::Value *dst)
5303{
Fariborz Jahanianad51ca02009-03-23 19:10:40 +00005304 const llvm::Type * SrcTy = src->getType();
5305 if (!isa<llvm::PointerType>(SrcTy)) {
5306 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5307 assert(Size <= 8 && "does not support size > 8");
5308 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5309 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian664da982009-03-13 00:42:52 +00005310 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5311 }
Fariborz Jahanian5eefb432009-02-16 22:52:32 +00005312 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5313 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5314 CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn,
5315 src, dst, "globalassign");
5316 return;
5317}
Fariborz Jahanianebb82c62009-02-11 20:51:17 +00005318
Daniel Dunbar75de89f2009-02-24 07:47:38 +00005319void
5320CGObjCNonFragileABIMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
5321 const Stmt &S) {
Daniel Dunbar75de89f2009-02-24 07:47:38 +00005322 bool isTry = isa<ObjCAtTryStmt>(S);
5323 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
5324 llvm::BasicBlock *PrevLandingPad = CGF.getInvokeDest();
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005325 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar75de89f2009-02-24 07:47:38 +00005326 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005327 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
Daniel Dunbar75de89f2009-02-24 07:47:38 +00005328 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
5329
5330 // For @synchronized, call objc_sync_enter(sync.expr). The
5331 // evaluation of the expression must occur before we enter the
5332 // @synchronized. We can safely avoid a temp here because jumps into
5333 // @synchronized are illegal & this will dominate uses.
5334 llvm::Value *SyncArg = 0;
5335 if (!isTry) {
5336 SyncArg =
5337 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
5338 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattner23e24652009-04-06 16:53:45 +00005339 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar75de89f2009-02-24 07:47:38 +00005340 }
5341
5342 // Push an EH context entry, used for handling rethrows and jumps
5343 // through finally.
5344 CGF.PushCleanupBlock(FinallyBlock);
5345
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005346 CGF.setInvokeDest(TryHandler);
Daniel Dunbar75de89f2009-02-24 07:47:38 +00005347
5348 CGF.EmitBlock(TryBlock);
5349 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
5350 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
5351 CGF.EmitBranchThroughCleanup(FinallyEnd);
5352
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005353 // Emit the exception handler.
5354
5355 CGF.EmitBlock(TryHandler);
5356
5357 llvm::Value *llvm_eh_exception =
5358 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_exception);
5359 llvm::Value *llvm_eh_selector_i64 =
5360 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector_i64);
5361 llvm::Value *llvm_eh_typeid_for_i64 =
5362 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for_i64);
5363 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5364 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(Exc->getType(), "_rethrow");
5365
5366 llvm::SmallVector<llvm::Value*, 8> SelectorArgs;
5367 SelectorArgs.push_back(Exc);
Chris Lattner23e24652009-04-06 16:53:45 +00005368 SelectorArgs.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005369
5370 // Construct the lists of (type, catch body) to handle.
Daniel Dunbar0098e7a2009-03-06 00:01:21 +00005371 llvm::SmallVector<std::pair<const ParmVarDecl*, const Stmt*>, 8> Handlers;
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005372 bool HasCatchAll = false;
5373 if (isTry) {
5374 if (const ObjCAtCatchStmt* CatchStmt =
5375 cast<ObjCAtTryStmt>(S).getCatchStmts()) {
5376 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbar0098e7a2009-03-06 00:01:21 +00005377 const ParmVarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
Steve Naroff0e8b96a2009-03-03 19:52:17 +00005378 Handlers.push_back(std::make_pair(CatchDecl, CatchStmt->getCatchBody()));
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005379
5380 // catch(...) always matches.
Steve Naroff0e8b96a2009-03-03 19:52:17 +00005381 if (!CatchDecl) {
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005382 // Use i8* null here to signal this is a catch all, not a cleanup.
5383 llvm::Value *Null = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
5384 SelectorArgs.push_back(Null);
5385 HasCatchAll = true;
5386 break;
5387 }
5388
Daniel Dunbar0098e7a2009-03-06 00:01:21 +00005389 if (CGF.getContext().isObjCIdType(CatchDecl->getType()) ||
5390 CatchDecl->getType()->isObjCQualifiedIdType()) {
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005391 llvm::Value *IDEHType =
5392 CGM.getModule().getGlobalVariable("OBJC_EHTYPE_id");
5393 if (!IDEHType)
5394 IDEHType =
5395 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5396 llvm::GlobalValue::ExternalLinkage,
5397 0, "OBJC_EHTYPE_id", &CGM.getModule());
5398 SelectorArgs.push_back(IDEHType);
5399 HasCatchAll = true;
5400 break;
5401 }
5402
5403 // All other types should be Objective-C interface pointer types.
Daniel Dunbar0098e7a2009-03-06 00:01:21 +00005404 const PointerType *PT = CatchDecl->getType()->getAsPointerType();
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005405 assert(PT && "Invalid @catch type.");
5406 const ObjCInterfaceType *IT =
5407 PT->getPointeeType()->getAsObjCInterfaceType();
5408 assert(IT && "Invalid @catch type.");
Daniel Dunbarc2129532009-04-08 04:21:03 +00005409 llvm::Value *EHType = GetInterfaceEHType(IT->getDecl(), false);
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005410 SelectorArgs.push_back(EHType);
5411 }
5412 }
5413 }
5414
5415 // We use a cleanup unless there was already a catch all.
5416 if (!HasCatchAll) {
5417 SelectorArgs.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
Daniel Dunbar0098e7a2009-03-06 00:01:21 +00005418 Handlers.push_back(std::make_pair((const ParmVarDecl*) 0, (const Stmt*) 0));
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005419 }
5420
5421 llvm::Value *Selector =
5422 CGF.Builder.CreateCall(llvm_eh_selector_i64,
5423 SelectorArgs.begin(), SelectorArgs.end(),
5424 "selector");
5425 for (unsigned i = 0, e = Handlers.size(); i != e; ++i) {
Daniel Dunbar0098e7a2009-03-06 00:01:21 +00005426 const ParmVarDecl *CatchParam = Handlers[i].first;
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005427 const Stmt *CatchBody = Handlers[i].second;
5428
5429 llvm::BasicBlock *Next = 0;
5430
5431 // The last handler always matches.
5432 if (i + 1 != e) {
5433 assert(CatchParam && "Only last handler can be a catch all.");
5434
5435 llvm::BasicBlock *Match = CGF.createBasicBlock("match");
5436 Next = CGF.createBasicBlock("catch.next");
5437 llvm::Value *Id =
5438 CGF.Builder.CreateCall(llvm_eh_typeid_for_i64,
5439 CGF.Builder.CreateBitCast(SelectorArgs[i+2],
5440 ObjCTypes.Int8PtrTy));
5441 CGF.Builder.CreateCondBr(CGF.Builder.CreateICmpEQ(Selector, Id),
5442 Match, Next);
5443
5444 CGF.EmitBlock(Match);
5445 }
5446
5447 if (CatchBody) {
5448 llvm::BasicBlock *MatchEnd = CGF.createBasicBlock("match.end");
5449 llvm::BasicBlock *MatchHandler = CGF.createBasicBlock("match.handler");
5450
5451 // Cleanups must call objc_end_catch.
5452 //
5453 // FIXME: It seems incorrect for objc_begin_catch to be inside
5454 // this context, but this matches gcc.
5455 CGF.PushCleanupBlock(MatchEnd);
5456 CGF.setInvokeDest(MatchHandler);
5457
5458 llvm::Value *ExcObject =
5459 CGF.Builder.CreateCall(ObjCTypes.ObjCBeginCatchFn, Exc);
5460
5461 // Bind the catch parameter if it exists.
5462 if (CatchParam) {
Daniel Dunbar0098e7a2009-03-06 00:01:21 +00005463 ExcObject =
5464 CGF.Builder.CreateBitCast(ExcObject,
5465 CGF.ConvertType(CatchParam->getType()));
5466 // CatchParam is a ParmVarDecl because of the grammar
5467 // construction used to handle this, but for codegen purposes
5468 // we treat this as a local decl.
5469 CGF.EmitLocalBlockVarDecl(*CatchParam);
5470 CGF.Builder.CreateStore(ExcObject, CGF.GetAddrOfLocalVar(CatchParam));
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005471 }
5472
5473 CGF.ObjCEHValueStack.push_back(ExcObject);
5474 CGF.EmitStmt(CatchBody);
5475 CGF.ObjCEHValueStack.pop_back();
5476
5477 CGF.EmitBranchThroughCleanup(FinallyEnd);
5478
5479 CGF.EmitBlock(MatchHandler);
5480
5481 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5482 // We are required to emit this call to satisfy LLVM, even
5483 // though we don't use the result.
5484 llvm::SmallVector<llvm::Value*, 8> Args;
5485 Args.push_back(Exc);
Chris Lattner23e24652009-04-06 16:53:45 +00005486 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005487 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5488 0));
5489 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5490 CGF.Builder.CreateStore(Exc, RethrowPtr);
5491 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5492
5493 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5494
5495 CGF.EmitBlock(MatchEnd);
5496
5497 // Unfortunately, we also have to generate another EH frame here
5498 // in case this throws.
5499 llvm::BasicBlock *MatchEndHandler =
5500 CGF.createBasicBlock("match.end.handler");
5501 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
5502 CGF.Builder.CreateInvoke(ObjCTypes.ObjCEndCatchFn,
5503 Cont, MatchEndHandler,
5504 Args.begin(), Args.begin());
5505
5506 CGF.EmitBlock(Cont);
5507 if (Info.SwitchBlock)
5508 CGF.EmitBlock(Info.SwitchBlock);
5509 if (Info.EndBlock)
5510 CGF.EmitBlock(Info.EndBlock);
5511
5512 CGF.EmitBlock(MatchEndHandler);
5513 Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5514 // We are required to emit this call to satisfy LLVM, even
5515 // though we don't use the result.
5516 Args.clear();
5517 Args.push_back(Exc);
Chris Lattner23e24652009-04-06 16:53:45 +00005518 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005519 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5520 0));
5521 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5522 CGF.Builder.CreateStore(Exc, RethrowPtr);
5523 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5524
5525 if (Next)
5526 CGF.EmitBlock(Next);
5527 } else {
5528 assert(!Next && "catchup should be last handler.");
5529
5530 CGF.Builder.CreateStore(Exc, RethrowPtr);
5531 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5532 }
5533 }
5534
Daniel Dunbar75de89f2009-02-24 07:47:38 +00005535 // Pop the cleanup entry, the @finally is outside this cleanup
5536 // scope.
5537 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5538 CGF.setInvokeDest(PrevLandingPad);
5539
5540 CGF.EmitBlock(FinallyBlock);
5541
5542 if (isTry) {
5543 if (const ObjCAtFinallyStmt* FinallyStmt =
5544 cast<ObjCAtTryStmt>(S).getFinallyStmt())
5545 CGF.EmitStmt(FinallyStmt->getFinallyBody());
5546 } else {
5547 // Emit 'objc_sync_exit(expr)' as finally's sole statement for
5548 // @synchronized.
5549 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, SyncArg);
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005550 }
Daniel Dunbar75de89f2009-02-24 07:47:38 +00005551
5552 if (Info.SwitchBlock)
5553 CGF.EmitBlock(Info.SwitchBlock);
5554 if (Info.EndBlock)
5555 CGF.EmitBlock(Info.EndBlock);
5556
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005557 // Branch around the rethrow code.
Daniel Dunbar75de89f2009-02-24 07:47:38 +00005558 CGF.EmitBranch(FinallyEnd);
5559
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005560 CGF.EmitBlock(FinallyRethrow);
5561 CGF.Builder.CreateCall(ObjCTypes.UnwindResumeOrRethrowFn,
5562 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbar75de89f2009-02-24 07:47:38 +00005563 CGF.Builder.CreateUnreachable();
5564
5565 CGF.EmitBlock(FinallyEnd);
5566}
5567
Anders Carlsson1cf75362009-02-16 22:59:18 +00005568/// EmitThrowStmt - Generate code for a throw statement.
5569void CGObjCNonFragileABIMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
5570 const ObjCAtThrowStmt &S) {
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005571 llvm::Value *Exception;
Anders Carlsson1cf75362009-02-16 22:59:18 +00005572 if (const Expr *ThrowExpr = S.getThrowExpr()) {
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005573 Exception = CGF.EmitScalarExpr(ThrowExpr);
Anders Carlsson1cf75362009-02-16 22:59:18 +00005574 } else {
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005575 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
5576 "Unexpected rethrow outside @catch block.");
5577 Exception = CGF.ObjCEHValueStack.back();
Anders Carlsson1cf75362009-02-16 22:59:18 +00005578 }
5579
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005580 llvm::Value *ExceptionAsObject =
5581 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
5582 llvm::BasicBlock *InvokeDest = CGF.getInvokeDest();
5583 if (InvokeDest) {
5584 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
5585 CGF.Builder.CreateInvoke(ObjCTypes.ExceptionThrowFn,
5586 Cont, InvokeDest,
5587 &ExceptionAsObject, &ExceptionAsObject + 1);
5588 CGF.EmitBlock(Cont);
5589 } else
5590 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
5591 CGF.Builder.CreateUnreachable();
5592
Anders Carlsson1cf75362009-02-16 22:59:18 +00005593 // Clear the insertion point to indicate we are in unreachable code.
5594 CGF.Builder.ClearInsertionPoint();
5595}
Daniel Dunbar9c285e72009-03-01 04:46:24 +00005596
5597llvm::Value *
Daniel Dunbarc2129532009-04-08 04:21:03 +00005598CGObjCNonFragileABIMac::GetInterfaceEHType(const ObjCInterfaceDecl *ID,
5599 bool ForDefinition) {
Daniel Dunbar9c285e72009-03-01 04:46:24 +00005600 llvm::GlobalVariable * &Entry = EHTypeReferences[ID->getIdentifier()];
Daniel Dunbar9c285e72009-03-01 04:46:24 +00005601
Daniel Dunbarc2129532009-04-08 04:21:03 +00005602 // If we don't need a definition, return the entry if found or check
5603 // if we use an external reference.
5604 if (!ForDefinition) {
5605 if (Entry)
5606 return Entry;
Daniel Dunbarafac9be2009-04-07 06:43:45 +00005607
Daniel Dunbarc2129532009-04-08 04:21:03 +00005608 // If this type (or a super class) has the __objc_exception__
5609 // attribute, emit an external reference.
5610 if (hasObjCExceptionAttribute(ID))
5611 return Entry =
5612 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5613 llvm::GlobalValue::ExternalLinkage,
5614 0,
5615 (std::string("OBJC_EHTYPE_$_") +
5616 ID->getIdentifier()->getName()),
5617 &CGM.getModule());
5618 }
5619
5620 // Otherwise we need to either make a new entry or fill in the
5621 // initializer.
5622 assert((!Entry || !Entry->hasInitializer()) && "Duplicate EHType definition");
Daniel Dunbara2d275d2009-04-07 05:48:37 +00005623 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbar9c285e72009-03-01 04:46:24 +00005624 std::string VTableName = "objc_ehtype_vtable";
5625 llvm::GlobalVariable *VTableGV =
5626 CGM.getModule().getGlobalVariable(VTableName);
5627 if (!VTableGV)
5628 VTableGV = new llvm::GlobalVariable(ObjCTypes.Int8PtrTy, false,
5629 llvm::GlobalValue::ExternalLinkage,
5630 0, VTableName, &CGM.getModule());
5631
5632 llvm::Value *VTableIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, 2);
5633
5634 std::vector<llvm::Constant*> Values(3);
5635 Values[0] = llvm::ConstantExpr::getGetElementPtr(VTableGV, &VTableIdx, 1);
5636 Values[1] = GetClassName(ID->getIdentifier());
Fariborz Jahanianab438842009-04-14 18:41:56 +00005637 Values[2] = GetClassGlobal(ClassName);
Daniel Dunbar9c285e72009-03-01 04:46:24 +00005638 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.EHTypeTy, Values);
5639
Daniel Dunbarc2129532009-04-08 04:21:03 +00005640 if (Entry) {
5641 Entry->setInitializer(Init);
5642 } else {
5643 Entry = new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5644 llvm::GlobalValue::WeakAnyLinkage,
5645 Init,
5646 (std::string("OBJC_EHTYPE_$_") +
5647 ID->getIdentifier()->getName()),
5648 &CGM.getModule());
5649 }
5650
Daniel Dunbar8394fda2009-04-14 06:00:08 +00005651 if (CGM.getLangOptions().getVisibilityMode() == LangOptions::Hidden)
Daniel Dunbara2d275d2009-04-07 05:48:37 +00005652 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbarc2129532009-04-08 04:21:03 +00005653 Entry->setAlignment(8);
5654
5655 if (ForDefinition) {
5656 Entry->setSection("__DATA,__objc_const");
5657 Entry->setLinkage(llvm::GlobalValue::ExternalLinkage);
5658 } else {
5659 Entry->setSection("__DATA,__datacoal_nt,coalesced");
5660 }
Daniel Dunbar9c285e72009-03-01 04:46:24 +00005661
5662 return Entry;
5663}
Anders Carlsson1cf75362009-02-16 22:59:18 +00005664
Daniel Dunbardaf4ad42008-08-12 00:12:39 +00005665/* *** */
5666
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00005667CodeGen::CGObjCRuntime *
5668CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00005669 return new CGObjCMac(CGM);
5670}
Fariborz Jahanian48543f52009-01-21 22:04:16 +00005671
5672CodeGen::CGObjCRuntime *
Fariborz Jahaniand0374812009-01-22 23:02:58 +00005673CodeGen::CreateMacNonFragileABIObjCRuntime(CodeGen::CodeGenModule &CGM) {
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00005674 return new CGObjCNonFragileABIMac(CGM);
Fariborz Jahanian48543f52009-01-21 22:04:16 +00005675}