blob: b95e67e7074bbfd5b11a7921175a78b1ebbf59b6 [file] [log] [blame]
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001//===------- CGObjCMac.cpp - Interface to Apple Objective-C Runtime -------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This provides Objective-C code generation targetting the Apple runtime.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CGObjCRuntime.h"
Daniel Dunbarf77ac862008-08-11 21:35:06 +000015
16#include "CodeGenModule.h"
Daniel Dunbarb7ec2462008-08-16 03:19:19 +000017#include "CodeGenFunction.h"
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000018#include "clang/AST/ASTContext.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000019#include "clang/AST/Decl.h"
Daniel Dunbar6efc0c52008-08-13 03:21:16 +000020#include "clang/AST/DeclObjC.h"
Daniel Dunbarf77ac862008-08-11 21:35:06 +000021#include "clang/Basic/LangOptions.h"
22
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +000023#include "llvm/Intrinsics.h"
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000024#include "llvm/Module.h"
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +000025#include "llvm/ADT/DenseSet.h"
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +000026#include "llvm/Target/TargetData.h"
Daniel Dunbarb7ec2462008-08-16 03:19:19 +000027#include <sstream>
Daniel Dunbarc17a4d32008-08-11 02:45:11 +000028
29using namespace clang;
Daniel Dunbar46f45b92008-09-09 01:06:48 +000030using namespace CodeGen;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +000031
32namespace {
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000033
Daniel Dunbarae226fa2008-08-27 02:31:56 +000034 typedef std::vector<llvm::Constant*> ConstantVector;
35
Daniel Dunbar6efc0c52008-08-13 03:21:16 +000036 // FIXME: We should find a nicer way to make the labels for
37 // metadata, string concatenation is lame.
38
Fariborz Jahanianee0af742009-01-21 22:04:16 +000039class ObjCCommonTypesHelper {
40protected:
41 CodeGen::CodeGenModule &CGM;
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000042
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000043public:
Fariborz Jahanian0a855d02009-03-23 19:10:40 +000044 const llvm::Type *ShortTy, *IntTy, *LongTy, *LongLongTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +000045 const llvm::Type *Int8PtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +000046
Daniel Dunbar2bedbf82008-08-12 05:28:47 +000047 /// ObjectPtrTy - LLVM type for object handles (typeof(id))
48 const llvm::Type *ObjectPtrTy;
Fariborz Jahanian6d657c42008-11-18 20:18:11 +000049
50 /// PtrObjectPtrTy - LLVM type for id *
51 const llvm::Type *PtrObjectPtrTy;
52
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +000053 /// SelectorPtrTy - LLVM type for selector handles (typeof(SEL))
Daniel Dunbar2bedbf82008-08-12 05:28:47 +000054 const llvm::Type *SelectorPtrTy;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +000055 /// ProtocolPtrTy - LLVM type for external protocol handles
56 /// (typeof(Protocol))
57 const llvm::Type *ExternalProtocolPtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +000058
Daniel Dunbar19cd87e2008-08-30 03:02:31 +000059 // SuperCTy - clang type for struct objc_super.
60 QualType SuperCTy;
61 // SuperPtrCTy - clang type for struct objc_super *.
62 QualType SuperPtrCTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +000063
Daniel Dunbare8b470d2008-08-23 04:28:29 +000064 /// SuperTy - LLVM type for struct objc_super.
65 const llvm::StructType *SuperTy;
Daniel Dunbar14c80b72008-08-23 09:25:55 +000066 /// SuperPtrTy - LLVM type for struct objc_super *.
67 const llvm::Type *SuperPtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +000068
Fariborz Jahanian30bc5712009-01-22 23:02:58 +000069 /// PropertyTy - LLVM type for struct objc_property (struct _prop_t
70 /// in GCC parlance).
71 const llvm::StructType *PropertyTy;
72
73 /// PropertyListTy - LLVM type for struct objc_property_list
74 /// (_prop_list_t in GCC parlance).
75 const llvm::StructType *PropertyListTy;
76 /// PropertyListPtrTy - LLVM type for struct objc_property_list*.
77 const llvm::Type *PropertyListPtrTy;
78
79 // MethodTy - LLVM type for struct objc_method.
80 const llvm::StructType *MethodTy;
81
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +000082 /// CacheTy - LLVM type for struct objc_cache.
83 const llvm::Type *CacheTy;
84 /// CachePtrTy - LLVM type for struct objc_cache *.
85 const llvm::Type *CachePtrTy;
86
Chris Lattner74391b42009-03-22 21:03:39 +000087 llvm::Constant *GetPropertyFn, *SetPropertyFn;
Fariborz Jahaniandb286862009-01-22 00:37:21 +000088
Chris Lattner74391b42009-03-22 21:03:39 +000089 llvm::Constant *EnumerationMutationFn;
Fariborz Jahaniandb286862009-01-22 00:37:21 +000090
91 /// GcReadWeakFn -- LLVM objc_read_weak (id *src) function.
Chris Lattner74391b42009-03-22 21:03:39 +000092 llvm::Constant *GcReadWeakFn;
Fariborz Jahaniandb286862009-01-22 00:37:21 +000093
94 /// GcAssignWeakFn -- LLVM objc_assign_weak function.
Chris Lattner96508e12009-04-17 22:12:36 +000095 llvm::Constant *getGcAssignWeakFn() {
96 // id objc_assign_weak (id, id *)
97 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
98 Args.push_back(ObjectPtrTy->getPointerTo());
99 llvm::FunctionType *FTy =
100 llvm::FunctionType::get(ObjectPtrTy, Args, false);
101 return CGM.CreateRuntimeFunction(FTy, "objc_assign_weak");
102 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000103
104 /// GcAssignGlobalFn -- LLVM objc_assign_global function.
Chris Lattner74391b42009-03-22 21:03:39 +0000105 llvm::Constant *GcAssignGlobalFn;
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000106
107 /// GcAssignIvarFn -- LLVM objc_assign_ivar function.
Chris Lattner74391b42009-03-22 21:03:39 +0000108 llvm::Constant *GcAssignIvarFn;
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000109
110 /// GcAssignStrongCastFn -- LLVM objc_assign_strongCast function.
Chris Lattner74391b42009-03-22 21:03:39 +0000111 llvm::Constant *GcAssignStrongCastFn;
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000112
113 /// ExceptionThrowFn - LLVM objc_exception_throw function.
Chris Lattner74391b42009-03-22 21:03:39 +0000114 llvm::Constant *ExceptionThrowFn;
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000115
Daniel Dunbar1c566672009-02-24 01:43:46 +0000116 /// SyncEnterFn - LLVM object_sync_enter function.
Chris Lattnerb02e53b2009-04-06 16:53:45 +0000117 llvm::Constant *getSyncEnterFn() {
118 // void objc_sync_enter (id)
119 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
120 llvm::FunctionType *FTy =
121 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
122 return CGM.CreateRuntimeFunction(FTy, "objc_sync_enter");
123 }
Daniel Dunbar1c566672009-02-24 01:43:46 +0000124
125 /// SyncExitFn - LLVM object_sync_exit function.
Chris Lattner74391b42009-03-22 21:03:39 +0000126 llvm::Constant *SyncExitFn;
Daniel Dunbar1c566672009-02-24 01:43:46 +0000127
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000128 ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm);
129 ~ObjCCommonTypesHelper(){}
130};
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000131
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000132/// ObjCTypesHelper - Helper class that encapsulates lazy
133/// construction of varies types used during ObjC generation.
134class ObjCTypesHelper : public ObjCCommonTypesHelper {
135private:
136
Chris Lattner74391b42009-03-22 21:03:39 +0000137 llvm::Constant *MessageSendFn, *MessageSendStretFn, *MessageSendFpretFn;
138 llvm::Constant *MessageSendSuperFn, *MessageSendSuperStretFn,
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000139 *MessageSendSuperFpretFn;
140
141public:
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000142 /// SymtabTy - LLVM type for struct objc_symtab.
143 const llvm::StructType *SymtabTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000144 /// SymtabPtrTy - LLVM type for struct objc_symtab *.
145 const llvm::Type *SymtabPtrTy;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000146 /// ModuleTy - LLVM type for struct objc_module.
147 const llvm::StructType *ModuleTy;
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000148
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000149 /// ProtocolTy - LLVM type for struct objc_protocol.
150 const llvm::StructType *ProtocolTy;
151 /// ProtocolPtrTy - LLVM type for struct objc_protocol *.
152 const llvm::Type *ProtocolPtrTy;
153 /// ProtocolExtensionTy - LLVM type for struct
154 /// objc_protocol_extension.
155 const llvm::StructType *ProtocolExtensionTy;
156 /// ProtocolExtensionTy - LLVM type for struct
157 /// objc_protocol_extension *.
158 const llvm::Type *ProtocolExtensionPtrTy;
159 /// MethodDescriptionTy - LLVM type for struct
160 /// objc_method_description.
161 const llvm::StructType *MethodDescriptionTy;
162 /// MethodDescriptionListTy - LLVM type for struct
163 /// objc_method_description_list.
164 const llvm::StructType *MethodDescriptionListTy;
165 /// MethodDescriptionListPtrTy - LLVM type for struct
166 /// objc_method_description_list *.
167 const llvm::Type *MethodDescriptionListPtrTy;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000168 /// ProtocolListTy - LLVM type for struct objc_property_list.
169 const llvm::Type *ProtocolListTy;
170 /// ProtocolListPtrTy - LLVM type for struct objc_property_list*.
171 const llvm::Type *ProtocolListPtrTy;
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000172 /// CategoryTy - LLVM type for struct objc_category.
173 const llvm::StructType *CategoryTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000174 /// ClassTy - LLVM type for struct objc_class.
175 const llvm::StructType *ClassTy;
176 /// ClassPtrTy - LLVM type for struct objc_class *.
177 const llvm::Type *ClassPtrTy;
178 /// ClassExtensionTy - LLVM type for struct objc_class_ext.
179 const llvm::StructType *ClassExtensionTy;
180 /// ClassExtensionPtrTy - LLVM type for struct objc_class_ext *.
181 const llvm::Type *ClassExtensionPtrTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000182 // IvarTy - LLVM type for struct objc_ivar.
183 const llvm::StructType *IvarTy;
184 /// IvarListTy - LLVM type for struct objc_ivar_list.
185 const llvm::Type *IvarListTy;
186 /// IvarListPtrTy - LLVM type for struct objc_ivar_list *.
187 const llvm::Type *IvarListPtrTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000188 /// MethodListTy - LLVM type for struct objc_method_list.
189 const llvm::Type *MethodListTy;
190 /// MethodListPtrTy - LLVM type for struct objc_method_list *.
191 const llvm::Type *MethodListPtrTy;
Anders Carlsson124526b2008-09-09 10:10:21 +0000192
193 /// ExceptionDataTy - LLVM type for struct _objc_exception_data.
194 const llvm::Type *ExceptionDataTy;
195
Anders Carlsson124526b2008-09-09 10:10:21 +0000196 /// ExceptionTryEnterFn - LLVM objc_exception_try_enter function.
Chris Lattner74391b42009-03-22 21:03:39 +0000197 llvm::Constant *ExceptionTryEnterFn;
Anders Carlsson124526b2008-09-09 10:10:21 +0000198
199 /// ExceptionTryExitFn - LLVM objc_exception_try_exit function.
Chris Lattner74391b42009-03-22 21:03:39 +0000200 llvm::Constant *ExceptionTryExitFn;
Anders Carlsson124526b2008-09-09 10:10:21 +0000201
202 /// ExceptionExtractFn - LLVM objc_exception_extract function.
Chris Lattner74391b42009-03-22 21:03:39 +0000203 llvm::Constant *ExceptionExtractFn;
Anders Carlsson124526b2008-09-09 10:10:21 +0000204
205 /// ExceptionMatchFn - LLVM objc_exception_match function.
Chris Lattner74391b42009-03-22 21:03:39 +0000206 llvm::Constant *ExceptionMatchFn;
Anders Carlsson124526b2008-09-09 10:10:21 +0000207
208 /// SetJmpFn - LLVM _setjmp function.
Chris Lattner74391b42009-03-22 21:03:39 +0000209 llvm::Constant *SetJmpFn;
Chris Lattner10cac6f2008-11-15 21:26:17 +0000210
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000211public:
212 ObjCTypesHelper(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000213 ~ObjCTypesHelper() {}
Daniel Dunbar5669e572008-10-17 03:24:53 +0000214
215
Chris Lattner74391b42009-03-22 21:03:39 +0000216 llvm::Constant *getSendFn(bool IsSuper) {
Daniel Dunbar5669e572008-10-17 03:24:53 +0000217 return IsSuper ? MessageSendSuperFn : MessageSendFn;
218 }
219
Chris Lattner74391b42009-03-22 21:03:39 +0000220 llvm::Constant *getSendStretFn(bool IsSuper) {
Daniel Dunbar5669e572008-10-17 03:24:53 +0000221 return IsSuper ? MessageSendSuperStretFn : MessageSendStretFn;
222 }
223
Chris Lattner74391b42009-03-22 21:03:39 +0000224 llvm::Constant *getSendFpretFn(bool IsSuper) {
Daniel Dunbar5669e572008-10-17 03:24:53 +0000225 return IsSuper ? MessageSendSuperFpretFn : MessageSendFpretFn;
226 }
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000227};
228
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000229/// ObjCNonFragileABITypesHelper - will have all types needed by objective-c's
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000230/// modern abi
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000231class ObjCNonFragileABITypesHelper : public ObjCCommonTypesHelper {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000232public:
Chris Lattner74391b42009-03-22 21:03:39 +0000233 llvm::Constant *MessageSendFixupFn, *MessageSendFpretFixupFn,
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000234 *MessageSendStretFixupFn, *MessageSendIdFixupFn,
235 *MessageSendIdStretFixupFn, *MessageSendSuper2FixupFn,
236 *MessageSendSuper2StretFixupFn;
237
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000238 // MethodListnfABITy - LLVM for struct _method_list_t
239 const llvm::StructType *MethodListnfABITy;
240
241 // MethodListnfABIPtrTy - LLVM for struct _method_list_t*
242 const llvm::Type *MethodListnfABIPtrTy;
243
244 // ProtocolnfABITy = LLVM for struct _protocol_t
245 const llvm::StructType *ProtocolnfABITy;
246
Daniel Dunbar948e2582009-02-15 07:36:20 +0000247 // ProtocolnfABIPtrTy = LLVM for struct _protocol_t*
248 const llvm::Type *ProtocolnfABIPtrTy;
249
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000250 // ProtocolListnfABITy - LLVM for struct _objc_protocol_list
251 const llvm::StructType *ProtocolListnfABITy;
252
253 // ProtocolListnfABIPtrTy - LLVM for struct _objc_protocol_list*
254 const llvm::Type *ProtocolListnfABIPtrTy;
255
256 // ClassnfABITy - LLVM for struct _class_t
257 const llvm::StructType *ClassnfABITy;
258
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000259 // ClassnfABIPtrTy - LLVM for struct _class_t*
260 const llvm::Type *ClassnfABIPtrTy;
261
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000262 // IvarnfABITy - LLVM for struct _ivar_t
263 const llvm::StructType *IvarnfABITy;
264
265 // IvarListnfABITy - LLVM for struct _ivar_list_t
266 const llvm::StructType *IvarListnfABITy;
267
268 // IvarListnfABIPtrTy = LLVM for struct _ivar_list_t*
269 const llvm::Type *IvarListnfABIPtrTy;
270
271 // ClassRonfABITy - LLVM for struct _class_ro_t
272 const llvm::StructType *ClassRonfABITy;
273
274 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
275 const llvm::Type *ImpnfABITy;
276
277 // CategorynfABITy - LLVM for struct _category_t
278 const llvm::StructType *CategorynfABITy;
279
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000280 // New types for nonfragile abi messaging.
281
282 // MessageRefTy - LLVM for:
283 // struct _message_ref_t {
284 // IMP messenger;
285 // SEL name;
286 // };
287 const llvm::StructType *MessageRefTy;
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000288 // MessageRefCTy - clang type for struct _message_ref_t
289 QualType MessageRefCTy;
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000290
291 // MessageRefPtrTy - LLVM for struct _message_ref_t*
292 const llvm::Type *MessageRefPtrTy;
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000293 // MessageRefCPtrTy - clang type for struct _message_ref_t*
294 QualType MessageRefCPtrTy;
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000295
Fariborz Jahanianef163782009-02-05 01:13:09 +0000296 // MessengerTy - Type of the messenger (shown as IMP above)
297 const llvm::FunctionType *MessengerTy;
298
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000299 // SuperMessageRefTy - LLVM for:
300 // struct _super_message_ref_t {
301 // SUPER_IMP messenger;
302 // SEL name;
303 // };
304 const llvm::StructType *SuperMessageRefTy;
305
306 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
307 const llvm::Type *SuperMessageRefPtrTy;
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000308
309 /// EHPersonalityPtr - LLVM value for an i8* to the Objective-C
310 /// exception personality function.
Chris Lattnerb02e53b2009-04-06 16:53:45 +0000311 llvm::Value *getEHPersonalityPtr() {
312 llvm::Constant *Personality =
313 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
314 std::vector<const llvm::Type*>(),
315 true),
316 "__objc_personality_v0");
317 return llvm::ConstantExpr::getBitCast(Personality, Int8PtrTy);
318 }
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000319
Chris Lattner74391b42009-03-22 21:03:39 +0000320 llvm::Constant *UnwindResumeOrRethrowFn, *ObjCBeginCatchFn, *ObjCEndCatchFn;
Daniel Dunbare588b992009-03-01 04:46:24 +0000321
322 const llvm::StructType *EHTypeTy;
323 const llvm::Type *EHTypePtrTy;
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000324
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000325 ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm);
326 ~ObjCNonFragileABITypesHelper(){}
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000327};
328
329class CGObjCCommonMac : public CodeGen::CGObjCRuntime {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000330public:
331 // FIXME - accessibility
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000332 class GC_IVAR {
Fariborz Jahanian820e0202009-03-11 00:07:04 +0000333 public:
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000334 unsigned int ivar_bytepos;
335 unsigned int ivar_size;
336 GC_IVAR() : ivar_bytepos(0), ivar_size(0) {}
337 };
338
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000339 class SKIP_SCAN {
340 public:
341 unsigned int skip;
342 unsigned int scan;
343 SKIP_SCAN() : skip(0), scan(0) {}
344 };
345
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000346protected:
347 CodeGen::CodeGenModule &CGM;
348 // FIXME! May not be needing this after all.
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000349 unsigned ObjCABI;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000350
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000351 // gc ivar layout bitmap calculation helper caches.
352 llvm::SmallVector<GC_IVAR, 16> SkipIvars;
353 llvm::SmallVector<GC_IVAR, 16> IvarsInfo;
354 llvm::SmallVector<SKIP_SCAN, 32> SkipScanIvars;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000355
Daniel Dunbar242d4dc2008-08-25 06:02:07 +0000356 /// LazySymbols - Symbols to generate a lazy reference for. See
357 /// DefinedSymbols and FinishModule().
358 std::set<IdentifierInfo*> LazySymbols;
359
360 /// DefinedSymbols - External symbols which are defined by this
361 /// module. The symbols in this list and LazySymbols are used to add
362 /// special linker symbols which ensure that Objective-C modules are
363 /// linked properly.
364 std::set<IdentifierInfo*> DefinedSymbols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000365
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000366 /// ClassNames - uniqued class names.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000367 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000368
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000369 /// MethodVarNames - uniqued method variable names.
370 llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000371
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000372 /// MethodVarTypes - uniqued method type signatures. We have to use
373 /// a StringMap here because have no other unique reference.
374 llvm::StringMap<llvm::GlobalVariable*> MethodVarTypes;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000375
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000376 /// MethodDefinitions - map of methods which have been defined in
377 /// this translation unit.
378 llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> MethodDefinitions;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000379
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000380 /// PropertyNames - uniqued method variable names.
381 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000382
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000383 /// ClassReferences - uniqued class references.
384 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000385
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000386 /// SelectorReferences - uniqued selector references.
387 llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000388
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000389 /// Protocols - Protocols for which an objc_protocol structure has
390 /// been emitted. Forward declarations are handled by creating an
391 /// empty structure whose initializer is filled in when/if defined.
392 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> Protocols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000393
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000394 /// DefinedProtocols - Protocols which have actually been
395 /// defined. We should not need this, see FIXME in GenerateProtocol.
396 llvm::DenseSet<IdentifierInfo*> DefinedProtocols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000397
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000398 /// DefinedClasses - List of defined classes.
399 std::vector<llvm::GlobalValue*> DefinedClasses;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000400
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000401 /// DefinedCategories - List of defined categories.
402 std::vector<llvm::GlobalValue*> DefinedCategories;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000403
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000404 /// UsedGlobals - List of globals to pack into the llvm.used metadata
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000405 /// to prevent them from being clobbered.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000406 std::vector<llvm::GlobalVariable*> UsedGlobals;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000407
Fariborz Jahanian56210f72009-01-21 23:34:32 +0000408 /// GetNameForMethod - Return a name for the given method.
409 /// \param[out] NameOut - The return value.
410 void GetNameForMethod(const ObjCMethodDecl *OMD,
411 const ObjCContainerDecl *CD,
412 std::string &NameOut);
413
414 /// GetMethodVarName - Return a unique constant for the given
415 /// selector's name. The return value has type char *.
416 llvm::Constant *GetMethodVarName(Selector Sel);
417 llvm::Constant *GetMethodVarName(IdentifierInfo *Ident);
418 llvm::Constant *GetMethodVarName(const std::string &Name);
419
420 /// GetMethodVarType - Return a unique constant for the given
421 /// selector's name. The return value has type char *.
422
423 // FIXME: This is a horrible name.
424 llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D);
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +0000425 llvm::Constant *GetMethodVarType(const FieldDecl *D);
Fariborz Jahanian56210f72009-01-21 23:34:32 +0000426
427 /// GetPropertyName - Return a unique constant for the given
428 /// name. The return value has type char *.
429 llvm::Constant *GetPropertyName(IdentifierInfo *Ident);
430
431 // FIXME: This can be dropped once string functions are unified.
432 llvm::Constant *GetPropertyTypeString(const ObjCPropertyDecl *PD,
433 const Decl *Container);
434
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000435 /// GetClassName - Return a unique constant for the given selector's
436 /// name. The return value has type char *.
437 llvm::Constant *GetClassName(IdentifierInfo *Ident);
438
Fariborz Jahanian21e6f172009-03-11 21:42:00 +0000439 /// GetInterfaceDeclStructLayout - Get layout for ivars of given
440 /// interface declaration.
441 const llvm::StructLayout *GetInterfaceDeclStructLayout(
442 const ObjCInterfaceDecl *ID) const;
443
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000444 /// BuildIvarLayout - Builds ivar layout bitmap for the class
445 /// implementation for the __strong or __weak case.
446 ///
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000447 llvm::Constant *BuildIvarLayout(const ObjCImplementationDecl *OI,
448 bool ForStrongLayout);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000449
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000450 void BuildAggrIvarLayout(const ObjCInterfaceDecl *OI,
451 const llvm::StructLayout *Layout,
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000452 const RecordDecl *RD,
Chris Lattnerf1690852009-03-31 08:48:01 +0000453 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000454 unsigned int BytePos, bool ForStrongLayout,
455 int &Index, int &SkIndex, bool &HasUnion);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000456
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +0000457 /// GetIvarLayoutName - Returns a unique constant for the given
458 /// ivar layout bitmap.
459 llvm::Constant *GetIvarLayoutName(IdentifierInfo *Ident,
460 const ObjCCommonTypesHelper &ObjCTypes);
461
Fariborz Jahanian46b86c62009-01-28 19:12:34 +0000462 const RecordDecl *GetFirstIvarInRecord(const ObjCInterfaceDecl *OID,
463 RecordDecl::field_iterator &FIV,
464 RecordDecl::field_iterator &PIV);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +0000465 /// EmitPropertyList - Emit the given property list. The return
466 /// value has type PropertyListPtrTy.
467 llvm::Constant *EmitPropertyList(const std::string &Name,
468 const Decl *Container,
469 const ObjCContainerDecl *OCD,
470 const ObjCCommonTypesHelper &ObjCTypes);
471
Fariborz Jahanianda320092009-01-29 19:24:30 +0000472 /// GetProtocolRef - Return a reference to the internal protocol
473 /// description, creating an empty one if it has not been
474 /// defined. The return value has type ProtocolPtrTy.
475 llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +0000476
477 /// GetIvarBaseOffset - returns ivars byte offset.
478 uint64_t GetIvarBaseOffset(const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +0000479 const FieldDecl *Field);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000480
Chris Lattnercd0ee142009-03-31 08:33:16 +0000481 /// GetFieldBaseOffset - return's field byte offset.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000482 uint64_t GetFieldBaseOffset(const ObjCInterfaceDecl *OI,
483 const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +0000484 const FieldDecl *Field);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000485
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000486 /// CreateMetadataVar - Create a global variable with internal
487 /// linkage for use by the Objective-C runtime.
488 ///
489 /// This is a convenience wrapper which not only creates the
490 /// variable, but also sets the section and alignment and adds the
491 /// global to the UsedGlobals list.
Daniel Dunbar35bd7632009-03-09 20:50:13 +0000492 ///
493 /// \param Name - The variable name.
494 /// \param Init - The variable initializer; this is also used to
495 /// define the type of the variable.
496 /// \param Section - The section the variable should go into, or 0.
497 /// \param Align - The alignment for the variable, or 0.
498 /// \param AddToUsed - Whether the variable should be added to
Daniel Dunbarc1583062009-04-14 17:42:51 +0000499 /// "llvm.used".
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000500 llvm::GlobalVariable *CreateMetadataVar(const std::string &Name,
501 llvm::Constant *Init,
502 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +0000503 unsigned Align,
504 bool AddToUsed);
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000505
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +0000506 /// GetNamedIvarList - Return the list of ivars in the interface
507 /// itself (not including super classes and not including unnamed
508 /// bitfields).
509 ///
510 /// For the non-fragile ABI, this also includes synthesized property
511 /// ivars.
512 void GetNamedIvarList(const ObjCInterfaceDecl *OID,
513 llvm::SmallVector<ObjCIvarDecl*, 16> &Res) const;
514
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000515public:
516 CGObjCCommonMac(CodeGen::CodeGenModule &cgm) : CGM(cgm)
517 { }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000518
Steve Naroff33fdb732009-03-31 16:53:37 +0000519 virtual llvm::Constant *GenerateConstantString(const ObjCStringLiteral *SL);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000520
521 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
522 const ObjCContainerDecl *CD=0);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000523
524 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
525
526 /// GetOrEmitProtocol - Get the protocol object for the given
527 /// declaration, emitting it if necessary. The return value has type
528 /// ProtocolPtrTy.
529 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD)=0;
530
531 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
532 /// object for the given declaration, emitting it if needed. These
533 /// forward references will be filled in with empty bodies if no
534 /// definition is seen. The return value has type ProtocolPtrTy.
535 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD)=0;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000536};
537
538class CGObjCMac : public CGObjCCommonMac {
539private:
540 ObjCTypesHelper ObjCTypes;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000541 /// EmitImageInfo - Emit the image info marker used to encode some module
542 /// level information.
543 void EmitImageInfo();
544
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000545 /// EmitModuleInfo - Another marker encoding module level
546 /// information.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000547 void EmitModuleInfo();
548
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000549 /// EmitModuleSymols - Emit module symbols, the list of defined
550 /// classes and categories. The result has type SymtabPtrTy.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000551 llvm::Constant *EmitModuleSymbols();
552
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000553 /// FinishModule - Write out global data structures at the end of
554 /// processing a translation unit.
555 void FinishModule();
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000556
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000557 /// EmitClassExtension - Generate the class extension structure used
558 /// to store the weak ivar layout and properties. The return value
559 /// has type ClassExtensionPtrTy.
560 llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID);
561
562 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
563 /// for the given class.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000564 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000565 const ObjCInterfaceDecl *ID);
566
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000567 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000568 QualType ResultType,
569 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000570 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000571 QualType Arg0Ty,
572 bool IsSuper,
573 const CallArgList &CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000574
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000575 /// EmitIvarList - Emit the ivar list for the given
576 /// implementation. If ForClass is true the list of class ivars
577 /// (i.e. metaclass ivars) is emitted, otherwise the list of
578 /// interface ivars will be emitted. The return value has type
579 /// IvarListPtrTy.
580 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +0000581 bool ForClass);
582
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000583 /// EmitMetaClass - Emit a forward reference to the class structure
584 /// for the metaclass of the given interface. The return value has
585 /// type ClassPtrTy.
586 llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
587
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000588 /// EmitMetaClass - Emit a class structure for the metaclass of the
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000589 /// given implementation. The return value has type ClassPtrTy.
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000590 llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
591 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000592 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000593 const ConstantVector &Methods);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000594
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000595 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000596
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000597 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000598
599 /// EmitMethodList - Emit the method list for the given
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000600 /// implementation. The return value has type MethodListPtrTy.
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000601 llvm::Constant *EmitMethodList(const std::string &Name,
602 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000603 const ConstantVector &Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000604
605 /// EmitMethodDescList - Emit a method description list for a list of
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000606 /// method declarations.
607 /// - TypeName: The name for the type containing the methods.
608 /// - IsProtocol: True iff these methods are for a protocol.
609 /// - ClassMethds: True iff these are class methods.
610 /// - Required: When true, only "required" methods are
611 /// listed. Similarly, when false only "optional" methods are
612 /// listed. For classes this should always be true.
613 /// - begin, end: The method list to output.
614 ///
615 /// The return value has type MethodDescriptionListPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000616 llvm::Constant *EmitMethodDescList(const std::string &Name,
617 const char *Section,
618 const ConstantVector &Methods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000619
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000620 /// GetOrEmitProtocol - Get the protocol object for the given
621 /// declaration, emitting it if necessary. The return value has type
622 /// ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +0000623 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000624
625 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
626 /// object for the given declaration, emitting it if needed. These
627 /// forward references will be filled in with empty bodies if no
628 /// definition is seen. The return value has type ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +0000629 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000630
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000631 /// EmitProtocolExtension - Generate the protocol extension
632 /// structure used to store optional instance and class methods, and
633 /// protocol properties. The return value has type
634 /// ProtocolExtensionPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000635 llvm::Constant *
636 EmitProtocolExtension(const ObjCProtocolDecl *PD,
637 const ConstantVector &OptInstanceMethods,
638 const ConstantVector &OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000639
640 /// EmitProtocolList - Generate the list of referenced
641 /// protocols. The return value has type ProtocolListPtrTy.
Daniel Dunbardbc933702008-08-21 21:57:41 +0000642 llvm::Constant *EmitProtocolList(const std::string &Name,
643 ObjCProtocolDecl::protocol_iterator begin,
644 ObjCProtocolDecl::protocol_iterator end);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000645
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000646 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
647 /// for the given selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000648 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000649
Fariborz Jahanianda320092009-01-29 19:24:30 +0000650 public:
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000651 CGObjCMac(CodeGen::CodeGenModule &cgm);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000652
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000653 virtual llvm::Function *ModuleInitFunction();
654
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000655 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000656 QualType ResultType,
657 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000658 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000659 bool IsClassMessage,
660 const CallArgList &CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000661
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000662 virtual CodeGen::RValue
663 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000664 QualType ResultType,
665 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000666 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000667 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000668 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000669 bool IsClassMessage,
670 const CallArgList &CallArgs);
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000671
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000672 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000673 const ObjCInterfaceDecl *ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000674
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000675 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000676
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000677 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000678
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000679 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000680
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000681 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000682 const ObjCProtocolDecl *PD);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000683
Chris Lattner74391b42009-03-22 21:03:39 +0000684 virtual llvm::Constant *GetPropertyGetFunction();
685 virtual llvm::Constant *GetPropertySetFunction();
686 virtual llvm::Constant *EnumerationMutationFunction();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000687
Fariborz Jahanianbd71be42008-11-21 00:49:24 +0000688 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
689 const Stmt &S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000690 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
691 const ObjCAtThrowStmt &S);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000692 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +0000693 llvm::Value *AddrWeakObj);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000694 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
695 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000696 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
697 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian7eda8362008-11-20 19:23:36 +0000698 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
699 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000700 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
701 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian0bb20362009-02-02 20:02:29 +0000702
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000703 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
704 QualType ObjectTy,
705 llvm::Value *BaseValue,
706 const ObjCIvarDecl *Ivar,
707 const FieldDecl *Field,
708 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000709 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
710 ObjCInterfaceDecl *Interface,
711 const ObjCIvarDecl *Ivar);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000712};
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000713
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000714class CGObjCNonFragileABIMac : public CGObjCCommonMac {
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000715private:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000716 ObjCNonFragileABITypesHelper ObjCTypes;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000717 llvm::GlobalVariable* ObjCEmptyCacheVar;
718 llvm::GlobalVariable* ObjCEmptyVtableVar;
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000719
Daniel Dunbar11394522009-04-18 08:51:00 +0000720 /// SuperClassReferences - uniqued super class references.
721 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> SuperClassReferences;
722
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000723 /// MetaClassReferences - uniqued meta class references.
724 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> MetaClassReferences;
Daniel Dunbare588b992009-03-01 04:46:24 +0000725
726 /// EHTypeReferences - uniqued class ehtype references.
727 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> EHTypeReferences;
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000728
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000729 /// FinishNonFragileABIModule - Write out global data structures at the end of
730 /// processing a translation unit.
731 void FinishNonFragileABIModule();
Daniel Dunbar8158a2f2009-04-08 04:21:03 +0000732
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000733 llvm::GlobalVariable * BuildClassRoTInitializer(unsigned flags,
734 unsigned InstanceStart,
735 unsigned InstanceSize,
736 const ObjCImplementationDecl *ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +0000737 llvm::GlobalVariable * BuildClassMetaData(std::string &ClassName,
738 llvm::Constant *IsAGV,
739 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +0000740 llvm::Constant *ClassRoGV,
741 bool HiddenVisibility);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000742
743 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
744
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +0000745 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
746
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000747 /// EmitMethodList - Emit the method list for the given
748 /// implementation. The return value has type MethodListnfABITy.
749 llvm::Constant *EmitMethodList(const std::string &Name,
750 const char *Section,
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +0000751 const ConstantVector &Methods);
752 /// EmitIvarList - Emit the ivar list for the given
753 /// implementation. If ForClass is true the list of class ivars
754 /// (i.e. metaclass ivars) is emitted, otherwise the list of
755 /// interface ivars will be emitted. The return value has type
756 /// IvarListnfABIPtrTy.
757 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000758
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000759 llvm::Constant *EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +0000760 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +0000761 unsigned long int offset);
762
Fariborz Jahanianda320092009-01-29 19:24:30 +0000763 /// GetOrEmitProtocol - Get the protocol object for the given
764 /// declaration, emitting it if necessary. The return value has type
765 /// ProtocolPtrTy.
766 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
767
768 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
769 /// object for the given declaration, emitting it if needed. These
770 /// forward references will be filled in with empty bodies if no
771 /// definition is seen. The return value has type ProtocolPtrTy.
772 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
773
774 /// EmitProtocolList - Generate the list of referenced
775 /// protocols. The return value has type ProtocolListPtrTy.
776 llvm::Constant *EmitProtocolList(const std::string &Name,
777 ObjCProtocolDecl::protocol_iterator begin,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000778 ObjCProtocolDecl::protocol_iterator end);
779
780 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
781 QualType ResultType,
782 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000783 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000784 QualType Arg0Ty,
785 bool IsSuper,
786 const CallArgList &CallArgs);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +0000787
788 /// GetClassGlobal - Return the global variable for the Objective-C
789 /// class of the given name.
Fariborz Jahanian0f902942009-04-14 18:41:56 +0000790 llvm::GlobalVariable *GetClassGlobal(const std::string &Name);
791
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000792 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
Daniel Dunbar11394522009-04-18 08:51:00 +0000793 /// for the given class reference.
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000794 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar11394522009-04-18 08:51:00 +0000795 const ObjCInterfaceDecl *ID);
796
797 /// EmitSuperClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
798 /// for the given super class reference.
799 llvm::Value *EmitSuperClassRef(CGBuilderTy &Builder,
800 const ObjCInterfaceDecl *ID);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000801
802 /// EmitMetaClassRef - Return a Value * of the address of _class_t
803 /// meta-data
804 llvm::Value *EmitMetaClassRef(CGBuilderTy &Builder,
805 const ObjCInterfaceDecl *ID);
806
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000807 /// ObjCIvarOffsetVariable - Returns the ivar offset variable for
808 /// the given ivar.
809 ///
Daniel Dunbar5e88bea2009-04-19 00:31:15 +0000810 llvm::GlobalVariable * ObjCIvarOffsetVariable(
Fariborz Jahanian01a0c362009-02-12 18:51:23 +0000811 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000812 const ObjCIvarDecl *Ivar);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000813
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +0000814 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
815 /// for the given selector.
816 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbare588b992009-03-01 04:46:24 +0000817
Daniel Dunbar8158a2f2009-04-08 04:21:03 +0000818 /// GetInterfaceEHType - Get the cached ehtype for the given Objective-C
Daniel Dunbare588b992009-03-01 04:46:24 +0000819 /// interface. The return value has type EHTypePtrTy.
Daniel Dunbar8158a2f2009-04-08 04:21:03 +0000820 llvm::Value *GetInterfaceEHType(const ObjCInterfaceDecl *ID,
821 bool ForDefinition);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +0000822
823 const char *getMetaclassSymbolPrefix() const {
824 return "OBJC_METACLASS_$_";
825 }
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000826
Daniel Dunbar6ab187a2009-04-07 05:48:37 +0000827 const char *getClassSymbolPrefix() const {
828 return "OBJC_CLASS_$_";
829 }
830
Daniel Dunbarb02532a2009-04-19 23:41:48 +0000831 void GetClassSizeInfo(const ObjCInterfaceDecl *OID,
832 uint32_t &InstanceStart,
833 uint32_t &InstanceSize);
834
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000835public:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000836 CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000837 // FIXME. All stubs for now!
838 virtual llvm::Function *ModuleInitFunction();
839
840 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
841 QualType ResultType,
842 Selector Sel,
843 llvm::Value *Receiver,
844 bool IsClassMessage,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000845 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000846
847 virtual CodeGen::RValue
848 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
849 QualType ResultType,
850 Selector Sel,
851 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000852 bool isCategoryImpl,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000853 llvm::Value *Receiver,
854 bool IsClassMessage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000855 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000856
857 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000858 const ObjCInterfaceDecl *ID);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000859
860 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel)
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +0000861 { return EmitSelector(Builder, Sel); }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000862
Fariborz Jahanianeb062d92009-01-26 18:32:24 +0000863 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000864
865 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000866 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +0000867 const ObjCProtocolDecl *PD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000868
Chris Lattner74391b42009-03-22 21:03:39 +0000869 virtual llvm::Constant *GetPropertyGetFunction() {
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000870 return ObjCTypes.GetPropertyFn;
871 }
Chris Lattner74391b42009-03-22 21:03:39 +0000872 virtual llvm::Constant *GetPropertySetFunction() {
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000873 return ObjCTypes.SetPropertyFn;
874 }
Chris Lattner74391b42009-03-22 21:03:39 +0000875 virtual llvm::Constant *EnumerationMutationFunction() {
Daniel Dunbar28ed0842009-02-16 18:48:45 +0000876 return ObjCTypes.EnumerationMutationFn;
877 }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000878
879 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000880 const Stmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000881 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000882 const ObjCAtThrowStmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000883 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000884 llvm::Value *AddrWeakObj);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000885 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000886 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000887 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000888 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000889 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000890 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000891 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000892 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000893 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
894 QualType ObjectTy,
895 llvm::Value *BaseValue,
896 const ObjCIvarDecl *Ivar,
897 const FieldDecl *Field,
898 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000899 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
900 ObjCInterfaceDecl *Interface,
901 const ObjCIvarDecl *Ivar);
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000902};
903
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000904} // end anonymous namespace
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000905
906/* *** Helper Functions *** */
907
908/// getConstantGEP() - Help routine to construct simple GEPs.
909static llvm::Constant *getConstantGEP(llvm::Constant *C,
910 unsigned idx0,
911 unsigned idx1) {
912 llvm::Value *Idxs[] = {
913 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx0),
914 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx1)
915 };
916 return llvm::ConstantExpr::getGetElementPtr(C, Idxs, 2);
917}
918
Daniel Dunbar8158a2f2009-04-08 04:21:03 +0000919/// hasObjCExceptionAttribute - Return true if this class or any super
920/// class has the __objc_exception__ attribute.
921static bool hasObjCExceptionAttribute(const ObjCInterfaceDecl *OID) {
Daniel Dunbarb11fa0d2009-04-13 21:08:27 +0000922 if (OID->hasAttr<ObjCExceptionAttr>())
Daniel Dunbar8158a2f2009-04-08 04:21:03 +0000923 return true;
924 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
925 return hasObjCExceptionAttribute(Super);
926 return false;
927}
928
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000929/* *** CGObjCMac Public Interface *** */
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000930
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000931CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm),
932 ObjCTypes(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000933{
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000934 ObjCABI = 1;
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000935 EmitImageInfo();
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000936}
937
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000938/// GetClass - Return a reference to the class for the given interface
939/// decl.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000940llvm::Value *CGObjCMac::GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000941 const ObjCInterfaceDecl *ID) {
942 return EmitClassRef(Builder, ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000943}
944
945/// GetSelector - Return the pointer to the unique'd string for this selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000946llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000947 return EmitSelector(Builder, Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000948}
949
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000950/// Generate a constant CFString object.
951/*
952 struct __builtin_CFString {
953 const int *isa; // point to __CFConstantStringClassReference
954 int flags;
955 const char *str;
956 long length;
957 };
958*/
959
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000960llvm::Constant *CGObjCCommonMac::GenerateConstantString(
Steve Naroff33fdb732009-03-31 16:53:37 +0000961 const ObjCStringLiteral *SL) {
Steve Naroff8d4141f2009-04-01 13:55:36 +0000962 return CGM.GetAddrOfConstantCFString(SL->getString());
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000963}
964
965/// Generates a message send where the super is the receiver. This is
966/// a message send to self with special delivery semantics indicating
967/// which class's method should be called.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000968CodeGen::RValue
969CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000970 QualType ResultType,
971 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000972 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000973 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000974 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000975 bool IsClassMessage,
Daniel Dunbar46f45b92008-09-09 01:06:48 +0000976 const CodeGen::CallArgList &CallArgs) {
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000977 // Create and init a super structure; this is a (receiver, class)
978 // pair we will pass to objc_msgSendSuper.
979 llvm::Value *ObjCSuper =
980 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
981 llvm::Value *ReceiverAsObject =
982 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
983 CGF.Builder.CreateStore(ReceiverAsObject,
984 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000985
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000986 // If this is a class message the metaclass is passed as the target.
987 llvm::Value *Target;
988 if (IsClassMessage) {
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000989 if (isCategoryImpl) {
990 // Message sent to 'super' in a class method defined in a category
991 // implementation requires an odd treatment.
992 // If we are in a class method, we must retrieve the
993 // _metaclass_ for the current class, pointed at by
994 // the class's "isa" pointer. The following assumes that
995 // isa" is the first ivar in a class (which it must be).
996 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
997 Target = CGF.Builder.CreateStructGEP(Target, 0);
998 Target = CGF.Builder.CreateLoad(Target);
999 }
1000 else {
1001 llvm::Value *MetaClassPtr = EmitMetaClassRef(Class);
1002 llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1);
1003 llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr);
1004 Target = Super;
1005 }
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001006 } else {
1007 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
1008 }
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001009 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
1010 // and ObjCTypes types.
1011 const llvm::Type *ClassTy =
1012 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001013 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001014 CGF.Builder.CreateStore(Target,
1015 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
1016
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001017 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001018 ObjCSuper, ObjCTypes.SuperPtrCTy,
1019 true, CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001020}
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001021
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001022/// Generate code for a message send expression.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +00001023CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001024 QualType ResultType,
1025 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001026 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001027 bool IsClassMessage,
1028 const CallArgList &CallArgs) {
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001029 llvm::Value *Arg0 =
1030 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy, "tmp");
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001031 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001032 Arg0, CGF.getContext().getObjCIdType(),
1033 false, CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001034}
1035
1036CodeGen::RValue CGObjCMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001037 QualType ResultType,
1038 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001039 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001040 QualType Arg0Ty,
1041 bool IsSuper,
1042 const CallArgList &CallArgs) {
1043 CallArgList ActualArgs;
Daniel Dunbar46f45b92008-09-09 01:06:48 +00001044 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
1045 ActualArgs.push_back(std::make_pair(RValue::get(EmitSelector(CGF.Builder,
1046 Sel)),
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001047 CGF.getContext().getObjCSelType()));
1048 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001049
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001050 CodeGenTypes &Types = CGM.getTypes();
1051 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs);
1052 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo, false);
Daniel Dunbar5669e572008-10-17 03:24:53 +00001053
1054 llvm::Constant *Fn;
Daniel Dunbar88b53962009-02-02 22:03:45 +00001055 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Daniel Dunbar5669e572008-10-17 03:24:53 +00001056 Fn = ObjCTypes.getSendStretFn(IsSuper);
1057 } else if (ResultType->isFloatingType()) {
1058 // FIXME: Sadly, this is wrong. This actually depends on the
1059 // architecture. This happens to be right for x86-32 though.
1060 Fn = ObjCTypes.getSendFpretFn(IsSuper);
1061 } else {
1062 Fn = ObjCTypes.getSendFn(IsSuper);
1063 }
Daniel Dunbar62d5c1b2008-09-10 07:00:50 +00001064 Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy));
Daniel Dunbar88b53962009-02-02 22:03:45 +00001065 return CGF.EmitCall(FnInfo, Fn, ActualArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001066}
1067
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001068llvm::Value *CGObjCMac::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001069 const ObjCProtocolDecl *PD) {
Daniel Dunbarc67876d2008-09-04 04:33:15 +00001070 // FIXME: I don't understand why gcc generates this, or where it is
1071 // resolved. Investigate. Its also wasteful to look this up over and
1072 // over.
1073 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1074
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001075 return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
1076 ObjCTypes.ExternalProtocolPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001077}
1078
Fariborz Jahanianda320092009-01-29 19:24:30 +00001079void CGObjCCommonMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001080 // FIXME: We shouldn't need this, the protocol decl should contain
1081 // enough information to tell us whether this was a declaration or a
1082 // definition.
1083 DefinedProtocols.insert(PD->getIdentifier());
1084
1085 // If we have generated a forward reference to this protocol, emit
1086 // it now. Otherwise do nothing, the protocol objects are lazily
1087 // emitted.
1088 if (Protocols.count(PD->getIdentifier()))
1089 GetOrEmitProtocol(PD);
1090}
1091
Fariborz Jahanianda320092009-01-29 19:24:30 +00001092llvm::Constant *CGObjCCommonMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001093 if (DefinedProtocols.count(PD->getIdentifier()))
1094 return GetOrEmitProtocol(PD);
1095 return GetOrEmitProtocolRef(PD);
1096}
1097
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001098/*
1099 // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions
1100 struct _objc_protocol {
1101 struct _objc_protocol_extension *isa;
1102 char *protocol_name;
1103 struct _objc_protocol_list *protocol_list;
1104 struct _objc__method_prototype_list *instance_methods;
1105 struct _objc__method_prototype_list *class_methods
1106 };
1107
1108 See EmitProtocolExtension().
1109*/
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001110llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
1111 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1112
1113 // Early exit if a defining object has already been generated.
1114 if (Entry && Entry->hasInitializer())
1115 return Entry;
1116
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001117 // FIXME: I don't understand why gcc generates this, or where it is
1118 // resolved. Investigate. Its also wasteful to look this up over and
1119 // over.
1120 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1121
Chris Lattner8ec03f52008-11-24 03:54:41 +00001122 const char *ProtocolName = PD->getNameAsCString();
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001123
1124 // Construct method lists.
1125 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1126 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregor6ab35242009-04-09 21:40:53 +00001127 for (ObjCProtocolDecl::instmeth_iterator
1128 i = PD->instmeth_begin(CGM.getContext()),
1129 e = PD->instmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001130 ObjCMethodDecl *MD = *i;
1131 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1132 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1133 OptInstanceMethods.push_back(C);
1134 } else {
1135 InstanceMethods.push_back(C);
1136 }
1137 }
1138
Douglas Gregor6ab35242009-04-09 21:40:53 +00001139 for (ObjCProtocolDecl::classmeth_iterator
1140 i = PD->classmeth_begin(CGM.getContext()),
1141 e = PD->classmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001142 ObjCMethodDecl *MD = *i;
1143 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1144 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1145 OptClassMethods.push_back(C);
1146 } else {
1147 ClassMethods.push_back(C);
1148 }
1149 }
1150
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001151 std::vector<llvm::Constant*> Values(5);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001152 Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001153 Values[1] = GetClassName(PD->getIdentifier());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001154 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001155 EmitProtocolList("\01L_OBJC_PROTOCOL_REFS_" + PD->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001156 PD->protocol_begin(),
1157 PD->protocol_end());
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001158 Values[3] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001159 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_"
1160 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001161 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1162 InstanceMethods);
1163 Values[4] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001164 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_"
1165 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001166 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1167 ClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001168 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
1169 Values);
1170
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001171 if (Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001172 // Already created, fix the linkage and update the initializer.
1173 Entry->setLinkage(llvm::GlobalValue::InternalLinkage);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001174 Entry->setInitializer(Init);
1175 } else {
1176 Entry =
1177 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
1178 llvm::GlobalValue::InternalLinkage,
1179 Init,
1180 std::string("\01L_OBJC_PROTOCOL_")+ProtocolName,
1181 &CGM.getModule());
1182 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001183 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001184 UsedGlobals.push_back(Entry);
1185 // FIXME: Is this necessary? Why only for protocol?
1186 Entry->setAlignment(4);
1187 }
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001188
1189 return Entry;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001190}
1191
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001192llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001193 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1194
1195 if (!Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001196 // We use the initializer as a marker of whether this is a forward
1197 // reference or not. At module finalization we add the empty
1198 // contents for protocols which were referenced but never defined.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001199 Entry =
1200 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001201 llvm::GlobalValue::ExternalLinkage,
1202 0,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001203 "\01L_OBJC_PROTOCOL_" + PD->getNameAsString(),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001204 &CGM.getModule());
1205 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001206 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001207 UsedGlobals.push_back(Entry);
1208 // FIXME: Is this necessary? Why only for protocol?
1209 Entry->setAlignment(4);
1210 }
1211
1212 return Entry;
1213}
1214
1215/*
1216 struct _objc_protocol_extension {
1217 uint32_t size;
1218 struct objc_method_description_list *optional_instance_methods;
1219 struct objc_method_description_list *optional_class_methods;
1220 struct objc_property_list *instance_properties;
1221 };
1222*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001223llvm::Constant *
1224CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
1225 const ConstantVector &OptInstanceMethods,
1226 const ConstantVector &OptClassMethods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001227 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001228 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolExtensionTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001229 std::vector<llvm::Constant*> Values(4);
1230 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001231 Values[1] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001232 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_"
1233 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001234 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1235 OptInstanceMethods);
1236 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001237 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_"
1238 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001239 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1240 OptClassMethods);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001241 Values[3] = EmitPropertyList("\01L_OBJC_$_PROP_PROTO_LIST_" +
1242 PD->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001243 0, PD, ObjCTypes);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001244
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001245 // Return null if no extension bits are used.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001246 if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
1247 Values[3]->isNullValue())
1248 return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
1249
1250 llvm::Constant *Init =
1251 llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001252
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001253 // No special section, but goes in llvm.used
1254 return CreateMetadataVar("\01L_OBJC_PROTOCOLEXT_" + PD->getNameAsString(),
1255 Init,
1256 0, 0, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001257}
1258
1259/*
1260 struct objc_protocol_list {
1261 struct objc_protocol_list *next;
1262 long count;
1263 Protocol *list[];
1264 };
1265*/
Daniel Dunbardbc933702008-08-21 21:57:41 +00001266llvm::Constant *
1267CGObjCMac::EmitProtocolList(const std::string &Name,
1268 ObjCProtocolDecl::protocol_iterator begin,
1269 ObjCProtocolDecl::protocol_iterator end) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001270 std::vector<llvm::Constant*> ProtocolRefs;
1271
Daniel Dunbardbc933702008-08-21 21:57:41 +00001272 for (; begin != end; ++begin)
1273 ProtocolRefs.push_back(GetProtocolRef(*begin));
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001274
1275 // Just return null for empty protocol lists
1276 if (ProtocolRefs.empty())
1277 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1278
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001279 // This list is null terminated.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001280 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
1281
1282 std::vector<llvm::Constant*> Values(3);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001283 // This field is only used by the runtime.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001284 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1285 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
1286 Values[2] =
1287 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
1288 ProtocolRefs.size()),
1289 ProtocolRefs);
1290
1291 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1292 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001293 CreateMetadataVar(Name, Init, "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001294 4, false);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001295 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
1296}
1297
1298/*
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001299 struct _objc_property {
1300 const char * const name;
1301 const char * const attributes;
1302 };
1303
1304 struct _objc_property_list {
1305 uint32_t entsize; // sizeof (struct _objc_property)
1306 uint32_t prop_count;
1307 struct _objc_property[prop_count];
1308 };
1309*/
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001310llvm::Constant *CGObjCCommonMac::EmitPropertyList(const std::string &Name,
1311 const Decl *Container,
1312 const ObjCContainerDecl *OCD,
1313 const ObjCCommonTypesHelper &ObjCTypes) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001314 std::vector<llvm::Constant*> Properties, Prop(2);
Douglas Gregor6ab35242009-04-09 21:40:53 +00001315 for (ObjCContainerDecl::prop_iterator I = OCD->prop_begin(CGM.getContext()),
1316 E = OCD->prop_end(CGM.getContext()); I != E; ++I) {
Steve Naroff93983f82009-01-11 12:47:58 +00001317 const ObjCPropertyDecl *PD = *I;
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001318 Prop[0] = GetPropertyName(PD->getIdentifier());
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00001319 Prop[1] = GetPropertyTypeString(PD, Container);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001320 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
1321 Prop));
1322 }
1323
1324 // Return null for empty list.
1325 if (Properties.empty())
1326 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1327
1328 unsigned PropertySize =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001329 CGM.getTargetData().getTypePaddedSize(ObjCTypes.PropertyTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001330 std::vector<llvm::Constant*> Values(3);
1331 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
1332 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
1333 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
1334 Properties.size());
1335 Values[2] = llvm::ConstantArray::get(AT, Properties);
1336 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1337
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001338 llvm::GlobalVariable *GV =
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001339 CreateMetadataVar(Name, Init,
1340 (ObjCABI == 2) ? "__DATA, __objc_const" :
1341 "__OBJC,__property,regular,no_dead_strip",
1342 (ObjCABI == 2) ? 8 : 4,
1343 true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001344 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.PropertyListPtrTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001345}
1346
1347/*
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001348 struct objc_method_description_list {
1349 int count;
1350 struct objc_method_description list[];
1351 };
1352*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001353llvm::Constant *
1354CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
1355 std::vector<llvm::Constant*> Desc(2);
1356 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1357 ObjCTypes.SelectorPtrTy);
1358 Desc[1] = GetMethodVarType(MD);
1359 return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
1360 Desc);
1361}
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001362
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001363llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name,
1364 const char *Section,
1365 const ConstantVector &Methods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001366 // Return null for empty list.
1367 if (Methods.empty())
1368 return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
1369
1370 std::vector<llvm::Constant*> Values(2);
1371 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1372 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
1373 Methods.size());
1374 Values[1] = llvm::ConstantArray::get(AT, Methods);
1375 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1376
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001377 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001378 return llvm::ConstantExpr::getBitCast(GV,
1379 ObjCTypes.MethodDescriptionListPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001380}
1381
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001382/*
1383 struct _objc_category {
1384 char *category_name;
1385 char *class_name;
1386 struct _objc_method_list *instance_methods;
1387 struct _objc_method_list *class_methods;
1388 struct _objc_protocol_list *protocols;
1389 uint32_t size; // <rdar://4585769>
1390 struct _objc_property_list *instance_properties;
1391 };
1392 */
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001393void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001394 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.CategoryTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001395
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001396 // FIXME: This is poor design, the OCD should have a pointer to the
1397 // category decl. Additionally, note that Category can be null for
1398 // the @implementation w/o an @interface case. Sema should just
1399 // create one for us as it does for @implementation so everyone else
1400 // can live life under a clear blue sky.
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001401 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001402 const ObjCCategoryDecl *Category =
1403 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001404 std::string ExtName(Interface->getNameAsString() + "_" +
1405 OCD->getNameAsString());
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001406
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001407 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1408 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
1409 e = OCD->instmeth_end(); i != e; ++i) {
1410 // Instance methods should always be defined.
1411 InstanceMethods.push_back(GetMethodConstant(*i));
1412 }
1413 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
1414 e = OCD->classmeth_end(); i != e; ++i) {
1415 // Class methods should always be defined.
1416 ClassMethods.push_back(GetMethodConstant(*i));
1417 }
1418
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001419 std::vector<llvm::Constant*> Values(7);
1420 Values[0] = GetClassName(OCD->getIdentifier());
1421 Values[1] = GetClassName(Interface->getIdentifier());
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001422 Values[2] =
1423 EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") +
1424 ExtName,
1425 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001426 InstanceMethods);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001427 Values[3] =
1428 EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName,
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001429 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001430 ClassMethods);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001431 if (Category) {
1432 Values[4] =
1433 EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName,
1434 Category->protocol_begin(),
1435 Category->protocol_end());
1436 } else {
1437 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1438 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001439 Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001440
1441 // If there is no category @interface then there can be no properties.
1442 if (Category) {
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001443 Values[6] = EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001444 OCD, Category, ObjCTypes);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001445 } else {
1446 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1447 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001448
1449 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
1450 Values);
1451
1452 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001453 CreateMetadataVar(std::string("\01L_OBJC_CATEGORY_")+ExtName, Init,
1454 "__OBJC,__category,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001455 4, true);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001456 DefinedCategories.push_back(GV);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001457}
1458
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001459// FIXME: Get from somewhere?
1460enum ClassFlags {
1461 eClassFlags_Factory = 0x00001,
1462 eClassFlags_Meta = 0x00002,
1463 // <rdr://5142207>
1464 eClassFlags_HasCXXStructors = 0x02000,
1465 eClassFlags_Hidden = 0x20000,
1466 eClassFlags_ABI2_Hidden = 0x00010,
1467 eClassFlags_ABI2_HasCXXStructors = 0x00004 // <rdr://4923634>
1468};
1469
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001470/*
1471 struct _objc_class {
1472 Class isa;
1473 Class super_class;
1474 const char *name;
1475 long version;
1476 long info;
1477 long instance_size;
1478 struct _objc_ivar_list *ivars;
1479 struct _objc_method_list *methods;
1480 struct _objc_cache *cache;
1481 struct _objc_protocol_list *protocols;
1482 // Objective-C 1.0 extensions (<rdr://4585769>)
1483 const char *ivar_layout;
1484 struct _objc_class_ext *ext;
1485 };
1486
1487 See EmitClassExtension();
1488 */
1489void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001490 DefinedSymbols.insert(ID->getIdentifier());
1491
Chris Lattner8ec03f52008-11-24 03:54:41 +00001492 std::string ClassName = ID->getNameAsString();
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001493 // FIXME: Gross
1494 ObjCInterfaceDecl *Interface =
1495 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001496 llvm::Constant *Protocols =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001497 EmitProtocolList("\01L_OBJC_CLASS_PROTOCOLS_" + ID->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001498 Interface->protocol_begin(),
1499 Interface->protocol_end());
Chris Lattnerb7b58b12009-04-19 06:02:28 +00001500 const llvm::Type *InterfaceTy;
1501 if (Interface->isForwardDecl())
1502 InterfaceTy = llvm::StructType::get(NULL, NULL);
1503 else
1504 InterfaceTy =
Chris Lattner03d9f342009-04-01 06:23:52 +00001505 CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(Interface));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001506 unsigned Flags = eClassFlags_Factory;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001507 unsigned Size = CGM.getTargetData().getTypePaddedSize(InterfaceTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001508
1509 // FIXME: Set CXX-structors flag.
Daniel Dunbar04d40782009-04-14 06:00:08 +00001510 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001511 Flags |= eClassFlags_Hidden;
1512
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001513 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1514 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
1515 e = ID->instmeth_end(); i != e; ++i) {
1516 // Instance methods should always be defined.
1517 InstanceMethods.push_back(GetMethodConstant(*i));
1518 }
1519 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
1520 e = ID->classmeth_end(); i != e; ++i) {
1521 // Class methods should always be defined.
1522 ClassMethods.push_back(GetMethodConstant(*i));
1523 }
1524
1525 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
1526 e = ID->propimpl_end(); i != e; ++i) {
1527 ObjCPropertyImplDecl *PID = *i;
1528
1529 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1530 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1531
1532 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
1533 if (llvm::Constant *C = GetMethodConstant(MD))
1534 InstanceMethods.push_back(C);
1535 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
1536 if (llvm::Constant *C = GetMethodConstant(MD))
1537 InstanceMethods.push_back(C);
1538 }
1539 }
1540
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001541 std::vector<llvm::Constant*> Values(12);
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001542 Values[ 0] = EmitMetaClass(ID, Protocols, InterfaceTy, ClassMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001543 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001544 // Record a reference to the super class.
1545 LazySymbols.insert(Super->getIdentifier());
1546
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001547 Values[ 1] =
1548 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1549 ObjCTypes.ClassPtrTy);
1550 } else {
1551 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1552 }
1553 Values[ 2] = GetClassName(ID->getIdentifier());
1554 // Version is always 0.
1555 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1556 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1557 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001558 Values[ 6] = EmitIvarList(ID, false);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001559 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001560 EmitMethodList("\01L_OBJC_INSTANCE_METHODS_" + ID->getNameAsString(),
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001561 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001562 InstanceMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001563 // cache is always NULL.
1564 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1565 Values[ 9] = Protocols;
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001566 // FIXME: Set ivar_layout
Fariborz Jahanian667423a2009-03-25 22:36:49 +00001567 // Values[10] = BuildIvarLayout(ID, true);
1568 Values[10] = GetIvarLayoutName(0, ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001569 Values[11] = EmitClassExtension(ID);
1570 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1571 Values);
1572
1573 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001574 CreateMetadataVar(std::string("\01L_OBJC_CLASS_")+ClassName, Init,
1575 "__OBJC,__class,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001576 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001577 DefinedClasses.push_back(GV);
1578}
1579
1580llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
1581 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001582 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001583 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001584 unsigned Flags = eClassFlags_Meta;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001585 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001586
Daniel Dunbar04d40782009-04-14 06:00:08 +00001587 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001588 Flags |= eClassFlags_Hidden;
1589
1590 std::vector<llvm::Constant*> Values(12);
1591 // The isa for the metaclass is the root of the hierarchy.
1592 const ObjCInterfaceDecl *Root = ID->getClassInterface();
1593 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
1594 Root = Super;
1595 Values[ 0] =
1596 llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
1597 ObjCTypes.ClassPtrTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001598 // The super class for the metaclass is emitted as the name of the
1599 // super class. The runtime fixes this up to point to the
1600 // *metaclass* for the super class.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001601 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
1602 Values[ 1] =
1603 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1604 ObjCTypes.ClassPtrTy);
1605 } else {
1606 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1607 }
1608 Values[ 2] = GetClassName(ID->getIdentifier());
1609 // Version is always 0.
1610 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1611 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1612 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001613 Values[ 6] = EmitIvarList(ID, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001614 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001615 EmitMethodList("\01L_OBJC_CLASS_METHODS_" + ID->getNameAsString(),
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001616 "__OBJC,__cls_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001617 Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001618 // cache is always NULL.
1619 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1620 Values[ 9] = Protocols;
1621 // ivar_layout for metaclass is always NULL.
1622 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1623 // The class extension is always unused for metaclasses.
1624 Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1625 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1626 Values);
1627
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001628 std::string Name("\01L_OBJC_METACLASS_");
Chris Lattner8ec03f52008-11-24 03:54:41 +00001629 Name += ID->getNameAsCString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001630
1631 // Check for a forward reference.
1632 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
1633 if (GV) {
1634 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1635 "Forward metaclass reference has incorrect type.");
1636 GV->setLinkage(llvm::GlobalValue::InternalLinkage);
1637 GV->setInitializer(Init);
1638 } else {
1639 GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1640 llvm::GlobalValue::InternalLinkage,
1641 Init, Name,
1642 &CGM.getModule());
1643 }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001644 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001645 GV->setAlignment(4);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001646 UsedGlobals.push_back(GV);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001647
1648 return GV;
1649}
1650
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001651llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001652 std::string Name = "\01L_OBJC_METACLASS_" + ID->getNameAsString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001653
1654 // FIXME: Should we look these up somewhere other than the
1655 // module. Its a bit silly since we only generate these while
1656 // processing an implementation, so exactly one pointer would work
1657 // if know when we entered/exitted an implementation block.
1658
1659 // Check for an existing forward reference.
Fariborz Jahanianb0d27942009-01-07 20:11:22 +00001660 // Previously, metaclass with internal linkage may have been defined.
1661 // pass 'true' as 2nd argument so it is returned.
1662 if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true)) {
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001663 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1664 "Forward metaclass reference has incorrect type.");
1665 return GV;
1666 } else {
1667 // Generate as an external reference to keep a consistent
1668 // module. This will be patched up when we emit the metaclass.
1669 return new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1670 llvm::GlobalValue::ExternalLinkage,
1671 0,
1672 Name,
1673 &CGM.getModule());
1674 }
1675}
1676
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001677/*
1678 struct objc_class_ext {
1679 uint32_t size;
1680 const char *weak_ivar_layout;
1681 struct _objc_property_list *properties;
1682 };
1683*/
1684llvm::Constant *
1685CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
1686 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001687 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassExtensionTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001688
1689 std::vector<llvm::Constant*> Values(3);
1690 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001691 // FIXME: Output weak_ivar_layout string.
Fariborz Jahanian667423a2009-03-25 22:36:49 +00001692 // Values[1] = BuildIvarLayout(ID, false);
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00001693 Values[1] = GetIvarLayoutName(0, ObjCTypes);
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001694 Values[2] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001695 ID, ID->getClassInterface(), ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001696
1697 // Return null if no extension bits are used.
1698 if (Values[1]->isNullValue() && Values[2]->isNullValue())
1699 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1700
1701 llvm::Constant *Init =
1702 llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001703 return CreateMetadataVar("\01L_OBJC_CLASSEXT_" + ID->getNameAsString(),
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001704 Init, "__OBJC,__class_ext,regular,no_dead_strip",
1705 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001706}
1707
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001708/// countInheritedIvars - count number of ivars in class and its super class(s)
1709///
Douglas Gregor6ab35242009-04-09 21:40:53 +00001710static int countInheritedIvars(const ObjCInterfaceDecl *OI,
1711 ASTContext &Context) {
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001712 int count = 0;
1713 if (!OI)
1714 return 0;
1715 const ObjCInterfaceDecl *SuperClass = OI->getSuperClass();
1716 if (SuperClass)
Douglas Gregor6ab35242009-04-09 21:40:53 +00001717 count += countInheritedIvars(SuperClass, Context);
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001718 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1719 E = OI->ivar_end(); I != E; ++I)
1720 ++count;
Fariborz Jahanian18191882009-03-31 18:11:23 +00001721 // look into properties.
Douglas Gregor6ab35242009-04-09 21:40:53 +00001722 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(Context),
1723 E = OI->prop_end(Context); I != E; ++I) {
Fariborz Jahanian18191882009-03-31 18:11:23 +00001724 if ((*I)->getPropertyIvarDecl())
1725 ++count;
1726 }
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001727 return count;
1728}
1729
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001730/// getInterfaceDeclForIvar - Get the interface declaration node where
1731/// this ivar is declared in.
1732/// FIXME. Ideally, this info should be in the ivar node. But currently
1733/// it is not and prevailing wisdom is that ASTs should not have more
1734/// info than is absolutely needed, even though this info reflects the
1735/// source language.
1736///
1737static const ObjCInterfaceDecl *getInterfaceDeclForIvar(
1738 const ObjCInterfaceDecl *OI,
Douglas Gregor6ab35242009-04-09 21:40:53 +00001739 const ObjCIvarDecl *IVD,
1740 ASTContext &Context) {
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001741 if (!OI)
1742 return 0;
1743 assert(isa<ObjCInterfaceDecl>(OI) && "OI is not an interface");
1744 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1745 E = OI->ivar_end(); I != E; ++I)
1746 if ((*I)->getIdentifier() == IVD->getIdentifier())
1747 return OI;
Fariborz Jahanian5a4b4532009-03-31 17:00:52 +00001748 // look into properties.
Douglas Gregor6ab35242009-04-09 21:40:53 +00001749 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(Context),
1750 E = OI->prop_end(Context); I != E; ++I) {
Fariborz Jahanian5a4b4532009-03-31 17:00:52 +00001751 ObjCPropertyDecl *PDecl = (*I);
1752 if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl())
1753 if (IV->getIdentifier() == IVD->getIdentifier())
1754 return OI;
1755 }
Douglas Gregor6ab35242009-04-09 21:40:53 +00001756 return getInterfaceDeclForIvar(OI->getSuperClass(), IVD, Context);
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001757}
1758
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001759/*
1760 struct objc_ivar {
1761 char *ivar_name;
1762 char *ivar_type;
1763 int ivar_offset;
1764 };
1765
1766 struct objc_ivar_list {
1767 int ivar_count;
1768 struct objc_ivar list[count];
1769 };
1770 */
1771llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001772 bool ForClass) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001773 std::vector<llvm::Constant*> Ivars, Ivar(3);
1774
1775 // When emitting the root class GCC emits ivar entries for the
1776 // actual class structure. It is not clear if we need to follow this
1777 // behavior; for now lets try and get away with not doing it. If so,
1778 // the cleanest solution would be to make up an ObjCInterfaceDecl
1779 // for the class.
1780 if (ForClass)
1781 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001782
1783 ObjCInterfaceDecl *OID =
1784 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00001785 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001786
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00001787 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
1788 GetNamedIvarList(OID, OIvars);
1789
1790 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
1791 ObjCIvarDecl *IVD = OIvars[i];
1792 const FieldDecl *Field = OID->lookupFieldDeclForIvar(CGM.getContext(), IVD);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00001793 uint64_t Offset = GetIvarBaseOffset(Layout, Field);
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00001794 Ivar[0] = GetMethodVarName(Field->getIdentifier());
Devang Patel7794bb82009-03-04 18:21:39 +00001795 Ivar[1] = GetMethodVarType(Field);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001796 Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy, Offset);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001797 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001798 }
1799
1800 // Return null for empty list.
1801 if (Ivars.empty())
1802 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
1803
1804 std::vector<llvm::Constant*> Values(2);
1805 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
1806 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
1807 Ivars.size());
1808 Values[1] = llvm::ConstantArray::get(AT, Ivars);
1809 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1810
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001811 llvm::GlobalVariable *GV;
1812 if (ForClass)
1813 GV = CreateMetadataVar("\01L_OBJC_CLASS_VARIABLES_" + ID->getNameAsString(),
Daniel Dunbar58a29122009-03-09 22:18:41 +00001814 Init, "__OBJC,__class_vars,regular,no_dead_strip",
1815 4, true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001816 else
1817 GV = CreateMetadataVar("\01L_OBJC_INSTANCE_VARIABLES_"
1818 + ID->getNameAsString(),
1819 Init, "__OBJC,__instance_vars,regular,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001820 4, true);
1821 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.IvarListPtrTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001822}
1823
1824/*
1825 struct objc_method {
1826 SEL method_name;
1827 char *method_types;
1828 void *method;
1829 };
1830
1831 struct objc_method_list {
1832 struct objc_method_list *obsolete;
1833 int count;
1834 struct objc_method methods_list[count];
1835 };
1836*/
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001837
1838/// GetMethodConstant - Return a struct objc_method constant for the
1839/// given method if it has been defined. The result is null if the
1840/// method has not been defined. The return value has type MethodPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001841llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001842 // FIXME: Use DenseMap::lookup
1843 llvm::Function *Fn = MethodDefinitions[MD];
1844 if (!Fn)
1845 return 0;
1846
1847 std::vector<llvm::Constant*> Method(3);
1848 Method[0] =
1849 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1850 ObjCTypes.SelectorPtrTy);
1851 Method[1] = GetMethodVarType(MD);
1852 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
1853 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
1854}
1855
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001856llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name,
1857 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001858 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001859 // Return null for empty list.
1860 if (Methods.empty())
1861 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
1862
1863 std::vector<llvm::Constant*> Values(3);
1864 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1865 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1866 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
1867 Methods.size());
1868 Values[2] = llvm::ConstantArray::get(AT, Methods);
1869 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1870
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001871 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001872 return llvm::ConstantExpr::getBitCast(GV,
1873 ObjCTypes.MethodListPtrTy);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001874}
1875
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001876llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD,
Daniel Dunbarbb36d332009-02-02 21:43:58 +00001877 const ObjCContainerDecl *CD) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001878 std::string Name;
Fariborz Jahanian679a5022009-01-10 21:06:09 +00001879 GetNameForMethod(OMD, CD, Name);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001880
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001881 CodeGenTypes &Types = CGM.getTypes();
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001882 const llvm::FunctionType *MethodTy =
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001883 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001884 llvm::Function *Method =
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001885 llvm::Function::Create(MethodTy,
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001886 llvm::GlobalValue::InternalLinkage,
1887 Name,
1888 &CGM.getModule());
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001889 MethodDefinitions.insert(std::make_pair(OMD, Method));
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001890
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001891 return Method;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001892}
1893
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00001894uint64_t CGObjCCommonMac::GetIvarBaseOffset(const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +00001895 const FieldDecl *Field) {
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00001896 if (!Field->isBitField())
Daniel Dunbar48fa0642009-04-19 02:03:42 +00001897 return Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(Field));
1898
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00001899 // FIXME. Must be a better way of getting a bitfield base offset.
Daniel Dunbar48fa0642009-04-19 02:03:42 +00001900 CodeGenTypes::BitFieldInfo BFI = CGM.getTypes().getBitFieldInfo(Field);
1901 // FIXME: The "field no" for bitfields is something completely
1902 // different; it is the offset in multiples of the base type size!
1903 uint64_t Offset = CGM.getTypes().getLLVMFieldNo(Field);
1904 const llvm::Type *Ty =
1905 CGM.getTypes().ConvertTypeForMemRecursive(Field->getType());
1906 Offset *= CGM.getTypes().getTargetData().getTypePaddedSizeInBits(Ty);
1907 return (Offset + BFI.Begin) / 8;
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00001908}
1909
Daniel Dunbar48fa0642009-04-19 02:03:42 +00001910/// GetFieldBaseOffset - return the field's byte offset.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00001911uint64_t CGObjCCommonMac::GetFieldBaseOffset(const ObjCInterfaceDecl *OI,
1912 const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +00001913 const FieldDecl *Field) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00001914 const ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
Chris Lattnercd0ee142009-03-31 08:33:16 +00001915 const FieldDecl *FD = OI->lookupFieldDeclForIvar(CGM.getContext(), Ivar);
1916 return GetIvarBaseOffset(Layout, FD);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00001917}
1918
Daniel Dunbarfd65d372009-03-09 20:09:19 +00001919llvm::GlobalVariable *
1920CGObjCCommonMac::CreateMetadataVar(const std::string &Name,
1921 llvm::Constant *Init,
1922 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +00001923 unsigned Align,
1924 bool AddToUsed) {
Daniel Dunbarfd65d372009-03-09 20:09:19 +00001925 const llvm::Type *Ty = Init->getType();
1926 llvm::GlobalVariable *GV =
1927 new llvm::GlobalVariable(Ty, false,
1928 llvm::GlobalValue::InternalLinkage,
1929 Init,
1930 Name,
1931 &CGM.getModule());
1932 if (Section)
1933 GV->setSection(Section);
Daniel Dunbar35bd7632009-03-09 20:50:13 +00001934 if (Align)
1935 GV->setAlignment(Align);
1936 if (AddToUsed)
Daniel Dunbarfd65d372009-03-09 20:09:19 +00001937 UsedGlobals.push_back(GV);
1938 return GV;
1939}
1940
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001941llvm::Function *CGObjCMac::ModuleInitFunction() {
Daniel Dunbarf77ac862008-08-11 21:35:06 +00001942 // Abuse this interface function as a place to finalize.
1943 FinishModule();
1944
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001945 return NULL;
1946}
1947
Chris Lattner74391b42009-03-22 21:03:39 +00001948llvm::Constant *CGObjCMac::GetPropertyGetFunction() {
Daniel Dunbar49f66022008-09-24 03:38:44 +00001949 return ObjCTypes.GetPropertyFn;
1950}
1951
Chris Lattner74391b42009-03-22 21:03:39 +00001952llvm::Constant *CGObjCMac::GetPropertySetFunction() {
Daniel Dunbar49f66022008-09-24 03:38:44 +00001953 return ObjCTypes.SetPropertyFn;
1954}
1955
Chris Lattner74391b42009-03-22 21:03:39 +00001956llvm::Constant *CGObjCMac::EnumerationMutationFunction() {
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001957 return ObjCTypes.EnumerationMutationFn;
1958}
1959
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001960/*
1961
1962Objective-C setjmp-longjmp (sjlj) Exception Handling
1963--
1964
1965The basic framework for a @try-catch-finally is as follows:
1966{
1967 objc_exception_data d;
1968 id _rethrow = null;
Anders Carlsson190d00e2009-02-07 21:26:04 +00001969 bool _call_try_exit = true;
1970
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001971 objc_exception_try_enter(&d);
1972 if (!setjmp(d.jmp_buf)) {
1973 ... try body ...
1974 } else {
1975 // exception path
1976 id _caught = objc_exception_extract(&d);
1977
1978 // enter new try scope for handlers
1979 if (!setjmp(d.jmp_buf)) {
1980 ... match exception and execute catch blocks ...
1981
1982 // fell off end, rethrow.
1983 _rethrow = _caught;
Daniel Dunbar898d5082008-09-30 01:06:03 +00001984 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001985 } else {
1986 // exception in catch block
1987 _rethrow = objc_exception_extract(&d);
Anders Carlsson190d00e2009-02-07 21:26:04 +00001988 _call_try_exit = false;
1989 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001990 }
1991 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00001992 ... jump-through-finally to finally_end ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001993
1994finally:
Anders Carlsson190d00e2009-02-07 21:26:04 +00001995 if (_call_try_exit)
1996 objc_exception_try_exit(&d);
1997
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001998 ... finally block ....
Daniel Dunbar898d5082008-09-30 01:06:03 +00001999 ... dispatch to finally destination ...
2000
2001finally_rethrow:
2002 objc_exception_throw(_rethrow);
2003
2004finally_end:
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002005}
2006
2007This framework differs slightly from the one gcc uses, in that gcc
Daniel Dunbar898d5082008-09-30 01:06:03 +00002008uses _rethrow to determine if objc_exception_try_exit should be called
2009and if the object should be rethrown. This breaks in the face of
2010throwing nil and introduces unnecessary branches.
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002011
2012We specialize this framework for a few particular circumstances:
2013
2014 - If there are no catch blocks, then we avoid emitting the second
2015 exception handling context.
2016
2017 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
2018 e)) we avoid emitting the code to rethrow an uncaught exception.
2019
2020 - FIXME: If there is no @finally block we can do a few more
2021 simplifications.
2022
2023Rethrows and Jumps-Through-Finally
2024--
2025
2026Support for implicit rethrows and jumping through the finally block is
2027handled by storing the current exception-handling context in
2028ObjCEHStack.
2029
Daniel Dunbar898d5082008-09-30 01:06:03 +00002030In order to implement proper @finally semantics, we support one basic
2031mechanism for jumping through the finally block to an arbitrary
2032destination. Constructs which generate exits from a @try or @catch
2033block use this mechanism to implement the proper semantics by chaining
2034jumps, as necessary.
2035
2036This mechanism works like the one used for indirect goto: we
2037arbitrarily assign an ID to each destination and store the ID for the
2038destination in a variable prior to entering the finally block. At the
2039end of the finally block we simply create a switch to the proper
2040destination.
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002041
2042Code gen for @synchronized(expr) stmt;
2043Effectively generating code for:
2044objc_sync_enter(expr);
2045@try stmt @finally { objc_sync_exit(expr); }
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002046*/
2047
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002048void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
2049 const Stmt &S) {
2050 bool isTry = isa<ObjCAtTryStmt>(S);
Daniel Dunbar898d5082008-09-30 01:06:03 +00002051 // Create various blocks we refer to for handling @finally.
Daniel Dunbar55e87422008-11-11 02:29:29 +00002052 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002053 llvm::BasicBlock *FinallyExit = CGF.createBasicBlock("finally.exit");
Daniel Dunbar55e87422008-11-11 02:29:29 +00002054 llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
2055 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
2056 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
Daniel Dunbar1c566672009-02-24 01:43:46 +00002057
2058 // For @synchronized, call objc_sync_enter(sync.expr). The
2059 // evaluation of the expression must occur before we enter the
2060 // @synchronized. We can safely avoid a temp here because jumps into
2061 // @synchronized are illegal & this will dominate uses.
2062 llvm::Value *SyncArg = 0;
2063 if (!isTry) {
2064 SyncArg =
2065 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
2066 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00002067 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar1c566672009-02-24 01:43:46 +00002068 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00002069
2070 // Push an EH context entry, used for handling rethrows and jumps
2071 // through finally.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002072 CGF.PushCleanupBlock(FinallyBlock);
2073
Anders Carlsson273558f2009-02-07 21:37:21 +00002074 CGF.ObjCEHValueStack.push_back(0);
2075
Daniel Dunbar898d5082008-09-30 01:06:03 +00002076 // Allocate memory for the exception data and rethrow pointer.
Anders Carlsson80f25672008-09-09 17:59:25 +00002077 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
2078 "exceptiondata.ptr");
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002079 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
2080 "_rethrow");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002081 llvm::Value *CallTryExitPtr = CGF.CreateTempAlloca(llvm::Type::Int1Ty,
2082 "_call_try_exit");
2083 CGF.Builder.CreateStore(llvm::ConstantInt::getTrue(), CallTryExitPtr);
2084
Anders Carlsson80f25672008-09-09 17:59:25 +00002085 // Enter a new try block and call setjmp.
2086 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
2087 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
2088 "jmpbufarray");
2089 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
2090 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
2091 JmpBufPtr, "result");
Daniel Dunbar898d5082008-09-30 01:06:03 +00002092
Daniel Dunbar55e87422008-11-11 02:29:29 +00002093 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
2094 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002095 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002096 TryHandler, TryBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002097
2098 // Emit the @try block.
2099 CGF.EmitBlock(TryBlock);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002100 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
2101 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002102 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002103
2104 // Emit the "exception in @try" block.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002105 CGF.EmitBlock(TryHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002106
2107 // Retrieve the exception object. We may emit multiple blocks but
2108 // nothing can cross this so the value is already in SSA form.
2109 llvm::Value *Caught = CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
2110 ExceptionData,
2111 "caught");
Anders Carlsson273558f2009-02-07 21:37:21 +00002112 CGF.ObjCEHValueStack.back() = Caught;
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002113 if (!isTry)
2114 {
2115 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002116 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002117 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002118 }
2119 else if (const ObjCAtCatchStmt* CatchStmt =
2120 cast<ObjCAtTryStmt>(S).getCatchStmts())
2121 {
Daniel Dunbar55e40722008-09-27 07:03:52 +00002122 // Enter a new exception try block (in case a @catch block throws
2123 // an exception).
Anders Carlsson80f25672008-09-09 17:59:25 +00002124 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002125
Anders Carlsson80f25672008-09-09 17:59:25 +00002126 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
2127 JmpBufPtr, "result");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002128 llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw");
Anders Carlsson80f25672008-09-09 17:59:25 +00002129
Daniel Dunbar55e87422008-11-11 02:29:29 +00002130 llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch");
2131 llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler");
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002132 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002133
2134 CGF.EmitBlock(CatchBlock);
2135
Daniel Dunbar55e40722008-09-27 07:03:52 +00002136 // Handle catch list. As a special case we check if everything is
2137 // matched and avoid generating code for falling off the end if
2138 // so.
2139 bool AllMatched = false;
Anders Carlsson80f25672008-09-09 17:59:25 +00002140 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbar55e87422008-11-11 02:29:29 +00002141 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch");
Anders Carlsson80f25672008-09-09 17:59:25 +00002142
Steve Naroff7ba138a2009-03-03 19:52:17 +00002143 const ParmVarDecl *CatchParam = CatchStmt->getCatchParamDecl();
Daniel Dunbar129271a2008-09-27 07:36:24 +00002144 const PointerType *PT = 0;
2145
Anders Carlsson80f25672008-09-09 17:59:25 +00002146 // catch(...) always matches.
Daniel Dunbar55e40722008-09-27 07:03:52 +00002147 if (!CatchParam) {
2148 AllMatched = true;
2149 } else {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002150 PT = CatchParam->getType()->getAsPointerType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002151
Daniel Dunbar97f61d12008-09-27 22:21:14 +00002152 // catch(id e) always matches.
2153 // FIXME: For the time being we also match id<X>; this should
2154 // be rejected by Sema instead.
Steve Naroff389bf462009-02-12 17:52:19 +00002155 if ((PT && CGF.getContext().isObjCIdStructType(PT->getPointeeType())) ||
Steve Naroff7ba138a2009-03-03 19:52:17 +00002156 CatchParam->getType()->isObjCQualifiedIdType())
Daniel Dunbar55e40722008-09-27 07:03:52 +00002157 AllMatched = true;
Anders Carlsson80f25672008-09-09 17:59:25 +00002158 }
2159
Daniel Dunbar55e40722008-09-27 07:03:52 +00002160 if (AllMatched) {
Anders Carlssondde0a942008-09-11 09:15:33 +00002161 if (CatchParam) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002162 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002163 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002164 CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002165 }
Anders Carlsson1452f552008-09-11 08:21:54 +00002166
Anders Carlssondde0a942008-09-11 09:15:33 +00002167 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002168 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002169 break;
2170 }
2171
Daniel Dunbar129271a2008-09-27 07:36:24 +00002172 assert(PT && "Unexpected non-pointer type in @catch");
2173 QualType T = PT->getPointeeType();
Anders Carlsson4b7ff6e2008-09-11 06:35:14 +00002174 const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002175 assert(ObjCType && "Catch parameter must have Objective-C type!");
2176
2177 // Check if the @catch block matches the exception object.
2178 llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl());
2179
Anders Carlsson80f25672008-09-09 17:59:25 +00002180 llvm::Value *Match = CGF.Builder.CreateCall2(ObjCTypes.ExceptionMatchFn,
2181 Class, Caught, "match");
Anders Carlsson80f25672008-09-09 17:59:25 +00002182
Daniel Dunbar55e87422008-11-11 02:29:29 +00002183 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched");
Anders Carlsson80f25672008-09-09 17:59:25 +00002184
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002185 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002186 MatchedBlock, NextCatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002187
2188 // Emit the @catch block.
2189 CGF.EmitBlock(MatchedBlock);
Steve Naroff7ba138a2009-03-03 19:52:17 +00002190 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002191 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002192
2193 llvm::Value *Tmp =
Steve Naroff7ba138a2009-03-03 19:52:17 +00002194 CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(CatchParam->getType()),
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002195 "tmp");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002196 CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002197
2198 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002199 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002200
2201 CGF.EmitBlock(NextCatchBlock);
2202 }
2203
Daniel Dunbar55e40722008-09-27 07:03:52 +00002204 if (!AllMatched) {
2205 // None of the handlers caught the exception, so store it to be
2206 // rethrown at the end of the @finally block.
2207 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002208 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002209 }
2210
2211 // Emit the exception handler for the @catch blocks.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002212 CGF.EmitBlock(CatchHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002213 CGF.Builder.CreateStore(CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
2214 ExceptionData),
2215 RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002216 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002217 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002218 } else {
Anders Carlsson80f25672008-09-09 17:59:25 +00002219 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002220 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002221 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Anders Carlsson80f25672008-09-09 17:59:25 +00002222 }
2223
Daniel Dunbar898d5082008-09-30 01:06:03 +00002224 // Pop the exception-handling stack entry. It is important to do
2225 // this now, because the code in the @finally block is not in this
2226 // context.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002227 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
2228
Anders Carlsson273558f2009-02-07 21:37:21 +00002229 CGF.ObjCEHValueStack.pop_back();
2230
Anders Carlsson80f25672008-09-09 17:59:25 +00002231 // Emit the @finally block.
2232 CGF.EmitBlock(FinallyBlock);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002233 llvm::Value* CallTryExit = CGF.Builder.CreateLoad(CallTryExitPtr, "tmp");
2234
2235 CGF.Builder.CreateCondBr(CallTryExit, FinallyExit, FinallyNoExit);
2236
2237 CGF.EmitBlock(FinallyExit);
Anders Carlsson80f25672008-09-09 17:59:25 +00002238 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryExitFn, ExceptionData);
Daniel Dunbar129271a2008-09-27 07:36:24 +00002239
2240 CGF.EmitBlock(FinallyNoExit);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002241 if (isTry) {
2242 if (const ObjCAtFinallyStmt* FinallyStmt =
2243 cast<ObjCAtTryStmt>(S).getFinallyStmt())
2244 CGF.EmitStmt(FinallyStmt->getFinallyBody());
Daniel Dunbar1c566672009-02-24 01:43:46 +00002245 } else {
2246 // Emit objc_sync_exit(expr); as finally's sole statement for
2247 // @synchronized.
2248 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, SyncArg);
Fariborz Jahanianf2878e52008-11-21 19:21:53 +00002249 }
Anders Carlsson80f25672008-09-09 17:59:25 +00002250
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002251 // Emit the switch block
2252 if (Info.SwitchBlock)
2253 CGF.EmitBlock(Info.SwitchBlock);
2254 if (Info.EndBlock)
2255 CGF.EmitBlock(Info.EndBlock);
2256
Daniel Dunbar898d5082008-09-30 01:06:03 +00002257 CGF.EmitBlock(FinallyRethrow);
2258 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn,
2259 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002260 CGF.Builder.CreateUnreachable();
Daniel Dunbar898d5082008-09-30 01:06:03 +00002261
2262 CGF.EmitBlock(FinallyEnd);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002263}
2264
2265void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar898d5082008-09-30 01:06:03 +00002266 const ObjCAtThrowStmt &S) {
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002267 llvm::Value *ExceptionAsObject;
2268
2269 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2270 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
2271 ExceptionAsObject =
2272 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
2273 } else {
Anders Carlsson273558f2009-02-07 21:37:21 +00002274 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002275 "Unexpected rethrow outside @catch block.");
Anders Carlsson273558f2009-02-07 21:37:21 +00002276 ExceptionAsObject = CGF.ObjCEHValueStack.back();
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002277 }
2278
2279 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
Anders Carlsson80f25672008-09-09 17:59:25 +00002280 CGF.Builder.CreateUnreachable();
Daniel Dunbara448fb22008-11-11 23:11:34 +00002281
2282 // Clear the insertion point to indicate we are in unreachable code.
2283 CGF.Builder.ClearInsertionPoint();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002284}
2285
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002286/// EmitObjCWeakRead - Code gen for loading value of a __weak
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002287/// object: objc_read_weak (id *src)
2288///
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002289llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002290 llvm::Value *AddrWeakObj)
2291{
Eli Friedman8339b352009-03-07 03:57:15 +00002292 const llvm::Type* DestTy =
2293 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002294 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002295 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002296 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00002297 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002298 return read_weak;
2299}
2300
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002301/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
2302/// objc_assign_weak (id src, id *dst)
2303///
2304void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
2305 llvm::Value *src, llvm::Value *dst)
2306{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002307 const llvm::Type * SrcTy = src->getType();
2308 if (!isa<llvm::PointerType>(SrcTy)) {
2309 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2310 assert(Size <= 8 && "does not support size > 8");
2311 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2312 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002313 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2314 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002315 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2316 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattner96508e12009-04-17 22:12:36 +00002317 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002318 src, dst, "weakassign");
2319 return;
2320}
2321
Fariborz Jahanian58626502008-11-19 00:59:10 +00002322/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
2323/// objc_assign_global (id src, id *dst)
2324///
2325void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
2326 llvm::Value *src, llvm::Value *dst)
2327{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002328 const llvm::Type * SrcTy = src->getType();
2329 if (!isa<llvm::PointerType>(SrcTy)) {
2330 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2331 assert(Size <= 8 && "does not support size > 8");
2332 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2333 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002334 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2335 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002336 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2337 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian58626502008-11-19 00:59:10 +00002338 CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn,
2339 src, dst, "globalassign");
2340 return;
2341}
2342
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002343/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
2344/// objc_assign_ivar (id src, id *dst)
2345///
2346void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
2347 llvm::Value *src, llvm::Value *dst)
2348{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002349 const llvm::Type * SrcTy = src->getType();
2350 if (!isa<llvm::PointerType>(SrcTy)) {
2351 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2352 assert(Size <= 8 && "does not support size > 8");
2353 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2354 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002355 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2356 }
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002357 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2358 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
2359 CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn,
2360 src, dst, "assignivar");
2361 return;
2362}
2363
Fariborz Jahanian58626502008-11-19 00:59:10 +00002364/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
2365/// objc_assign_strongCast (id src, id *dst)
2366///
2367void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
2368 llvm::Value *src, llvm::Value *dst)
2369{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002370 const llvm::Type * SrcTy = src->getType();
2371 if (!isa<llvm::PointerType>(SrcTy)) {
2372 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2373 assert(Size <= 8 && "does not support size > 8");
2374 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2375 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002376 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2377 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002378 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2379 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian58626502008-11-19 00:59:10 +00002380 CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn,
2381 src, dst, "weakassign");
2382 return;
2383}
2384
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002385/// EmitObjCValueForIvar - Code Gen for ivar reference.
2386///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002387LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
2388 QualType ObjectTy,
2389 llvm::Value *BaseValue,
2390 const ObjCIvarDecl *Ivar,
2391 const FieldDecl *Field,
2392 unsigned CVRQualifiers) {
2393 if (Ivar->isBitField())
2394 return CGF.EmitLValueForBitfield(BaseValue, const_cast<FieldDecl *>(Field),
2395 CVRQualifiers);
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002396 // TODO: Add a special case for isa (index 0)
2397 unsigned Index = CGM.getTypes().getLLVMFieldNo(Field);
2398 llvm::Value *V = CGF.Builder.CreateStructGEP(BaseValue, Index, "tmp");
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002399 LValue LV = LValue::MakeAddr(V,
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00002400 Ivar->getType().getCVRQualifiers()|CVRQualifiers,
2401 CGM.getContext().getObjCGCAttrKind(Ivar->getType()));
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002402 LValue::SetObjCIvar(LV, true);
2403 return LV;
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002404}
2405
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002406llvm::Value *CGObjCMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
2407 ObjCInterfaceDecl *Interface,
2408 const ObjCIvarDecl *Ivar) {
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002409 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(Interface);
Daniel Dunbar60952f92009-04-20 00:37:55 +00002410 const FieldDecl *Field =
2411 Interface->lookupFieldDeclForIvar(CGM.getContext(), Ivar);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00002412 uint64_t Offset = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002413 return llvm::ConstantInt::get(
2414 CGM.getTypes().ConvertType(CGM.getContext().LongTy),
2415 Offset);
2416}
2417
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002418/* *** Private Interface *** */
2419
2420/// EmitImageInfo - Emit the image info marker used to encode some module
2421/// level information.
2422///
2423/// See: <rdr://4810609&4810587&4810587>
2424/// struct IMAGE_INFO {
2425/// unsigned version;
2426/// unsigned flags;
2427/// };
2428enum ImageInfoFlags {
Daniel Dunbarc7c6dc02009-04-20 07:11:47 +00002429 eImageInfo_FixAndContinue = (1 << 0), // FIXME: Not sure what
2430 // this implies.
2431 eImageInfo_GarbageCollected = (1 << 1),
2432 eImageInfo_GCOnly = (1 << 2),
2433 eImageInfo_OptimizedByDyld = (1 << 3), // FIXME: When is this set.
2434
2435 // A flag indicating that the module has no instances of an
2436 // @synthesize of a superclass variable. <rdar://problem/6803242>
2437 eImageInfo_CorrectedSynthesize = (1 << 4)
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002438};
2439
2440void CGObjCMac::EmitImageInfo() {
2441 unsigned version = 0; // Version is unused?
2442 unsigned flags = 0;
2443
2444 // FIXME: Fix and continue?
2445 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
2446 flags |= eImageInfo_GarbageCollected;
2447 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
2448 flags |= eImageInfo_GCOnly;
Daniel Dunbarc7c6dc02009-04-20 07:11:47 +00002449
2450 // We never allow @synthesize of a superclass property.
2451 flags |= eImageInfo_CorrectedSynthesize;
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002452
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002453 // Emitted as int[2];
2454 llvm::Constant *values[2] = {
2455 llvm::ConstantInt::get(llvm::Type::Int32Ty, version),
2456 llvm::ConstantInt::get(llvm::Type::Int32Ty, flags)
2457 };
2458 llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002459
2460 const char *Section;
2461 if (ObjCABI == 1)
2462 Section = "__OBJC, __image_info,regular";
2463 else
2464 Section = "__DATA, __objc_imageinfo, regular, no_dead_strip";
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002465 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002466 CreateMetadataVar("\01L_OBJC_IMAGE_INFO",
2467 llvm::ConstantArray::get(AT, values, 2),
2468 Section,
2469 0,
2470 true);
2471 GV->setConstant(true);
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002472}
2473
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002474
2475// struct objc_module {
2476// unsigned long version;
2477// unsigned long size;
2478// const char *name;
2479// Symtab symtab;
2480// };
2481
2482// FIXME: Get from somewhere
2483static const int ModuleVersion = 7;
2484
2485void CGObjCMac::EmitModuleInfo() {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00002486 uint64_t Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ModuleTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002487
2488 std::vector<llvm::Constant*> Values(4);
2489 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
2490 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002491 // This used to be the filename, now it is unused. <rdr://4327263>
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002492 Values[2] = GetClassName(&CGM.getContext().Idents.get(""));
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002493 Values[3] = EmitModuleSymbols();
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002494 CreateMetadataVar("\01L_OBJC_MODULES",
2495 llvm::ConstantStruct::get(ObjCTypes.ModuleTy, Values),
2496 "__OBJC,__module_info,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00002497 4, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002498}
2499
2500llvm::Constant *CGObjCMac::EmitModuleSymbols() {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002501 unsigned NumClasses = DefinedClasses.size();
2502 unsigned NumCategories = DefinedCategories.size();
2503
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002504 // Return null if no symbols were defined.
2505 if (!NumClasses && !NumCategories)
2506 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
2507
2508 std::vector<llvm::Constant*> Values(5);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002509 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2510 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
2511 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
2512 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
2513
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002514 // The runtime expects exactly the list of defined classes followed
2515 // by the list of defined categories, in a single array.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002516 std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002517 for (unsigned i=0; i<NumClasses; i++)
2518 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
2519 ObjCTypes.Int8PtrTy);
2520 for (unsigned i=0; i<NumCategories; i++)
2521 Symbols[NumClasses + i] =
2522 llvm::ConstantExpr::getBitCast(DefinedCategories[i],
2523 ObjCTypes.Int8PtrTy);
2524
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002525 Values[4] =
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002526 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002527 NumClasses + NumCategories),
2528 Symbols);
2529
2530 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2531
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002532 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002533 CreateMetadataVar("\01L_OBJC_SYMBOLS", Init,
2534 "__OBJC,__symbols,regular,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002535 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002536 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
2537}
2538
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002539llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002540 const ObjCInterfaceDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002541 LazySymbols.insert(ID->getIdentifier());
2542
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002543 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
2544
2545 if (!Entry) {
2546 llvm::Constant *Casted =
2547 llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()),
2548 ObjCTypes.ClassPtrTy);
2549 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002550 CreateMetadataVar("\01L_OBJC_CLASS_REFERENCES_", Casted,
2551 "__OBJC,__cls_refs,literal_pointers,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002552 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002553 }
2554
2555 return Builder.CreateLoad(Entry, false, "tmp");
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002556}
2557
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002558llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002559 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
2560
2561 if (!Entry) {
2562 llvm::Constant *Casted =
2563 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
2564 ObjCTypes.SelectorPtrTy);
2565 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002566 CreateMetadataVar("\01L_OBJC_SELECTOR_REFERENCES_", Casted,
2567 "__OBJC,__message_refs,literal_pointers,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002568 4, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002569 }
2570
2571 return Builder.CreateLoad(Entry, false, "tmp");
2572}
2573
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00002574llvm::Constant *CGObjCCommonMac::GetClassName(IdentifierInfo *Ident) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002575 llvm::GlobalVariable *&Entry = ClassNames[Ident];
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002576
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002577 if (!Entry)
2578 Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
2579 llvm::ConstantArray::get(Ident->getName()),
2580 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00002581 1, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002582
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002583 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002584}
2585
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002586/// GetInterfaceDeclStructLayout - Get layout for ivars of given
2587/// interface declaration.
2588const llvm::StructLayout *CGObjCCommonMac::GetInterfaceDeclStructLayout(
2589 const ObjCInterfaceDecl *OID) const {
Chris Lattnerb7b58b12009-04-19 06:02:28 +00002590 const llvm::Type *InterfaceTy;
2591
Daniel Dunbarb02532a2009-04-19 23:41:48 +00002592 // FIXME: When does this happen? It seems pretty bad to do this...
Chris Lattnerb7b58b12009-04-19 06:02:28 +00002593 if (OID->isForwardDecl()) {
2594 InterfaceTy = llvm::StructType::get(NULL, NULL);
2595 } else {
2596 QualType T = CGM.getContext().getObjCInterfaceType(
2597 const_cast<ObjCInterfaceDecl*>(OID));
2598 InterfaceTy = CGM.getTypes().ConvertType(T);
2599 }
2600
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002601 const llvm::StructLayout *Layout =
2602 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceTy));
2603 return Layout;
2604}
2605
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00002606/// GetIvarLayoutName - Returns a unique constant for the given
2607/// ivar layout bitmap.
2608llvm::Constant *CGObjCCommonMac::GetIvarLayoutName(IdentifierInfo *Ident,
2609 const ObjCCommonTypesHelper &ObjCTypes) {
2610 return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2611}
2612
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002613void CGObjCCommonMac::BuildAggrIvarLayout(const ObjCInterfaceDecl *OI,
2614 const llvm::StructLayout *Layout,
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002615 const RecordDecl *RD,
Chris Lattnerf1690852009-03-31 08:48:01 +00002616 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002617 unsigned int BytePos, bool ForStrongLayout,
2618 int &Index, int &SkIndex, bool &HasUnion) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002619 bool IsUnion = (RD && RD->isUnion());
2620 uint64_t MaxUnionIvarSize = 0;
2621 uint64_t MaxSkippedUnionIvarSize = 0;
2622 FieldDecl *MaxField = 0;
2623 FieldDecl *MaxSkippedField = 0;
Chris Lattnerf1690852009-03-31 08:48:01 +00002624 unsigned base = 0;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002625 if (RecFields.empty())
2626 return;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002627 if (IsUnion)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002628 base = BytePos + GetFieldBaseOffset(OI, Layout, RecFields[0]);
Chris Lattnerf1690852009-03-31 08:48:01 +00002629 unsigned WordSizeInBits = CGM.getContext().Target.getPointerWidth(0);
2630 unsigned ByteSizeInBits = CGM.getContext().Target.getCharWidth();
2631
2632 llvm::SmallVector<FieldDecl*, 16> TmpRecFields;
2633
2634 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002635 FieldDecl *Field = RecFields[i];
2636 // Skip over unnamed or bitfields
2637 if (!Field->getIdentifier() || Field->isBitField())
2638 continue;
2639 QualType FQT = Field->getType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002640 if (FQT->isRecordType() || FQT->isUnionType()) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002641 if (FQT->isUnionType())
2642 HasUnion = true;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002643 else
2644 assert(FQT->isRecordType() &&
2645 "only union/record is supported for ivar layout bitmap");
2646
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002647 const RecordType *RT = FQT->getAsRecordType();
2648 const RecordDecl *RD = RT->getDecl();
Daniel Dunbarb02532a2009-04-19 23:41:48 +00002649 // FIXME - Find a more efficient way of passing records down.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002650 TmpRecFields.append(RD->field_begin(CGM.getContext()),
2651 RD->field_end(CGM.getContext()));
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002652 // FIXME - Is Layout correct?
Chris Lattnerf1690852009-03-31 08:48:01 +00002653 BuildAggrIvarLayout(OI, Layout, RD, TmpRecFields,
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002654 BytePos + GetFieldBaseOffset(OI, Layout, Field),
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002655 ForStrongLayout, Index, SkIndex,
2656 HasUnion);
Chris Lattnerf1690852009-03-31 08:48:01 +00002657 TmpRecFields.clear();
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002658 continue;
2659 }
Chris Lattnerf1690852009-03-31 08:48:01 +00002660
2661 if (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002662 const ConstantArrayType *CArray =
2663 dyn_cast_or_null<ConstantArrayType>(Array);
2664 assert(CArray && "only array with know element size is supported");
2665 FQT = CArray->getElementType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002666 while (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
2667 const ConstantArrayType *CArray =
2668 dyn_cast_or_null<ConstantArrayType>(Array);
2669 FQT = CArray->getElementType();
2670 }
2671
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002672 assert(!FQT->isUnionType() &&
2673 "layout for array of unions not supported");
2674 if (FQT->isRecordType()) {
2675 uint64_t ElCount = CArray->getSize().getZExtValue();
2676 int OldIndex = Index;
2677 int OldSkIndex = SkIndex;
2678
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002679 // FIXME - Use a common routine with the above!
2680 const RecordType *RT = FQT->getAsRecordType();
2681 const RecordDecl *RD = RT->getDecl();
2682 // FIXME - Find a more efficiant way of passing records down.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002683 TmpRecFields.append(RD->field_begin(CGM.getContext()),
2684 RD->field_end(CGM.getContext()));
Chris Lattnerf1690852009-03-31 08:48:01 +00002685
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002686 BuildAggrIvarLayout(OI, Layout, RD,
Chris Lattnerf1690852009-03-31 08:48:01 +00002687 TmpRecFields,
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002688 BytePos + GetFieldBaseOffset(OI, Layout, Field),
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002689 ForStrongLayout, Index, SkIndex,
2690 HasUnion);
Chris Lattnerf1690852009-03-31 08:48:01 +00002691 TmpRecFields.clear();
2692
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002693 // Replicate layout information for each array element. Note that
2694 // one element is already done.
2695 uint64_t ElIx = 1;
2696 for (int FirstIndex = Index, FirstSkIndex = SkIndex;
2697 ElIx < ElCount; ElIx++) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002698 uint64_t Size = CGM.getContext().getTypeSize(RT)/ByteSizeInBits;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002699 for (int i = OldIndex+1; i <= FirstIndex; ++i)
2700 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002701 GC_IVAR gcivar;
2702 gcivar.ivar_bytepos = IvarsInfo[i].ivar_bytepos + Size*ElIx;
2703 gcivar.ivar_size = IvarsInfo[i].ivar_size;
2704 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002705 }
2706
Chris Lattnerf1690852009-03-31 08:48:01 +00002707 for (int i = OldSkIndex+1; i <= FirstSkIndex; ++i) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002708 GC_IVAR skivar;
2709 skivar.ivar_bytepos = SkipIvars[i].ivar_bytepos + Size*ElIx;
2710 skivar.ivar_size = SkipIvars[i].ivar_size;
2711 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002712 }
2713 }
2714 continue;
2715 }
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002716 }
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002717 // At this point, we are done with Record/Union and array there of.
2718 // For other arrays we are down to its element type.
2719 QualType::GCAttrTypes GCAttr = QualType::GCNone;
2720 do {
2721 if (FQT.isObjCGCStrong() || FQT.isObjCGCWeak()) {
2722 GCAttr = FQT.isObjCGCStrong() ? QualType::Strong : QualType::Weak;
2723 break;
2724 }
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002725 else if (CGM.getContext().isObjCObjectPointerType(FQT)) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002726 GCAttr = QualType::Strong;
2727 break;
2728 }
2729 else if (const PointerType *PT = FQT->getAsPointerType()) {
2730 FQT = PT->getPointeeType();
2731 }
2732 else {
2733 break;
2734 }
2735 } while (true);
Chris Lattnerf1690852009-03-31 08:48:01 +00002736
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002737 if ((ForStrongLayout && GCAttr == QualType::Strong)
2738 || (!ForStrongLayout && GCAttr == QualType::Weak)) {
2739 if (IsUnion)
2740 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002741 uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType())
2742 / WordSizeInBits;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002743 if (UnionIvarSize > MaxUnionIvarSize)
2744 {
2745 MaxUnionIvarSize = UnionIvarSize;
2746 MaxField = Field;
2747 }
2748 }
2749 else
2750 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002751 GC_IVAR gcivar;
2752 gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field);
2753 gcivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) /
2754 WordSizeInBits;
2755 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002756 }
2757 }
2758 else if ((ForStrongLayout &&
2759 (GCAttr == QualType::GCNone || GCAttr == QualType::Weak))
2760 || (!ForStrongLayout && GCAttr != QualType::Weak)) {
2761 if (IsUnion)
2762 {
2763 uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType());
2764 if (UnionIvarSize > MaxSkippedUnionIvarSize)
2765 {
2766 MaxSkippedUnionIvarSize = UnionIvarSize;
2767 MaxSkippedField = Field;
2768 }
2769 }
2770 else
2771 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002772 GC_IVAR skivar;
2773 skivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field);
2774 skivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) /
2775 WordSizeInBits;
2776 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002777 }
2778 }
2779 }
Chris Lattnerf1690852009-03-31 08:48:01 +00002780 if (MaxField) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002781 GC_IVAR gcivar;
2782 gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, MaxField);
2783 gcivar.ivar_size = MaxUnionIvarSize;
2784 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002785 }
Chris Lattnerf1690852009-03-31 08:48:01 +00002786
2787 if (MaxSkippedField) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002788 GC_IVAR skivar;
2789 skivar.ivar_bytepos = BytePos +
2790 GetFieldBaseOffset(OI, Layout, MaxSkippedField);
2791 skivar.ivar_size = MaxSkippedUnionIvarSize;
2792 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002793 }
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002794}
2795
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002796static int
Chris Lattnerf1690852009-03-31 08:48:01 +00002797IvarBytePosCompare(const void *a, const void *b)
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002798{
2799 unsigned int sa = ((CGObjCCommonMac::GC_IVAR *)a)->ivar_bytepos;
2800 unsigned int sb = ((CGObjCCommonMac::GC_IVAR *)b)->ivar_bytepos;
2801
2802 if (sa < sb)
2803 return -1;
2804 if (sa > sb)
2805 return 1;
2806 return 0;
2807}
2808
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002809/// BuildIvarLayout - Builds ivar layout bitmap for the class
2810/// implementation for the __strong or __weak case.
2811/// The layout map displays which words in ivar list must be skipped
2812/// and which must be scanned by GC (see below). String is built of bytes.
2813/// Each byte is divided up in two nibbles (4-bit each). Left nibble is count
2814/// of words to skip and right nibble is count of words to scan. So, each
2815/// nibble represents up to 15 workds to skip or scan. Skipping the rest is
2816/// represented by a 0x00 byte which also ends the string.
2817/// 1. when ForStrongLayout is true, following ivars are scanned:
2818/// - id, Class
2819/// - object *
2820/// - __strong anything
2821///
2822/// 2. When ForStrongLayout is false, following ivars are scanned:
2823/// - __weak anything
2824///
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002825llvm::Constant *CGObjCCommonMac::BuildIvarLayout(
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002826 const ObjCImplementationDecl *OMD,
2827 bool ForStrongLayout) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002828 int Index = -1;
2829 int SkIndex = -1;
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002830 bool hasUnion = false;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002831 int SkipScan;
2832 unsigned int WordsToScan, WordsToSkip;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002833 const llvm::Type *PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
2834 if (CGM.getLangOptions().getGCMode() == LangOptions::NonGC)
2835 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002836
Chris Lattnerf1690852009-03-31 08:48:01 +00002837 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002838 const ObjCInterfaceDecl *OI = OMD->getClassInterface();
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002839 CGM.getContext().CollectObjCIvars(OI, RecFields);
2840 if (RecFields.empty())
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002841 return llvm::Constant::getNullValue(PtrTy);
Chris Lattnerf1690852009-03-31 08:48:01 +00002842
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002843 SkipIvars.clear();
2844 IvarsInfo.clear();
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002845
2846 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OI);
Chris Lattnerf1690852009-03-31 08:48:01 +00002847 BuildAggrIvarLayout(OI, Layout, 0, RecFields, 0, ForStrongLayout,
2848 Index, SkIndex, hasUnion);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002849 if (Index == -1)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002850 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002851
2852 // Sort on byte position in case we encounterred a union nested in
2853 // the ivar list.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002854 if (hasUnion && !IvarsInfo.empty())
2855 qsort(&IvarsInfo[0], Index+1, sizeof(GC_IVAR), IvarBytePosCompare);
2856 if (hasUnion && !SkipIvars.empty())
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002857 qsort(&SkipIvars[0], Index+1, sizeof(GC_IVAR), IvarBytePosCompare);
2858
2859 // Build the string of skip/scan nibbles
2860 SkipScan = -1;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002861 SkipScanIvars.clear();
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002862 unsigned int WordSize =
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002863 CGM.getTypes().getTargetData().getTypePaddedSize(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002864 if (IvarsInfo[0].ivar_bytepos == 0) {
2865 WordsToSkip = 0;
2866 WordsToScan = IvarsInfo[0].ivar_size;
2867 }
2868 else {
2869 WordsToSkip = IvarsInfo[0].ivar_bytepos/WordSize;
2870 WordsToScan = IvarsInfo[0].ivar_size;
2871 }
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002872 for (unsigned int i=1, Last=IvarsInfo.size(); i != Last; i++)
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002873 {
2874 unsigned int TailPrevGCObjC =
2875 IvarsInfo[i-1].ivar_bytepos + IvarsInfo[i-1].ivar_size * WordSize;
2876 if (IvarsInfo[i].ivar_bytepos == TailPrevGCObjC)
2877 {
2878 // consecutive 'scanned' object pointers.
2879 WordsToScan += IvarsInfo[i].ivar_size;
2880 }
2881 else
2882 {
2883 // Skip over 'gc'able object pointer which lay over each other.
2884 if (TailPrevGCObjC > IvarsInfo[i].ivar_bytepos)
2885 continue;
2886 // Must skip over 1 or more words. We save current skip/scan values
2887 // and start a new pair.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002888 SKIP_SCAN SkScan;
2889 SkScan.skip = WordsToSkip;
2890 SkScan.scan = WordsToScan;
2891 SkipScanIvars.push_back(SkScan); ++SkipScan;
2892
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002893 // Skip the hole.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002894 SkScan.skip = (IvarsInfo[i].ivar_bytepos - TailPrevGCObjC) / WordSize;
2895 SkScan.scan = 0;
2896 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002897 WordsToSkip = 0;
2898 WordsToScan = IvarsInfo[i].ivar_size;
2899 }
2900 }
2901 if (WordsToScan > 0)
2902 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002903 SKIP_SCAN SkScan;
2904 SkScan.skip = WordsToSkip;
2905 SkScan.scan = WordsToScan;
2906 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002907 }
2908
2909 bool BytesSkipped = false;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002910 if (!SkipIvars.empty())
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002911 {
2912 int LastByteSkipped =
2913 SkipIvars[SkIndex].ivar_bytepos + SkipIvars[SkIndex].ivar_size;
2914 int LastByteScanned =
2915 IvarsInfo[Index].ivar_bytepos + IvarsInfo[Index].ivar_size * WordSize;
2916 BytesSkipped = (LastByteSkipped > LastByteScanned);
2917 // Compute number of bytes to skip at the tail end of the last ivar scanned.
2918 if (BytesSkipped)
2919 {
2920 unsigned int TotalWords = (LastByteSkipped + (WordSize -1)) / WordSize;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002921 SKIP_SCAN SkScan;
2922 SkScan.skip = TotalWords - (LastByteScanned/WordSize);
2923 SkScan.scan = 0;
2924 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002925 }
2926 }
2927 // Mini optimization of nibbles such that an 0xM0 followed by 0x0N is produced
2928 // as 0xMN.
2929 for (int i = 0; i <= SkipScan; i++)
2930 {
2931 if ((i < SkipScan) && SkipScanIvars[i].skip && SkipScanIvars[i].scan == 0
2932 && SkipScanIvars[i+1].skip == 0 && SkipScanIvars[i+1].scan) {
2933 // 0xM0 followed by 0x0N detected.
2934 SkipScanIvars[i].scan = SkipScanIvars[i+1].scan;
2935 for (int j = i+1; j < SkipScan; j++)
2936 SkipScanIvars[j] = SkipScanIvars[j+1];
2937 --SkipScan;
2938 }
2939 }
2940
2941 // Generate the string.
2942 std::string BitMap;
2943 for (int i = 0; i <= SkipScan; i++)
2944 {
2945 unsigned char byte;
2946 unsigned int skip_small = SkipScanIvars[i].skip % 0xf;
2947 unsigned int scan_small = SkipScanIvars[i].scan % 0xf;
2948 unsigned int skip_big = SkipScanIvars[i].skip / 0xf;
2949 unsigned int scan_big = SkipScanIvars[i].scan / 0xf;
2950
2951 if (skip_small > 0 || skip_big > 0)
2952 BytesSkipped = true;
2953 // first skip big.
2954 for (unsigned int ix = 0; ix < skip_big; ix++)
2955 BitMap += (unsigned char)(0xf0);
2956
2957 // next (skip small, scan)
2958 if (skip_small)
2959 {
2960 byte = skip_small << 4;
2961 if (scan_big > 0)
2962 {
2963 byte |= 0xf;
2964 --scan_big;
2965 }
2966 else if (scan_small)
2967 {
2968 byte |= scan_small;
2969 scan_small = 0;
2970 }
2971 BitMap += byte;
2972 }
2973 // next scan big
2974 for (unsigned int ix = 0; ix < scan_big; ix++)
2975 BitMap += (unsigned char)(0x0f);
2976 // last scan small
2977 if (scan_small)
2978 {
2979 byte = scan_small;
2980 BitMap += byte;
2981 }
2982 }
2983 // null terminate string.
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002984 unsigned char zero = 0;
2985 BitMap += zero;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002986 // if ivar_layout bitmap is all 1 bits (nothing skipped) then use NULL as
2987 // final layout.
2988 if (ForStrongLayout && !BytesSkipped)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002989 return llvm::Constant::getNullValue(PtrTy);
2990 llvm::GlobalVariable * Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
2991 llvm::ConstantArray::get(BitMap.c_str()),
2992 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00002993 1, true);
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002994 // FIXME. Need a commomand-line option for this eventually.
2995 if (ForStrongLayout)
2996 printf("\nstrong ivar layout: ");
2997 else
2998 printf("\nweak ivar layout: ");
2999 const unsigned char *s = (unsigned char*)BitMap.c_str();
3000 for (unsigned i = 0; i < BitMap.size(); i++)
Fariborz Jahaniandbf15cb2009-03-26 19:10:36 +00003001 if (!(s[i] & 0xf0))
3002 printf("0x0%x%s", s[i], s[i] != 0 ? ", " : "");
3003 else
3004 printf("0x%x%s", s[i], s[i] != 0 ? ", " : "");
Fariborz Jahanian667423a2009-03-25 22:36:49 +00003005 printf("\n");
3006
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003007 return getConstantGEP(Entry, 0, 0);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003008}
3009
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003010llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003011 llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
3012
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003013 // FIXME: Avoid std::string copying.
3014 if (!Entry)
3015 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_NAME_",
3016 llvm::ConstantArray::get(Sel.getAsString()),
3017 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003018 1, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003019
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003020 return getConstantGEP(Entry, 0, 0);
3021}
3022
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003023// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003024llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003025 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
3026}
3027
3028// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003029llvm::Constant *CGObjCCommonMac::GetMethodVarName(const std::string &Name) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003030 return GetMethodVarName(&CGM.getContext().Idents.get(Name));
3031}
3032
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00003033llvm::Constant *CGObjCCommonMac::GetMethodVarType(const FieldDecl *Field) {
Devang Patel7794bb82009-03-04 18:21:39 +00003034 std::string TypeStr;
3035 CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
3036
3037 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003038
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003039 if (!Entry)
3040 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3041 llvm::ConstantArray::get(TypeStr),
3042 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003043 1, true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003044
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003045 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003046}
3047
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003048llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003049 std::string TypeStr;
Daniel Dunbarc45ef602008-08-26 21:51:14 +00003050 CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D),
3051 TypeStr);
Devang Patel7794bb82009-03-04 18:21:39 +00003052
3053 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
3054
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003055 if (!Entry)
3056 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3057 llvm::ConstantArray::get(TypeStr),
3058 "__TEXT,__cstring,cstring_literals",
3059 1, true);
Devang Patel7794bb82009-03-04 18:21:39 +00003060
3061 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003062}
3063
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003064// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003065llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003066 llvm::GlobalVariable *&Entry = PropertyNames[Ident];
3067
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003068 if (!Entry)
3069 Entry = CreateMetadataVar("\01L_OBJC_PROP_NAME_ATTR_",
3070 llvm::ConstantArray::get(Ident->getName()),
3071 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003072 1, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003073
3074 return getConstantGEP(Entry, 0, 0);
3075}
3076
3077// FIXME: Merge into a single cstring creation function.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003078// FIXME: This Decl should be more precise.
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003079llvm::Constant *
3080 CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
3081 const Decl *Container) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003082 std::string TypeStr;
3083 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003084 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
3085}
3086
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003087void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D,
3088 const ObjCContainerDecl *CD,
3089 std::string &NameOut) {
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00003090 NameOut = '\01';
3091 NameOut += (D->isInstanceMethod() ? '-' : '+');
Chris Lattner077bf5e2008-11-24 03:33:13 +00003092 NameOut += '[';
Fariborz Jahanian679a5022009-01-10 21:06:09 +00003093 assert (CD && "Missing container decl in GetNameForMethod");
3094 NameOut += CD->getNameAsString();
Fariborz Jahanian1e9aef32009-04-16 18:34:20 +00003095 if (const ObjCCategoryImplDecl *CID =
3096 dyn_cast<ObjCCategoryImplDecl>(D->getDeclContext())) {
3097 NameOut += '(';
3098 NameOut += CID->getNameAsString();
3099 NameOut+= ')';
3100 }
Chris Lattner077bf5e2008-11-24 03:33:13 +00003101 NameOut += ' ';
3102 NameOut += D->getSelector().getAsString();
3103 NameOut += ']';
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00003104}
3105
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00003106/// GetFirstIvarInRecord - This routine returns the record for the
3107/// implementation of the fiven class OID. It also returns field
3108/// corresponding to the first ivar in the class in FIV. It also
3109/// returns the one before the first ivar.
3110///
3111const RecordDecl *CGObjCCommonMac::GetFirstIvarInRecord(
3112 const ObjCInterfaceDecl *OID,
3113 RecordDecl::field_iterator &FIV,
3114 RecordDecl::field_iterator &PIV) {
Douglas Gregor6ab35242009-04-09 21:40:53 +00003115 int countSuperClassIvars = countInheritedIvars(OID->getSuperClass(),
3116 CGM.getContext());
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00003117 const RecordDecl *RD = CGM.getContext().addRecordToClass(OID);
Douglas Gregor6ab35242009-04-09 21:40:53 +00003118 RecordDecl::field_iterator ifield = RD->field_begin(CGM.getContext());
3119 RecordDecl::field_iterator pfield = RD->field_end(CGM.getContext());
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00003120 while (countSuperClassIvars-- > 0) {
3121 pfield = ifield;
3122 ++ifield;
3123 }
3124 FIV = ifield;
3125 PIV = pfield;
3126 return RD;
3127}
3128
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003129void CGObjCMac::FinishModule() {
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003130 EmitModuleInfo();
3131
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003132 // Emit the dummy bodies for any protocols which were referenced but
3133 // never defined.
3134 for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
3135 i = Protocols.begin(), e = Protocols.end(); i != e; ++i) {
3136 if (i->second->hasInitializer())
3137 continue;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003138
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003139 std::vector<llvm::Constant*> Values(5);
3140 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
3141 Values[1] = GetClassName(i->first);
3142 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
3143 Values[3] = Values[4] =
3144 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
3145 i->second->setLinkage(llvm::GlobalValue::InternalLinkage);
3146 i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
3147 Values));
3148 }
3149
3150 std::vector<llvm::Constant*> Used;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003151 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003152 e = UsedGlobals.end(); i != e; ++i) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003153 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003154 }
3155
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003156 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003157 llvm::GlobalValue *GV =
3158 new llvm::GlobalVariable(AT, false,
3159 llvm::GlobalValue::AppendingLinkage,
3160 llvm::ConstantArray::get(AT, Used),
3161 "llvm.used",
3162 &CGM.getModule());
3163
3164 GV->setSection("llvm.metadata");
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003165
3166 // Add assembler directives to add lazy undefined symbol references
3167 // for classes which are referenced but not defined. This is
3168 // important for correct linker interaction.
3169
3170 // FIXME: Uh, this isn't particularly portable.
3171 std::stringstream s;
Anders Carlsson565c99f2008-12-10 02:21:04 +00003172
3173 if (!CGM.getModule().getModuleInlineAsm().empty())
3174 s << "\n";
3175
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003176 for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(),
3177 e = LazySymbols.end(); i != e; ++i) {
3178 s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n";
3179 }
3180 for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(),
3181 e = DefinedSymbols.end(); i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003182 s << "\t.objc_class_name_" << (*i)->getName() << "=0\n"
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003183 << "\t.globl .objc_class_name_" << (*i)->getName() << "\n";
3184 }
Anders Carlsson565c99f2008-12-10 02:21:04 +00003185
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003186 CGM.getModule().appendModuleInlineAsm(s.str());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003187}
3188
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003189CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003190 : CGObjCCommonMac(cgm),
3191 ObjCTypes(cgm)
3192{
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003193 ObjCEmptyCacheVar = ObjCEmptyVtableVar = NULL;
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003194 ObjCABI = 2;
3195}
3196
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003197/* *** */
3198
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003199ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm)
3200: CGM(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003201{
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003202 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3203 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003204
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003205 ShortTy = Types.ConvertType(Ctx.ShortTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003206 IntTy = Types.ConvertType(Ctx.IntTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003207 LongTy = Types.ConvertType(Ctx.LongTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00003208 LongLongTy = Types.ConvertType(Ctx.LongLongTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003209 Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3210
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003211 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00003212 PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003213 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003214
3215 // FIXME: It would be nice to unify this with the opaque type, so
3216 // that the IR comes out a bit cleaner.
3217 const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
3218 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003219
3220 // I'm not sure I like this. The implicit coordination is a bit
3221 // gross. We should solve this in a reasonable fashion because this
3222 // is a pretty common task (match some runtime data structure with
3223 // an LLVM data structure).
3224
3225 // FIXME: This is leaked.
3226 // FIXME: Merge with rewriter code?
3227
3228 // struct _objc_super {
3229 // id self;
3230 // Class cls;
3231 // }
3232 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3233 SourceLocation(),
3234 &Ctx.Idents.get("_objc_super"));
Douglas Gregor6ab35242009-04-09 21:40:53 +00003235 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3236 Ctx.getObjCIdType(), 0, false));
3237 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3238 Ctx.getObjCClassType(), 0, false));
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003239 RD->completeDefinition(Ctx);
3240
3241 SuperCTy = Ctx.getTagDeclType(RD);
3242 SuperPtrCTy = Ctx.getPointerType(SuperCTy);
3243
3244 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003245 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
3246
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003247 // struct _prop_t {
3248 // char *name;
3249 // char *attributes;
3250 // }
3251 PropertyTy = llvm::StructType::get(Int8PtrTy,
3252 Int8PtrTy,
3253 NULL);
3254 CGM.getModule().addTypeName("struct._prop_t",
3255 PropertyTy);
3256
3257 // struct _prop_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003258 // uint32_t entsize; // sizeof(struct _prop_t)
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003259 // uint32_t count_of_properties;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003260 // struct _prop_t prop_list[count_of_properties];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003261 // }
3262 PropertyListTy = llvm::StructType::get(IntTy,
3263 IntTy,
3264 llvm::ArrayType::get(PropertyTy, 0),
3265 NULL);
3266 CGM.getModule().addTypeName("struct._prop_list_t",
3267 PropertyListTy);
3268 // struct _prop_list_t *
3269 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
3270
3271 // struct _objc_method {
3272 // SEL _cmd;
3273 // char *method_type;
3274 // char *_imp;
3275 // }
3276 MethodTy = llvm::StructType::get(SelectorPtrTy,
3277 Int8PtrTy,
3278 Int8PtrTy,
3279 NULL);
3280 CGM.getModule().addTypeName("struct._objc_method", MethodTy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003281
3282 // struct _objc_cache *
3283 CacheTy = llvm::OpaqueType::get();
3284 CGM.getModule().addTypeName("struct._objc_cache", CacheTy);
3285 CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003286
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003287 // Property manipulation functions.
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003288
3289 QualType IdType = Ctx.getObjCIdType();
3290 QualType SelType = Ctx.getObjCSelType();
3291 llvm::SmallVector<QualType,16> Params;
3292 const llvm::FunctionType *FTy;
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003293
3294 // id objc_getProperty (id, SEL, ptrdiff_t, bool)
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003295 Params.push_back(IdType);
3296 Params.push_back(SelType);
3297 Params.push_back(Ctx.LongTy);
3298 Params.push_back(Ctx.BoolTy);
3299 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params),
3300 false);
3301 GetPropertyFn = CGM.CreateRuntimeFunction(FTy, "objc_getProperty");
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003302
3303 // void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool)
3304 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003305 Params.push_back(IdType);
3306 Params.push_back(SelType);
3307 Params.push_back(Ctx.LongTy);
3308 Params.push_back(IdType);
3309 Params.push_back(Ctx.BoolTy);
3310 Params.push_back(Ctx.BoolTy);
3311 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
3312 SetPropertyFn = CGM.CreateRuntimeFunction(FTy, "objc_setProperty");
3313
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003314 // Enumeration mutation.
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003315
3316 // void objc_enumerationMutation (id)
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003317 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003318 Params.push_back(IdType);
3319 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
3320 EnumerationMutationFn = CGM.CreateRuntimeFunction(FTy,
3321 "objc_enumerationMutation");
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003322
3323 // gc's API
3324 // id objc_read_weak (id *)
3325 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003326 Params.push_back(Ctx.getPointerType(IdType));
3327 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
3328 GcReadWeakFn = CGM.CreateRuntimeFunction(FTy, "objc_read_weak");
3329
Chris Lattner96508e12009-04-17 22:12:36 +00003330 // id objc_assign_global (id, id *)
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003331 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003332 Params.push_back(IdType);
3333 Params.push_back(Ctx.getPointerType(IdType));
3334
3335 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003336 GcAssignGlobalFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_global");
3337 GcAssignIvarFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_ivar");
3338 GcAssignStrongCastFn =
3339 CGM.CreateRuntimeFunction(FTy, "objc_assign_strongCast");
Anders Carlssonf57c5b22009-02-16 22:59:18 +00003340
3341 // void objc_exception_throw(id)
3342 Params.clear();
3343 Params.push_back(IdType);
3344
3345 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00003346 ExceptionThrowFn =
3347 CGM.CreateRuntimeFunction(FTy, "objc_exception_throw");
Daniel Dunbar1c566672009-02-24 01:43:46 +00003348
3349 // synchronized APIs
Daniel Dunbar1c566672009-02-24 01:43:46 +00003350 // void objc_sync_exit (id)
3351 Params.clear();
3352 Params.push_back(IdType);
3353
3354 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
Daniel Dunbar1c566672009-02-24 01:43:46 +00003355 SyncExitFn = CGM.CreateRuntimeFunction(FTy, "objc_sync_exit");
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003356}
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003357
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003358ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
3359 : ObjCCommonTypesHelper(cgm)
3360{
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003361 // struct _objc_method_description {
3362 // SEL name;
3363 // char *types;
3364 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003365 MethodDescriptionTy =
3366 llvm::StructType::get(SelectorPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003367 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003368 NULL);
3369 CGM.getModule().addTypeName("struct._objc_method_description",
3370 MethodDescriptionTy);
3371
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003372 // struct _objc_method_description_list {
3373 // int count;
3374 // struct _objc_method_description[1];
3375 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003376 MethodDescriptionListTy =
3377 llvm::StructType::get(IntTy,
3378 llvm::ArrayType::get(MethodDescriptionTy, 0),
3379 NULL);
3380 CGM.getModule().addTypeName("struct._objc_method_description_list",
3381 MethodDescriptionListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003382
3383 // struct _objc_method_description_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003384 MethodDescriptionListPtrTy =
3385 llvm::PointerType::getUnqual(MethodDescriptionListTy);
3386
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003387 // Protocol description structures
3388
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003389 // struct _objc_protocol_extension {
3390 // uint32_t size; // sizeof(struct _objc_protocol_extension)
3391 // struct _objc_method_description_list *optional_instance_methods;
3392 // struct _objc_method_description_list *optional_class_methods;
3393 // struct _objc_property_list *instance_properties;
3394 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003395 ProtocolExtensionTy =
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003396 llvm::StructType::get(IntTy,
3397 MethodDescriptionListPtrTy,
3398 MethodDescriptionListPtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003399 PropertyListPtrTy,
3400 NULL);
3401 CGM.getModule().addTypeName("struct._objc_protocol_extension",
3402 ProtocolExtensionTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003403
3404 // struct _objc_protocol_extension *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003405 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
3406
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003407 // Handle recursive construction of Protocol and ProtocolList types
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003408
3409 llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get();
3410 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3411
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003412 const llvm::Type *T =
3413 llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder),
3414 LongTy,
3415 llvm::ArrayType::get(ProtocolTyHolder, 0),
3416 NULL);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003417 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T);
3418
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003419 // struct _objc_protocol {
3420 // struct _objc_protocol_extension *isa;
3421 // char *protocol_name;
3422 // struct _objc_protocol **_objc_protocol_list;
3423 // struct _objc_method_description_list *instance_methods;
3424 // struct _objc_method_description_list *class_methods;
3425 // }
3426 T = llvm::StructType::get(ProtocolExtensionPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003427 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003428 llvm::PointerType::getUnqual(ProtocolListTyHolder),
3429 MethodDescriptionListPtrTy,
3430 MethodDescriptionListPtrTy,
3431 NULL);
3432 cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T);
3433
3434 ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get());
3435 CGM.getModule().addTypeName("struct._objc_protocol_list",
3436 ProtocolListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003437 // struct _objc_protocol_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003438 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
3439
3440 ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get());
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003441 CGM.getModule().addTypeName("struct._objc_protocol", ProtocolTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003442 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003443
3444 // Class description structures
3445
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003446 // struct _objc_ivar {
3447 // char *ivar_name;
3448 // char *ivar_type;
3449 // int ivar_offset;
3450 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003451 IvarTy = llvm::StructType::get(Int8PtrTy,
3452 Int8PtrTy,
3453 IntTy,
3454 NULL);
3455 CGM.getModule().addTypeName("struct._objc_ivar", IvarTy);
3456
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003457 // struct _objc_ivar_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003458 IvarListTy = llvm::OpaqueType::get();
3459 CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy);
3460 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
3461
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003462 // struct _objc_method_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003463 MethodListTy = llvm::OpaqueType::get();
3464 CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy);
3465 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
3466
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003467 // struct _objc_class_extension *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003468 ClassExtensionTy =
3469 llvm::StructType::get(IntTy,
3470 Int8PtrTy,
3471 PropertyListPtrTy,
3472 NULL);
3473 CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy);
3474 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
3475
3476 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3477
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003478 // struct _objc_class {
3479 // Class isa;
3480 // Class super_class;
3481 // char *name;
3482 // long version;
3483 // long info;
3484 // long instance_size;
3485 // struct _objc_ivar_list *ivars;
3486 // struct _objc_method_list *methods;
3487 // struct _objc_cache *cache;
3488 // struct _objc_protocol_list *protocols;
3489 // char *ivar_layout;
3490 // struct _objc_class_ext *ext;
3491 // };
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003492 T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3493 llvm::PointerType::getUnqual(ClassTyHolder),
3494 Int8PtrTy,
3495 LongTy,
3496 LongTy,
3497 LongTy,
3498 IvarListPtrTy,
3499 MethodListPtrTy,
3500 CachePtrTy,
3501 ProtocolListPtrTy,
3502 Int8PtrTy,
3503 ClassExtensionPtrTy,
3504 NULL);
3505 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T);
3506
3507 ClassTy = cast<llvm::StructType>(ClassTyHolder.get());
3508 CGM.getModule().addTypeName("struct._objc_class", ClassTy);
3509 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
3510
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003511 // struct _objc_category {
3512 // char *category_name;
3513 // char *class_name;
3514 // struct _objc_method_list *instance_method;
3515 // struct _objc_method_list *class_method;
3516 // uint32_t size; // sizeof(struct _objc_category)
3517 // struct _objc_property_list *instance_properties;// category's @property
3518 // }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003519 CategoryTy = llvm::StructType::get(Int8PtrTy,
3520 Int8PtrTy,
3521 MethodListPtrTy,
3522 MethodListPtrTy,
3523 ProtocolListPtrTy,
3524 IntTy,
3525 PropertyListPtrTy,
3526 NULL);
3527 CGM.getModule().addTypeName("struct._objc_category", CategoryTy);
3528
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003529 // Global metadata structures
3530
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003531 // struct _objc_symtab {
3532 // long sel_ref_cnt;
3533 // SEL *refs;
3534 // short cls_def_cnt;
3535 // short cat_def_cnt;
3536 // char *defs[cls_def_cnt + cat_def_cnt];
3537 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003538 SymtabTy = llvm::StructType::get(LongTy,
3539 SelectorPtrTy,
3540 ShortTy,
3541 ShortTy,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003542 llvm::ArrayType::get(Int8PtrTy, 0),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003543 NULL);
3544 CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy);
3545 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
3546
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003547 // struct _objc_module {
3548 // long version;
3549 // long size; // sizeof(struct _objc_module)
3550 // char *name;
3551 // struct _objc_symtab* symtab;
3552 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003553 ModuleTy =
3554 llvm::StructType::get(LongTy,
3555 LongTy,
3556 Int8PtrTy,
3557 SymtabPtrTy,
3558 NULL);
3559 CGM.getModule().addTypeName("struct._objc_module", ModuleTy);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003560
Daniel Dunbar49f66022008-09-24 03:38:44 +00003561 // Message send functions.
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003562
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003563 // id objc_msgSend (id, SEL, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003564 std::vector<const llvm::Type*> Params;
3565 Params.push_back(ObjectPtrTy);
3566 Params.push_back(SelectorPtrTy);
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003567 MessageSendFn =
3568 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3569 Params,
3570 true),
3571 "objc_msgSend");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003572
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003573 // id objc_msgSend_stret (id, SEL, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003574 Params.clear();
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003575 Params.push_back(ObjectPtrTy);
3576 Params.push_back(SelectorPtrTy);
3577 MessageSendStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003578 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3579 Params,
3580 true),
3581 "objc_msgSend_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00003582
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003583 //
Daniel Dunbar5669e572008-10-17 03:24:53 +00003584 Params.clear();
3585 Params.push_back(ObjectPtrTy);
3586 Params.push_back(SelectorPtrTy);
3587 // FIXME: This should be long double on x86_64?
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003588 // [double | long double] objc_msgSend_fpret(id self, SEL op, ...)
Daniel Dunbar5669e572008-10-17 03:24:53 +00003589 MessageSendFpretFn =
3590 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::DoubleTy,
3591 Params,
3592 true),
3593 "objc_msgSend_fpret");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003594
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003595 // id objc_msgSendSuper(struct objc_super *super, SEL op, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003596 Params.clear();
3597 Params.push_back(SuperPtrTy);
3598 Params.push_back(SelectorPtrTy);
3599 MessageSendSuperFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003600 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3601 Params,
3602 true),
3603 "objc_msgSendSuper");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003604
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003605 // void objc_msgSendSuper_stret(void * stretAddr, struct objc_super *super,
3606 // SEL op, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003607 Params.clear();
3608 Params.push_back(Int8PtrTy);
3609 Params.push_back(SuperPtrTy);
3610 Params.push_back(SelectorPtrTy);
3611 MessageSendSuperStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003612 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3613 Params,
3614 true),
3615 "objc_msgSendSuper_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00003616
3617 // There is no objc_msgSendSuper_fpret? How can that work?
3618 MessageSendSuperFpretFn = MessageSendSuperFn;
Anders Carlsson2abd89c2008-08-31 04:05:03 +00003619
Anders Carlsson124526b2008-09-09 10:10:21 +00003620 // FIXME: This is the size of the setjmp buffer and should be
3621 // target specific. 18 is what's used on 32-bit X86.
3622 uint64_t SetJmpBufferSize = 18;
3623
3624 // Exceptions
3625 const llvm::Type *StackPtrTy =
Daniel Dunbar10004912008-09-27 06:32:25 +00003626 llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4);
Anders Carlsson124526b2008-09-09 10:10:21 +00003627
3628 ExceptionDataTy =
3629 llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty,
3630 SetJmpBufferSize),
3631 StackPtrTy, NULL);
3632 CGM.getModule().addTypeName("struct._objc_exception_data",
3633 ExceptionDataTy);
3634
3635 Params.clear();
Anders Carlsson124526b2008-09-09 10:10:21 +00003636 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
3637 ExceptionTryEnterFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003638 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3639 Params,
3640 false),
3641 "objc_exception_try_enter");
Anders Carlsson124526b2008-09-09 10:10:21 +00003642 ExceptionTryExitFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003643 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3644 Params,
3645 false),
3646 "objc_exception_try_exit");
Anders Carlsson124526b2008-09-09 10:10:21 +00003647 ExceptionExtractFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003648 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3649 Params,
3650 false),
3651 "objc_exception_extract");
Anders Carlsson124526b2008-09-09 10:10:21 +00003652
3653 Params.clear();
3654 Params.push_back(ClassPtrTy);
3655 Params.push_back(ObjectPtrTy);
3656 ExceptionMatchFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003657 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
3658 Params,
3659 false),
3660 "objc_exception_match");
Chris Lattner10cac6f2008-11-15 21:26:17 +00003661
Anders Carlsson124526b2008-09-09 10:10:21 +00003662 Params.clear();
3663 Params.push_back(llvm::PointerType::getUnqual(llvm::Type::Int32Ty));
3664 SetJmpFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003665 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
3666 Params,
3667 false),
3668 "_setjmp");
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00003669
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003670}
3671
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003672ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003673: ObjCCommonTypesHelper(cgm)
3674{
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003675 // struct _method_list_t {
3676 // uint32_t entsize; // sizeof(struct _objc_method)
3677 // uint32_t method_count;
3678 // struct _objc_method method_list[method_count];
3679 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003680 MethodListnfABITy = llvm::StructType::get(IntTy,
3681 IntTy,
3682 llvm::ArrayType::get(MethodTy, 0),
3683 NULL);
3684 CGM.getModule().addTypeName("struct.__method_list_t",
3685 MethodListnfABITy);
3686 // struct method_list_t *
3687 MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003688
3689 // struct _protocol_t {
3690 // id isa; // NULL
3691 // const char * const protocol_name;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003692 // const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003693 // const struct method_list_t * const instance_methods;
3694 // const struct method_list_t * const class_methods;
3695 // const struct method_list_t *optionalInstanceMethods;
3696 // const struct method_list_t *optionalClassMethods;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003697 // const struct _prop_list_t * properties;
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003698 // const uint32_t size; // sizeof(struct _protocol_t)
3699 // const uint32_t flags; // = 0
3700 // }
3701
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003702 // Holder for struct _protocol_list_t *
3703 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3704
3705 ProtocolnfABITy = llvm::StructType::get(ObjectPtrTy,
3706 Int8PtrTy,
3707 llvm::PointerType::getUnqual(
3708 ProtocolListTyHolder),
3709 MethodListnfABIPtrTy,
3710 MethodListnfABIPtrTy,
3711 MethodListnfABIPtrTy,
3712 MethodListnfABIPtrTy,
3713 PropertyListPtrTy,
3714 IntTy,
3715 IntTy,
3716 NULL);
3717 CGM.getModule().addTypeName("struct._protocol_t",
3718 ProtocolnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003719
3720 // struct _protocol_t*
3721 ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003722
Fariborz Jahanianda320092009-01-29 19:24:30 +00003723 // struct _protocol_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003724 // long protocol_count; // Note, this is 32/64 bit
Daniel Dunbar948e2582009-02-15 07:36:20 +00003725 // struct _protocol_t *[protocol_count];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003726 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003727 ProtocolListnfABITy = llvm::StructType::get(LongTy,
3728 llvm::ArrayType::get(
Daniel Dunbar948e2582009-02-15 07:36:20 +00003729 ProtocolnfABIPtrTy, 0),
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003730 NULL);
3731 CGM.getModule().addTypeName("struct._objc_protocol_list",
3732 ProtocolListnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003733 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(
3734 ProtocolListnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003735
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003736 // struct _objc_protocol_list*
3737 ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003738
3739 // struct _ivar_t {
3740 // unsigned long int *offset; // pointer to ivar offset location
3741 // char *name;
3742 // char *type;
3743 // uint32_t alignment;
3744 // uint32_t size;
3745 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003746 IvarnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(LongTy),
3747 Int8PtrTy,
3748 Int8PtrTy,
3749 IntTy,
3750 IntTy,
3751 NULL);
3752 CGM.getModule().addTypeName("struct._ivar_t", IvarnfABITy);
3753
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003754 // struct _ivar_list_t {
3755 // uint32 entsize; // sizeof(struct _ivar_t)
3756 // uint32 count;
3757 // struct _iver_t list[count];
3758 // }
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003759 IvarListnfABITy = llvm::StructType::get(IntTy,
3760 IntTy,
3761 llvm::ArrayType::get(
3762 IvarnfABITy, 0),
3763 NULL);
3764 CGM.getModule().addTypeName("struct._ivar_list_t", IvarListnfABITy);
3765
3766 IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003767
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003768 // struct _class_ro_t {
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003769 // uint32_t const flags;
3770 // uint32_t const instanceStart;
3771 // uint32_t const instanceSize;
3772 // uint32_t const reserved; // only when building for 64bit targets
3773 // const uint8_t * const ivarLayout;
3774 // const char *const name;
3775 // const struct _method_list_t * const baseMethods;
3776 // const struct _objc_protocol_list *const baseProtocols;
3777 // const struct _ivar_list_t *const ivars;
3778 // const uint8_t * const weakIvarLayout;
3779 // const struct _prop_list_t * const properties;
3780 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003781
3782 // FIXME. Add 'reserved' field in 64bit abi mode!
3783 ClassRonfABITy = llvm::StructType::get(IntTy,
3784 IntTy,
3785 IntTy,
3786 Int8PtrTy,
3787 Int8PtrTy,
3788 MethodListnfABIPtrTy,
3789 ProtocolListnfABIPtrTy,
3790 IvarListnfABIPtrTy,
3791 Int8PtrTy,
3792 PropertyListPtrTy,
3793 NULL);
3794 CGM.getModule().addTypeName("struct._class_ro_t",
3795 ClassRonfABITy);
3796
3797 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
3798 std::vector<const llvm::Type*> Params;
3799 Params.push_back(ObjectPtrTy);
3800 Params.push_back(SelectorPtrTy);
3801 ImpnfABITy = llvm::PointerType::getUnqual(
3802 llvm::FunctionType::get(ObjectPtrTy, Params, false));
3803
3804 // struct _class_t {
3805 // struct _class_t *isa;
3806 // struct _class_t * const superclass;
3807 // void *cache;
3808 // IMP *vtable;
3809 // struct class_ro_t *ro;
3810 // }
3811
3812 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3813 ClassnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3814 llvm::PointerType::getUnqual(ClassTyHolder),
3815 CachePtrTy,
3816 llvm::PointerType::getUnqual(ImpnfABITy),
3817 llvm::PointerType::getUnqual(
3818 ClassRonfABITy),
3819 NULL);
3820 CGM.getModule().addTypeName("struct._class_t", ClassnfABITy);
3821
3822 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(
3823 ClassnfABITy);
3824
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003825 // LLVM for struct _class_t *
3826 ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy);
3827
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003828 // struct _category_t {
3829 // const char * const name;
3830 // struct _class_t *const cls;
3831 // const struct _method_list_t * const instance_methods;
3832 // const struct _method_list_t * const class_methods;
3833 // const struct _protocol_list_t * const protocols;
3834 // const struct _prop_list_t * const properties;
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003835 // }
3836 CategorynfABITy = llvm::StructType::get(Int8PtrTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003837 ClassnfABIPtrTy,
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003838 MethodListnfABIPtrTy,
3839 MethodListnfABIPtrTy,
3840 ProtocolListnfABIPtrTy,
3841 PropertyListPtrTy,
3842 NULL);
3843 CGM.getModule().addTypeName("struct._category_t", CategorynfABITy);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003844
3845 // New types for nonfragile abi messaging.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003846 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3847 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003848
3849 // MessageRefTy - LLVM for:
3850 // struct _message_ref_t {
3851 // IMP messenger;
3852 // SEL name;
3853 // };
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003854
3855 // First the clang type for struct _message_ref_t
3856 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3857 SourceLocation(),
3858 &Ctx.Idents.get("_message_ref_t"));
Douglas Gregor6ab35242009-04-09 21:40:53 +00003859 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3860 Ctx.VoidPtrTy, 0, false));
3861 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3862 Ctx.getObjCSelType(), 0, false));
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003863 RD->completeDefinition(Ctx);
3864
3865 MessageRefCTy = Ctx.getTagDeclType(RD);
3866 MessageRefCPtrTy = Ctx.getPointerType(MessageRefCTy);
3867 MessageRefTy = cast<llvm::StructType>(Types.ConvertType(MessageRefCTy));
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003868
3869 // MessageRefPtrTy - LLVM for struct _message_ref_t*
3870 MessageRefPtrTy = llvm::PointerType::getUnqual(MessageRefTy);
3871
3872 // SuperMessageRefTy - LLVM for:
3873 // struct _super_message_ref_t {
3874 // SUPER_IMP messenger;
3875 // SEL name;
3876 // };
3877 SuperMessageRefTy = llvm::StructType::get(ImpnfABITy,
3878 SelectorPtrTy,
3879 NULL);
3880 CGM.getModule().addTypeName("struct._super_message_ref_t", SuperMessageRefTy);
3881
3882 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
3883 SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy);
3884
3885 // id objc_msgSend_fixup (id, struct message_ref_t*, ...)
3886 Params.clear();
3887 Params.push_back(ObjectPtrTy);
3888 Params.push_back(MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00003889 MessengerTy = llvm::FunctionType::get(ObjectPtrTy,
3890 Params,
3891 true);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003892 MessageSendFixupFn =
Fariborz Jahanianef163782009-02-05 01:13:09 +00003893 CGM.CreateRuntimeFunction(MessengerTy,
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003894 "objc_msgSend_fixup");
3895
3896 // id objc_msgSend_fpret_fixup (id, struct message_ref_t*, ...)
3897 MessageSendFpretFixupFn =
3898 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3899 Params,
3900 true),
3901 "objc_msgSend_fpret_fixup");
3902
3903 // id objc_msgSend_stret_fixup (id, struct message_ref_t*, ...)
3904 MessageSendStretFixupFn =
3905 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3906 Params,
3907 true),
3908 "objc_msgSend_stret_fixup");
3909
3910 // id objc_msgSendId_fixup (id, struct message_ref_t*, ...)
3911 MessageSendIdFixupFn =
3912 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3913 Params,
3914 true),
3915 "objc_msgSendId_fixup");
3916
3917
3918 // id objc_msgSendId_stret_fixup (id, struct message_ref_t*, ...)
3919 MessageSendIdStretFixupFn =
3920 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3921 Params,
3922 true),
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003923 "objc_msgSendId_stret_fixup");
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003924
3925 // id objc_msgSendSuper2_fixup (struct objc_super *,
3926 // struct _super_message_ref_t*, ...)
3927 Params.clear();
3928 Params.push_back(SuperPtrTy);
3929 Params.push_back(SuperMessageRefPtrTy);
3930 MessageSendSuper2FixupFn =
3931 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3932 Params,
3933 true),
3934 "objc_msgSendSuper2_fixup");
3935
3936
3937 // id objc_msgSendSuper2_stret_fixup (struct objc_super *,
3938 // struct _super_message_ref_t*, ...)
3939 MessageSendSuper2StretFixupFn =
3940 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3941 Params,
3942 true),
3943 "objc_msgSendSuper2_stret_fixup");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00003944
3945 Params.clear();
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00003946 Params.push_back(Int8PtrTy);
3947 UnwindResumeOrRethrowFn =
3948 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3949 Params,
3950 false),
3951 "_Unwind_Resume_or_Rethrow");
Daniel Dunbare588b992009-03-01 04:46:24 +00003952 ObjCBeginCatchFn =
3953 CGM.CreateRuntimeFunction(llvm::FunctionType::get(Int8PtrTy,
3954 Params,
3955 false),
3956 "objc_begin_catch");
3957
3958 Params.clear();
3959 ObjCEndCatchFn =
3960 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3961 Params,
3962 false),
3963 "objc_end_catch");
3964
3965 // struct objc_typeinfo {
3966 // const void** vtable; // objc_ehtype_vtable + 2
3967 // const char* name; // c++ typeinfo string
3968 // Class cls;
3969 // };
3970 EHTypeTy = llvm::StructType::get(llvm::PointerType::getUnqual(Int8PtrTy),
3971 Int8PtrTy,
3972 ClassnfABIPtrTy,
3973 NULL);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00003974 CGM.getModule().addTypeName("struct._objc_typeinfo", EHTypeTy);
Daniel Dunbare588b992009-03-01 04:46:24 +00003975 EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy);
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003976}
3977
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003978llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() {
3979 FinishNonFragileABIModule();
3980
3981 return NULL;
3982}
3983
3984void CGObjCNonFragileABIMac::FinishNonFragileABIModule() {
3985 // nonfragile abi has no module definition.
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003986
3987 // Build list of all implemented classe addresses in array
3988 // L_OBJC_LABEL_CLASS_$.
3989 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CLASS_$
3990 // list of 'nonlazy' implementations (defined as those with a +load{}
3991 // method!!).
3992 unsigned NumClasses = DefinedClasses.size();
3993 if (NumClasses) {
3994 std::vector<llvm::Constant*> Symbols(NumClasses);
3995 for (unsigned i=0; i<NumClasses; i++)
3996 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
3997 ObjCTypes.Int8PtrTy);
3998 llvm::Constant* Init =
3999 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
4000 NumClasses),
4001 Symbols);
4002
4003 llvm::GlobalVariable *GV =
4004 new llvm::GlobalVariable(Init->getType(), false,
4005 llvm::GlobalValue::InternalLinkage,
4006 Init,
4007 "\01L_OBJC_LABEL_CLASS_$",
4008 &CGM.getModule());
Daniel Dunbar58a29122009-03-09 22:18:41 +00004009 GV->setAlignment(8);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004010 GV->setSection("__DATA, __objc_classlist, regular, no_dead_strip");
4011 UsedGlobals.push_back(GV);
4012 }
4013
4014 // Build list of all implemented category addresses in array
4015 // L_OBJC_LABEL_CATEGORY_$.
4016 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CATEGORY_$
4017 // list of 'nonlazy' category implementations (defined as those with a +load{}
4018 // method!!).
4019 unsigned NumCategory = DefinedCategories.size();
4020 if (NumCategory) {
4021 std::vector<llvm::Constant*> Symbols(NumCategory);
4022 for (unsigned i=0; i<NumCategory; i++)
4023 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedCategories[i],
4024 ObjCTypes.Int8PtrTy);
4025 llvm::Constant* Init =
4026 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
4027 NumCategory),
4028 Symbols);
4029
4030 llvm::GlobalVariable *GV =
4031 new llvm::GlobalVariable(Init->getType(), false,
4032 llvm::GlobalValue::InternalLinkage,
4033 Init,
4034 "\01L_OBJC_LABEL_CATEGORY_$",
4035 &CGM.getModule());
Daniel Dunbar58a29122009-03-09 22:18:41 +00004036 GV->setAlignment(8);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004037 GV->setSection("__DATA, __objc_catlist, regular, no_dead_strip");
4038 UsedGlobals.push_back(GV);
4039 }
4040
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004041 // static int L_OBJC_IMAGE_INFO[2] = { 0, flags };
4042 // FIXME. flags can be 0 | 1 | 2 | 6. For now just use 0
4043 std::vector<llvm::Constant*> Values(2);
4044 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, 0);
Fariborz Jahanian067986e2009-02-24 21:08:09 +00004045 unsigned int flags = 0;
Fariborz Jahanian66a5c2c2009-02-24 23:34:44 +00004046 // FIXME: Fix and continue?
4047 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
4048 flags |= eImageInfo_GarbageCollected;
4049 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
4050 flags |= eImageInfo_GCOnly;
Fariborz Jahanian067986e2009-02-24 21:08:09 +00004051 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004052 llvm::Constant* Init = llvm::ConstantArray::get(
4053 llvm::ArrayType::get(ObjCTypes.IntTy, 2),
4054 Values);
4055 llvm::GlobalVariable *IMGV =
4056 new llvm::GlobalVariable(Init->getType(), false,
4057 llvm::GlobalValue::InternalLinkage,
4058 Init,
4059 "\01L_OBJC_IMAGE_INFO",
4060 &CGM.getModule());
4061 IMGV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
4062 UsedGlobals.push_back(IMGV);
4063
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004064 std::vector<llvm::Constant*> Used;
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004065
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004066 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
4067 e = UsedGlobals.end(); i != e; ++i) {
4068 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
4069 }
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004070
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004071 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
4072 llvm::GlobalValue *GV =
4073 new llvm::GlobalVariable(AT, false,
4074 llvm::GlobalValue::AppendingLinkage,
4075 llvm::ConstantArray::get(AT, Used),
4076 "llvm.used",
4077 &CGM.getModule());
4078
4079 GV->setSection("llvm.metadata");
4080
4081}
4082
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004083// Metadata flags
4084enum MetaDataDlags {
4085 CLS = 0x0,
4086 CLS_META = 0x1,
4087 CLS_ROOT = 0x2,
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004088 OBJC2_CLS_HIDDEN = 0x10,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004089 CLS_EXCEPTION = 0x20
4090};
4091/// BuildClassRoTInitializer - generate meta-data for:
4092/// struct _class_ro_t {
4093/// uint32_t const flags;
4094/// uint32_t const instanceStart;
4095/// uint32_t const instanceSize;
4096/// uint32_t const reserved; // only when building for 64bit targets
4097/// const uint8_t * const ivarLayout;
4098/// const char *const name;
4099/// const struct _method_list_t * const baseMethods;
Fariborz Jahanianda320092009-01-29 19:24:30 +00004100/// const struct _protocol_list_t *const baseProtocols;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004101/// const struct _ivar_list_t *const ivars;
4102/// const uint8_t * const weakIvarLayout;
4103/// const struct _prop_list_t * const properties;
4104/// }
4105///
4106llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer(
4107 unsigned flags,
4108 unsigned InstanceStart,
4109 unsigned InstanceSize,
4110 const ObjCImplementationDecl *ID) {
4111 std::string ClassName = ID->getNameAsString();
4112 std::vector<llvm::Constant*> Values(10); // 11 for 64bit targets!
4113 Values[ 0] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
4114 Values[ 1] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceStart);
4115 Values[ 2] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceSize);
4116 // FIXME. For 64bit targets add 0 here.
Fariborz Jahanianda320092009-01-29 19:24:30 +00004117 // FIXME. ivarLayout is currently null!
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00004118 Values[ 3] = GetIvarLayoutName(0, ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004119 Values[ 4] = GetClassName(ID->getIdentifier());
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004120 // const struct _method_list_t * const baseMethods;
4121 std::vector<llvm::Constant*> Methods;
4122 std::string MethodListName("\01l_OBJC_$_");
4123 if (flags & CLS_META) {
4124 MethodListName += "CLASS_METHODS_" + ID->getNameAsString();
4125 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
4126 e = ID->classmeth_end(); i != e; ++i) {
4127 // Class methods should always be defined.
4128 Methods.push_back(GetMethodConstant(*i));
4129 }
4130 } else {
4131 MethodListName += "INSTANCE_METHODS_" + ID->getNameAsString();
4132 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
4133 e = ID->instmeth_end(); i != e; ++i) {
4134 // Instance methods should always be defined.
4135 Methods.push_back(GetMethodConstant(*i));
4136 }
Fariborz Jahanian939abce2009-01-28 22:46:49 +00004137 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
4138 e = ID->propimpl_end(); i != e; ++i) {
4139 ObjCPropertyImplDecl *PID = *i;
4140
4141 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize){
4142 ObjCPropertyDecl *PD = PID->getPropertyDecl();
4143
4144 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
4145 if (llvm::Constant *C = GetMethodConstant(MD))
4146 Methods.push_back(C);
4147 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
4148 if (llvm::Constant *C = GetMethodConstant(MD))
4149 Methods.push_back(C);
4150 }
4151 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004152 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004153 Values[ 5] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004154 "__DATA, __objc_const", Methods);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004155
4156 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4157 assert(OID && "CGObjCNonFragileABIMac::BuildClassRoTInitializer");
4158 Values[ 6] = EmitProtocolList("\01l_OBJC_CLASS_PROTOCOLS_$_"
4159 + OID->getNameAsString(),
4160 OID->protocol_begin(),
4161 OID->protocol_end());
4162
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004163 if (flags & CLS_META)
4164 Values[ 7] = llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4165 else
4166 Values[ 7] = EmitIvarList(ID);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004167 // FIXME. weakIvarLayout is currently null.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00004168 Values[ 8] = GetIvarLayoutName(0, ObjCTypes);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004169 if (flags & CLS_META)
4170 Values[ 9] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4171 else
4172 Values[ 9] =
4173 EmitPropertyList(
4174 "\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
4175 ID, ID->getClassInterface(), ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004176 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassRonfABITy,
4177 Values);
4178 llvm::GlobalVariable *CLASS_RO_GV =
4179 new llvm::GlobalVariable(ObjCTypes.ClassRonfABITy, false,
4180 llvm::GlobalValue::InternalLinkage,
4181 Init,
4182 (flags & CLS_META) ?
4183 std::string("\01l_OBJC_METACLASS_RO_$_")+ClassName :
4184 std::string("\01l_OBJC_CLASS_RO_$_")+ClassName,
4185 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004186 CLASS_RO_GV->setAlignment(
4187 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassRonfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004188 CLASS_RO_GV->setSection("__DATA, __objc_const");
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004189 return CLASS_RO_GV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004190
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004191}
4192
4193/// BuildClassMetaData - This routine defines that to-level meta-data
4194/// for the given ClassName for:
4195/// struct _class_t {
4196/// struct _class_t *isa;
4197/// struct _class_t * const superclass;
4198/// void *cache;
4199/// IMP *vtable;
4200/// struct class_ro_t *ro;
4201/// }
4202///
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004203llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassMetaData(
4204 std::string &ClassName,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004205 llvm::Constant *IsAGV,
4206 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004207 llvm::Constant *ClassRoGV,
4208 bool HiddenVisibility) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004209 std::vector<llvm::Constant*> Values(5);
4210 Values[0] = IsAGV;
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004211 Values[1] = SuperClassGV
4212 ? SuperClassGV
4213 : llvm::Constant::getNullValue(ObjCTypes.ClassnfABIPtrTy);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004214 Values[2] = ObjCEmptyCacheVar; // &ObjCEmptyCacheVar
4215 Values[3] = ObjCEmptyVtableVar; // &ObjCEmptyVtableVar
4216 Values[4] = ClassRoGV; // &CLASS_RO_GV
4217 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassnfABITy,
4218 Values);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004219 llvm::GlobalVariable *GV = GetClassGlobal(ClassName);
4220 GV->setInitializer(Init);
Fariborz Jahaniandd0db2a2009-01-31 01:07:39 +00004221 GV->setSection("__DATA, __objc_data");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004222 GV->setAlignment(
4223 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassnfABITy));
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004224 if (HiddenVisibility)
4225 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004226 return GV;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004227}
4228
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004229void CGObjCNonFragileABIMac::GetClassSizeInfo(const ObjCInterfaceDecl *OID,
4230 uint32_t &InstanceStart,
4231 uint32_t &InstanceSize) {
4232 // FIXME. Share this with the one in EmitIvarList.
4233 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID);
4234
4235 RecordDecl::field_iterator firstField, lastField;
4236 const RecordDecl *RD = GetFirstIvarInRecord(OID, firstField, lastField);
4237
4238 for (RecordDecl::field_iterator e = RD->field_end(CGM.getContext()),
4239 ifield = firstField; ifield != e; ++ifield)
4240 lastField = ifield;
4241
4242 InstanceStart = InstanceSize = 0;
4243 if (lastField != RD->field_end(CGM.getContext())) {
4244 FieldDecl *Field = *lastField;
4245 const llvm::Type *FieldTy =
4246 CGM.getTypes().ConvertTypeForMem(Field->getType());
4247 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
4248 InstanceSize = GetIvarBaseOffset(Layout, Field) + Size;
4249 if (firstField == RD->field_end(CGM.getContext()))
4250 InstanceStart = InstanceSize;
4251 else {
4252 Field = *firstField;
4253 InstanceStart = GetIvarBaseOffset(Layout, Field);
4254 }
4255 }
4256}
4257
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004258void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) {
4259 std::string ClassName = ID->getNameAsString();
4260 if (!ObjCEmptyCacheVar) {
4261 ObjCEmptyCacheVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004262 ObjCTypes.CacheTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004263 false,
4264 llvm::GlobalValue::ExternalLinkage,
4265 0,
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004266 "_objc_empty_cache",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004267 &CGM.getModule());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004268
4269 ObjCEmptyVtableVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004270 ObjCTypes.ImpnfABITy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004271 false,
4272 llvm::GlobalValue::ExternalLinkage,
4273 0,
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004274 "_objc_empty_vtable",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004275 &CGM.getModule());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004276 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004277 assert(ID->getClassInterface() &&
4278 "CGObjCNonFragileABIMac::GenerateClass - class is 0");
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004279 // FIXME: Is this correct (That meta class size is never computed)?
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004280 uint32_t InstanceStart =
4281 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassnfABITy);
4282 uint32_t InstanceSize = InstanceStart;
4283 uint32_t flags = CLS_META;
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004284 std::string ObjCMetaClassName(getMetaclassSymbolPrefix());
4285 std::string ObjCClassName(getClassSymbolPrefix());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004286
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004287 llvm::GlobalVariable *SuperClassGV, *IsAGV;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004288
Daniel Dunbar04d40782009-04-14 06:00:08 +00004289 bool classIsHidden =
4290 CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004291 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004292 flags |= OBJC2_CLS_HIDDEN;
4293 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004294 // class is root
4295 flags |= CLS_ROOT;
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004296 SuperClassGV = GetClassGlobal(ObjCClassName + ClassName);
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004297 IsAGV = GetClassGlobal(ObjCMetaClassName + ClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004298 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004299 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004300 const ObjCInterfaceDecl *Root = ID->getClassInterface();
4301 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
4302 Root = Super;
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004303 IsAGV = GetClassGlobal(ObjCMetaClassName + Root->getNameAsString());
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004304 // work on super class metadata symbol.
4305 std::string SuperClassName =
4306 ObjCMetaClassName + ID->getClassInterface()->getSuperClass()->getNameAsString();
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004307 SuperClassGV = GetClassGlobal(SuperClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004308 }
4309 llvm::GlobalVariable *CLASS_RO_GV = BuildClassRoTInitializer(flags,
4310 InstanceStart,
4311 InstanceSize,ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004312 std::string TClassName = ObjCMetaClassName + ClassName;
4313 llvm::GlobalVariable *MetaTClass =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004314 BuildClassMetaData(TClassName, IsAGV, SuperClassGV, CLASS_RO_GV,
4315 classIsHidden);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004316
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004317 // Metadata for the class
4318 flags = CLS;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004319 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004320 flags |= OBJC2_CLS_HIDDEN;
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004321
4322 if (hasObjCExceptionAttribute(ID->getClassInterface()))
4323 flags |= CLS_EXCEPTION;
4324
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004325 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004326 flags |= CLS_ROOT;
4327 SuperClassGV = 0;
Chris Lattnerb7b58b12009-04-19 06:02:28 +00004328 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004329 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004330 std::string RootClassName =
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004331 ID->getClassInterface()->getSuperClass()->getNameAsString();
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004332 SuperClassGV = GetClassGlobal(ObjCClassName + RootClassName);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004333 }
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004334 GetClassSizeInfo(ID->getClassInterface(), InstanceStart, InstanceSize);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004335 CLASS_RO_GV = BuildClassRoTInitializer(flags,
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004336 InstanceStart,
4337 InstanceSize,
4338 ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004339
4340 TClassName = ObjCClassName + ClassName;
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004341 llvm::GlobalVariable *ClassMD =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004342 BuildClassMetaData(TClassName, MetaTClass, SuperClassGV, CLASS_RO_GV,
4343 classIsHidden);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004344 DefinedClasses.push_back(ClassMD);
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004345
4346 // Force the definition of the EHType if necessary.
4347 if (flags & CLS_EXCEPTION)
4348 GetInterfaceEHType(ID->getClassInterface(), true);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004349}
4350
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004351/// GenerateProtocolRef - This routine is called to generate code for
4352/// a protocol reference expression; as in:
4353/// @code
4354/// @protocol(Proto1);
4355/// @endcode
4356/// It generates a weak reference to l_OBJC_PROTOCOL_REFERENCE_$_Proto1
4357/// which will hold address of the protocol meta-data.
4358///
4359llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CGBuilderTy &Builder,
4360 const ObjCProtocolDecl *PD) {
4361
Fariborz Jahanian960cd062009-04-10 18:47:34 +00004362 // This routine is called for @protocol only. So, we must build definition
4363 // of protocol's meta-data (not a reference to it!)
4364 //
4365 llvm::Constant *Init = llvm::ConstantExpr::getBitCast(GetOrEmitProtocol(PD),
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004366 ObjCTypes.ExternalProtocolPtrTy);
4367
4368 std::string ProtocolName("\01l_OBJC_PROTOCOL_REFERENCE_$_");
4369 ProtocolName += PD->getNameAsCString();
4370
4371 llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName);
4372 if (PTGV)
4373 return Builder.CreateLoad(PTGV, false, "tmp");
4374 PTGV = new llvm::GlobalVariable(
4375 Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00004376 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004377 Init,
4378 ProtocolName,
4379 &CGM.getModule());
4380 PTGV->setSection("__DATA, __objc_protorefs, coalesced, no_dead_strip");
4381 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4382 UsedGlobals.push_back(PTGV);
4383 return Builder.CreateLoad(PTGV, false, "tmp");
4384}
4385
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004386/// GenerateCategory - Build metadata for a category implementation.
4387/// struct _category_t {
4388/// const char * const name;
4389/// struct _class_t *const cls;
4390/// const struct _method_list_t * const instance_methods;
4391/// const struct _method_list_t * const class_methods;
4392/// const struct _protocol_list_t * const protocols;
4393/// const struct _prop_list_t * const properties;
4394/// }
4395///
4396void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD)
4397{
4398 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004399 const char *Prefix = "\01l_OBJC_$_CATEGORY_";
4400 std::string ExtCatName(Prefix + Interface->getNameAsString()+
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004401 "_$_" + OCD->getNameAsString());
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004402 std::string ExtClassName(getClassSymbolPrefix() +
4403 Interface->getNameAsString());
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004404
4405 std::vector<llvm::Constant*> Values(6);
4406 Values[0] = GetClassName(OCD->getIdentifier());
4407 // meta-class entry symbol
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004408 llvm::GlobalVariable *ClassGV = GetClassGlobal(ExtClassName);
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004409 Values[1] = ClassGV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004410 std::vector<llvm::Constant*> Methods;
4411 std::string MethodListName(Prefix);
4412 MethodListName += "INSTANCE_METHODS_" + Interface->getNameAsString() +
4413 "_$_" + OCD->getNameAsString();
4414
4415 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
4416 e = OCD->instmeth_end(); i != e; ++i) {
4417 // Instance methods should always be defined.
4418 Methods.push_back(GetMethodConstant(*i));
4419 }
4420
4421 Values[2] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004422 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004423 Methods);
4424
4425 MethodListName = Prefix;
4426 MethodListName += "CLASS_METHODS_" + Interface->getNameAsString() + "_$_" +
4427 OCD->getNameAsString();
4428 Methods.clear();
4429 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
4430 e = OCD->classmeth_end(); i != e; ++i) {
4431 // Class methods should always be defined.
4432 Methods.push_back(GetMethodConstant(*i));
4433 }
4434
4435 Values[3] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004436 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004437 Methods);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004438 const ObjCCategoryDecl *Category =
4439 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Fariborz Jahanian943ed6f2009-02-13 17:52:22 +00004440 if (Category) {
4441 std::string ExtName(Interface->getNameAsString() + "_$_" +
4442 OCD->getNameAsString());
4443 Values[4] = EmitProtocolList("\01l_OBJC_CATEGORY_PROTOCOLS_$_"
4444 + Interface->getNameAsString() + "_$_"
4445 + Category->getNameAsString(),
4446 Category->protocol_begin(),
4447 Category->protocol_end());
4448 Values[5] =
4449 EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
4450 OCD, Category, ObjCTypes);
4451 }
4452 else {
4453 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4454 Values[5] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4455 }
4456
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004457 llvm::Constant *Init =
4458 llvm::ConstantStruct::get(ObjCTypes.CategorynfABITy,
4459 Values);
4460 llvm::GlobalVariable *GCATV
4461 = new llvm::GlobalVariable(ObjCTypes.CategorynfABITy,
4462 false,
4463 llvm::GlobalValue::InternalLinkage,
4464 Init,
4465 ExtCatName,
4466 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004467 GCATV->setAlignment(
4468 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.CategorynfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004469 GCATV->setSection("__DATA, __objc_const");
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004470 UsedGlobals.push_back(GCATV);
4471 DefinedCategories.push_back(GCATV);
4472}
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004473
4474/// GetMethodConstant - Return a struct objc_method constant for the
4475/// given method if it has been defined. The result is null if the
4476/// method has not been defined. The return value has type MethodPtrTy.
4477llvm::Constant *CGObjCNonFragileABIMac::GetMethodConstant(
4478 const ObjCMethodDecl *MD) {
4479 // FIXME: Use DenseMap::lookup
4480 llvm::Function *Fn = MethodDefinitions[MD];
4481 if (!Fn)
4482 return 0;
4483
4484 std::vector<llvm::Constant*> Method(3);
4485 Method[0] =
4486 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4487 ObjCTypes.SelectorPtrTy);
4488 Method[1] = GetMethodVarType(MD);
4489 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
4490 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
4491}
4492
4493/// EmitMethodList - Build meta-data for method declarations
4494/// struct _method_list_t {
4495/// uint32_t entsize; // sizeof(struct _objc_method)
4496/// uint32_t method_count;
4497/// struct _objc_method method_list[method_count];
4498/// }
4499///
4500llvm::Constant *CGObjCNonFragileABIMac::EmitMethodList(
4501 const std::string &Name,
4502 const char *Section,
4503 const ConstantVector &Methods) {
4504 // Return null for empty list.
4505 if (Methods.empty())
4506 return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy);
4507
4508 std::vector<llvm::Constant*> Values(3);
4509 // sizeof(struct _objc_method)
4510 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.MethodTy);
4511 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4512 // method_count
4513 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
4514 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
4515 Methods.size());
4516 Values[2] = llvm::ConstantArray::get(AT, Methods);
4517 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4518
4519 llvm::GlobalVariable *GV =
4520 new llvm::GlobalVariable(Init->getType(), false,
4521 llvm::GlobalValue::InternalLinkage,
4522 Init,
4523 Name,
4524 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004525 GV->setAlignment(
4526 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004527 GV->setSection(Section);
4528 UsedGlobals.push_back(GV);
4529 return llvm::ConstantExpr::getBitCast(GV,
4530 ObjCTypes.MethodListnfABIPtrTy);
4531}
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004532
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004533/// ObjCIvarOffsetVariable - Returns the ivar offset variable for
4534/// the given ivar.
4535///
4536llvm::GlobalVariable * CGObjCNonFragileABIMac::ObjCIvarOffsetVariable(
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004537 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004538 const ObjCIvarDecl *Ivar) {
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00004539 std::string Name = "OBJC_IVAR_$_" +
Douglas Gregor6ab35242009-04-09 21:40:53 +00004540 getInterfaceDeclForIvar(ID, Ivar, CGM.getContext())->getNameAsString() +
4541 '.' + Ivar->getNameAsString();
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004542 llvm::GlobalVariable *IvarOffsetGV =
4543 CGM.getModule().getGlobalVariable(Name);
4544 if (!IvarOffsetGV)
4545 IvarOffsetGV =
4546 new llvm::GlobalVariable(ObjCTypes.LongTy,
4547 false,
4548 llvm::GlobalValue::ExternalLinkage,
4549 0,
4550 Name,
4551 &CGM.getModule());
4552 return IvarOffsetGV;
4553}
4554
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004555llvm::Constant * CGObjCNonFragileABIMac::EmitIvarOffsetVar(
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004556 const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004557 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004558 unsigned long int Offset) {
Daniel Dunbar737c5022009-04-19 00:44:02 +00004559 llvm::GlobalVariable *IvarOffsetGV = ObjCIvarOffsetVariable(ID, Ivar);
4560 IvarOffsetGV->setInitializer(llvm::ConstantInt::get(ObjCTypes.LongTy,
4561 Offset));
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004562 IvarOffsetGV->setAlignment(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004563 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.LongTy));
Daniel Dunbar737c5022009-04-19 00:44:02 +00004564
4565 // FIXME: This matches gcc, but shouldn't the visibility be set on
4566 // the use as well (i.e., in ObjCIvarOffsetVariable).
4567 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
4568 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
4569 CGM.getDeclVisibilityMode(ID) == LangOptions::Hidden)
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004570 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar04d40782009-04-14 06:00:08 +00004571 else
Fariborz Jahanian77c9fd22009-04-06 18:30:00 +00004572 IvarOffsetGV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004573 IvarOffsetGV->setSection("__DATA, __objc_const");
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004574 return IvarOffsetGV;
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004575}
4576
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004577/// EmitIvarList - Emit the ivar list for the given
Daniel Dunbar11394522009-04-18 08:51:00 +00004578/// implementation. The return value has type
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004579/// IvarListnfABIPtrTy.
4580/// struct _ivar_t {
4581/// unsigned long int *offset; // pointer to ivar offset location
4582/// char *name;
4583/// char *type;
4584/// uint32_t alignment;
4585/// uint32_t size;
4586/// }
4587/// struct _ivar_list_t {
4588/// uint32 entsize; // sizeof(struct _ivar_t)
4589/// uint32 count;
4590/// struct _iver_t list[count];
4591/// }
4592///
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004593
4594void CGObjCCommonMac::GetNamedIvarList(const ObjCInterfaceDecl *OID,
4595 llvm::SmallVector<ObjCIvarDecl*, 16> &Res) const {
4596 for (ObjCInterfaceDecl::ivar_iterator I = OID->ivar_begin(),
4597 E = OID->ivar_end(); I != E; ++I) {
4598 // Ignore unnamed bit-fields.
4599 if (!(*I)->getDeclName())
4600 continue;
4601
4602 Res.push_back(*I);
4603 }
4604
4605 for (ObjCInterfaceDecl::prop_iterator I = OID->prop_begin(CGM.getContext()),
4606 E = OID->prop_end(CGM.getContext()); I != E; ++I)
4607 if (ObjCIvarDecl *IV = (*I)->getPropertyIvarDecl())
4608 Res.push_back(IV);
4609}
4610
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004611llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList(
4612 const ObjCImplementationDecl *ID) {
4613
4614 std::vector<llvm::Constant*> Ivars, Ivar(5);
4615
4616 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4617 assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface");
4618
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004619 // FIXME. Consolidate this with similar code in GenerateClass.
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00004620 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00004621
Daniel Dunbar91636d62009-04-20 00:33:43 +00004622 // Collect declared and synthesized ivars in a small vector.
Fariborz Jahanian18191882009-03-31 18:11:23 +00004623 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004624 GetNamedIvarList(OID, OIvars);
Fariborz Jahanian99eee362009-04-01 19:37:34 +00004625
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004626 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
4627 ObjCIvarDecl *IVD = OIvars[i];
4628 const FieldDecl *Field = OID->lookupFieldDeclForIvar(CGM.getContext(), IVD);
Daniel Dunbar3eec8aa2009-04-20 05:53:40 +00004629 Ivar[0] = EmitIvarOffsetVar(ID->getClassInterface(), IVD,
Daniel Dunbar48fa0642009-04-19 02:03:42 +00004630 GetIvarBaseOffset(Layout, Field));
Daniel Dunbar3eec8aa2009-04-20 05:53:40 +00004631 Ivar[1] = GetMethodVarName(Field->getIdentifier());
Devang Patel7794bb82009-03-04 18:21:39 +00004632 Ivar[2] = GetMethodVarType(Field);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004633 const llvm::Type *FieldTy =
4634 CGM.getTypes().ConvertTypeForMem(Field->getType());
4635 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
4636 unsigned Align = CGM.getContext().getPreferredTypeAlign(
4637 Field->getType().getTypePtr()) >> 3;
4638 Align = llvm::Log2_32(Align);
4639 Ivar[3] = llvm::ConstantInt::get(ObjCTypes.IntTy, Align);
Daniel Dunbar91636d62009-04-20 00:33:43 +00004640 // NOTE. Size of a bitfield does not match gcc's, because of the
4641 // way bitfields are treated special in each. But I am told that
4642 // 'size' for bitfield ivars is ignored by the runtime so it does
4643 // not matter. If it matters, there is enough info to get the
4644 // bitfield right!
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004645 Ivar[4] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4646 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarnfABITy, Ivar));
4647 }
4648 // Return null for empty list.
4649 if (Ivars.empty())
4650 return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4651 std::vector<llvm::Constant*> Values(3);
4652 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.IvarnfABITy);
4653 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4654 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
4655 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarnfABITy,
4656 Ivars.size());
4657 Values[2] = llvm::ConstantArray::get(AT, Ivars);
4658 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4659 const char *Prefix = "\01l_OBJC_$_INSTANCE_VARIABLES_";
4660 llvm::GlobalVariable *GV =
4661 new llvm::GlobalVariable(Init->getType(), false,
4662 llvm::GlobalValue::InternalLinkage,
4663 Init,
4664 Prefix + OID->getNameAsString(),
4665 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004666 GV->setAlignment(
4667 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004668 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004669
4670 UsedGlobals.push_back(GV);
4671 return llvm::ConstantExpr::getBitCast(GV,
4672 ObjCTypes.IvarListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004673}
4674
4675llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef(
4676 const ObjCProtocolDecl *PD) {
4677 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4678
4679 if (!Entry) {
4680 // We use the initializer as a marker of whether this is a forward
4681 // reference or not. At module finalization we add the empty
4682 // contents for protocols which were referenced but never defined.
4683 Entry =
4684 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
4685 llvm::GlobalValue::ExternalLinkage,
4686 0,
4687 "\01l_OBJC_PROTOCOL_$_" + PD->getNameAsString(),
4688 &CGM.getModule());
4689 Entry->setSection("__DATA,__datacoal_nt,coalesced");
4690 UsedGlobals.push_back(Entry);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004691 }
4692
4693 return Entry;
4694}
4695
4696/// GetOrEmitProtocol - Generate the protocol meta-data:
4697/// @code
4698/// struct _protocol_t {
4699/// id isa; // NULL
4700/// const char * const protocol_name;
4701/// const struct _protocol_list_t * protocol_list; // super protocols
4702/// const struct method_list_t * const instance_methods;
4703/// const struct method_list_t * const class_methods;
4704/// const struct method_list_t *optionalInstanceMethods;
4705/// const struct method_list_t *optionalClassMethods;
4706/// const struct _prop_list_t * properties;
4707/// const uint32_t size; // sizeof(struct _protocol_t)
4708/// const uint32_t flags; // = 0
4709/// }
4710/// @endcode
4711///
4712
4713llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol(
4714 const ObjCProtocolDecl *PD) {
4715 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4716
4717 // Early exit if a defining object has already been generated.
4718 if (Entry && Entry->hasInitializer())
4719 return Entry;
4720
4721 const char *ProtocolName = PD->getNameAsCString();
4722
4723 // Construct method lists.
4724 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
4725 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregor6ab35242009-04-09 21:40:53 +00004726 for (ObjCProtocolDecl::instmeth_iterator
4727 i = PD->instmeth_begin(CGM.getContext()),
4728 e = PD->instmeth_end(CGM.getContext());
4729 i != e; ++i) {
Fariborz Jahanianda320092009-01-29 19:24:30 +00004730 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004731 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004732 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4733 OptInstanceMethods.push_back(C);
4734 } else {
4735 InstanceMethods.push_back(C);
4736 }
4737 }
4738
Douglas Gregor6ab35242009-04-09 21:40:53 +00004739 for (ObjCProtocolDecl::classmeth_iterator
4740 i = PD->classmeth_begin(CGM.getContext()),
4741 e = PD->classmeth_end(CGM.getContext());
4742 i != e; ++i) {
Fariborz Jahanianda320092009-01-29 19:24:30 +00004743 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004744 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004745 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4746 OptClassMethods.push_back(C);
4747 } else {
4748 ClassMethods.push_back(C);
4749 }
4750 }
4751
4752 std::vector<llvm::Constant*> Values(10);
4753 // isa is NULL
4754 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ObjectPtrTy);
4755 Values[1] = GetClassName(PD->getIdentifier());
4756 Values[2] = EmitProtocolList(
4757 "\01l_OBJC_$_PROTOCOL_REFS_" + PD->getNameAsString(),
4758 PD->protocol_begin(),
4759 PD->protocol_end());
4760
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004761 Values[3] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004762 + PD->getNameAsString(),
4763 "__DATA, __objc_const",
4764 InstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004765 Values[4] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004766 + PD->getNameAsString(),
4767 "__DATA, __objc_const",
4768 ClassMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004769 Values[5] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004770 + PD->getNameAsString(),
4771 "__DATA, __objc_const",
4772 OptInstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004773 Values[6] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004774 + PD->getNameAsString(),
4775 "__DATA, __objc_const",
4776 OptClassMethods);
4777 Values[7] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + PD->getNameAsString(),
4778 0, PD, ObjCTypes);
4779 uint32_t Size =
4780 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolnfABITy);
4781 Values[8] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4782 Values[9] = llvm::Constant::getNullValue(ObjCTypes.IntTy);
4783 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolnfABITy,
4784 Values);
4785
4786 if (Entry) {
4787 // Already created, fix the linkage and update the initializer.
Mike Stump286acbd2009-03-07 16:33:28 +00004788 Entry->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004789 Entry->setInitializer(Init);
4790 } else {
4791 Entry =
4792 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004793 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004794 Init,
4795 std::string("\01l_OBJC_PROTOCOL_$_")+ProtocolName,
4796 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004797 Entry->setAlignment(
4798 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABITy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004799 Entry->setSection("__DATA,__datacoal_nt,coalesced");
Fariborz Jahanianda320092009-01-29 19:24:30 +00004800 }
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004801 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
4802
4803 // Use this protocol meta-data to build protocol list table in section
4804 // __DATA, __objc_protolist
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004805 llvm::GlobalVariable *PTGV = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004806 ObjCTypes.ProtocolnfABIPtrTy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004807 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004808 Entry,
4809 std::string("\01l_OBJC_LABEL_PROTOCOL_$_")
4810 +ProtocolName,
4811 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004812 PTGV->setAlignment(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004813 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABIPtrTy));
Daniel Dunbar0bf21992009-04-15 02:56:18 +00004814 PTGV->setSection("__DATA, __objc_protolist, coalesced, no_dead_strip");
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004815 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4816 UsedGlobals.push_back(PTGV);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004817 return Entry;
4818}
4819
4820/// EmitProtocolList - Generate protocol list meta-data:
4821/// @code
4822/// struct _protocol_list_t {
4823/// long protocol_count; // Note, this is 32/64 bit
4824/// struct _protocol_t[protocol_count];
4825/// }
4826/// @endcode
4827///
4828llvm::Constant *
4829CGObjCNonFragileABIMac::EmitProtocolList(const std::string &Name,
4830 ObjCProtocolDecl::protocol_iterator begin,
4831 ObjCProtocolDecl::protocol_iterator end) {
4832 std::vector<llvm::Constant*> ProtocolRefs;
4833
Fariborz Jahanianda320092009-01-29 19:24:30 +00004834 // Just return null for empty protocol lists
Daniel Dunbar948e2582009-02-15 07:36:20 +00004835 if (begin == end)
Fariborz Jahanianda320092009-01-29 19:24:30 +00004836 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4837
Daniel Dunbar948e2582009-02-15 07:36:20 +00004838 // FIXME: We shouldn't need to do this lookup here, should we?
Fariborz Jahanianda320092009-01-29 19:24:30 +00004839 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
4840 if (GV)
Daniel Dunbar948e2582009-02-15 07:36:20 +00004841 return llvm::ConstantExpr::getBitCast(GV,
4842 ObjCTypes.ProtocolListnfABIPtrTy);
4843
4844 for (; begin != end; ++begin)
4845 ProtocolRefs.push_back(GetProtocolRef(*begin)); // Implemented???
4846
Fariborz Jahanianda320092009-01-29 19:24:30 +00004847 // This list is null terminated.
4848 ProtocolRefs.push_back(llvm::Constant::getNullValue(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004849 ObjCTypes.ProtocolnfABIPtrTy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004850
4851 std::vector<llvm::Constant*> Values(2);
4852 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
4853 Values[1] =
Daniel Dunbar948e2582009-02-15 07:36:20 +00004854 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolnfABIPtrTy,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004855 ProtocolRefs.size()),
4856 ProtocolRefs);
4857
4858 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4859 GV = new llvm::GlobalVariable(Init->getType(), false,
4860 llvm::GlobalValue::InternalLinkage,
4861 Init,
4862 Name,
4863 &CGM.getModule());
4864 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004865 GV->setAlignment(
4866 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004867 UsedGlobals.push_back(GV);
Daniel Dunbar948e2582009-02-15 07:36:20 +00004868 return llvm::ConstantExpr::getBitCast(GV,
4869 ObjCTypes.ProtocolListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004870}
4871
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004872/// GetMethodDescriptionConstant - This routine build following meta-data:
4873/// struct _objc_method {
4874/// SEL _cmd;
4875/// char *method_type;
4876/// char *_imp;
4877/// }
4878
4879llvm::Constant *
4880CGObjCNonFragileABIMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
4881 std::vector<llvm::Constant*> Desc(3);
4882 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4883 ObjCTypes.SelectorPtrTy);
4884 Desc[1] = GetMethodVarType(MD);
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004885 // Protocol methods have no implementation. So, this entry is always NULL.
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004886 Desc[2] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
4887 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Desc);
4888}
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004889
4890/// EmitObjCValueForIvar - Code Gen for nonfragile ivar reference.
4891/// This code gen. amounts to generating code for:
4892/// @code
4893/// (type *)((char *)base + _OBJC_IVAR_$_.ivar;
4894/// @encode
4895///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004896LValue CGObjCNonFragileABIMac::EmitObjCValueForIvar(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004897 CodeGen::CodeGenFunction &CGF,
4898 QualType ObjectTy,
4899 llvm::Value *BaseValue,
4900 const ObjCIvarDecl *Ivar,
4901 const FieldDecl *Field,
4902 unsigned CVRQualifiers) {
4903 assert(ObjectTy->isObjCInterfaceType() &&
4904 "CGObjCNonFragileABIMac::EmitObjCValueForIvar");
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004905 ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00004906 llvm::GlobalVariable *IvarOffsetGV = ObjCIvarOffsetVariable(ID, Ivar);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004907
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004908 // (char *) BaseValue
Chris Lattner51123fe2009-04-17 17:46:19 +00004909 llvm::Value *V = CGF.Builder.CreateBitCast(BaseValue, ObjCTypes.Int8PtrTy);
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004910 llvm::Value *Offset = CGF.Builder.CreateLoad(IvarOffsetGV);
4911 // (char*)BaseValue + Offset_symbol
4912 V = CGF.Builder.CreateGEP(V, Offset, "add.ptr");
4913 // (type *)((char*)BaseValue + Offset_symbol)
4914 const llvm::Type *IvarTy =
Chris Lattner51123fe2009-04-17 17:46:19 +00004915 CGM.getTypes().ConvertTypeForMem(Ivar->getType());
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004916 llvm::Type *ptrIvarTy = llvm::PointerType::getUnqual(IvarTy);
4917 V = CGF.Builder.CreateBitCast(V, ptrIvarTy);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004918
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00004919 if (Ivar->isBitField()) {
Chris Lattner51123fe2009-04-17 17:46:19 +00004920 QualType FieldTy = Field->getType();
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00004921 CodeGenTypes::BitFieldInfo bitFieldInfo =
4922 CGM.getTypes().getBitFieldInfo(Field);
4923 return LValue::MakeBitfield(V, bitFieldInfo.Begin, bitFieldInfo.Size,
Chris Lattner51123fe2009-04-17 17:46:19 +00004924 FieldTy->isSignedIntegerType(),
4925 FieldTy.getCVRQualifiers()|CVRQualifiers);
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00004926 }
4927
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004928 LValue LV = LValue::MakeAddr(V,
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004929 Ivar->getType().getCVRQualifiers()|CVRQualifiers,
4930 CGM.getContext().getObjCGCAttrKind(Ivar->getType()));
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004931 LValue::SetObjCIvar(LV, true);
4932 return LV;
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004933}
4934
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004935llvm::Value *CGObjCNonFragileABIMac::EmitIvarOffset(
4936 CodeGen::CodeGenFunction &CGF,
4937 ObjCInterfaceDecl *Interface,
4938 const ObjCIvarDecl *Ivar) {
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00004939 return CGF.Builder.CreateLoad(ObjCIvarOffsetVariable(Interface, Ivar),
4940 false, "ivar");
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004941}
4942
Fariborz Jahanian46551122009-02-04 00:22:57 +00004943CodeGen::RValue CGObjCNonFragileABIMac::EmitMessageSend(
4944 CodeGen::CodeGenFunction &CGF,
4945 QualType ResultType,
4946 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004947 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +00004948 QualType Arg0Ty,
4949 bool IsSuper,
4950 const CallArgList &CallArgs) {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004951 // FIXME. Even though IsSuper is passes. This function doese not
4952 // handle calls to 'super' receivers.
4953 CodeGenTypes &Types = CGM.getTypes();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004954 llvm::Value *Arg0 = Receiver;
4955 if (!IsSuper)
4956 Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy, "tmp");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004957
4958 // Find the message function name.
Fariborz Jahanianef163782009-02-05 01:13:09 +00004959 // FIXME. This is too much work to get the ABI-specific result type
4960 // needed to find the message name.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004961 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType,
4962 llvm::SmallVector<QualType, 16>());
4963 llvm::Constant *Fn;
4964 std::string Name("\01l_");
4965 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004966#if 0
4967 // unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004968 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
4969 Fn = ObjCTypes.MessageSendIdStretFixupFn;
4970 // FIXME. Is there a better way of getting these names.
4971 // They are available in RuntimeFunctions vector pair.
4972 Name += "objc_msgSendId_stret_fixup";
4973 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004974 else
4975#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004976 if (IsSuper) {
4977 Fn = ObjCTypes.MessageSendSuper2StretFixupFn;
4978 Name += "objc_msgSendSuper2_stret_fixup";
4979 }
4980 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004981 {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004982 Fn = ObjCTypes.MessageSendStretFixupFn;
4983 Name += "objc_msgSend_stret_fixup";
4984 }
4985 }
Fariborz Jahanian1a6b3682009-02-05 19:35:43 +00004986 else if (ResultType->isFloatingType() &&
4987 // Selection of frret API only happens in 32bit nonfragile ABI.
4988 CGM.getTargetData().getTypePaddedSize(ObjCTypes.LongTy) == 4) {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004989 Fn = ObjCTypes.MessageSendFpretFixupFn;
4990 Name += "objc_msgSend_fpret_fixup";
4991 }
4992 else {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004993#if 0
4994// unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004995 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
4996 Fn = ObjCTypes.MessageSendIdFixupFn;
4997 Name += "objc_msgSendId_fixup";
4998 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004999 else
5000#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005001 if (IsSuper) {
5002 Fn = ObjCTypes.MessageSendSuper2FixupFn;
5003 Name += "objc_msgSendSuper2_fixup";
5004 }
5005 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005006 {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005007 Fn = ObjCTypes.MessageSendFixupFn;
5008 Name += "objc_msgSend_fixup";
5009 }
5010 }
5011 Name += '_';
5012 std::string SelName(Sel.getAsString());
5013 // Replace all ':' in selector name with '_' ouch!
5014 for(unsigned i = 0; i < SelName.size(); i++)
5015 if (SelName[i] == ':')
5016 SelName[i] = '_';
5017 Name += SelName;
5018 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5019 if (!GV) {
Daniel Dunbar33af70f2009-04-15 19:03:14 +00005020 // Build message ref table entry.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005021 std::vector<llvm::Constant*> Values(2);
5022 Values[0] = Fn;
5023 Values[1] = GetMethodVarName(Sel);
5024 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
5025 GV = new llvm::GlobalVariable(Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00005026 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005027 Init,
5028 Name,
5029 &CGM.getModule());
5030 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbarf59c1a62009-04-15 19:04:46 +00005031 GV->setAlignment(16);
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005032 GV->setSection("__DATA, __objc_msgrefs, coalesced");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005033 }
5034 llvm::Value *Arg1 = CGF.Builder.CreateBitCast(GV, ObjCTypes.MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00005035
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005036 CallArgList ActualArgs;
5037 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
5038 ActualArgs.push_back(std::make_pair(RValue::get(Arg1),
5039 ObjCTypes.MessageRefCPtrTy));
5040 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Fariborz Jahanianef163782009-02-05 01:13:09 +00005041 const CGFunctionInfo &FnInfo1 = Types.getFunctionInfo(ResultType, ActualArgs);
5042 llvm::Value *Callee = CGF.Builder.CreateStructGEP(Arg1, 0);
5043 Callee = CGF.Builder.CreateLoad(Callee);
Fariborz Jahanian3ab75bd2009-02-14 21:25:36 +00005044 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo1, true);
Fariborz Jahanianef163782009-02-05 01:13:09 +00005045 Callee = CGF.Builder.CreateBitCast(Callee,
5046 llvm::PointerType::getUnqual(FTy));
5047 return CGF.EmitCall(FnInfo1, Callee, ActualArgs);
Fariborz Jahanian46551122009-02-04 00:22:57 +00005048}
5049
5050/// Generate code for a message send expression in the nonfragile abi.
5051CodeGen::RValue CGObjCNonFragileABIMac::GenerateMessageSend(
5052 CodeGen::CodeGenFunction &CGF,
5053 QualType ResultType,
5054 Selector Sel,
5055 llvm::Value *Receiver,
5056 bool IsClassMessage,
5057 const CallArgList &CallArgs) {
Fariborz Jahanian46551122009-02-04 00:22:57 +00005058 return EmitMessageSend(CGF, ResultType, Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005059 Receiver, CGF.getContext().getObjCIdType(),
Fariborz Jahanian46551122009-02-04 00:22:57 +00005060 false, CallArgs);
5061}
5062
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005063llvm::GlobalVariable *
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005064CGObjCNonFragileABIMac::GetClassGlobal(const std::string &Name) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005065 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5066
Daniel Dunbardfff2302009-03-02 05:18:14 +00005067 if (!GV) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005068 GV = new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
5069 llvm::GlobalValue::ExternalLinkage,
5070 0, Name, &CGM.getModule());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005071 }
5072
5073 return GV;
5074}
5075
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005076llvm::Value *CGObjCNonFragileABIMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar11394522009-04-18 08:51:00 +00005077 const ObjCInterfaceDecl *ID) {
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005078 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
5079
5080 if (!Entry) {
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005081 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005082 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005083 Entry =
5084 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5085 llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005086 ClassGV,
Daniel Dunbar11394522009-04-18 08:51:00 +00005087 "\01L_OBJC_CLASSLIST_REFERENCES_$_",
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005088 &CGM.getModule());
5089 Entry->setAlignment(
5090 CGM.getTargetData().getPrefTypeAlignment(
5091 ObjCTypes.ClassnfABIPtrTy));
Daniel Dunbar11394522009-04-18 08:51:00 +00005092 Entry->setSection("__DATA, __objc_classrefs, regular, no_dead_strip");
5093 UsedGlobals.push_back(Entry);
5094 }
5095
5096 return Builder.CreateLoad(Entry, false, "tmp");
5097}
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005098
Daniel Dunbar11394522009-04-18 08:51:00 +00005099llvm::Value *
5100CGObjCNonFragileABIMac::EmitSuperClassRef(CGBuilderTy &Builder,
5101 const ObjCInterfaceDecl *ID) {
5102 llvm::GlobalVariable *&Entry = SuperClassReferences[ID->getIdentifier()];
5103
5104 if (!Entry) {
5105 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
5106 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
5107 Entry =
5108 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5109 llvm::GlobalValue::InternalLinkage,
5110 ClassGV,
5111 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5112 &CGM.getModule());
5113 Entry->setAlignment(
5114 CGM.getTargetData().getPrefTypeAlignment(
5115 ObjCTypes.ClassnfABIPtrTy));
5116 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005117 UsedGlobals.push_back(Entry);
5118 }
5119
5120 return Builder.CreateLoad(Entry, false, "tmp");
5121}
5122
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005123/// EmitMetaClassRef - Return a Value * of the address of _class_t
5124/// meta-data
5125///
5126llvm::Value *CGObjCNonFragileABIMac::EmitMetaClassRef(CGBuilderTy &Builder,
5127 const ObjCInterfaceDecl *ID) {
5128 llvm::GlobalVariable * &Entry = MetaClassReferences[ID->getIdentifier()];
5129 if (Entry)
5130 return Builder.CreateLoad(Entry, false, "tmp");
5131
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005132 std::string MetaClassName(getMetaclassSymbolPrefix() + ID->getNameAsString());
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005133 llvm::GlobalVariable *MetaClassGV = GetClassGlobal(MetaClassName);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005134 Entry =
5135 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5136 llvm::GlobalValue::InternalLinkage,
5137 MetaClassGV,
5138 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5139 &CGM.getModule());
5140 Entry->setAlignment(
5141 CGM.getTargetData().getPrefTypeAlignment(
5142 ObjCTypes.ClassnfABIPtrTy));
5143
Daniel Dunbar33af70f2009-04-15 19:03:14 +00005144 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005145 UsedGlobals.push_back(Entry);
5146
5147 return Builder.CreateLoad(Entry, false, "tmp");
5148}
5149
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005150/// GetClass - Return a reference to the class for the given interface
5151/// decl.
5152llvm::Value *CGObjCNonFragileABIMac::GetClass(CGBuilderTy &Builder,
5153 const ObjCInterfaceDecl *ID) {
5154 return EmitClassRef(Builder, ID);
5155}
5156
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005157/// Generates a message send where the super is the receiver. This is
5158/// a message send to self with special delivery semantics indicating
5159/// which class's method should be called.
5160CodeGen::RValue
5161CGObjCNonFragileABIMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
5162 QualType ResultType,
5163 Selector Sel,
5164 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005165 bool isCategoryImpl,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005166 llvm::Value *Receiver,
5167 bool IsClassMessage,
5168 const CodeGen::CallArgList &CallArgs) {
5169 // ...
5170 // Create and init a super structure; this is a (receiver, class)
5171 // pair we will pass to objc_msgSendSuper.
5172 llvm::Value *ObjCSuper =
5173 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
5174
5175 llvm::Value *ReceiverAsObject =
5176 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
5177 CGF.Builder.CreateStore(ReceiverAsObject,
5178 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
5179
5180 // If this is a class message the metaclass is passed as the target.
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005181 llvm::Value *Target;
5182 if (IsClassMessage) {
5183 if (isCategoryImpl) {
5184 // Message sent to "super' in a class method defined in
5185 // a category implementation.
Daniel Dunbar11394522009-04-18 08:51:00 +00005186 Target = EmitClassRef(CGF.Builder, Class);
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005187 Target = CGF.Builder.CreateStructGEP(Target, 0);
5188 Target = CGF.Builder.CreateLoad(Target);
5189 }
5190 else
5191 Target = EmitMetaClassRef(CGF.Builder, Class);
5192 }
5193 else
Daniel Dunbar11394522009-04-18 08:51:00 +00005194 Target = EmitSuperClassRef(CGF.Builder, Class);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005195
5196 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
5197 // and ObjCTypes types.
5198 const llvm::Type *ClassTy =
5199 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
5200 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
5201 CGF.Builder.CreateStore(Target,
5202 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
5203
5204 return EmitMessageSend(CGF, ResultType, Sel,
5205 ObjCSuper, ObjCTypes.SuperPtrCTy,
5206 true, CallArgs);
5207}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005208
5209llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CGBuilderTy &Builder,
5210 Selector Sel) {
5211 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
5212
5213 if (!Entry) {
5214 llvm::Constant *Casted =
5215 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
5216 ObjCTypes.SelectorPtrTy);
5217 Entry =
5218 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
5219 llvm::GlobalValue::InternalLinkage,
5220 Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
5221 &CGM.getModule());
5222 Entry->setSection("__DATA,__objc_selrefs,literal_pointers,no_dead_strip");
5223 UsedGlobals.push_back(Entry);
5224 }
5225
5226 return Builder.CreateLoad(Entry, false, "tmp");
5227}
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005228/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
5229/// objc_assign_ivar (id src, id *dst)
5230///
5231void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
5232 llvm::Value *src, llvm::Value *dst)
5233{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005234 const llvm::Type * SrcTy = src->getType();
5235 if (!isa<llvm::PointerType>(SrcTy)) {
5236 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5237 assert(Size <= 8 && "does not support size > 8");
5238 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5239 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005240 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5241 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005242 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5243 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5244 CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn,
5245 src, dst, "assignivar");
5246 return;
5247}
5248
5249/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
5250/// objc_assign_strongCast (id src, id *dst)
5251///
5252void CGObjCNonFragileABIMac::EmitObjCStrongCastAssign(
5253 CodeGen::CodeGenFunction &CGF,
5254 llvm::Value *src, llvm::Value *dst)
5255{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005256 const llvm::Type * SrcTy = src->getType();
5257 if (!isa<llvm::PointerType>(SrcTy)) {
5258 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5259 assert(Size <= 8 && "does not support size > 8");
5260 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5261 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005262 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5263 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005264 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5265 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5266 CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn,
5267 src, dst, "weakassign");
5268 return;
5269}
5270
5271/// EmitObjCWeakRead - Code gen for loading value of a __weak
5272/// object: objc_read_weak (id *src)
5273///
5274llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead(
5275 CodeGen::CodeGenFunction &CGF,
5276 llvm::Value *AddrWeakObj)
5277{
Eli Friedman8339b352009-03-07 03:57:15 +00005278 const llvm::Type* DestTy =
5279 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005280 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
5281 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
5282 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00005283 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005284 return read_weak;
5285}
5286
5287/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
5288/// objc_assign_weak (id src, id *dst)
5289///
5290void CGObjCNonFragileABIMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
5291 llvm::Value *src, llvm::Value *dst)
5292{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005293 const llvm::Type * SrcTy = src->getType();
5294 if (!isa<llvm::PointerType>(SrcTy)) {
5295 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5296 assert(Size <= 8 && "does not support size > 8");
5297 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5298 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005299 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5300 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005301 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5302 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattner96508e12009-04-17 22:12:36 +00005303 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005304 src, dst, "weakassign");
5305 return;
5306}
5307
5308/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
5309/// objc_assign_global (id src, id *dst)
5310///
5311void CGObjCNonFragileABIMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
5312 llvm::Value *src, llvm::Value *dst)
5313{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005314 const llvm::Type * SrcTy = src->getType();
5315 if (!isa<llvm::PointerType>(SrcTy)) {
5316 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5317 assert(Size <= 8 && "does not support size > 8");
5318 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5319 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005320 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5321 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005322 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5323 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5324 CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn,
5325 src, dst, "globalassign");
5326 return;
5327}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005328
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005329void
5330CGObjCNonFragileABIMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
5331 const Stmt &S) {
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005332 bool isTry = isa<ObjCAtTryStmt>(S);
5333 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
5334 llvm::BasicBlock *PrevLandingPad = CGF.getInvokeDest();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005335 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005336 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005337 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005338 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
5339
5340 // For @synchronized, call objc_sync_enter(sync.expr). The
5341 // evaluation of the expression must occur before we enter the
5342 // @synchronized. We can safely avoid a temp here because jumps into
5343 // @synchronized are illegal & this will dominate uses.
5344 llvm::Value *SyncArg = 0;
5345 if (!isTry) {
5346 SyncArg =
5347 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
5348 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005349 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005350 }
5351
5352 // Push an EH context entry, used for handling rethrows and jumps
5353 // through finally.
5354 CGF.PushCleanupBlock(FinallyBlock);
5355
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005356 CGF.setInvokeDest(TryHandler);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005357
5358 CGF.EmitBlock(TryBlock);
5359 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
5360 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
5361 CGF.EmitBranchThroughCleanup(FinallyEnd);
5362
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005363 // Emit the exception handler.
5364
5365 CGF.EmitBlock(TryHandler);
5366
5367 llvm::Value *llvm_eh_exception =
5368 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_exception);
5369 llvm::Value *llvm_eh_selector_i64 =
5370 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector_i64);
5371 llvm::Value *llvm_eh_typeid_for_i64 =
5372 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for_i64);
5373 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5374 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(Exc->getType(), "_rethrow");
5375
5376 llvm::SmallVector<llvm::Value*, 8> SelectorArgs;
5377 SelectorArgs.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005378 SelectorArgs.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005379
5380 // Construct the lists of (type, catch body) to handle.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005381 llvm::SmallVector<std::pair<const ParmVarDecl*, const Stmt*>, 8> Handlers;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005382 bool HasCatchAll = false;
5383 if (isTry) {
5384 if (const ObjCAtCatchStmt* CatchStmt =
5385 cast<ObjCAtTryStmt>(S).getCatchStmts()) {
5386 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005387 const ParmVarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
Steve Naroff7ba138a2009-03-03 19:52:17 +00005388 Handlers.push_back(std::make_pair(CatchDecl, CatchStmt->getCatchBody()));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005389
5390 // catch(...) always matches.
Steve Naroff7ba138a2009-03-03 19:52:17 +00005391 if (!CatchDecl) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005392 // Use i8* null here to signal this is a catch all, not a cleanup.
5393 llvm::Value *Null = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
5394 SelectorArgs.push_back(Null);
5395 HasCatchAll = true;
5396 break;
5397 }
5398
Daniel Dunbarede8de92009-03-06 00:01:21 +00005399 if (CGF.getContext().isObjCIdType(CatchDecl->getType()) ||
5400 CatchDecl->getType()->isObjCQualifiedIdType()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005401 llvm::Value *IDEHType =
5402 CGM.getModule().getGlobalVariable("OBJC_EHTYPE_id");
5403 if (!IDEHType)
5404 IDEHType =
5405 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5406 llvm::GlobalValue::ExternalLinkage,
5407 0, "OBJC_EHTYPE_id", &CGM.getModule());
5408 SelectorArgs.push_back(IDEHType);
5409 HasCatchAll = true;
5410 break;
5411 }
5412
5413 // All other types should be Objective-C interface pointer types.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005414 const PointerType *PT = CatchDecl->getType()->getAsPointerType();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005415 assert(PT && "Invalid @catch type.");
5416 const ObjCInterfaceType *IT =
5417 PT->getPointeeType()->getAsObjCInterfaceType();
5418 assert(IT && "Invalid @catch type.");
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005419 llvm::Value *EHType = GetInterfaceEHType(IT->getDecl(), false);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005420 SelectorArgs.push_back(EHType);
5421 }
5422 }
5423 }
5424
5425 // We use a cleanup unless there was already a catch all.
5426 if (!HasCatchAll) {
5427 SelectorArgs.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
Daniel Dunbarede8de92009-03-06 00:01:21 +00005428 Handlers.push_back(std::make_pair((const ParmVarDecl*) 0, (const Stmt*) 0));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005429 }
5430
5431 llvm::Value *Selector =
5432 CGF.Builder.CreateCall(llvm_eh_selector_i64,
5433 SelectorArgs.begin(), SelectorArgs.end(),
5434 "selector");
5435 for (unsigned i = 0, e = Handlers.size(); i != e; ++i) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005436 const ParmVarDecl *CatchParam = Handlers[i].first;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005437 const Stmt *CatchBody = Handlers[i].second;
5438
5439 llvm::BasicBlock *Next = 0;
5440
5441 // The last handler always matches.
5442 if (i + 1 != e) {
5443 assert(CatchParam && "Only last handler can be a catch all.");
5444
5445 llvm::BasicBlock *Match = CGF.createBasicBlock("match");
5446 Next = CGF.createBasicBlock("catch.next");
5447 llvm::Value *Id =
5448 CGF.Builder.CreateCall(llvm_eh_typeid_for_i64,
5449 CGF.Builder.CreateBitCast(SelectorArgs[i+2],
5450 ObjCTypes.Int8PtrTy));
5451 CGF.Builder.CreateCondBr(CGF.Builder.CreateICmpEQ(Selector, Id),
5452 Match, Next);
5453
5454 CGF.EmitBlock(Match);
5455 }
5456
5457 if (CatchBody) {
5458 llvm::BasicBlock *MatchEnd = CGF.createBasicBlock("match.end");
5459 llvm::BasicBlock *MatchHandler = CGF.createBasicBlock("match.handler");
5460
5461 // Cleanups must call objc_end_catch.
5462 //
5463 // FIXME: It seems incorrect for objc_begin_catch to be inside
5464 // this context, but this matches gcc.
5465 CGF.PushCleanupBlock(MatchEnd);
5466 CGF.setInvokeDest(MatchHandler);
5467
5468 llvm::Value *ExcObject =
5469 CGF.Builder.CreateCall(ObjCTypes.ObjCBeginCatchFn, Exc);
5470
5471 // Bind the catch parameter if it exists.
5472 if (CatchParam) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005473 ExcObject =
5474 CGF.Builder.CreateBitCast(ExcObject,
5475 CGF.ConvertType(CatchParam->getType()));
5476 // CatchParam is a ParmVarDecl because of the grammar
5477 // construction used to handle this, but for codegen purposes
5478 // we treat this as a local decl.
5479 CGF.EmitLocalBlockVarDecl(*CatchParam);
5480 CGF.Builder.CreateStore(ExcObject, CGF.GetAddrOfLocalVar(CatchParam));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005481 }
5482
5483 CGF.ObjCEHValueStack.push_back(ExcObject);
5484 CGF.EmitStmt(CatchBody);
5485 CGF.ObjCEHValueStack.pop_back();
5486
5487 CGF.EmitBranchThroughCleanup(FinallyEnd);
5488
5489 CGF.EmitBlock(MatchHandler);
5490
5491 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5492 // We are required to emit this call to satisfy LLVM, even
5493 // though we don't use the result.
5494 llvm::SmallVector<llvm::Value*, 8> Args;
5495 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005496 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005497 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5498 0));
5499 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5500 CGF.Builder.CreateStore(Exc, RethrowPtr);
5501 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5502
5503 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5504
5505 CGF.EmitBlock(MatchEnd);
5506
5507 // Unfortunately, we also have to generate another EH frame here
5508 // in case this throws.
5509 llvm::BasicBlock *MatchEndHandler =
5510 CGF.createBasicBlock("match.end.handler");
5511 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
5512 CGF.Builder.CreateInvoke(ObjCTypes.ObjCEndCatchFn,
5513 Cont, MatchEndHandler,
5514 Args.begin(), Args.begin());
5515
5516 CGF.EmitBlock(Cont);
5517 if (Info.SwitchBlock)
5518 CGF.EmitBlock(Info.SwitchBlock);
5519 if (Info.EndBlock)
5520 CGF.EmitBlock(Info.EndBlock);
5521
5522 CGF.EmitBlock(MatchEndHandler);
5523 Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5524 // We are required to emit this call to satisfy LLVM, even
5525 // though we don't use the result.
5526 Args.clear();
5527 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005528 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005529 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5530 0));
5531 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5532 CGF.Builder.CreateStore(Exc, RethrowPtr);
5533 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5534
5535 if (Next)
5536 CGF.EmitBlock(Next);
5537 } else {
5538 assert(!Next && "catchup should be last handler.");
5539
5540 CGF.Builder.CreateStore(Exc, RethrowPtr);
5541 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5542 }
5543 }
5544
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005545 // Pop the cleanup entry, the @finally is outside this cleanup
5546 // scope.
5547 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5548 CGF.setInvokeDest(PrevLandingPad);
5549
5550 CGF.EmitBlock(FinallyBlock);
5551
5552 if (isTry) {
5553 if (const ObjCAtFinallyStmt* FinallyStmt =
5554 cast<ObjCAtTryStmt>(S).getFinallyStmt())
5555 CGF.EmitStmt(FinallyStmt->getFinallyBody());
5556 } else {
5557 // Emit 'objc_sync_exit(expr)' as finally's sole statement for
5558 // @synchronized.
5559 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, SyncArg);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005560 }
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005561
5562 if (Info.SwitchBlock)
5563 CGF.EmitBlock(Info.SwitchBlock);
5564 if (Info.EndBlock)
5565 CGF.EmitBlock(Info.EndBlock);
5566
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005567 // Branch around the rethrow code.
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005568 CGF.EmitBranch(FinallyEnd);
5569
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005570 CGF.EmitBlock(FinallyRethrow);
5571 CGF.Builder.CreateCall(ObjCTypes.UnwindResumeOrRethrowFn,
5572 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005573 CGF.Builder.CreateUnreachable();
5574
5575 CGF.EmitBlock(FinallyEnd);
5576}
5577
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005578/// EmitThrowStmt - Generate code for a throw statement.
5579void CGObjCNonFragileABIMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
5580 const ObjCAtThrowStmt &S) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005581 llvm::Value *Exception;
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005582 if (const Expr *ThrowExpr = S.getThrowExpr()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005583 Exception = CGF.EmitScalarExpr(ThrowExpr);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005584 } else {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005585 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
5586 "Unexpected rethrow outside @catch block.");
5587 Exception = CGF.ObjCEHValueStack.back();
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005588 }
5589
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005590 llvm::Value *ExceptionAsObject =
5591 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
5592 llvm::BasicBlock *InvokeDest = CGF.getInvokeDest();
5593 if (InvokeDest) {
5594 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
5595 CGF.Builder.CreateInvoke(ObjCTypes.ExceptionThrowFn,
5596 Cont, InvokeDest,
5597 &ExceptionAsObject, &ExceptionAsObject + 1);
5598 CGF.EmitBlock(Cont);
5599 } else
5600 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
5601 CGF.Builder.CreateUnreachable();
5602
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005603 // Clear the insertion point to indicate we are in unreachable code.
5604 CGF.Builder.ClearInsertionPoint();
5605}
Daniel Dunbare588b992009-03-01 04:46:24 +00005606
5607llvm::Value *
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005608CGObjCNonFragileABIMac::GetInterfaceEHType(const ObjCInterfaceDecl *ID,
5609 bool ForDefinition) {
Daniel Dunbare588b992009-03-01 04:46:24 +00005610 llvm::GlobalVariable * &Entry = EHTypeReferences[ID->getIdentifier()];
Daniel Dunbare588b992009-03-01 04:46:24 +00005611
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005612 // If we don't need a definition, return the entry if found or check
5613 // if we use an external reference.
5614 if (!ForDefinition) {
5615 if (Entry)
5616 return Entry;
Daniel Dunbar7e075cb2009-04-07 06:43:45 +00005617
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005618 // If this type (or a super class) has the __objc_exception__
5619 // attribute, emit an external reference.
5620 if (hasObjCExceptionAttribute(ID))
5621 return Entry =
5622 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5623 llvm::GlobalValue::ExternalLinkage,
5624 0,
5625 (std::string("OBJC_EHTYPE_$_") +
5626 ID->getIdentifier()->getName()),
5627 &CGM.getModule());
5628 }
5629
5630 // Otherwise we need to either make a new entry or fill in the
5631 // initializer.
5632 assert((!Entry || !Entry->hasInitializer()) && "Duplicate EHType definition");
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005633 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbare588b992009-03-01 04:46:24 +00005634 std::string VTableName = "objc_ehtype_vtable";
5635 llvm::GlobalVariable *VTableGV =
5636 CGM.getModule().getGlobalVariable(VTableName);
5637 if (!VTableGV)
5638 VTableGV = new llvm::GlobalVariable(ObjCTypes.Int8PtrTy, false,
5639 llvm::GlobalValue::ExternalLinkage,
5640 0, VTableName, &CGM.getModule());
5641
5642 llvm::Value *VTableIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, 2);
5643
5644 std::vector<llvm::Constant*> Values(3);
5645 Values[0] = llvm::ConstantExpr::getGetElementPtr(VTableGV, &VTableIdx, 1);
5646 Values[1] = GetClassName(ID->getIdentifier());
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005647 Values[2] = GetClassGlobal(ClassName);
Daniel Dunbare588b992009-03-01 04:46:24 +00005648 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.EHTypeTy, Values);
5649
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005650 if (Entry) {
5651 Entry->setInitializer(Init);
5652 } else {
5653 Entry = new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5654 llvm::GlobalValue::WeakAnyLinkage,
5655 Init,
5656 (std::string("OBJC_EHTYPE_$_") +
5657 ID->getIdentifier()->getName()),
5658 &CGM.getModule());
5659 }
5660
Daniel Dunbar04d40782009-04-14 06:00:08 +00005661 if (CGM.getLangOptions().getVisibilityMode() == LangOptions::Hidden)
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005662 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005663 Entry->setAlignment(8);
5664
5665 if (ForDefinition) {
5666 Entry->setSection("__DATA,__objc_const");
5667 Entry->setLinkage(llvm::GlobalValue::ExternalLinkage);
5668 } else {
5669 Entry->setSection("__DATA,__datacoal_nt,coalesced");
5670 }
Daniel Dunbare588b992009-03-01 04:46:24 +00005671
5672 return Entry;
5673}
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005674
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00005675/* *** */
5676
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00005677CodeGen::CGObjCRuntime *
5678CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00005679 return new CGObjCMac(CGM);
5680}
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005681
5682CodeGen::CGObjCRuntime *
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00005683CodeGen::CreateMacNonFragileABIObjCRuntime(CodeGen::CodeGenModule &CGM) {
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00005684 return new CGObjCNonFragileABIMac(CGM);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005685}