blob: e04f723b1d781b8c73429eab94e6983fbd6698e6 [file] [log] [blame]
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001//===------- CGObjCMac.cpp - Interface to Apple Objective-C Runtime -------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This provides Objective-C code generation targetting the Apple runtime.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CGObjCRuntime.h"
Daniel Dunbarf77ac862008-08-11 21:35:06 +000015
16#include "CodeGenModule.h"
Daniel Dunbarb7ec2462008-08-16 03:19:19 +000017#include "CodeGenFunction.h"
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000018#include "clang/AST/ASTContext.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000019#include "clang/AST/Decl.h"
Daniel Dunbar6efc0c52008-08-13 03:21:16 +000020#include "clang/AST/DeclObjC.h"
Daniel Dunbarf77ac862008-08-11 21:35:06 +000021#include "clang/Basic/LangOptions.h"
22
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +000023#include "llvm/Intrinsics.h"
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000024#include "llvm/Module.h"
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +000025#include "llvm/ADT/DenseSet.h"
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +000026#include "llvm/Target/TargetData.h"
Daniel Dunbarb7ec2462008-08-16 03:19:19 +000027#include <sstream>
Daniel Dunbarc17a4d32008-08-11 02:45:11 +000028
29using namespace clang;
Daniel Dunbar46f45b92008-09-09 01:06:48 +000030using namespace CodeGen;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +000031
32namespace {
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000033
Daniel Dunbarae226fa2008-08-27 02:31:56 +000034 typedef std::vector<llvm::Constant*> ConstantVector;
35
Daniel Dunbar6efc0c52008-08-13 03:21:16 +000036 // FIXME: We should find a nicer way to make the labels for
37 // metadata, string concatenation is lame.
38
Fariborz Jahanianee0af742009-01-21 22:04:16 +000039class ObjCCommonTypesHelper {
40protected:
41 CodeGen::CodeGenModule &CGM;
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000042
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000043public:
Fariborz Jahanian0a855d02009-03-23 19:10:40 +000044 const llvm::Type *ShortTy, *IntTy, *LongTy, *LongLongTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +000045 const llvm::Type *Int8PtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +000046
Daniel Dunbar2bedbf82008-08-12 05:28:47 +000047 /// ObjectPtrTy - LLVM type for object handles (typeof(id))
48 const llvm::Type *ObjectPtrTy;
Fariborz Jahanian6d657c42008-11-18 20:18:11 +000049
50 /// PtrObjectPtrTy - LLVM type for id *
51 const llvm::Type *PtrObjectPtrTy;
52
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +000053 /// SelectorPtrTy - LLVM type for selector handles (typeof(SEL))
Daniel Dunbar2bedbf82008-08-12 05:28:47 +000054 const llvm::Type *SelectorPtrTy;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +000055 /// ProtocolPtrTy - LLVM type for external protocol handles
56 /// (typeof(Protocol))
57 const llvm::Type *ExternalProtocolPtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +000058
Daniel Dunbar19cd87e2008-08-30 03:02:31 +000059 // SuperCTy - clang type for struct objc_super.
60 QualType SuperCTy;
61 // SuperPtrCTy - clang type for struct objc_super *.
62 QualType SuperPtrCTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +000063
Daniel Dunbare8b470d2008-08-23 04:28:29 +000064 /// SuperTy - LLVM type for struct objc_super.
65 const llvm::StructType *SuperTy;
Daniel Dunbar14c80b72008-08-23 09:25:55 +000066 /// SuperPtrTy - LLVM type for struct objc_super *.
67 const llvm::Type *SuperPtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +000068
Fariborz Jahanian30bc5712009-01-22 23:02:58 +000069 /// PropertyTy - LLVM type for struct objc_property (struct _prop_t
70 /// in GCC parlance).
71 const llvm::StructType *PropertyTy;
72
73 /// PropertyListTy - LLVM type for struct objc_property_list
74 /// (_prop_list_t in GCC parlance).
75 const llvm::StructType *PropertyListTy;
76 /// PropertyListPtrTy - LLVM type for struct objc_property_list*.
77 const llvm::Type *PropertyListPtrTy;
78
79 // MethodTy - LLVM type for struct objc_method.
80 const llvm::StructType *MethodTy;
81
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +000082 /// CacheTy - LLVM type for struct objc_cache.
83 const llvm::Type *CacheTy;
84 /// CachePtrTy - LLVM type for struct objc_cache *.
85 const llvm::Type *CachePtrTy;
86
Chris Lattner74391b42009-03-22 21:03:39 +000087 llvm::Constant *GetPropertyFn, *SetPropertyFn;
Fariborz Jahaniandb286862009-01-22 00:37:21 +000088
Chris Lattner74391b42009-03-22 21:03:39 +000089 llvm::Constant *EnumerationMutationFn;
Fariborz Jahaniandb286862009-01-22 00:37:21 +000090
91 /// GcReadWeakFn -- LLVM objc_read_weak (id *src) function.
Chris Lattner74391b42009-03-22 21:03:39 +000092 llvm::Constant *GcReadWeakFn;
Fariborz Jahaniandb286862009-01-22 00:37:21 +000093
94 /// GcAssignWeakFn -- LLVM objc_assign_weak function.
Chris Lattner96508e12009-04-17 22:12:36 +000095 llvm::Constant *getGcAssignWeakFn() {
96 // id objc_assign_weak (id, id *)
97 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
98 Args.push_back(ObjectPtrTy->getPointerTo());
99 llvm::FunctionType *FTy =
100 llvm::FunctionType::get(ObjectPtrTy, Args, false);
101 return CGM.CreateRuntimeFunction(FTy, "objc_assign_weak");
102 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000103
104 /// GcAssignGlobalFn -- LLVM objc_assign_global function.
Chris Lattner74391b42009-03-22 21:03:39 +0000105 llvm::Constant *GcAssignGlobalFn;
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000106
107 /// GcAssignIvarFn -- LLVM objc_assign_ivar function.
Chris Lattner74391b42009-03-22 21:03:39 +0000108 llvm::Constant *GcAssignIvarFn;
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000109
110 /// GcAssignStrongCastFn -- LLVM objc_assign_strongCast function.
Chris Lattner74391b42009-03-22 21:03:39 +0000111 llvm::Constant *GcAssignStrongCastFn;
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000112
113 /// ExceptionThrowFn - LLVM objc_exception_throw function.
Chris Lattner74391b42009-03-22 21:03:39 +0000114 llvm::Constant *ExceptionThrowFn;
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000115
Daniel Dunbar1c566672009-02-24 01:43:46 +0000116 /// SyncEnterFn - LLVM object_sync_enter function.
Chris Lattnerb02e53b2009-04-06 16:53:45 +0000117 llvm::Constant *getSyncEnterFn() {
118 // void objc_sync_enter (id)
119 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
120 llvm::FunctionType *FTy =
121 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
122 return CGM.CreateRuntimeFunction(FTy, "objc_sync_enter");
123 }
Daniel Dunbar1c566672009-02-24 01:43:46 +0000124
125 /// SyncExitFn - LLVM object_sync_exit function.
Chris Lattner74391b42009-03-22 21:03:39 +0000126 llvm::Constant *SyncExitFn;
Daniel Dunbar1c566672009-02-24 01:43:46 +0000127
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000128 ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm);
129 ~ObjCCommonTypesHelper(){}
130};
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000131
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000132/// ObjCTypesHelper - Helper class that encapsulates lazy
133/// construction of varies types used during ObjC generation.
134class ObjCTypesHelper : public ObjCCommonTypesHelper {
135private:
136
Chris Lattner74391b42009-03-22 21:03:39 +0000137 llvm::Constant *MessageSendFn, *MessageSendStretFn, *MessageSendFpretFn;
138 llvm::Constant *MessageSendSuperFn, *MessageSendSuperStretFn,
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000139 *MessageSendSuperFpretFn;
140
141public:
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000142 /// SymtabTy - LLVM type for struct objc_symtab.
143 const llvm::StructType *SymtabTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000144 /// SymtabPtrTy - LLVM type for struct objc_symtab *.
145 const llvm::Type *SymtabPtrTy;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000146 /// ModuleTy - LLVM type for struct objc_module.
147 const llvm::StructType *ModuleTy;
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000148
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000149 /// ProtocolTy - LLVM type for struct objc_protocol.
150 const llvm::StructType *ProtocolTy;
151 /// ProtocolPtrTy - LLVM type for struct objc_protocol *.
152 const llvm::Type *ProtocolPtrTy;
153 /// ProtocolExtensionTy - LLVM type for struct
154 /// objc_protocol_extension.
155 const llvm::StructType *ProtocolExtensionTy;
156 /// ProtocolExtensionTy - LLVM type for struct
157 /// objc_protocol_extension *.
158 const llvm::Type *ProtocolExtensionPtrTy;
159 /// MethodDescriptionTy - LLVM type for struct
160 /// objc_method_description.
161 const llvm::StructType *MethodDescriptionTy;
162 /// MethodDescriptionListTy - LLVM type for struct
163 /// objc_method_description_list.
164 const llvm::StructType *MethodDescriptionListTy;
165 /// MethodDescriptionListPtrTy - LLVM type for struct
166 /// objc_method_description_list *.
167 const llvm::Type *MethodDescriptionListPtrTy;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000168 /// ProtocolListTy - LLVM type for struct objc_property_list.
169 const llvm::Type *ProtocolListTy;
170 /// ProtocolListPtrTy - LLVM type for struct objc_property_list*.
171 const llvm::Type *ProtocolListPtrTy;
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000172 /// CategoryTy - LLVM type for struct objc_category.
173 const llvm::StructType *CategoryTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000174 /// ClassTy - LLVM type for struct objc_class.
175 const llvm::StructType *ClassTy;
176 /// ClassPtrTy - LLVM type for struct objc_class *.
177 const llvm::Type *ClassPtrTy;
178 /// ClassExtensionTy - LLVM type for struct objc_class_ext.
179 const llvm::StructType *ClassExtensionTy;
180 /// ClassExtensionPtrTy - LLVM type for struct objc_class_ext *.
181 const llvm::Type *ClassExtensionPtrTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000182 // IvarTy - LLVM type for struct objc_ivar.
183 const llvm::StructType *IvarTy;
184 /// IvarListTy - LLVM type for struct objc_ivar_list.
185 const llvm::Type *IvarListTy;
186 /// IvarListPtrTy - LLVM type for struct objc_ivar_list *.
187 const llvm::Type *IvarListPtrTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000188 /// MethodListTy - LLVM type for struct objc_method_list.
189 const llvm::Type *MethodListTy;
190 /// MethodListPtrTy - LLVM type for struct objc_method_list *.
191 const llvm::Type *MethodListPtrTy;
Anders Carlsson124526b2008-09-09 10:10:21 +0000192
193 /// ExceptionDataTy - LLVM type for struct _objc_exception_data.
194 const llvm::Type *ExceptionDataTy;
195
Anders Carlsson124526b2008-09-09 10:10:21 +0000196 /// ExceptionTryEnterFn - LLVM objc_exception_try_enter function.
Chris Lattner74391b42009-03-22 21:03:39 +0000197 llvm::Constant *ExceptionTryEnterFn;
Anders Carlsson124526b2008-09-09 10:10:21 +0000198
199 /// ExceptionTryExitFn - LLVM objc_exception_try_exit function.
Chris Lattner74391b42009-03-22 21:03:39 +0000200 llvm::Constant *ExceptionTryExitFn;
Anders Carlsson124526b2008-09-09 10:10:21 +0000201
202 /// ExceptionExtractFn - LLVM objc_exception_extract function.
Chris Lattner74391b42009-03-22 21:03:39 +0000203 llvm::Constant *ExceptionExtractFn;
Anders Carlsson124526b2008-09-09 10:10:21 +0000204
205 /// ExceptionMatchFn - LLVM objc_exception_match function.
Chris Lattner74391b42009-03-22 21:03:39 +0000206 llvm::Constant *ExceptionMatchFn;
Anders Carlsson124526b2008-09-09 10:10:21 +0000207
208 /// SetJmpFn - LLVM _setjmp function.
Chris Lattner74391b42009-03-22 21:03:39 +0000209 llvm::Constant *SetJmpFn;
Chris Lattner10cac6f2008-11-15 21:26:17 +0000210
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000211public:
212 ObjCTypesHelper(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000213 ~ObjCTypesHelper() {}
Daniel Dunbar5669e572008-10-17 03:24:53 +0000214
215
Chris Lattner74391b42009-03-22 21:03:39 +0000216 llvm::Constant *getSendFn(bool IsSuper) {
Daniel Dunbar5669e572008-10-17 03:24:53 +0000217 return IsSuper ? MessageSendSuperFn : MessageSendFn;
218 }
219
Chris Lattner74391b42009-03-22 21:03:39 +0000220 llvm::Constant *getSendStretFn(bool IsSuper) {
Daniel Dunbar5669e572008-10-17 03:24:53 +0000221 return IsSuper ? MessageSendSuperStretFn : MessageSendStretFn;
222 }
223
Chris Lattner74391b42009-03-22 21:03:39 +0000224 llvm::Constant *getSendFpretFn(bool IsSuper) {
Daniel Dunbar5669e572008-10-17 03:24:53 +0000225 return IsSuper ? MessageSendSuperFpretFn : MessageSendFpretFn;
226 }
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000227};
228
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000229/// ObjCNonFragileABITypesHelper - will have all types needed by objective-c's
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000230/// modern abi
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000231class ObjCNonFragileABITypesHelper : public ObjCCommonTypesHelper {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000232public:
Chris Lattner74391b42009-03-22 21:03:39 +0000233 llvm::Constant *MessageSendFixupFn, *MessageSendFpretFixupFn,
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000234 *MessageSendStretFixupFn, *MessageSendIdFixupFn,
235 *MessageSendIdStretFixupFn, *MessageSendSuper2FixupFn,
236 *MessageSendSuper2StretFixupFn;
237
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000238 // MethodListnfABITy - LLVM for struct _method_list_t
239 const llvm::StructType *MethodListnfABITy;
240
241 // MethodListnfABIPtrTy - LLVM for struct _method_list_t*
242 const llvm::Type *MethodListnfABIPtrTy;
243
244 // ProtocolnfABITy = LLVM for struct _protocol_t
245 const llvm::StructType *ProtocolnfABITy;
246
Daniel Dunbar948e2582009-02-15 07:36:20 +0000247 // ProtocolnfABIPtrTy = LLVM for struct _protocol_t*
248 const llvm::Type *ProtocolnfABIPtrTy;
249
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000250 // ProtocolListnfABITy - LLVM for struct _objc_protocol_list
251 const llvm::StructType *ProtocolListnfABITy;
252
253 // ProtocolListnfABIPtrTy - LLVM for struct _objc_protocol_list*
254 const llvm::Type *ProtocolListnfABIPtrTy;
255
256 // ClassnfABITy - LLVM for struct _class_t
257 const llvm::StructType *ClassnfABITy;
258
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000259 // ClassnfABIPtrTy - LLVM for struct _class_t*
260 const llvm::Type *ClassnfABIPtrTy;
261
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000262 // IvarnfABITy - LLVM for struct _ivar_t
263 const llvm::StructType *IvarnfABITy;
264
265 // IvarListnfABITy - LLVM for struct _ivar_list_t
266 const llvm::StructType *IvarListnfABITy;
267
268 // IvarListnfABIPtrTy = LLVM for struct _ivar_list_t*
269 const llvm::Type *IvarListnfABIPtrTy;
270
271 // ClassRonfABITy - LLVM for struct _class_ro_t
272 const llvm::StructType *ClassRonfABITy;
273
274 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
275 const llvm::Type *ImpnfABITy;
276
277 // CategorynfABITy - LLVM for struct _category_t
278 const llvm::StructType *CategorynfABITy;
279
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000280 // New types for nonfragile abi messaging.
281
282 // MessageRefTy - LLVM for:
283 // struct _message_ref_t {
284 // IMP messenger;
285 // SEL name;
286 // };
287 const llvm::StructType *MessageRefTy;
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000288 // MessageRefCTy - clang type for struct _message_ref_t
289 QualType MessageRefCTy;
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000290
291 // MessageRefPtrTy - LLVM for struct _message_ref_t*
292 const llvm::Type *MessageRefPtrTy;
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000293 // MessageRefCPtrTy - clang type for struct _message_ref_t*
294 QualType MessageRefCPtrTy;
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000295
Fariborz Jahanianef163782009-02-05 01:13:09 +0000296 // MessengerTy - Type of the messenger (shown as IMP above)
297 const llvm::FunctionType *MessengerTy;
298
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000299 // SuperMessageRefTy - LLVM for:
300 // struct _super_message_ref_t {
301 // SUPER_IMP messenger;
302 // SEL name;
303 // };
304 const llvm::StructType *SuperMessageRefTy;
305
306 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
307 const llvm::Type *SuperMessageRefPtrTy;
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000308
309 /// EHPersonalityPtr - LLVM value for an i8* to the Objective-C
310 /// exception personality function.
Chris Lattnerb02e53b2009-04-06 16:53:45 +0000311 llvm::Value *getEHPersonalityPtr() {
312 llvm::Constant *Personality =
313 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
314 std::vector<const llvm::Type*>(),
315 true),
316 "__objc_personality_v0");
317 return llvm::ConstantExpr::getBitCast(Personality, Int8PtrTy);
318 }
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000319
Chris Lattner74391b42009-03-22 21:03:39 +0000320 llvm::Constant *UnwindResumeOrRethrowFn, *ObjCBeginCatchFn, *ObjCEndCatchFn;
Daniel Dunbare588b992009-03-01 04:46:24 +0000321
322 const llvm::StructType *EHTypeTy;
323 const llvm::Type *EHTypePtrTy;
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000324
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000325 ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm);
326 ~ObjCNonFragileABITypesHelper(){}
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000327};
328
329class CGObjCCommonMac : public CodeGen::CGObjCRuntime {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000330public:
331 // FIXME - accessibility
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000332 class GC_IVAR {
Fariborz Jahanian820e0202009-03-11 00:07:04 +0000333 public:
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000334 unsigned int ivar_bytepos;
335 unsigned int ivar_size;
336 GC_IVAR() : ivar_bytepos(0), ivar_size(0) {}
337 };
338
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000339 class SKIP_SCAN {
340 public:
341 unsigned int skip;
342 unsigned int scan;
343 SKIP_SCAN() : skip(0), scan(0) {}
344 };
345
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000346protected:
347 CodeGen::CodeGenModule &CGM;
348 // FIXME! May not be needing this after all.
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000349 unsigned ObjCABI;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000350
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000351 // gc ivar layout bitmap calculation helper caches.
352 llvm::SmallVector<GC_IVAR, 16> SkipIvars;
353 llvm::SmallVector<GC_IVAR, 16> IvarsInfo;
354 llvm::SmallVector<SKIP_SCAN, 32> SkipScanIvars;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000355
Daniel Dunbar242d4dc2008-08-25 06:02:07 +0000356 /// LazySymbols - Symbols to generate a lazy reference for. See
357 /// DefinedSymbols and FinishModule().
358 std::set<IdentifierInfo*> LazySymbols;
359
360 /// DefinedSymbols - External symbols which are defined by this
361 /// module. The symbols in this list and LazySymbols are used to add
362 /// special linker symbols which ensure that Objective-C modules are
363 /// linked properly.
364 std::set<IdentifierInfo*> DefinedSymbols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000365
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000366 /// ClassNames - uniqued class names.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000367 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000368
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000369 /// MethodVarNames - uniqued method variable names.
370 llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000371
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000372 /// MethodVarTypes - uniqued method type signatures. We have to use
373 /// a StringMap here because have no other unique reference.
374 llvm::StringMap<llvm::GlobalVariable*> MethodVarTypes;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000375
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000376 /// MethodDefinitions - map of methods which have been defined in
377 /// this translation unit.
378 llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> MethodDefinitions;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000379
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000380 /// PropertyNames - uniqued method variable names.
381 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000382
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000383 /// ClassReferences - uniqued class references.
384 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000385
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000386 /// SelectorReferences - uniqued selector references.
387 llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000388
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000389 /// Protocols - Protocols for which an objc_protocol structure has
390 /// been emitted. Forward declarations are handled by creating an
391 /// empty structure whose initializer is filled in when/if defined.
392 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> Protocols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000393
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000394 /// DefinedProtocols - Protocols which have actually been
395 /// defined. We should not need this, see FIXME in GenerateProtocol.
396 llvm::DenseSet<IdentifierInfo*> DefinedProtocols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000397
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000398 /// DefinedClasses - List of defined classes.
399 std::vector<llvm::GlobalValue*> DefinedClasses;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000400
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000401 /// DefinedCategories - List of defined categories.
402 std::vector<llvm::GlobalValue*> DefinedCategories;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000403
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000404 /// UsedGlobals - List of globals to pack into the llvm.used metadata
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000405 /// to prevent them from being clobbered.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000406 std::vector<llvm::GlobalVariable*> UsedGlobals;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000407
Fariborz Jahanian56210f72009-01-21 23:34:32 +0000408 /// GetNameForMethod - Return a name for the given method.
409 /// \param[out] NameOut - The return value.
410 void GetNameForMethod(const ObjCMethodDecl *OMD,
411 const ObjCContainerDecl *CD,
412 std::string &NameOut);
413
414 /// GetMethodVarName - Return a unique constant for the given
415 /// selector's name. The return value has type char *.
416 llvm::Constant *GetMethodVarName(Selector Sel);
417 llvm::Constant *GetMethodVarName(IdentifierInfo *Ident);
418 llvm::Constant *GetMethodVarName(const std::string &Name);
419
420 /// GetMethodVarType - Return a unique constant for the given
421 /// selector's name. The return value has type char *.
422
423 // FIXME: This is a horrible name.
424 llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D);
Devang Patel7794bb82009-03-04 18:21:39 +0000425 llvm::Constant *GetMethodVarType(FieldDecl *D);
Fariborz Jahanian56210f72009-01-21 23:34:32 +0000426
427 /// GetPropertyName - Return a unique constant for the given
428 /// name. The return value has type char *.
429 llvm::Constant *GetPropertyName(IdentifierInfo *Ident);
430
431 // FIXME: This can be dropped once string functions are unified.
432 llvm::Constant *GetPropertyTypeString(const ObjCPropertyDecl *PD,
433 const Decl *Container);
434
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000435 /// GetClassName - Return a unique constant for the given selector's
436 /// name. The return value has type char *.
437 llvm::Constant *GetClassName(IdentifierInfo *Ident);
438
Fariborz Jahanian21e6f172009-03-11 21:42:00 +0000439 /// GetInterfaceDeclStructLayout - Get layout for ivars of given
440 /// interface declaration.
441 const llvm::StructLayout *GetInterfaceDeclStructLayout(
442 const ObjCInterfaceDecl *ID) const;
443
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000444 /// BuildIvarLayout - Builds ivar layout bitmap for the class
445 /// implementation for the __strong or __weak case.
446 ///
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000447 llvm::Constant *BuildIvarLayout(const ObjCImplementationDecl *OI,
448 bool ForStrongLayout);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000449
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000450 void BuildAggrIvarLayout(const ObjCInterfaceDecl *OI,
451 const llvm::StructLayout *Layout,
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000452 const RecordDecl *RD,
Chris Lattnerf1690852009-03-31 08:48:01 +0000453 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000454 unsigned int BytePos, bool ForStrongLayout,
455 int &Index, int &SkIndex, bool &HasUnion);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000456
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +0000457 /// GetIvarLayoutName - Returns a unique constant for the given
458 /// ivar layout bitmap.
459 llvm::Constant *GetIvarLayoutName(IdentifierInfo *Ident,
460 const ObjCCommonTypesHelper &ObjCTypes);
461
Fariborz Jahanian46b86c62009-01-28 19:12:34 +0000462 const RecordDecl *GetFirstIvarInRecord(const ObjCInterfaceDecl *OID,
463 RecordDecl::field_iterator &FIV,
464 RecordDecl::field_iterator &PIV);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +0000465 /// EmitPropertyList - Emit the given property list. The return
466 /// value has type PropertyListPtrTy.
467 llvm::Constant *EmitPropertyList(const std::string &Name,
468 const Decl *Container,
469 const ObjCContainerDecl *OCD,
470 const ObjCCommonTypesHelper &ObjCTypes);
471
Fariborz Jahanianda320092009-01-29 19:24:30 +0000472 /// GetProtocolRef - Return a reference to the internal protocol
473 /// description, creating an empty one if it has not been
474 /// defined. The return value has type ProtocolPtrTy.
475 llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +0000476
477 /// GetIvarBaseOffset - returns ivars byte offset.
478 uint64_t GetIvarBaseOffset(const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +0000479 const FieldDecl *Field);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000480
Chris Lattnercd0ee142009-03-31 08:33:16 +0000481 /// GetFieldBaseOffset - return's field byte offset.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000482 uint64_t GetFieldBaseOffset(const ObjCInterfaceDecl *OI,
483 const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +0000484 const FieldDecl *Field);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000485
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000486 /// CreateMetadataVar - Create a global variable with internal
487 /// linkage for use by the Objective-C runtime.
488 ///
489 /// This is a convenience wrapper which not only creates the
490 /// variable, but also sets the section and alignment and adds the
491 /// global to the UsedGlobals list.
Daniel Dunbar35bd7632009-03-09 20:50:13 +0000492 ///
493 /// \param Name - The variable name.
494 /// \param Init - The variable initializer; this is also used to
495 /// define the type of the variable.
496 /// \param Section - The section the variable should go into, or 0.
497 /// \param Align - The alignment for the variable, or 0.
498 /// \param AddToUsed - Whether the variable should be added to
Daniel Dunbarc1583062009-04-14 17:42:51 +0000499 /// "llvm.used".
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000500 llvm::GlobalVariable *CreateMetadataVar(const std::string &Name,
501 llvm::Constant *Init,
502 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +0000503 unsigned Align,
504 bool AddToUsed);
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000505
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000506public:
507 CGObjCCommonMac(CodeGen::CodeGenModule &cgm) : CGM(cgm)
508 { }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000509
Steve Naroff33fdb732009-03-31 16:53:37 +0000510 virtual llvm::Constant *GenerateConstantString(const ObjCStringLiteral *SL);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000511
512 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
513 const ObjCContainerDecl *CD=0);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000514
515 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
516
517 /// GetOrEmitProtocol - Get the protocol object for the given
518 /// declaration, emitting it if necessary. The return value has type
519 /// ProtocolPtrTy.
520 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD)=0;
521
522 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
523 /// object for the given declaration, emitting it if needed. These
524 /// forward references will be filled in with empty bodies if no
525 /// definition is seen. The return value has type ProtocolPtrTy.
526 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD)=0;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000527};
528
529class CGObjCMac : public CGObjCCommonMac {
530private:
531 ObjCTypesHelper ObjCTypes;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000532 /// EmitImageInfo - Emit the image info marker used to encode some module
533 /// level information.
534 void EmitImageInfo();
535
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000536 /// EmitModuleInfo - Another marker encoding module level
537 /// information.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000538 void EmitModuleInfo();
539
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000540 /// EmitModuleSymols - Emit module symbols, the list of defined
541 /// classes and categories. The result has type SymtabPtrTy.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000542 llvm::Constant *EmitModuleSymbols();
543
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000544 /// FinishModule - Write out global data structures at the end of
545 /// processing a translation unit.
546 void FinishModule();
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000547
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000548 /// EmitClassExtension - Generate the class extension structure used
549 /// to store the weak ivar layout and properties. The return value
550 /// has type ClassExtensionPtrTy.
551 llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID);
552
553 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
554 /// for the given class.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000555 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000556 const ObjCInterfaceDecl *ID);
557
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000558 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000559 QualType ResultType,
560 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000561 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000562 QualType Arg0Ty,
563 bool IsSuper,
564 const CallArgList &CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000565
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000566 /// EmitIvarList - Emit the ivar list for the given
567 /// implementation. If ForClass is true the list of class ivars
568 /// (i.e. metaclass ivars) is emitted, otherwise the list of
569 /// interface ivars will be emitted. The return value has type
570 /// IvarListPtrTy.
571 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +0000572 bool ForClass);
573
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000574 /// EmitMetaClass - Emit a forward reference to the class structure
575 /// for the metaclass of the given interface. The return value has
576 /// type ClassPtrTy.
577 llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
578
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000579 /// EmitMetaClass - Emit a class structure for the metaclass of the
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000580 /// given implementation. The return value has type ClassPtrTy.
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000581 llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
582 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000583 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000584 const ConstantVector &Methods);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000585
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000586 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000587
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000588 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000589
590 /// EmitMethodList - Emit the method list for the given
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000591 /// implementation. The return value has type MethodListPtrTy.
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000592 llvm::Constant *EmitMethodList(const std::string &Name,
593 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000594 const ConstantVector &Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000595
596 /// EmitMethodDescList - Emit a method description list for a list of
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000597 /// method declarations.
598 /// - TypeName: The name for the type containing the methods.
599 /// - IsProtocol: True iff these methods are for a protocol.
600 /// - ClassMethds: True iff these are class methods.
601 /// - Required: When true, only "required" methods are
602 /// listed. Similarly, when false only "optional" methods are
603 /// listed. For classes this should always be true.
604 /// - begin, end: The method list to output.
605 ///
606 /// The return value has type MethodDescriptionListPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000607 llvm::Constant *EmitMethodDescList(const std::string &Name,
608 const char *Section,
609 const ConstantVector &Methods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000610
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000611 /// GetOrEmitProtocol - Get the protocol object for the given
612 /// declaration, emitting it if necessary. The return value has type
613 /// ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +0000614 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000615
616 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
617 /// object for the given declaration, emitting it if needed. These
618 /// forward references will be filled in with empty bodies if no
619 /// definition is seen. The return value has type ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +0000620 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000621
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000622 /// EmitProtocolExtension - Generate the protocol extension
623 /// structure used to store optional instance and class methods, and
624 /// protocol properties. The return value has type
625 /// ProtocolExtensionPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000626 llvm::Constant *
627 EmitProtocolExtension(const ObjCProtocolDecl *PD,
628 const ConstantVector &OptInstanceMethods,
629 const ConstantVector &OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000630
631 /// EmitProtocolList - Generate the list of referenced
632 /// protocols. The return value has type ProtocolListPtrTy.
Daniel Dunbardbc933702008-08-21 21:57:41 +0000633 llvm::Constant *EmitProtocolList(const std::string &Name,
634 ObjCProtocolDecl::protocol_iterator begin,
635 ObjCProtocolDecl::protocol_iterator end);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000636
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000637 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
638 /// for the given selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000639 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000640
Fariborz Jahanianda320092009-01-29 19:24:30 +0000641 public:
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000642 CGObjCMac(CodeGen::CodeGenModule &cgm);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000643
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000644 virtual llvm::Function *ModuleInitFunction();
645
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000646 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000647 QualType ResultType,
648 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000649 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000650 bool IsClassMessage,
651 const CallArgList &CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000652
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000653 virtual CodeGen::RValue
654 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000655 QualType ResultType,
656 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000657 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000658 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000659 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000660 bool IsClassMessage,
661 const CallArgList &CallArgs);
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000662
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000663 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000664 const ObjCInterfaceDecl *ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000665
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000666 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000667
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000668 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000669
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000670 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000671
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000672 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000673 const ObjCProtocolDecl *PD);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000674
Chris Lattner74391b42009-03-22 21:03:39 +0000675 virtual llvm::Constant *GetPropertyGetFunction();
676 virtual llvm::Constant *GetPropertySetFunction();
677 virtual llvm::Constant *EnumerationMutationFunction();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000678
Fariborz Jahanianbd71be42008-11-21 00:49:24 +0000679 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
680 const Stmt &S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000681 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
682 const ObjCAtThrowStmt &S);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000683 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +0000684 llvm::Value *AddrWeakObj);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000685 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
686 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000687 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
688 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian7eda8362008-11-20 19:23:36 +0000689 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
690 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000691 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
692 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian0bb20362009-02-02 20:02:29 +0000693
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000694 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
695 QualType ObjectTy,
696 llvm::Value *BaseValue,
697 const ObjCIvarDecl *Ivar,
698 const FieldDecl *Field,
699 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000700 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
701 ObjCInterfaceDecl *Interface,
702 const ObjCIvarDecl *Ivar);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000703};
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000704
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000705class CGObjCNonFragileABIMac : public CGObjCCommonMac {
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000706private:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000707 ObjCNonFragileABITypesHelper ObjCTypes;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000708 llvm::GlobalVariable* ObjCEmptyCacheVar;
709 llvm::GlobalVariable* ObjCEmptyVtableVar;
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000710
Daniel Dunbar11394522009-04-18 08:51:00 +0000711 /// SuperClassReferences - uniqued super class references.
712 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> SuperClassReferences;
713
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000714 /// MetaClassReferences - uniqued meta class references.
715 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> MetaClassReferences;
Daniel Dunbare588b992009-03-01 04:46:24 +0000716
717 /// EHTypeReferences - uniqued class ehtype references.
718 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> EHTypeReferences;
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000719
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000720 /// FinishNonFragileABIModule - Write out global data structures at the end of
721 /// processing a translation unit.
722 void FinishNonFragileABIModule();
Daniel Dunbar8158a2f2009-04-08 04:21:03 +0000723
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000724 llvm::GlobalVariable * BuildClassRoTInitializer(unsigned flags,
725 unsigned InstanceStart,
726 unsigned InstanceSize,
727 const ObjCImplementationDecl *ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +0000728 llvm::GlobalVariable * BuildClassMetaData(std::string &ClassName,
729 llvm::Constant *IsAGV,
730 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +0000731 llvm::Constant *ClassRoGV,
732 bool HiddenVisibility);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000733
734 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
735
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +0000736 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
737
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000738 /// EmitMethodList - Emit the method list for the given
739 /// implementation. The return value has type MethodListnfABITy.
740 llvm::Constant *EmitMethodList(const std::string &Name,
741 const char *Section,
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +0000742 const ConstantVector &Methods);
743 /// EmitIvarList - Emit the ivar list for the given
744 /// implementation. If ForClass is true the list of class ivars
745 /// (i.e. metaclass ivars) is emitted, otherwise the list of
746 /// interface ivars will be emitted. The return value has type
747 /// IvarListnfABIPtrTy.
748 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000749
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000750 llvm::Constant *EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +0000751 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +0000752 unsigned long int offset);
753
Fariborz Jahanianda320092009-01-29 19:24:30 +0000754 /// GetOrEmitProtocol - Get the protocol object for the given
755 /// declaration, emitting it if necessary. The return value has type
756 /// ProtocolPtrTy.
757 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
758
759 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
760 /// object for the given declaration, emitting it if needed. These
761 /// forward references will be filled in with empty bodies if no
762 /// definition is seen. The return value has type ProtocolPtrTy.
763 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
764
765 /// EmitProtocolList - Generate the list of referenced
766 /// protocols. The return value has type ProtocolListPtrTy.
767 llvm::Constant *EmitProtocolList(const std::string &Name,
768 ObjCProtocolDecl::protocol_iterator begin,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000769 ObjCProtocolDecl::protocol_iterator end);
770
771 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
772 QualType ResultType,
773 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000774 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000775 QualType Arg0Ty,
776 bool IsSuper,
777 const CallArgList &CallArgs);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +0000778
779 /// GetClassGlobal - Return the global variable for the Objective-C
780 /// class of the given name.
Fariborz Jahanian0f902942009-04-14 18:41:56 +0000781 llvm::GlobalVariable *GetClassGlobal(const std::string &Name);
782
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000783 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
Daniel Dunbar11394522009-04-18 08:51:00 +0000784 /// for the given class reference.
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000785 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar11394522009-04-18 08:51:00 +0000786 const ObjCInterfaceDecl *ID);
787
788 /// EmitSuperClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
789 /// for the given super class reference.
790 llvm::Value *EmitSuperClassRef(CGBuilderTy &Builder,
791 const ObjCInterfaceDecl *ID);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000792
793 /// EmitMetaClassRef - Return a Value * of the address of _class_t
794 /// meta-data
795 llvm::Value *EmitMetaClassRef(CGBuilderTy &Builder,
796 const ObjCInterfaceDecl *ID);
797
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000798 /// ObjCIvarOffsetVariable - Returns the ivar offset variable for
799 /// the given ivar.
800 ///
Daniel Dunbar5e88bea2009-04-19 00:31:15 +0000801 llvm::GlobalVariable * ObjCIvarOffsetVariable(
Fariborz Jahanian01a0c362009-02-12 18:51:23 +0000802 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000803 const ObjCIvarDecl *Ivar);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000804
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +0000805 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
806 /// for the given selector.
807 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbare588b992009-03-01 04:46:24 +0000808
Daniel Dunbar8158a2f2009-04-08 04:21:03 +0000809 /// GetInterfaceEHType - Get the cached ehtype for the given Objective-C
Daniel Dunbare588b992009-03-01 04:46:24 +0000810 /// interface. The return value has type EHTypePtrTy.
Daniel Dunbar8158a2f2009-04-08 04:21:03 +0000811 llvm::Value *GetInterfaceEHType(const ObjCInterfaceDecl *ID,
812 bool ForDefinition);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +0000813
814 const char *getMetaclassSymbolPrefix() const {
815 return "OBJC_METACLASS_$_";
816 }
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000817
Daniel Dunbar6ab187a2009-04-07 05:48:37 +0000818 const char *getClassSymbolPrefix() const {
819 return "OBJC_CLASS_$_";
820 }
821
Daniel Dunbarb02532a2009-04-19 23:41:48 +0000822 void GetClassSizeInfo(const ObjCInterfaceDecl *OID,
823 uint32_t &InstanceStart,
824 uint32_t &InstanceSize);
825
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000826public:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000827 CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000828 // FIXME. All stubs for now!
829 virtual llvm::Function *ModuleInitFunction();
830
831 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
832 QualType ResultType,
833 Selector Sel,
834 llvm::Value *Receiver,
835 bool IsClassMessage,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000836 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000837
838 virtual CodeGen::RValue
839 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
840 QualType ResultType,
841 Selector Sel,
842 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000843 bool isCategoryImpl,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000844 llvm::Value *Receiver,
845 bool IsClassMessage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000846 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000847
848 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000849 const ObjCInterfaceDecl *ID);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000850
851 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel)
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +0000852 { return EmitSelector(Builder, Sel); }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000853
Fariborz Jahanianeb062d92009-01-26 18:32:24 +0000854 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000855
856 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000857 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +0000858 const ObjCProtocolDecl *PD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000859
Chris Lattner74391b42009-03-22 21:03:39 +0000860 virtual llvm::Constant *GetPropertyGetFunction() {
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000861 return ObjCTypes.GetPropertyFn;
862 }
Chris Lattner74391b42009-03-22 21:03:39 +0000863 virtual llvm::Constant *GetPropertySetFunction() {
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000864 return ObjCTypes.SetPropertyFn;
865 }
Chris Lattner74391b42009-03-22 21:03:39 +0000866 virtual llvm::Constant *EnumerationMutationFunction() {
Daniel Dunbar28ed0842009-02-16 18:48:45 +0000867 return ObjCTypes.EnumerationMutationFn;
868 }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000869
870 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000871 const Stmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000872 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000873 const ObjCAtThrowStmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000874 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000875 llvm::Value *AddrWeakObj);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000876 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000877 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000878 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000879 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000880 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000881 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000882 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000883 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000884 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
885 QualType ObjectTy,
886 llvm::Value *BaseValue,
887 const ObjCIvarDecl *Ivar,
888 const FieldDecl *Field,
889 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000890 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
891 ObjCInterfaceDecl *Interface,
892 const ObjCIvarDecl *Ivar);
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000893};
894
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000895} // end anonymous namespace
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000896
897/* *** Helper Functions *** */
898
899/// getConstantGEP() - Help routine to construct simple GEPs.
900static llvm::Constant *getConstantGEP(llvm::Constant *C,
901 unsigned idx0,
902 unsigned idx1) {
903 llvm::Value *Idxs[] = {
904 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx0),
905 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx1)
906 };
907 return llvm::ConstantExpr::getGetElementPtr(C, Idxs, 2);
908}
909
Daniel Dunbar8158a2f2009-04-08 04:21:03 +0000910/// hasObjCExceptionAttribute - Return true if this class or any super
911/// class has the __objc_exception__ attribute.
912static bool hasObjCExceptionAttribute(const ObjCInterfaceDecl *OID) {
Daniel Dunbarb11fa0d2009-04-13 21:08:27 +0000913 if (OID->hasAttr<ObjCExceptionAttr>())
Daniel Dunbar8158a2f2009-04-08 04:21:03 +0000914 return true;
915 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
916 return hasObjCExceptionAttribute(Super);
917 return false;
918}
919
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000920/* *** CGObjCMac Public Interface *** */
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000921
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000922CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm),
923 ObjCTypes(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000924{
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000925 ObjCABI = 1;
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000926 EmitImageInfo();
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000927}
928
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000929/// GetClass - Return a reference to the class for the given interface
930/// decl.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000931llvm::Value *CGObjCMac::GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000932 const ObjCInterfaceDecl *ID) {
933 return EmitClassRef(Builder, ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000934}
935
936/// GetSelector - Return the pointer to the unique'd string for this selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000937llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000938 return EmitSelector(Builder, Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000939}
940
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000941/// Generate a constant CFString object.
942/*
943 struct __builtin_CFString {
944 const int *isa; // point to __CFConstantStringClassReference
945 int flags;
946 const char *str;
947 long length;
948 };
949*/
950
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000951llvm::Constant *CGObjCCommonMac::GenerateConstantString(
Steve Naroff33fdb732009-03-31 16:53:37 +0000952 const ObjCStringLiteral *SL) {
Steve Naroff8d4141f2009-04-01 13:55:36 +0000953 return CGM.GetAddrOfConstantCFString(SL->getString());
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000954}
955
956/// Generates a message send where the super is the receiver. This is
957/// a message send to self with special delivery semantics indicating
958/// which class's method should be called.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000959CodeGen::RValue
960CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000961 QualType ResultType,
962 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000963 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000964 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000965 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000966 bool IsClassMessage,
Daniel Dunbar46f45b92008-09-09 01:06:48 +0000967 const CodeGen::CallArgList &CallArgs) {
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000968 // Create and init a super structure; this is a (receiver, class)
969 // pair we will pass to objc_msgSendSuper.
970 llvm::Value *ObjCSuper =
971 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
972 llvm::Value *ReceiverAsObject =
973 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
974 CGF.Builder.CreateStore(ReceiverAsObject,
975 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000976
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000977 // If this is a class message the metaclass is passed as the target.
978 llvm::Value *Target;
979 if (IsClassMessage) {
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000980 if (isCategoryImpl) {
981 // Message sent to 'super' in a class method defined in a category
982 // implementation requires an odd treatment.
983 // If we are in a class method, we must retrieve the
984 // _metaclass_ for the current class, pointed at by
985 // the class's "isa" pointer. The following assumes that
986 // isa" is the first ivar in a class (which it must be).
987 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
988 Target = CGF.Builder.CreateStructGEP(Target, 0);
989 Target = CGF.Builder.CreateLoad(Target);
990 }
991 else {
992 llvm::Value *MetaClassPtr = EmitMetaClassRef(Class);
993 llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1);
994 llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr);
995 Target = Super;
996 }
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000997 } else {
998 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
999 }
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001000 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
1001 // and ObjCTypes types.
1002 const llvm::Type *ClassTy =
1003 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001004 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001005 CGF.Builder.CreateStore(Target,
1006 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
1007
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001008 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001009 ObjCSuper, ObjCTypes.SuperPtrCTy,
1010 true, CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001011}
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001012
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001013/// Generate code for a message send expression.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +00001014CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001015 QualType ResultType,
1016 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001017 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001018 bool IsClassMessage,
1019 const CallArgList &CallArgs) {
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001020 llvm::Value *Arg0 =
1021 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy, "tmp");
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001022 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001023 Arg0, CGF.getContext().getObjCIdType(),
1024 false, CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001025}
1026
1027CodeGen::RValue CGObjCMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001028 QualType ResultType,
1029 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001030 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001031 QualType Arg0Ty,
1032 bool IsSuper,
1033 const CallArgList &CallArgs) {
1034 CallArgList ActualArgs;
Daniel Dunbar46f45b92008-09-09 01:06:48 +00001035 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
1036 ActualArgs.push_back(std::make_pair(RValue::get(EmitSelector(CGF.Builder,
1037 Sel)),
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001038 CGF.getContext().getObjCSelType()));
1039 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001040
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001041 CodeGenTypes &Types = CGM.getTypes();
1042 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs);
1043 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo, false);
Daniel Dunbar5669e572008-10-17 03:24:53 +00001044
1045 llvm::Constant *Fn;
Daniel Dunbar88b53962009-02-02 22:03:45 +00001046 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Daniel Dunbar5669e572008-10-17 03:24:53 +00001047 Fn = ObjCTypes.getSendStretFn(IsSuper);
1048 } else if (ResultType->isFloatingType()) {
1049 // FIXME: Sadly, this is wrong. This actually depends on the
1050 // architecture. This happens to be right for x86-32 though.
1051 Fn = ObjCTypes.getSendFpretFn(IsSuper);
1052 } else {
1053 Fn = ObjCTypes.getSendFn(IsSuper);
1054 }
Daniel Dunbar62d5c1b2008-09-10 07:00:50 +00001055 Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy));
Daniel Dunbar88b53962009-02-02 22:03:45 +00001056 return CGF.EmitCall(FnInfo, Fn, ActualArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001057}
1058
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001059llvm::Value *CGObjCMac::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001060 const ObjCProtocolDecl *PD) {
Daniel Dunbarc67876d2008-09-04 04:33:15 +00001061 // FIXME: I don't understand why gcc generates this, or where it is
1062 // resolved. Investigate. Its also wasteful to look this up over and
1063 // over.
1064 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1065
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001066 return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
1067 ObjCTypes.ExternalProtocolPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001068}
1069
Fariborz Jahanianda320092009-01-29 19:24:30 +00001070void CGObjCCommonMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001071 // FIXME: We shouldn't need this, the protocol decl should contain
1072 // enough information to tell us whether this was a declaration or a
1073 // definition.
1074 DefinedProtocols.insert(PD->getIdentifier());
1075
1076 // If we have generated a forward reference to this protocol, emit
1077 // it now. Otherwise do nothing, the protocol objects are lazily
1078 // emitted.
1079 if (Protocols.count(PD->getIdentifier()))
1080 GetOrEmitProtocol(PD);
1081}
1082
Fariborz Jahanianda320092009-01-29 19:24:30 +00001083llvm::Constant *CGObjCCommonMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001084 if (DefinedProtocols.count(PD->getIdentifier()))
1085 return GetOrEmitProtocol(PD);
1086 return GetOrEmitProtocolRef(PD);
1087}
1088
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001089/*
1090 // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions
1091 struct _objc_protocol {
1092 struct _objc_protocol_extension *isa;
1093 char *protocol_name;
1094 struct _objc_protocol_list *protocol_list;
1095 struct _objc__method_prototype_list *instance_methods;
1096 struct _objc__method_prototype_list *class_methods
1097 };
1098
1099 See EmitProtocolExtension().
1100*/
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001101llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
1102 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1103
1104 // Early exit if a defining object has already been generated.
1105 if (Entry && Entry->hasInitializer())
1106 return Entry;
1107
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001108 // FIXME: I don't understand why gcc generates this, or where it is
1109 // resolved. Investigate. Its also wasteful to look this up over and
1110 // over.
1111 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1112
Chris Lattner8ec03f52008-11-24 03:54:41 +00001113 const char *ProtocolName = PD->getNameAsCString();
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001114
1115 // Construct method lists.
1116 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1117 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregor6ab35242009-04-09 21:40:53 +00001118 for (ObjCProtocolDecl::instmeth_iterator
1119 i = PD->instmeth_begin(CGM.getContext()),
1120 e = PD->instmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001121 ObjCMethodDecl *MD = *i;
1122 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1123 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1124 OptInstanceMethods.push_back(C);
1125 } else {
1126 InstanceMethods.push_back(C);
1127 }
1128 }
1129
Douglas Gregor6ab35242009-04-09 21:40:53 +00001130 for (ObjCProtocolDecl::classmeth_iterator
1131 i = PD->classmeth_begin(CGM.getContext()),
1132 e = PD->classmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001133 ObjCMethodDecl *MD = *i;
1134 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1135 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1136 OptClassMethods.push_back(C);
1137 } else {
1138 ClassMethods.push_back(C);
1139 }
1140 }
1141
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001142 std::vector<llvm::Constant*> Values(5);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001143 Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001144 Values[1] = GetClassName(PD->getIdentifier());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001145 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001146 EmitProtocolList("\01L_OBJC_PROTOCOL_REFS_" + PD->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001147 PD->protocol_begin(),
1148 PD->protocol_end());
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001149 Values[3] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001150 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_"
1151 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001152 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1153 InstanceMethods);
1154 Values[4] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001155 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_"
1156 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001157 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1158 ClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001159 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
1160 Values);
1161
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001162 if (Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001163 // Already created, fix the linkage and update the initializer.
1164 Entry->setLinkage(llvm::GlobalValue::InternalLinkage);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001165 Entry->setInitializer(Init);
1166 } else {
1167 Entry =
1168 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
1169 llvm::GlobalValue::InternalLinkage,
1170 Init,
1171 std::string("\01L_OBJC_PROTOCOL_")+ProtocolName,
1172 &CGM.getModule());
1173 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001174 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001175 UsedGlobals.push_back(Entry);
1176 // FIXME: Is this necessary? Why only for protocol?
1177 Entry->setAlignment(4);
1178 }
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001179
1180 return Entry;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001181}
1182
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001183llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001184 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1185
1186 if (!Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001187 // We use the initializer as a marker of whether this is a forward
1188 // reference or not. At module finalization we add the empty
1189 // contents for protocols which were referenced but never defined.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001190 Entry =
1191 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001192 llvm::GlobalValue::ExternalLinkage,
1193 0,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001194 "\01L_OBJC_PROTOCOL_" + PD->getNameAsString(),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001195 &CGM.getModule());
1196 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001197 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001198 UsedGlobals.push_back(Entry);
1199 // FIXME: Is this necessary? Why only for protocol?
1200 Entry->setAlignment(4);
1201 }
1202
1203 return Entry;
1204}
1205
1206/*
1207 struct _objc_protocol_extension {
1208 uint32_t size;
1209 struct objc_method_description_list *optional_instance_methods;
1210 struct objc_method_description_list *optional_class_methods;
1211 struct objc_property_list *instance_properties;
1212 };
1213*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001214llvm::Constant *
1215CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
1216 const ConstantVector &OptInstanceMethods,
1217 const ConstantVector &OptClassMethods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001218 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001219 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolExtensionTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001220 std::vector<llvm::Constant*> Values(4);
1221 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001222 Values[1] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001223 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_"
1224 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001225 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1226 OptInstanceMethods);
1227 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001228 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_"
1229 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001230 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1231 OptClassMethods);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001232 Values[3] = EmitPropertyList("\01L_OBJC_$_PROP_PROTO_LIST_" +
1233 PD->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001234 0, PD, ObjCTypes);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001235
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001236 // Return null if no extension bits are used.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001237 if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
1238 Values[3]->isNullValue())
1239 return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
1240
1241 llvm::Constant *Init =
1242 llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001243
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001244 // No special section, but goes in llvm.used
1245 return CreateMetadataVar("\01L_OBJC_PROTOCOLEXT_" + PD->getNameAsString(),
1246 Init,
1247 0, 0, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001248}
1249
1250/*
1251 struct objc_protocol_list {
1252 struct objc_protocol_list *next;
1253 long count;
1254 Protocol *list[];
1255 };
1256*/
Daniel Dunbardbc933702008-08-21 21:57:41 +00001257llvm::Constant *
1258CGObjCMac::EmitProtocolList(const std::string &Name,
1259 ObjCProtocolDecl::protocol_iterator begin,
1260 ObjCProtocolDecl::protocol_iterator end) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001261 std::vector<llvm::Constant*> ProtocolRefs;
1262
Daniel Dunbardbc933702008-08-21 21:57:41 +00001263 for (; begin != end; ++begin)
1264 ProtocolRefs.push_back(GetProtocolRef(*begin));
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001265
1266 // Just return null for empty protocol lists
1267 if (ProtocolRefs.empty())
1268 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1269
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001270 // This list is null terminated.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001271 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
1272
1273 std::vector<llvm::Constant*> Values(3);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001274 // This field is only used by the runtime.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001275 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1276 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
1277 Values[2] =
1278 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
1279 ProtocolRefs.size()),
1280 ProtocolRefs);
1281
1282 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1283 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001284 CreateMetadataVar(Name, Init, "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001285 4, false);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001286 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
1287}
1288
1289/*
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001290 struct _objc_property {
1291 const char * const name;
1292 const char * const attributes;
1293 };
1294
1295 struct _objc_property_list {
1296 uint32_t entsize; // sizeof (struct _objc_property)
1297 uint32_t prop_count;
1298 struct _objc_property[prop_count];
1299 };
1300*/
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001301llvm::Constant *CGObjCCommonMac::EmitPropertyList(const std::string &Name,
1302 const Decl *Container,
1303 const ObjCContainerDecl *OCD,
1304 const ObjCCommonTypesHelper &ObjCTypes) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001305 std::vector<llvm::Constant*> Properties, Prop(2);
Douglas Gregor6ab35242009-04-09 21:40:53 +00001306 for (ObjCContainerDecl::prop_iterator I = OCD->prop_begin(CGM.getContext()),
1307 E = OCD->prop_end(CGM.getContext()); I != E; ++I) {
Steve Naroff93983f82009-01-11 12:47:58 +00001308 const ObjCPropertyDecl *PD = *I;
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001309 Prop[0] = GetPropertyName(PD->getIdentifier());
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00001310 Prop[1] = GetPropertyTypeString(PD, Container);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001311 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
1312 Prop));
1313 }
1314
1315 // Return null for empty list.
1316 if (Properties.empty())
1317 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1318
1319 unsigned PropertySize =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001320 CGM.getTargetData().getTypePaddedSize(ObjCTypes.PropertyTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001321 std::vector<llvm::Constant*> Values(3);
1322 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
1323 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
1324 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
1325 Properties.size());
1326 Values[2] = llvm::ConstantArray::get(AT, Properties);
1327 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1328
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001329 llvm::GlobalVariable *GV =
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001330 CreateMetadataVar(Name, Init,
1331 (ObjCABI == 2) ? "__DATA, __objc_const" :
1332 "__OBJC,__property,regular,no_dead_strip",
1333 (ObjCABI == 2) ? 8 : 4,
1334 true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001335 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.PropertyListPtrTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001336}
1337
1338/*
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001339 struct objc_method_description_list {
1340 int count;
1341 struct objc_method_description list[];
1342 };
1343*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001344llvm::Constant *
1345CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
1346 std::vector<llvm::Constant*> Desc(2);
1347 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1348 ObjCTypes.SelectorPtrTy);
1349 Desc[1] = GetMethodVarType(MD);
1350 return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
1351 Desc);
1352}
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001353
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001354llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name,
1355 const char *Section,
1356 const ConstantVector &Methods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001357 // Return null for empty list.
1358 if (Methods.empty())
1359 return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
1360
1361 std::vector<llvm::Constant*> Values(2);
1362 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1363 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
1364 Methods.size());
1365 Values[1] = llvm::ConstantArray::get(AT, Methods);
1366 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1367
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001368 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001369 return llvm::ConstantExpr::getBitCast(GV,
1370 ObjCTypes.MethodDescriptionListPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001371}
1372
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001373/*
1374 struct _objc_category {
1375 char *category_name;
1376 char *class_name;
1377 struct _objc_method_list *instance_methods;
1378 struct _objc_method_list *class_methods;
1379 struct _objc_protocol_list *protocols;
1380 uint32_t size; // <rdar://4585769>
1381 struct _objc_property_list *instance_properties;
1382 };
1383 */
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001384void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001385 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.CategoryTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001386
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001387 // FIXME: This is poor design, the OCD should have a pointer to the
1388 // category decl. Additionally, note that Category can be null for
1389 // the @implementation w/o an @interface case. Sema should just
1390 // create one for us as it does for @implementation so everyone else
1391 // can live life under a clear blue sky.
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001392 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001393 const ObjCCategoryDecl *Category =
1394 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001395 std::string ExtName(Interface->getNameAsString() + "_" +
1396 OCD->getNameAsString());
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001397
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001398 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1399 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
1400 e = OCD->instmeth_end(); i != e; ++i) {
1401 // Instance methods should always be defined.
1402 InstanceMethods.push_back(GetMethodConstant(*i));
1403 }
1404 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
1405 e = OCD->classmeth_end(); i != e; ++i) {
1406 // Class methods should always be defined.
1407 ClassMethods.push_back(GetMethodConstant(*i));
1408 }
1409
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001410 std::vector<llvm::Constant*> Values(7);
1411 Values[0] = GetClassName(OCD->getIdentifier());
1412 Values[1] = GetClassName(Interface->getIdentifier());
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001413 Values[2] =
1414 EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") +
1415 ExtName,
1416 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001417 InstanceMethods);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001418 Values[3] =
1419 EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName,
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001420 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001421 ClassMethods);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001422 if (Category) {
1423 Values[4] =
1424 EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName,
1425 Category->protocol_begin(),
1426 Category->protocol_end());
1427 } else {
1428 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1429 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001430 Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001431
1432 // If there is no category @interface then there can be no properties.
1433 if (Category) {
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001434 Values[6] = EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001435 OCD, Category, ObjCTypes);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001436 } else {
1437 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1438 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001439
1440 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
1441 Values);
1442
1443 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001444 CreateMetadataVar(std::string("\01L_OBJC_CATEGORY_")+ExtName, Init,
1445 "__OBJC,__category,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001446 4, true);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001447 DefinedCategories.push_back(GV);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001448}
1449
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001450// FIXME: Get from somewhere?
1451enum ClassFlags {
1452 eClassFlags_Factory = 0x00001,
1453 eClassFlags_Meta = 0x00002,
1454 // <rdr://5142207>
1455 eClassFlags_HasCXXStructors = 0x02000,
1456 eClassFlags_Hidden = 0x20000,
1457 eClassFlags_ABI2_Hidden = 0x00010,
1458 eClassFlags_ABI2_HasCXXStructors = 0x00004 // <rdr://4923634>
1459};
1460
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001461/*
1462 struct _objc_class {
1463 Class isa;
1464 Class super_class;
1465 const char *name;
1466 long version;
1467 long info;
1468 long instance_size;
1469 struct _objc_ivar_list *ivars;
1470 struct _objc_method_list *methods;
1471 struct _objc_cache *cache;
1472 struct _objc_protocol_list *protocols;
1473 // Objective-C 1.0 extensions (<rdr://4585769>)
1474 const char *ivar_layout;
1475 struct _objc_class_ext *ext;
1476 };
1477
1478 See EmitClassExtension();
1479 */
1480void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001481 DefinedSymbols.insert(ID->getIdentifier());
1482
Chris Lattner8ec03f52008-11-24 03:54:41 +00001483 std::string ClassName = ID->getNameAsString();
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001484 // FIXME: Gross
1485 ObjCInterfaceDecl *Interface =
1486 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001487 llvm::Constant *Protocols =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001488 EmitProtocolList("\01L_OBJC_CLASS_PROTOCOLS_" + ID->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001489 Interface->protocol_begin(),
1490 Interface->protocol_end());
Chris Lattnerb7b58b12009-04-19 06:02:28 +00001491 const llvm::Type *InterfaceTy;
1492 if (Interface->isForwardDecl())
1493 InterfaceTy = llvm::StructType::get(NULL, NULL);
1494 else
1495 InterfaceTy =
Chris Lattner03d9f342009-04-01 06:23:52 +00001496 CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(Interface));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001497 unsigned Flags = eClassFlags_Factory;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001498 unsigned Size = CGM.getTargetData().getTypePaddedSize(InterfaceTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001499
1500 // FIXME: Set CXX-structors flag.
Daniel Dunbar04d40782009-04-14 06:00:08 +00001501 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001502 Flags |= eClassFlags_Hidden;
1503
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001504 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1505 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
1506 e = ID->instmeth_end(); i != e; ++i) {
1507 // Instance methods should always be defined.
1508 InstanceMethods.push_back(GetMethodConstant(*i));
1509 }
1510 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
1511 e = ID->classmeth_end(); i != e; ++i) {
1512 // Class methods should always be defined.
1513 ClassMethods.push_back(GetMethodConstant(*i));
1514 }
1515
1516 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
1517 e = ID->propimpl_end(); i != e; ++i) {
1518 ObjCPropertyImplDecl *PID = *i;
1519
1520 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1521 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1522
1523 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
1524 if (llvm::Constant *C = GetMethodConstant(MD))
1525 InstanceMethods.push_back(C);
1526 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
1527 if (llvm::Constant *C = GetMethodConstant(MD))
1528 InstanceMethods.push_back(C);
1529 }
1530 }
1531
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001532 std::vector<llvm::Constant*> Values(12);
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001533 Values[ 0] = EmitMetaClass(ID, Protocols, InterfaceTy, ClassMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001534 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001535 // Record a reference to the super class.
1536 LazySymbols.insert(Super->getIdentifier());
1537
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001538 Values[ 1] =
1539 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1540 ObjCTypes.ClassPtrTy);
1541 } else {
1542 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1543 }
1544 Values[ 2] = GetClassName(ID->getIdentifier());
1545 // Version is always 0.
1546 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1547 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1548 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001549 Values[ 6] = EmitIvarList(ID, false);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001550 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001551 EmitMethodList("\01L_OBJC_INSTANCE_METHODS_" + ID->getNameAsString(),
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001552 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001553 InstanceMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001554 // cache is always NULL.
1555 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1556 Values[ 9] = Protocols;
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001557 // FIXME: Set ivar_layout
Fariborz Jahanian667423a2009-03-25 22:36:49 +00001558 // Values[10] = BuildIvarLayout(ID, true);
1559 Values[10] = GetIvarLayoutName(0, ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001560 Values[11] = EmitClassExtension(ID);
1561 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1562 Values);
1563
1564 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001565 CreateMetadataVar(std::string("\01L_OBJC_CLASS_")+ClassName, Init,
1566 "__OBJC,__class,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001567 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001568 DefinedClasses.push_back(GV);
1569}
1570
1571llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
1572 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001573 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001574 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001575 unsigned Flags = eClassFlags_Meta;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001576 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001577
Daniel Dunbar04d40782009-04-14 06:00:08 +00001578 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001579 Flags |= eClassFlags_Hidden;
1580
1581 std::vector<llvm::Constant*> Values(12);
1582 // The isa for the metaclass is the root of the hierarchy.
1583 const ObjCInterfaceDecl *Root = ID->getClassInterface();
1584 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
1585 Root = Super;
1586 Values[ 0] =
1587 llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
1588 ObjCTypes.ClassPtrTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001589 // The super class for the metaclass is emitted as the name of the
1590 // super class. The runtime fixes this up to point to the
1591 // *metaclass* for the super class.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001592 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
1593 Values[ 1] =
1594 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1595 ObjCTypes.ClassPtrTy);
1596 } else {
1597 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1598 }
1599 Values[ 2] = GetClassName(ID->getIdentifier());
1600 // Version is always 0.
1601 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1602 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1603 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001604 Values[ 6] = EmitIvarList(ID, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001605 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001606 EmitMethodList("\01L_OBJC_CLASS_METHODS_" + ID->getNameAsString(),
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001607 "__OBJC,__cls_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001608 Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001609 // cache is always NULL.
1610 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1611 Values[ 9] = Protocols;
1612 // ivar_layout for metaclass is always NULL.
1613 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1614 // The class extension is always unused for metaclasses.
1615 Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1616 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1617 Values);
1618
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001619 std::string Name("\01L_OBJC_METACLASS_");
Chris Lattner8ec03f52008-11-24 03:54:41 +00001620 Name += ID->getNameAsCString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001621
1622 // Check for a forward reference.
1623 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
1624 if (GV) {
1625 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1626 "Forward metaclass reference has incorrect type.");
1627 GV->setLinkage(llvm::GlobalValue::InternalLinkage);
1628 GV->setInitializer(Init);
1629 } else {
1630 GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1631 llvm::GlobalValue::InternalLinkage,
1632 Init, Name,
1633 &CGM.getModule());
1634 }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001635 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001636 GV->setAlignment(4);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001637 UsedGlobals.push_back(GV);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001638
1639 return GV;
1640}
1641
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001642llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001643 std::string Name = "\01L_OBJC_METACLASS_" + ID->getNameAsString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001644
1645 // FIXME: Should we look these up somewhere other than the
1646 // module. Its a bit silly since we only generate these while
1647 // processing an implementation, so exactly one pointer would work
1648 // if know when we entered/exitted an implementation block.
1649
1650 // Check for an existing forward reference.
Fariborz Jahanianb0d27942009-01-07 20:11:22 +00001651 // Previously, metaclass with internal linkage may have been defined.
1652 // pass 'true' as 2nd argument so it is returned.
1653 if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true)) {
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001654 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1655 "Forward metaclass reference has incorrect type.");
1656 return GV;
1657 } else {
1658 // Generate as an external reference to keep a consistent
1659 // module. This will be patched up when we emit the metaclass.
1660 return new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1661 llvm::GlobalValue::ExternalLinkage,
1662 0,
1663 Name,
1664 &CGM.getModule());
1665 }
1666}
1667
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001668/*
1669 struct objc_class_ext {
1670 uint32_t size;
1671 const char *weak_ivar_layout;
1672 struct _objc_property_list *properties;
1673 };
1674*/
1675llvm::Constant *
1676CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
1677 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001678 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassExtensionTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001679
1680 std::vector<llvm::Constant*> Values(3);
1681 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001682 // FIXME: Output weak_ivar_layout string.
Fariborz Jahanian667423a2009-03-25 22:36:49 +00001683 // Values[1] = BuildIvarLayout(ID, false);
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00001684 Values[1] = GetIvarLayoutName(0, ObjCTypes);
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001685 Values[2] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001686 ID, ID->getClassInterface(), ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001687
1688 // Return null if no extension bits are used.
1689 if (Values[1]->isNullValue() && Values[2]->isNullValue())
1690 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1691
1692 llvm::Constant *Init =
1693 llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001694 return CreateMetadataVar("\01L_OBJC_CLASSEXT_" + ID->getNameAsString(),
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001695 Init, "__OBJC,__class_ext,regular,no_dead_strip",
1696 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001697}
1698
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001699/// countInheritedIvars - count number of ivars in class and its super class(s)
1700///
Douglas Gregor6ab35242009-04-09 21:40:53 +00001701static int countInheritedIvars(const ObjCInterfaceDecl *OI,
1702 ASTContext &Context) {
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001703 int count = 0;
1704 if (!OI)
1705 return 0;
1706 const ObjCInterfaceDecl *SuperClass = OI->getSuperClass();
1707 if (SuperClass)
Douglas Gregor6ab35242009-04-09 21:40:53 +00001708 count += countInheritedIvars(SuperClass, Context);
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001709 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1710 E = OI->ivar_end(); I != E; ++I)
1711 ++count;
Fariborz Jahanian18191882009-03-31 18:11:23 +00001712 // look into properties.
Douglas Gregor6ab35242009-04-09 21:40:53 +00001713 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(Context),
1714 E = OI->prop_end(Context); I != E; ++I) {
Fariborz Jahanian18191882009-03-31 18:11:23 +00001715 if ((*I)->getPropertyIvarDecl())
1716 ++count;
1717 }
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001718 return count;
1719}
1720
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001721/// getInterfaceDeclForIvar - Get the interface declaration node where
1722/// this ivar is declared in.
1723/// FIXME. Ideally, this info should be in the ivar node. But currently
1724/// it is not and prevailing wisdom is that ASTs should not have more
1725/// info than is absolutely needed, even though this info reflects the
1726/// source language.
1727///
1728static const ObjCInterfaceDecl *getInterfaceDeclForIvar(
1729 const ObjCInterfaceDecl *OI,
Douglas Gregor6ab35242009-04-09 21:40:53 +00001730 const ObjCIvarDecl *IVD,
1731 ASTContext &Context) {
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001732 if (!OI)
1733 return 0;
1734 assert(isa<ObjCInterfaceDecl>(OI) && "OI is not an interface");
1735 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1736 E = OI->ivar_end(); I != E; ++I)
1737 if ((*I)->getIdentifier() == IVD->getIdentifier())
1738 return OI;
Fariborz Jahanian5a4b4532009-03-31 17:00:52 +00001739 // look into properties.
Douglas Gregor6ab35242009-04-09 21:40:53 +00001740 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(Context),
1741 E = OI->prop_end(Context); I != E; ++I) {
Fariborz Jahanian5a4b4532009-03-31 17:00:52 +00001742 ObjCPropertyDecl *PDecl = (*I);
1743 if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl())
1744 if (IV->getIdentifier() == IVD->getIdentifier())
1745 return OI;
1746 }
Douglas Gregor6ab35242009-04-09 21:40:53 +00001747 return getInterfaceDeclForIvar(OI->getSuperClass(), IVD, Context);
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001748}
1749
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001750/*
1751 struct objc_ivar {
1752 char *ivar_name;
1753 char *ivar_type;
1754 int ivar_offset;
1755 };
1756
1757 struct objc_ivar_list {
1758 int ivar_count;
1759 struct objc_ivar list[count];
1760 };
1761 */
1762llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001763 bool ForClass) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001764 std::vector<llvm::Constant*> Ivars, Ivar(3);
1765
1766 // When emitting the root class GCC emits ivar entries for the
1767 // actual class structure. It is not clear if we need to follow this
1768 // behavior; for now lets try and get away with not doing it. If so,
1769 // the cleanest solution would be to make up an ObjCInterfaceDecl
1770 // for the class.
1771 if (ForClass)
1772 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001773
1774 ObjCInterfaceDecl *OID =
1775 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00001776 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001777
1778 RecordDecl::field_iterator ifield, pfield;
1779 const RecordDecl *RD = GetFirstIvarInRecord(OID, ifield, pfield);
Douglas Gregor6ab35242009-04-09 21:40:53 +00001780 for (RecordDecl::field_iterator e = RD->field_end(CGM.getContext());
1781 ifield != e; ++ifield) {
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001782 FieldDecl *Field = *ifield;
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00001783 uint64_t Offset = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001784 if (Field->getIdentifier())
1785 Ivar[0] = GetMethodVarName(Field->getIdentifier());
1786 else
1787 Ivar[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Devang Patel7794bb82009-03-04 18:21:39 +00001788 Ivar[1] = GetMethodVarType(Field);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001789 Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy, Offset);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001790 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001791 }
1792
1793 // Return null for empty list.
1794 if (Ivars.empty())
1795 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
1796
1797 std::vector<llvm::Constant*> Values(2);
1798 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
1799 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
1800 Ivars.size());
1801 Values[1] = llvm::ConstantArray::get(AT, Ivars);
1802 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1803
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001804 llvm::GlobalVariable *GV;
1805 if (ForClass)
1806 GV = CreateMetadataVar("\01L_OBJC_CLASS_VARIABLES_" + ID->getNameAsString(),
Daniel Dunbar58a29122009-03-09 22:18:41 +00001807 Init, "__OBJC,__class_vars,regular,no_dead_strip",
1808 4, true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001809 else
1810 GV = CreateMetadataVar("\01L_OBJC_INSTANCE_VARIABLES_"
1811 + ID->getNameAsString(),
1812 Init, "__OBJC,__instance_vars,regular,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001813 4, true);
1814 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.IvarListPtrTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001815}
1816
1817/*
1818 struct objc_method {
1819 SEL method_name;
1820 char *method_types;
1821 void *method;
1822 };
1823
1824 struct objc_method_list {
1825 struct objc_method_list *obsolete;
1826 int count;
1827 struct objc_method methods_list[count];
1828 };
1829*/
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001830
1831/// GetMethodConstant - Return a struct objc_method constant for the
1832/// given method if it has been defined. The result is null if the
1833/// method has not been defined. The return value has type MethodPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001834llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001835 // FIXME: Use DenseMap::lookup
1836 llvm::Function *Fn = MethodDefinitions[MD];
1837 if (!Fn)
1838 return 0;
1839
1840 std::vector<llvm::Constant*> Method(3);
1841 Method[0] =
1842 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1843 ObjCTypes.SelectorPtrTy);
1844 Method[1] = GetMethodVarType(MD);
1845 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
1846 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
1847}
1848
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001849llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name,
1850 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001851 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001852 // Return null for empty list.
1853 if (Methods.empty())
1854 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
1855
1856 std::vector<llvm::Constant*> Values(3);
1857 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1858 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1859 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
1860 Methods.size());
1861 Values[2] = llvm::ConstantArray::get(AT, Methods);
1862 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1863
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001864 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001865 return llvm::ConstantExpr::getBitCast(GV,
1866 ObjCTypes.MethodListPtrTy);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001867}
1868
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001869llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD,
Daniel Dunbarbb36d332009-02-02 21:43:58 +00001870 const ObjCContainerDecl *CD) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001871 std::string Name;
Fariborz Jahanian679a5022009-01-10 21:06:09 +00001872 GetNameForMethod(OMD, CD, Name);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001873
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001874 CodeGenTypes &Types = CGM.getTypes();
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001875 const llvm::FunctionType *MethodTy =
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001876 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001877 llvm::Function *Method =
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001878 llvm::Function::Create(MethodTy,
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001879 llvm::GlobalValue::InternalLinkage,
1880 Name,
1881 &CGM.getModule());
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001882 MethodDefinitions.insert(std::make_pair(OMD, Method));
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001883
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001884 return Method;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001885}
1886
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00001887uint64_t CGObjCCommonMac::GetIvarBaseOffset(const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +00001888 const FieldDecl *Field) {
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00001889 if (!Field->isBitField())
Daniel Dunbar48fa0642009-04-19 02:03:42 +00001890 return Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(Field));
1891
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00001892 // FIXME. Must be a better way of getting a bitfield base offset.
Daniel Dunbar48fa0642009-04-19 02:03:42 +00001893 CodeGenTypes::BitFieldInfo BFI = CGM.getTypes().getBitFieldInfo(Field);
1894 // FIXME: The "field no" for bitfields is something completely
1895 // different; it is the offset in multiples of the base type size!
1896 uint64_t Offset = CGM.getTypes().getLLVMFieldNo(Field);
1897 const llvm::Type *Ty =
1898 CGM.getTypes().ConvertTypeForMemRecursive(Field->getType());
1899 Offset *= CGM.getTypes().getTargetData().getTypePaddedSizeInBits(Ty);
1900 return (Offset + BFI.Begin) / 8;
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00001901}
1902
Daniel Dunbar48fa0642009-04-19 02:03:42 +00001903/// GetFieldBaseOffset - return the field's byte offset.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00001904uint64_t CGObjCCommonMac::GetFieldBaseOffset(const ObjCInterfaceDecl *OI,
1905 const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +00001906 const FieldDecl *Field) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00001907 const ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
Chris Lattnercd0ee142009-03-31 08:33:16 +00001908 const FieldDecl *FD = OI->lookupFieldDeclForIvar(CGM.getContext(), Ivar);
1909 return GetIvarBaseOffset(Layout, FD);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00001910}
1911
Daniel Dunbarfd65d372009-03-09 20:09:19 +00001912llvm::GlobalVariable *
1913CGObjCCommonMac::CreateMetadataVar(const std::string &Name,
1914 llvm::Constant *Init,
1915 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +00001916 unsigned Align,
1917 bool AddToUsed) {
Daniel Dunbarfd65d372009-03-09 20:09:19 +00001918 const llvm::Type *Ty = Init->getType();
1919 llvm::GlobalVariable *GV =
1920 new llvm::GlobalVariable(Ty, false,
1921 llvm::GlobalValue::InternalLinkage,
1922 Init,
1923 Name,
1924 &CGM.getModule());
1925 if (Section)
1926 GV->setSection(Section);
Daniel Dunbar35bd7632009-03-09 20:50:13 +00001927 if (Align)
1928 GV->setAlignment(Align);
1929 if (AddToUsed)
Daniel Dunbarfd65d372009-03-09 20:09:19 +00001930 UsedGlobals.push_back(GV);
1931 return GV;
1932}
1933
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001934llvm::Function *CGObjCMac::ModuleInitFunction() {
Daniel Dunbarf77ac862008-08-11 21:35:06 +00001935 // Abuse this interface function as a place to finalize.
1936 FinishModule();
1937
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001938 return NULL;
1939}
1940
Chris Lattner74391b42009-03-22 21:03:39 +00001941llvm::Constant *CGObjCMac::GetPropertyGetFunction() {
Daniel Dunbar49f66022008-09-24 03:38:44 +00001942 return ObjCTypes.GetPropertyFn;
1943}
1944
Chris Lattner74391b42009-03-22 21:03:39 +00001945llvm::Constant *CGObjCMac::GetPropertySetFunction() {
Daniel Dunbar49f66022008-09-24 03:38:44 +00001946 return ObjCTypes.SetPropertyFn;
1947}
1948
Chris Lattner74391b42009-03-22 21:03:39 +00001949llvm::Constant *CGObjCMac::EnumerationMutationFunction() {
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001950 return ObjCTypes.EnumerationMutationFn;
1951}
1952
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001953/*
1954
1955Objective-C setjmp-longjmp (sjlj) Exception Handling
1956--
1957
1958The basic framework for a @try-catch-finally is as follows:
1959{
1960 objc_exception_data d;
1961 id _rethrow = null;
Anders Carlsson190d00e2009-02-07 21:26:04 +00001962 bool _call_try_exit = true;
1963
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001964 objc_exception_try_enter(&d);
1965 if (!setjmp(d.jmp_buf)) {
1966 ... try body ...
1967 } else {
1968 // exception path
1969 id _caught = objc_exception_extract(&d);
1970
1971 // enter new try scope for handlers
1972 if (!setjmp(d.jmp_buf)) {
1973 ... match exception and execute catch blocks ...
1974
1975 // fell off end, rethrow.
1976 _rethrow = _caught;
Daniel Dunbar898d5082008-09-30 01:06:03 +00001977 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001978 } else {
1979 // exception in catch block
1980 _rethrow = objc_exception_extract(&d);
Anders Carlsson190d00e2009-02-07 21:26:04 +00001981 _call_try_exit = false;
1982 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001983 }
1984 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00001985 ... jump-through-finally to finally_end ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001986
1987finally:
Anders Carlsson190d00e2009-02-07 21:26:04 +00001988 if (_call_try_exit)
1989 objc_exception_try_exit(&d);
1990
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001991 ... finally block ....
Daniel Dunbar898d5082008-09-30 01:06:03 +00001992 ... dispatch to finally destination ...
1993
1994finally_rethrow:
1995 objc_exception_throw(_rethrow);
1996
1997finally_end:
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001998}
1999
2000This framework differs slightly from the one gcc uses, in that gcc
Daniel Dunbar898d5082008-09-30 01:06:03 +00002001uses _rethrow to determine if objc_exception_try_exit should be called
2002and if the object should be rethrown. This breaks in the face of
2003throwing nil and introduces unnecessary branches.
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002004
2005We specialize this framework for a few particular circumstances:
2006
2007 - If there are no catch blocks, then we avoid emitting the second
2008 exception handling context.
2009
2010 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
2011 e)) we avoid emitting the code to rethrow an uncaught exception.
2012
2013 - FIXME: If there is no @finally block we can do a few more
2014 simplifications.
2015
2016Rethrows and Jumps-Through-Finally
2017--
2018
2019Support for implicit rethrows and jumping through the finally block is
2020handled by storing the current exception-handling context in
2021ObjCEHStack.
2022
Daniel Dunbar898d5082008-09-30 01:06:03 +00002023In order to implement proper @finally semantics, we support one basic
2024mechanism for jumping through the finally block to an arbitrary
2025destination. Constructs which generate exits from a @try or @catch
2026block use this mechanism to implement the proper semantics by chaining
2027jumps, as necessary.
2028
2029This mechanism works like the one used for indirect goto: we
2030arbitrarily assign an ID to each destination and store the ID for the
2031destination in a variable prior to entering the finally block. At the
2032end of the finally block we simply create a switch to the proper
2033destination.
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002034
2035Code gen for @synchronized(expr) stmt;
2036Effectively generating code for:
2037objc_sync_enter(expr);
2038@try stmt @finally { objc_sync_exit(expr); }
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002039*/
2040
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002041void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
2042 const Stmt &S) {
2043 bool isTry = isa<ObjCAtTryStmt>(S);
Daniel Dunbar898d5082008-09-30 01:06:03 +00002044 // Create various blocks we refer to for handling @finally.
Daniel Dunbar55e87422008-11-11 02:29:29 +00002045 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002046 llvm::BasicBlock *FinallyExit = CGF.createBasicBlock("finally.exit");
Daniel Dunbar55e87422008-11-11 02:29:29 +00002047 llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
2048 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
2049 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
Daniel Dunbar1c566672009-02-24 01:43:46 +00002050
2051 // For @synchronized, call objc_sync_enter(sync.expr). The
2052 // evaluation of the expression must occur before we enter the
2053 // @synchronized. We can safely avoid a temp here because jumps into
2054 // @synchronized are illegal & this will dominate uses.
2055 llvm::Value *SyncArg = 0;
2056 if (!isTry) {
2057 SyncArg =
2058 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
2059 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00002060 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar1c566672009-02-24 01:43:46 +00002061 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00002062
2063 // Push an EH context entry, used for handling rethrows and jumps
2064 // through finally.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002065 CGF.PushCleanupBlock(FinallyBlock);
2066
Anders Carlsson273558f2009-02-07 21:37:21 +00002067 CGF.ObjCEHValueStack.push_back(0);
2068
Daniel Dunbar898d5082008-09-30 01:06:03 +00002069 // Allocate memory for the exception data and rethrow pointer.
Anders Carlsson80f25672008-09-09 17:59:25 +00002070 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
2071 "exceptiondata.ptr");
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002072 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
2073 "_rethrow");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002074 llvm::Value *CallTryExitPtr = CGF.CreateTempAlloca(llvm::Type::Int1Ty,
2075 "_call_try_exit");
2076 CGF.Builder.CreateStore(llvm::ConstantInt::getTrue(), CallTryExitPtr);
2077
Anders Carlsson80f25672008-09-09 17:59:25 +00002078 // Enter a new try block and call setjmp.
2079 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
2080 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
2081 "jmpbufarray");
2082 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
2083 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
2084 JmpBufPtr, "result");
Daniel Dunbar898d5082008-09-30 01:06:03 +00002085
Daniel Dunbar55e87422008-11-11 02:29:29 +00002086 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
2087 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002088 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002089 TryHandler, TryBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002090
2091 // Emit the @try block.
2092 CGF.EmitBlock(TryBlock);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002093 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
2094 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002095 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002096
2097 // Emit the "exception in @try" block.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002098 CGF.EmitBlock(TryHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002099
2100 // Retrieve the exception object. We may emit multiple blocks but
2101 // nothing can cross this so the value is already in SSA form.
2102 llvm::Value *Caught = CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
2103 ExceptionData,
2104 "caught");
Anders Carlsson273558f2009-02-07 21:37:21 +00002105 CGF.ObjCEHValueStack.back() = Caught;
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002106 if (!isTry)
2107 {
2108 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002109 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002110 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002111 }
2112 else if (const ObjCAtCatchStmt* CatchStmt =
2113 cast<ObjCAtTryStmt>(S).getCatchStmts())
2114 {
Daniel Dunbar55e40722008-09-27 07:03:52 +00002115 // Enter a new exception try block (in case a @catch block throws
2116 // an exception).
Anders Carlsson80f25672008-09-09 17:59:25 +00002117 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002118
Anders Carlsson80f25672008-09-09 17:59:25 +00002119 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
2120 JmpBufPtr, "result");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002121 llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw");
Anders Carlsson80f25672008-09-09 17:59:25 +00002122
Daniel Dunbar55e87422008-11-11 02:29:29 +00002123 llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch");
2124 llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler");
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002125 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002126
2127 CGF.EmitBlock(CatchBlock);
2128
Daniel Dunbar55e40722008-09-27 07:03:52 +00002129 // Handle catch list. As a special case we check if everything is
2130 // matched and avoid generating code for falling off the end if
2131 // so.
2132 bool AllMatched = false;
Anders Carlsson80f25672008-09-09 17:59:25 +00002133 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbar55e87422008-11-11 02:29:29 +00002134 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch");
Anders Carlsson80f25672008-09-09 17:59:25 +00002135
Steve Naroff7ba138a2009-03-03 19:52:17 +00002136 const ParmVarDecl *CatchParam = CatchStmt->getCatchParamDecl();
Daniel Dunbar129271a2008-09-27 07:36:24 +00002137 const PointerType *PT = 0;
2138
Anders Carlsson80f25672008-09-09 17:59:25 +00002139 // catch(...) always matches.
Daniel Dunbar55e40722008-09-27 07:03:52 +00002140 if (!CatchParam) {
2141 AllMatched = true;
2142 } else {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002143 PT = CatchParam->getType()->getAsPointerType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002144
Daniel Dunbar97f61d12008-09-27 22:21:14 +00002145 // catch(id e) always matches.
2146 // FIXME: For the time being we also match id<X>; this should
2147 // be rejected by Sema instead.
Steve Naroff389bf462009-02-12 17:52:19 +00002148 if ((PT && CGF.getContext().isObjCIdStructType(PT->getPointeeType())) ||
Steve Naroff7ba138a2009-03-03 19:52:17 +00002149 CatchParam->getType()->isObjCQualifiedIdType())
Daniel Dunbar55e40722008-09-27 07:03:52 +00002150 AllMatched = true;
Anders Carlsson80f25672008-09-09 17:59:25 +00002151 }
2152
Daniel Dunbar55e40722008-09-27 07:03:52 +00002153 if (AllMatched) {
Anders Carlssondde0a942008-09-11 09:15:33 +00002154 if (CatchParam) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002155 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002156 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002157 CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002158 }
Anders Carlsson1452f552008-09-11 08:21:54 +00002159
Anders Carlssondde0a942008-09-11 09:15:33 +00002160 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002161 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002162 break;
2163 }
2164
Daniel Dunbar129271a2008-09-27 07:36:24 +00002165 assert(PT && "Unexpected non-pointer type in @catch");
2166 QualType T = PT->getPointeeType();
Anders Carlsson4b7ff6e2008-09-11 06:35:14 +00002167 const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002168 assert(ObjCType && "Catch parameter must have Objective-C type!");
2169
2170 // Check if the @catch block matches the exception object.
2171 llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl());
2172
Anders Carlsson80f25672008-09-09 17:59:25 +00002173 llvm::Value *Match = CGF.Builder.CreateCall2(ObjCTypes.ExceptionMatchFn,
2174 Class, Caught, "match");
Anders Carlsson80f25672008-09-09 17:59:25 +00002175
Daniel Dunbar55e87422008-11-11 02:29:29 +00002176 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched");
Anders Carlsson80f25672008-09-09 17:59:25 +00002177
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002178 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002179 MatchedBlock, NextCatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002180
2181 // Emit the @catch block.
2182 CGF.EmitBlock(MatchedBlock);
Steve Naroff7ba138a2009-03-03 19:52:17 +00002183 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002184 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002185
2186 llvm::Value *Tmp =
Steve Naroff7ba138a2009-03-03 19:52:17 +00002187 CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(CatchParam->getType()),
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002188 "tmp");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002189 CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002190
2191 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002192 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002193
2194 CGF.EmitBlock(NextCatchBlock);
2195 }
2196
Daniel Dunbar55e40722008-09-27 07:03:52 +00002197 if (!AllMatched) {
2198 // None of the handlers caught the exception, so store it to be
2199 // rethrown at the end of the @finally block.
2200 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002201 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002202 }
2203
2204 // Emit the exception handler for the @catch blocks.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002205 CGF.EmitBlock(CatchHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002206 CGF.Builder.CreateStore(CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
2207 ExceptionData),
2208 RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002209 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002210 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002211 } else {
Anders Carlsson80f25672008-09-09 17:59:25 +00002212 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002213 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002214 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Anders Carlsson80f25672008-09-09 17:59:25 +00002215 }
2216
Daniel Dunbar898d5082008-09-30 01:06:03 +00002217 // Pop the exception-handling stack entry. It is important to do
2218 // this now, because the code in the @finally block is not in this
2219 // context.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002220 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
2221
Anders Carlsson273558f2009-02-07 21:37:21 +00002222 CGF.ObjCEHValueStack.pop_back();
2223
Anders Carlsson80f25672008-09-09 17:59:25 +00002224 // Emit the @finally block.
2225 CGF.EmitBlock(FinallyBlock);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002226 llvm::Value* CallTryExit = CGF.Builder.CreateLoad(CallTryExitPtr, "tmp");
2227
2228 CGF.Builder.CreateCondBr(CallTryExit, FinallyExit, FinallyNoExit);
2229
2230 CGF.EmitBlock(FinallyExit);
Anders Carlsson80f25672008-09-09 17:59:25 +00002231 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryExitFn, ExceptionData);
Daniel Dunbar129271a2008-09-27 07:36:24 +00002232
2233 CGF.EmitBlock(FinallyNoExit);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002234 if (isTry) {
2235 if (const ObjCAtFinallyStmt* FinallyStmt =
2236 cast<ObjCAtTryStmt>(S).getFinallyStmt())
2237 CGF.EmitStmt(FinallyStmt->getFinallyBody());
Daniel Dunbar1c566672009-02-24 01:43:46 +00002238 } else {
2239 // Emit objc_sync_exit(expr); as finally's sole statement for
2240 // @synchronized.
2241 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, SyncArg);
Fariborz Jahanianf2878e52008-11-21 19:21:53 +00002242 }
Anders Carlsson80f25672008-09-09 17:59:25 +00002243
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002244 // Emit the switch block
2245 if (Info.SwitchBlock)
2246 CGF.EmitBlock(Info.SwitchBlock);
2247 if (Info.EndBlock)
2248 CGF.EmitBlock(Info.EndBlock);
2249
Daniel Dunbar898d5082008-09-30 01:06:03 +00002250 CGF.EmitBlock(FinallyRethrow);
2251 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn,
2252 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002253 CGF.Builder.CreateUnreachable();
Daniel Dunbar898d5082008-09-30 01:06:03 +00002254
2255 CGF.EmitBlock(FinallyEnd);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002256}
2257
2258void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar898d5082008-09-30 01:06:03 +00002259 const ObjCAtThrowStmt &S) {
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002260 llvm::Value *ExceptionAsObject;
2261
2262 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2263 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
2264 ExceptionAsObject =
2265 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
2266 } else {
Anders Carlsson273558f2009-02-07 21:37:21 +00002267 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002268 "Unexpected rethrow outside @catch block.");
Anders Carlsson273558f2009-02-07 21:37:21 +00002269 ExceptionAsObject = CGF.ObjCEHValueStack.back();
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002270 }
2271
2272 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
Anders Carlsson80f25672008-09-09 17:59:25 +00002273 CGF.Builder.CreateUnreachable();
Daniel Dunbara448fb22008-11-11 23:11:34 +00002274
2275 // Clear the insertion point to indicate we are in unreachable code.
2276 CGF.Builder.ClearInsertionPoint();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002277}
2278
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002279/// EmitObjCWeakRead - Code gen for loading value of a __weak
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002280/// object: objc_read_weak (id *src)
2281///
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002282llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002283 llvm::Value *AddrWeakObj)
2284{
Eli Friedman8339b352009-03-07 03:57:15 +00002285 const llvm::Type* DestTy =
2286 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002287 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002288 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002289 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00002290 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002291 return read_weak;
2292}
2293
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002294/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
2295/// objc_assign_weak (id src, id *dst)
2296///
2297void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
2298 llvm::Value *src, llvm::Value *dst)
2299{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002300 const llvm::Type * SrcTy = src->getType();
2301 if (!isa<llvm::PointerType>(SrcTy)) {
2302 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2303 assert(Size <= 8 && "does not support size > 8");
2304 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2305 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002306 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2307 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002308 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2309 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattner96508e12009-04-17 22:12:36 +00002310 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002311 src, dst, "weakassign");
2312 return;
2313}
2314
Fariborz Jahanian58626502008-11-19 00:59:10 +00002315/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
2316/// objc_assign_global (id src, id *dst)
2317///
2318void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
2319 llvm::Value *src, llvm::Value *dst)
2320{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002321 const llvm::Type * SrcTy = src->getType();
2322 if (!isa<llvm::PointerType>(SrcTy)) {
2323 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2324 assert(Size <= 8 && "does not support size > 8");
2325 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2326 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002327 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2328 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002329 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2330 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian58626502008-11-19 00:59:10 +00002331 CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn,
2332 src, dst, "globalassign");
2333 return;
2334}
2335
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002336/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
2337/// objc_assign_ivar (id src, id *dst)
2338///
2339void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
2340 llvm::Value *src, llvm::Value *dst)
2341{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002342 const llvm::Type * SrcTy = src->getType();
2343 if (!isa<llvm::PointerType>(SrcTy)) {
2344 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2345 assert(Size <= 8 && "does not support size > 8");
2346 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2347 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002348 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2349 }
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002350 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2351 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
2352 CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn,
2353 src, dst, "assignivar");
2354 return;
2355}
2356
Fariborz Jahanian58626502008-11-19 00:59:10 +00002357/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
2358/// objc_assign_strongCast (id src, id *dst)
2359///
2360void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
2361 llvm::Value *src, llvm::Value *dst)
2362{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002363 const llvm::Type * SrcTy = src->getType();
2364 if (!isa<llvm::PointerType>(SrcTy)) {
2365 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2366 assert(Size <= 8 && "does not support size > 8");
2367 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2368 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002369 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2370 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002371 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2372 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian58626502008-11-19 00:59:10 +00002373 CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn,
2374 src, dst, "weakassign");
2375 return;
2376}
2377
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002378/// EmitObjCValueForIvar - Code Gen for ivar reference.
2379///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002380LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
2381 QualType ObjectTy,
2382 llvm::Value *BaseValue,
2383 const ObjCIvarDecl *Ivar,
2384 const FieldDecl *Field,
2385 unsigned CVRQualifiers) {
2386 if (Ivar->isBitField())
2387 return CGF.EmitLValueForBitfield(BaseValue, const_cast<FieldDecl *>(Field),
2388 CVRQualifiers);
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002389 // TODO: Add a special case for isa (index 0)
2390 unsigned Index = CGM.getTypes().getLLVMFieldNo(Field);
2391 llvm::Value *V = CGF.Builder.CreateStructGEP(BaseValue, Index, "tmp");
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002392 LValue LV = LValue::MakeAddr(V,
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00002393 Ivar->getType().getCVRQualifiers()|CVRQualifiers,
2394 CGM.getContext().getObjCGCAttrKind(Ivar->getType()));
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002395 LValue::SetObjCIvar(LV, true);
2396 return LV;
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002397}
2398
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002399llvm::Value *CGObjCMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
2400 ObjCInterfaceDecl *Interface,
2401 const ObjCIvarDecl *Ivar) {
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002402 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(Interface);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002403 FieldDecl *Field = Interface->lookupFieldDeclForIvar(CGM.getContext(), Ivar);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00002404 uint64_t Offset = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002405 return llvm::ConstantInt::get(
2406 CGM.getTypes().ConvertType(CGM.getContext().LongTy),
2407 Offset);
2408}
2409
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002410/* *** Private Interface *** */
2411
2412/// EmitImageInfo - Emit the image info marker used to encode some module
2413/// level information.
2414///
2415/// See: <rdr://4810609&4810587&4810587>
2416/// struct IMAGE_INFO {
2417/// unsigned version;
2418/// unsigned flags;
2419/// };
2420enum ImageInfoFlags {
2421 eImageInfo_FixAndContinue = (1 << 0), // FIXME: Not sure what this implies
2422 eImageInfo_GarbageCollected = (1 << 1),
2423 eImageInfo_GCOnly = (1 << 2)
2424};
2425
2426void CGObjCMac::EmitImageInfo() {
2427 unsigned version = 0; // Version is unused?
2428 unsigned flags = 0;
2429
2430 // FIXME: Fix and continue?
2431 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
2432 flags |= eImageInfo_GarbageCollected;
2433 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
2434 flags |= eImageInfo_GCOnly;
2435
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002436 // Emitted as int[2];
2437 llvm::Constant *values[2] = {
2438 llvm::ConstantInt::get(llvm::Type::Int32Ty, version),
2439 llvm::ConstantInt::get(llvm::Type::Int32Ty, flags)
2440 };
2441 llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002442
2443 const char *Section;
2444 if (ObjCABI == 1)
2445 Section = "__OBJC, __image_info,regular";
2446 else
2447 Section = "__DATA, __objc_imageinfo, regular, no_dead_strip";
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002448 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002449 CreateMetadataVar("\01L_OBJC_IMAGE_INFO",
2450 llvm::ConstantArray::get(AT, values, 2),
2451 Section,
2452 0,
2453 true);
2454 GV->setConstant(true);
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002455}
2456
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002457
2458// struct objc_module {
2459// unsigned long version;
2460// unsigned long size;
2461// const char *name;
2462// Symtab symtab;
2463// };
2464
2465// FIXME: Get from somewhere
2466static const int ModuleVersion = 7;
2467
2468void CGObjCMac::EmitModuleInfo() {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00002469 uint64_t Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ModuleTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002470
2471 std::vector<llvm::Constant*> Values(4);
2472 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
2473 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002474 // This used to be the filename, now it is unused. <rdr://4327263>
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002475 Values[2] = GetClassName(&CGM.getContext().Idents.get(""));
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002476 Values[3] = EmitModuleSymbols();
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002477 CreateMetadataVar("\01L_OBJC_MODULES",
2478 llvm::ConstantStruct::get(ObjCTypes.ModuleTy, Values),
2479 "__OBJC,__module_info,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00002480 4, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002481}
2482
2483llvm::Constant *CGObjCMac::EmitModuleSymbols() {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002484 unsigned NumClasses = DefinedClasses.size();
2485 unsigned NumCategories = DefinedCategories.size();
2486
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002487 // Return null if no symbols were defined.
2488 if (!NumClasses && !NumCategories)
2489 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
2490
2491 std::vector<llvm::Constant*> Values(5);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002492 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2493 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
2494 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
2495 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
2496
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002497 // The runtime expects exactly the list of defined classes followed
2498 // by the list of defined categories, in a single array.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002499 std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002500 for (unsigned i=0; i<NumClasses; i++)
2501 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
2502 ObjCTypes.Int8PtrTy);
2503 for (unsigned i=0; i<NumCategories; i++)
2504 Symbols[NumClasses + i] =
2505 llvm::ConstantExpr::getBitCast(DefinedCategories[i],
2506 ObjCTypes.Int8PtrTy);
2507
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002508 Values[4] =
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002509 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002510 NumClasses + NumCategories),
2511 Symbols);
2512
2513 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2514
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002515 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002516 CreateMetadataVar("\01L_OBJC_SYMBOLS", Init,
2517 "__OBJC,__symbols,regular,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002518 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002519 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
2520}
2521
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002522llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002523 const ObjCInterfaceDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002524 LazySymbols.insert(ID->getIdentifier());
2525
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002526 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
2527
2528 if (!Entry) {
2529 llvm::Constant *Casted =
2530 llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()),
2531 ObjCTypes.ClassPtrTy);
2532 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002533 CreateMetadataVar("\01L_OBJC_CLASS_REFERENCES_", Casted,
2534 "__OBJC,__cls_refs,literal_pointers,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002535 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002536 }
2537
2538 return Builder.CreateLoad(Entry, false, "tmp");
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002539}
2540
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002541llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002542 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
2543
2544 if (!Entry) {
2545 llvm::Constant *Casted =
2546 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
2547 ObjCTypes.SelectorPtrTy);
2548 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002549 CreateMetadataVar("\01L_OBJC_SELECTOR_REFERENCES_", Casted,
2550 "__OBJC,__message_refs,literal_pointers,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002551 4, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002552 }
2553
2554 return Builder.CreateLoad(Entry, false, "tmp");
2555}
2556
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00002557llvm::Constant *CGObjCCommonMac::GetClassName(IdentifierInfo *Ident) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002558 llvm::GlobalVariable *&Entry = ClassNames[Ident];
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002559
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002560 if (!Entry)
2561 Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
2562 llvm::ConstantArray::get(Ident->getName()),
2563 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00002564 1, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002565
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002566 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002567}
2568
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002569/// GetInterfaceDeclStructLayout - Get layout for ivars of given
2570/// interface declaration.
2571const llvm::StructLayout *CGObjCCommonMac::GetInterfaceDeclStructLayout(
2572 const ObjCInterfaceDecl *OID) const {
Chris Lattnerb7b58b12009-04-19 06:02:28 +00002573 const llvm::Type *InterfaceTy;
2574
Daniel Dunbarb02532a2009-04-19 23:41:48 +00002575 // FIXME: When does this happen? It seems pretty bad to do this...
Chris Lattnerb7b58b12009-04-19 06:02:28 +00002576 if (OID->isForwardDecl()) {
2577 InterfaceTy = llvm::StructType::get(NULL, NULL);
2578 } else {
2579 QualType T = CGM.getContext().getObjCInterfaceType(
2580 const_cast<ObjCInterfaceDecl*>(OID));
2581 InterfaceTy = CGM.getTypes().ConvertType(T);
2582 }
2583
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002584 const llvm::StructLayout *Layout =
2585 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceTy));
2586 return Layout;
2587}
2588
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00002589/// GetIvarLayoutName - Returns a unique constant for the given
2590/// ivar layout bitmap.
2591llvm::Constant *CGObjCCommonMac::GetIvarLayoutName(IdentifierInfo *Ident,
2592 const ObjCCommonTypesHelper &ObjCTypes) {
2593 return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2594}
2595
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002596void CGObjCCommonMac::BuildAggrIvarLayout(const ObjCInterfaceDecl *OI,
2597 const llvm::StructLayout *Layout,
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002598 const RecordDecl *RD,
Chris Lattnerf1690852009-03-31 08:48:01 +00002599 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002600 unsigned int BytePos, bool ForStrongLayout,
2601 int &Index, int &SkIndex, bool &HasUnion) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002602 bool IsUnion = (RD && RD->isUnion());
2603 uint64_t MaxUnionIvarSize = 0;
2604 uint64_t MaxSkippedUnionIvarSize = 0;
2605 FieldDecl *MaxField = 0;
2606 FieldDecl *MaxSkippedField = 0;
Chris Lattnerf1690852009-03-31 08:48:01 +00002607 unsigned base = 0;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002608 if (RecFields.empty())
2609 return;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002610 if (IsUnion)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002611 base = BytePos + GetFieldBaseOffset(OI, Layout, RecFields[0]);
Chris Lattnerf1690852009-03-31 08:48:01 +00002612 unsigned WordSizeInBits = CGM.getContext().Target.getPointerWidth(0);
2613 unsigned ByteSizeInBits = CGM.getContext().Target.getCharWidth();
2614
2615 llvm::SmallVector<FieldDecl*, 16> TmpRecFields;
2616
2617 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002618 FieldDecl *Field = RecFields[i];
2619 // Skip over unnamed or bitfields
2620 if (!Field->getIdentifier() || Field->isBitField())
2621 continue;
2622 QualType FQT = Field->getType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002623 if (FQT->isRecordType() || FQT->isUnionType()) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002624 if (FQT->isUnionType())
2625 HasUnion = true;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002626 else
2627 assert(FQT->isRecordType() &&
2628 "only union/record is supported for ivar layout bitmap");
2629
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002630 const RecordType *RT = FQT->getAsRecordType();
2631 const RecordDecl *RD = RT->getDecl();
Daniel Dunbarb02532a2009-04-19 23:41:48 +00002632 // FIXME - Find a more efficient way of passing records down.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002633 TmpRecFields.append(RD->field_begin(CGM.getContext()),
2634 RD->field_end(CGM.getContext()));
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002635 // FIXME - Is Layout correct?
Chris Lattnerf1690852009-03-31 08:48:01 +00002636 BuildAggrIvarLayout(OI, Layout, RD, TmpRecFields,
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002637 BytePos + GetFieldBaseOffset(OI, Layout, Field),
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002638 ForStrongLayout, Index, SkIndex,
2639 HasUnion);
Chris Lattnerf1690852009-03-31 08:48:01 +00002640 TmpRecFields.clear();
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002641 continue;
2642 }
Chris Lattnerf1690852009-03-31 08:48:01 +00002643
2644 if (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002645 const ConstantArrayType *CArray =
2646 dyn_cast_or_null<ConstantArrayType>(Array);
2647 assert(CArray && "only array with know element size is supported");
2648 FQT = CArray->getElementType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002649 while (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
2650 const ConstantArrayType *CArray =
2651 dyn_cast_or_null<ConstantArrayType>(Array);
2652 FQT = CArray->getElementType();
2653 }
2654
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002655 assert(!FQT->isUnionType() &&
2656 "layout for array of unions not supported");
2657 if (FQT->isRecordType()) {
2658 uint64_t ElCount = CArray->getSize().getZExtValue();
2659 int OldIndex = Index;
2660 int OldSkIndex = SkIndex;
2661
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002662 // FIXME - Use a common routine with the above!
2663 const RecordType *RT = FQT->getAsRecordType();
2664 const RecordDecl *RD = RT->getDecl();
2665 // FIXME - Find a more efficiant way of passing records down.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002666 TmpRecFields.append(RD->field_begin(CGM.getContext()),
2667 RD->field_end(CGM.getContext()));
Chris Lattnerf1690852009-03-31 08:48:01 +00002668
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002669 BuildAggrIvarLayout(OI, Layout, RD,
Chris Lattnerf1690852009-03-31 08:48:01 +00002670 TmpRecFields,
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002671 BytePos + GetFieldBaseOffset(OI, Layout, Field),
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002672 ForStrongLayout, Index, SkIndex,
2673 HasUnion);
Chris Lattnerf1690852009-03-31 08:48:01 +00002674 TmpRecFields.clear();
2675
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002676 // Replicate layout information for each array element. Note that
2677 // one element is already done.
2678 uint64_t ElIx = 1;
2679 for (int FirstIndex = Index, FirstSkIndex = SkIndex;
2680 ElIx < ElCount; ElIx++) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002681 uint64_t Size = CGM.getContext().getTypeSize(RT)/ByteSizeInBits;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002682 for (int i = OldIndex+1; i <= FirstIndex; ++i)
2683 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002684 GC_IVAR gcivar;
2685 gcivar.ivar_bytepos = IvarsInfo[i].ivar_bytepos + Size*ElIx;
2686 gcivar.ivar_size = IvarsInfo[i].ivar_size;
2687 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002688 }
2689
Chris Lattnerf1690852009-03-31 08:48:01 +00002690 for (int i = OldSkIndex+1; i <= FirstSkIndex; ++i) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002691 GC_IVAR skivar;
2692 skivar.ivar_bytepos = SkipIvars[i].ivar_bytepos + Size*ElIx;
2693 skivar.ivar_size = SkipIvars[i].ivar_size;
2694 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002695 }
2696 }
2697 continue;
2698 }
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002699 }
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002700 // At this point, we are done with Record/Union and array there of.
2701 // For other arrays we are down to its element type.
2702 QualType::GCAttrTypes GCAttr = QualType::GCNone;
2703 do {
2704 if (FQT.isObjCGCStrong() || FQT.isObjCGCWeak()) {
2705 GCAttr = FQT.isObjCGCStrong() ? QualType::Strong : QualType::Weak;
2706 break;
2707 }
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002708 else if (CGM.getContext().isObjCObjectPointerType(FQT)) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002709 GCAttr = QualType::Strong;
2710 break;
2711 }
2712 else if (const PointerType *PT = FQT->getAsPointerType()) {
2713 FQT = PT->getPointeeType();
2714 }
2715 else {
2716 break;
2717 }
2718 } while (true);
Chris Lattnerf1690852009-03-31 08:48:01 +00002719
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002720 if ((ForStrongLayout && GCAttr == QualType::Strong)
2721 || (!ForStrongLayout && GCAttr == QualType::Weak)) {
2722 if (IsUnion)
2723 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002724 uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType())
2725 / WordSizeInBits;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002726 if (UnionIvarSize > MaxUnionIvarSize)
2727 {
2728 MaxUnionIvarSize = UnionIvarSize;
2729 MaxField = Field;
2730 }
2731 }
2732 else
2733 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002734 GC_IVAR gcivar;
2735 gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field);
2736 gcivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) /
2737 WordSizeInBits;
2738 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002739 }
2740 }
2741 else if ((ForStrongLayout &&
2742 (GCAttr == QualType::GCNone || GCAttr == QualType::Weak))
2743 || (!ForStrongLayout && GCAttr != QualType::Weak)) {
2744 if (IsUnion)
2745 {
2746 uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType());
2747 if (UnionIvarSize > MaxSkippedUnionIvarSize)
2748 {
2749 MaxSkippedUnionIvarSize = UnionIvarSize;
2750 MaxSkippedField = Field;
2751 }
2752 }
2753 else
2754 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002755 GC_IVAR skivar;
2756 skivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field);
2757 skivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) /
2758 WordSizeInBits;
2759 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002760 }
2761 }
2762 }
Chris Lattnerf1690852009-03-31 08:48:01 +00002763 if (MaxField) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002764 GC_IVAR gcivar;
2765 gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, MaxField);
2766 gcivar.ivar_size = MaxUnionIvarSize;
2767 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002768 }
Chris Lattnerf1690852009-03-31 08:48:01 +00002769
2770 if (MaxSkippedField) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002771 GC_IVAR skivar;
2772 skivar.ivar_bytepos = BytePos +
2773 GetFieldBaseOffset(OI, Layout, MaxSkippedField);
2774 skivar.ivar_size = MaxSkippedUnionIvarSize;
2775 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002776 }
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002777}
2778
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002779static int
Chris Lattnerf1690852009-03-31 08:48:01 +00002780IvarBytePosCompare(const void *a, const void *b)
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002781{
2782 unsigned int sa = ((CGObjCCommonMac::GC_IVAR *)a)->ivar_bytepos;
2783 unsigned int sb = ((CGObjCCommonMac::GC_IVAR *)b)->ivar_bytepos;
2784
2785 if (sa < sb)
2786 return -1;
2787 if (sa > sb)
2788 return 1;
2789 return 0;
2790}
2791
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002792/// BuildIvarLayout - Builds ivar layout bitmap for the class
2793/// implementation for the __strong or __weak case.
2794/// The layout map displays which words in ivar list must be skipped
2795/// and which must be scanned by GC (see below). String is built of bytes.
2796/// Each byte is divided up in two nibbles (4-bit each). Left nibble is count
2797/// of words to skip and right nibble is count of words to scan. So, each
2798/// nibble represents up to 15 workds to skip or scan. Skipping the rest is
2799/// represented by a 0x00 byte which also ends the string.
2800/// 1. when ForStrongLayout is true, following ivars are scanned:
2801/// - id, Class
2802/// - object *
2803/// - __strong anything
2804///
2805/// 2. When ForStrongLayout is false, following ivars are scanned:
2806/// - __weak anything
2807///
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002808llvm::Constant *CGObjCCommonMac::BuildIvarLayout(
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002809 const ObjCImplementationDecl *OMD,
2810 bool ForStrongLayout) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002811 int Index = -1;
2812 int SkIndex = -1;
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002813 bool hasUnion = false;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002814 int SkipScan;
2815 unsigned int WordsToScan, WordsToSkip;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002816 const llvm::Type *PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
2817 if (CGM.getLangOptions().getGCMode() == LangOptions::NonGC)
2818 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002819
Chris Lattnerf1690852009-03-31 08:48:01 +00002820 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002821 const ObjCInterfaceDecl *OI = OMD->getClassInterface();
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002822 CGM.getContext().CollectObjCIvars(OI, RecFields);
2823 if (RecFields.empty())
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002824 return llvm::Constant::getNullValue(PtrTy);
Chris Lattnerf1690852009-03-31 08:48:01 +00002825
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002826 SkipIvars.clear();
2827 IvarsInfo.clear();
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002828
2829 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OI);
Chris Lattnerf1690852009-03-31 08:48:01 +00002830 BuildAggrIvarLayout(OI, Layout, 0, RecFields, 0, ForStrongLayout,
2831 Index, SkIndex, hasUnion);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002832 if (Index == -1)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002833 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002834
2835 // Sort on byte position in case we encounterred a union nested in
2836 // the ivar list.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002837 if (hasUnion && !IvarsInfo.empty())
2838 qsort(&IvarsInfo[0], Index+1, sizeof(GC_IVAR), IvarBytePosCompare);
2839 if (hasUnion && !SkipIvars.empty())
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002840 qsort(&SkipIvars[0], Index+1, sizeof(GC_IVAR), IvarBytePosCompare);
2841
2842 // Build the string of skip/scan nibbles
2843 SkipScan = -1;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002844 SkipScanIvars.clear();
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002845 unsigned int WordSize =
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002846 CGM.getTypes().getTargetData().getTypePaddedSize(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002847 if (IvarsInfo[0].ivar_bytepos == 0) {
2848 WordsToSkip = 0;
2849 WordsToScan = IvarsInfo[0].ivar_size;
2850 }
2851 else {
2852 WordsToSkip = IvarsInfo[0].ivar_bytepos/WordSize;
2853 WordsToScan = IvarsInfo[0].ivar_size;
2854 }
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002855 for (unsigned int i=1, Last=IvarsInfo.size(); i != Last; i++)
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002856 {
2857 unsigned int TailPrevGCObjC =
2858 IvarsInfo[i-1].ivar_bytepos + IvarsInfo[i-1].ivar_size * WordSize;
2859 if (IvarsInfo[i].ivar_bytepos == TailPrevGCObjC)
2860 {
2861 // consecutive 'scanned' object pointers.
2862 WordsToScan += IvarsInfo[i].ivar_size;
2863 }
2864 else
2865 {
2866 // Skip over 'gc'able object pointer which lay over each other.
2867 if (TailPrevGCObjC > IvarsInfo[i].ivar_bytepos)
2868 continue;
2869 // Must skip over 1 or more words. We save current skip/scan values
2870 // and start a new pair.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002871 SKIP_SCAN SkScan;
2872 SkScan.skip = WordsToSkip;
2873 SkScan.scan = WordsToScan;
2874 SkipScanIvars.push_back(SkScan); ++SkipScan;
2875
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002876 // Skip the hole.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002877 SkScan.skip = (IvarsInfo[i].ivar_bytepos - TailPrevGCObjC) / WordSize;
2878 SkScan.scan = 0;
2879 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002880 WordsToSkip = 0;
2881 WordsToScan = IvarsInfo[i].ivar_size;
2882 }
2883 }
2884 if (WordsToScan > 0)
2885 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002886 SKIP_SCAN SkScan;
2887 SkScan.skip = WordsToSkip;
2888 SkScan.scan = WordsToScan;
2889 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002890 }
2891
2892 bool BytesSkipped = false;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002893 if (!SkipIvars.empty())
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002894 {
2895 int LastByteSkipped =
2896 SkipIvars[SkIndex].ivar_bytepos + SkipIvars[SkIndex].ivar_size;
2897 int LastByteScanned =
2898 IvarsInfo[Index].ivar_bytepos + IvarsInfo[Index].ivar_size * WordSize;
2899 BytesSkipped = (LastByteSkipped > LastByteScanned);
2900 // Compute number of bytes to skip at the tail end of the last ivar scanned.
2901 if (BytesSkipped)
2902 {
2903 unsigned int TotalWords = (LastByteSkipped + (WordSize -1)) / WordSize;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002904 SKIP_SCAN SkScan;
2905 SkScan.skip = TotalWords - (LastByteScanned/WordSize);
2906 SkScan.scan = 0;
2907 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002908 }
2909 }
2910 // Mini optimization of nibbles such that an 0xM0 followed by 0x0N is produced
2911 // as 0xMN.
2912 for (int i = 0; i <= SkipScan; i++)
2913 {
2914 if ((i < SkipScan) && SkipScanIvars[i].skip && SkipScanIvars[i].scan == 0
2915 && SkipScanIvars[i+1].skip == 0 && SkipScanIvars[i+1].scan) {
2916 // 0xM0 followed by 0x0N detected.
2917 SkipScanIvars[i].scan = SkipScanIvars[i+1].scan;
2918 for (int j = i+1; j < SkipScan; j++)
2919 SkipScanIvars[j] = SkipScanIvars[j+1];
2920 --SkipScan;
2921 }
2922 }
2923
2924 // Generate the string.
2925 std::string BitMap;
2926 for (int i = 0; i <= SkipScan; i++)
2927 {
2928 unsigned char byte;
2929 unsigned int skip_small = SkipScanIvars[i].skip % 0xf;
2930 unsigned int scan_small = SkipScanIvars[i].scan % 0xf;
2931 unsigned int skip_big = SkipScanIvars[i].skip / 0xf;
2932 unsigned int scan_big = SkipScanIvars[i].scan / 0xf;
2933
2934 if (skip_small > 0 || skip_big > 0)
2935 BytesSkipped = true;
2936 // first skip big.
2937 for (unsigned int ix = 0; ix < skip_big; ix++)
2938 BitMap += (unsigned char)(0xf0);
2939
2940 // next (skip small, scan)
2941 if (skip_small)
2942 {
2943 byte = skip_small << 4;
2944 if (scan_big > 0)
2945 {
2946 byte |= 0xf;
2947 --scan_big;
2948 }
2949 else if (scan_small)
2950 {
2951 byte |= scan_small;
2952 scan_small = 0;
2953 }
2954 BitMap += byte;
2955 }
2956 // next scan big
2957 for (unsigned int ix = 0; ix < scan_big; ix++)
2958 BitMap += (unsigned char)(0x0f);
2959 // last scan small
2960 if (scan_small)
2961 {
2962 byte = scan_small;
2963 BitMap += byte;
2964 }
2965 }
2966 // null terminate string.
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002967 unsigned char zero = 0;
2968 BitMap += zero;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002969 // if ivar_layout bitmap is all 1 bits (nothing skipped) then use NULL as
2970 // final layout.
2971 if (ForStrongLayout && !BytesSkipped)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002972 return llvm::Constant::getNullValue(PtrTy);
2973 llvm::GlobalVariable * Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
2974 llvm::ConstantArray::get(BitMap.c_str()),
2975 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00002976 1, true);
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002977 // FIXME. Need a commomand-line option for this eventually.
2978 if (ForStrongLayout)
2979 printf("\nstrong ivar layout: ");
2980 else
2981 printf("\nweak ivar layout: ");
2982 const unsigned char *s = (unsigned char*)BitMap.c_str();
2983 for (unsigned i = 0; i < BitMap.size(); i++)
Fariborz Jahaniandbf15cb2009-03-26 19:10:36 +00002984 if (!(s[i] & 0xf0))
2985 printf("0x0%x%s", s[i], s[i] != 0 ? ", " : "");
2986 else
2987 printf("0x%x%s", s[i], s[i] != 0 ? ", " : "");
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002988 printf("\n");
2989
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002990 return getConstantGEP(Entry, 0, 0);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002991}
2992
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002993llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002994 llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
2995
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002996 // FIXME: Avoid std::string copying.
2997 if (!Entry)
2998 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_NAME_",
2999 llvm::ConstantArray::get(Sel.getAsString()),
3000 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003001 1, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003002
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003003 return getConstantGEP(Entry, 0, 0);
3004}
3005
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003006// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003007llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003008 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
3009}
3010
3011// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003012llvm::Constant *CGObjCCommonMac::GetMethodVarName(const std::string &Name) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003013 return GetMethodVarName(&CGM.getContext().Idents.get(Name));
3014}
3015
Devang Patel7794bb82009-03-04 18:21:39 +00003016llvm::Constant *CGObjCCommonMac::GetMethodVarType(FieldDecl *Field) {
3017 std::string TypeStr;
3018 CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
3019
3020 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003021
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003022 if (!Entry)
3023 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3024 llvm::ConstantArray::get(TypeStr),
3025 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003026 1, true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003027
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003028 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003029}
3030
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003031llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003032 std::string TypeStr;
Daniel Dunbarc45ef602008-08-26 21:51:14 +00003033 CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D),
3034 TypeStr);
Devang Patel7794bb82009-03-04 18:21:39 +00003035
3036 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
3037
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003038 if (!Entry)
3039 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3040 llvm::ConstantArray::get(TypeStr),
3041 "__TEXT,__cstring,cstring_literals",
3042 1, true);
Devang Patel7794bb82009-03-04 18:21:39 +00003043
3044 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003045}
3046
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003047// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003048llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003049 llvm::GlobalVariable *&Entry = PropertyNames[Ident];
3050
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003051 if (!Entry)
3052 Entry = CreateMetadataVar("\01L_OBJC_PROP_NAME_ATTR_",
3053 llvm::ConstantArray::get(Ident->getName()),
3054 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003055 1, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003056
3057 return getConstantGEP(Entry, 0, 0);
3058}
3059
3060// FIXME: Merge into a single cstring creation function.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003061// FIXME: This Decl should be more precise.
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003062llvm::Constant *
3063 CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
3064 const Decl *Container) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003065 std::string TypeStr;
3066 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003067 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
3068}
3069
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003070void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D,
3071 const ObjCContainerDecl *CD,
3072 std::string &NameOut) {
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00003073 NameOut = '\01';
3074 NameOut += (D->isInstanceMethod() ? '-' : '+');
Chris Lattner077bf5e2008-11-24 03:33:13 +00003075 NameOut += '[';
Fariborz Jahanian679a5022009-01-10 21:06:09 +00003076 assert (CD && "Missing container decl in GetNameForMethod");
3077 NameOut += CD->getNameAsString();
Fariborz Jahanian1e9aef32009-04-16 18:34:20 +00003078 if (const ObjCCategoryImplDecl *CID =
3079 dyn_cast<ObjCCategoryImplDecl>(D->getDeclContext())) {
3080 NameOut += '(';
3081 NameOut += CID->getNameAsString();
3082 NameOut+= ')';
3083 }
Chris Lattner077bf5e2008-11-24 03:33:13 +00003084 NameOut += ' ';
3085 NameOut += D->getSelector().getAsString();
3086 NameOut += ']';
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00003087}
3088
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00003089/// GetFirstIvarInRecord - This routine returns the record for the
3090/// implementation of the fiven class OID. It also returns field
3091/// corresponding to the first ivar in the class in FIV. It also
3092/// returns the one before the first ivar.
3093///
3094const RecordDecl *CGObjCCommonMac::GetFirstIvarInRecord(
3095 const ObjCInterfaceDecl *OID,
3096 RecordDecl::field_iterator &FIV,
3097 RecordDecl::field_iterator &PIV) {
Douglas Gregor6ab35242009-04-09 21:40:53 +00003098 int countSuperClassIvars = countInheritedIvars(OID->getSuperClass(),
3099 CGM.getContext());
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00003100 const RecordDecl *RD = CGM.getContext().addRecordToClass(OID);
Douglas Gregor6ab35242009-04-09 21:40:53 +00003101 RecordDecl::field_iterator ifield = RD->field_begin(CGM.getContext());
3102 RecordDecl::field_iterator pfield = RD->field_end(CGM.getContext());
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00003103 while (countSuperClassIvars-- > 0) {
3104 pfield = ifield;
3105 ++ifield;
3106 }
3107 FIV = ifield;
3108 PIV = pfield;
3109 return RD;
3110}
3111
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003112void CGObjCMac::FinishModule() {
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003113 EmitModuleInfo();
3114
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003115 // Emit the dummy bodies for any protocols which were referenced but
3116 // never defined.
3117 for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
3118 i = Protocols.begin(), e = Protocols.end(); i != e; ++i) {
3119 if (i->second->hasInitializer())
3120 continue;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003121
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003122 std::vector<llvm::Constant*> Values(5);
3123 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
3124 Values[1] = GetClassName(i->first);
3125 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
3126 Values[3] = Values[4] =
3127 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
3128 i->second->setLinkage(llvm::GlobalValue::InternalLinkage);
3129 i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
3130 Values));
3131 }
3132
3133 std::vector<llvm::Constant*> Used;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003134 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003135 e = UsedGlobals.end(); i != e; ++i) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003136 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003137 }
3138
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003139 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003140 llvm::GlobalValue *GV =
3141 new llvm::GlobalVariable(AT, false,
3142 llvm::GlobalValue::AppendingLinkage,
3143 llvm::ConstantArray::get(AT, Used),
3144 "llvm.used",
3145 &CGM.getModule());
3146
3147 GV->setSection("llvm.metadata");
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003148
3149 // Add assembler directives to add lazy undefined symbol references
3150 // for classes which are referenced but not defined. This is
3151 // important for correct linker interaction.
3152
3153 // FIXME: Uh, this isn't particularly portable.
3154 std::stringstream s;
Anders Carlsson565c99f2008-12-10 02:21:04 +00003155
3156 if (!CGM.getModule().getModuleInlineAsm().empty())
3157 s << "\n";
3158
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003159 for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(),
3160 e = LazySymbols.end(); i != e; ++i) {
3161 s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n";
3162 }
3163 for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(),
3164 e = DefinedSymbols.end(); i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003165 s << "\t.objc_class_name_" << (*i)->getName() << "=0\n"
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003166 << "\t.globl .objc_class_name_" << (*i)->getName() << "\n";
3167 }
Anders Carlsson565c99f2008-12-10 02:21:04 +00003168
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003169 CGM.getModule().appendModuleInlineAsm(s.str());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003170}
3171
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003172CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003173 : CGObjCCommonMac(cgm),
3174 ObjCTypes(cgm)
3175{
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003176 ObjCEmptyCacheVar = ObjCEmptyVtableVar = NULL;
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003177 ObjCABI = 2;
3178}
3179
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003180/* *** */
3181
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003182ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm)
3183: CGM(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003184{
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003185 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3186 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003187
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003188 ShortTy = Types.ConvertType(Ctx.ShortTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003189 IntTy = Types.ConvertType(Ctx.IntTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003190 LongTy = Types.ConvertType(Ctx.LongTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00003191 LongLongTy = Types.ConvertType(Ctx.LongLongTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003192 Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3193
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003194 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00003195 PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003196 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003197
3198 // FIXME: It would be nice to unify this with the opaque type, so
3199 // that the IR comes out a bit cleaner.
3200 const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
3201 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003202
3203 // I'm not sure I like this. The implicit coordination is a bit
3204 // gross. We should solve this in a reasonable fashion because this
3205 // is a pretty common task (match some runtime data structure with
3206 // an LLVM data structure).
3207
3208 // FIXME: This is leaked.
3209 // FIXME: Merge with rewriter code?
3210
3211 // struct _objc_super {
3212 // id self;
3213 // Class cls;
3214 // }
3215 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3216 SourceLocation(),
3217 &Ctx.Idents.get("_objc_super"));
Douglas Gregor6ab35242009-04-09 21:40:53 +00003218 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3219 Ctx.getObjCIdType(), 0, false));
3220 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3221 Ctx.getObjCClassType(), 0, false));
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003222 RD->completeDefinition(Ctx);
3223
3224 SuperCTy = Ctx.getTagDeclType(RD);
3225 SuperPtrCTy = Ctx.getPointerType(SuperCTy);
3226
3227 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003228 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
3229
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003230 // struct _prop_t {
3231 // char *name;
3232 // char *attributes;
3233 // }
3234 PropertyTy = llvm::StructType::get(Int8PtrTy,
3235 Int8PtrTy,
3236 NULL);
3237 CGM.getModule().addTypeName("struct._prop_t",
3238 PropertyTy);
3239
3240 // struct _prop_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003241 // uint32_t entsize; // sizeof(struct _prop_t)
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003242 // uint32_t count_of_properties;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003243 // struct _prop_t prop_list[count_of_properties];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003244 // }
3245 PropertyListTy = llvm::StructType::get(IntTy,
3246 IntTy,
3247 llvm::ArrayType::get(PropertyTy, 0),
3248 NULL);
3249 CGM.getModule().addTypeName("struct._prop_list_t",
3250 PropertyListTy);
3251 // struct _prop_list_t *
3252 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
3253
3254 // struct _objc_method {
3255 // SEL _cmd;
3256 // char *method_type;
3257 // char *_imp;
3258 // }
3259 MethodTy = llvm::StructType::get(SelectorPtrTy,
3260 Int8PtrTy,
3261 Int8PtrTy,
3262 NULL);
3263 CGM.getModule().addTypeName("struct._objc_method", MethodTy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003264
3265 // struct _objc_cache *
3266 CacheTy = llvm::OpaqueType::get();
3267 CGM.getModule().addTypeName("struct._objc_cache", CacheTy);
3268 CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003269
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003270 // Property manipulation functions.
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003271
3272 QualType IdType = Ctx.getObjCIdType();
3273 QualType SelType = Ctx.getObjCSelType();
3274 llvm::SmallVector<QualType,16> Params;
3275 const llvm::FunctionType *FTy;
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003276
3277 // id objc_getProperty (id, SEL, ptrdiff_t, bool)
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003278 Params.push_back(IdType);
3279 Params.push_back(SelType);
3280 Params.push_back(Ctx.LongTy);
3281 Params.push_back(Ctx.BoolTy);
3282 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params),
3283 false);
3284 GetPropertyFn = CGM.CreateRuntimeFunction(FTy, "objc_getProperty");
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003285
3286 // void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool)
3287 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003288 Params.push_back(IdType);
3289 Params.push_back(SelType);
3290 Params.push_back(Ctx.LongTy);
3291 Params.push_back(IdType);
3292 Params.push_back(Ctx.BoolTy);
3293 Params.push_back(Ctx.BoolTy);
3294 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
3295 SetPropertyFn = CGM.CreateRuntimeFunction(FTy, "objc_setProperty");
3296
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003297 // Enumeration mutation.
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003298
3299 // void objc_enumerationMutation (id)
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003300 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003301 Params.push_back(IdType);
3302 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
3303 EnumerationMutationFn = CGM.CreateRuntimeFunction(FTy,
3304 "objc_enumerationMutation");
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003305
3306 // gc's API
3307 // id objc_read_weak (id *)
3308 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003309 Params.push_back(Ctx.getPointerType(IdType));
3310 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
3311 GcReadWeakFn = CGM.CreateRuntimeFunction(FTy, "objc_read_weak");
3312
Chris Lattner96508e12009-04-17 22:12:36 +00003313 // id objc_assign_global (id, id *)
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003314 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003315 Params.push_back(IdType);
3316 Params.push_back(Ctx.getPointerType(IdType));
3317
3318 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003319 GcAssignGlobalFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_global");
3320 GcAssignIvarFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_ivar");
3321 GcAssignStrongCastFn =
3322 CGM.CreateRuntimeFunction(FTy, "objc_assign_strongCast");
Anders Carlssonf57c5b22009-02-16 22:59:18 +00003323
3324 // void objc_exception_throw(id)
3325 Params.clear();
3326 Params.push_back(IdType);
3327
3328 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00003329 ExceptionThrowFn =
3330 CGM.CreateRuntimeFunction(FTy, "objc_exception_throw");
Daniel Dunbar1c566672009-02-24 01:43:46 +00003331
3332 // synchronized APIs
Daniel Dunbar1c566672009-02-24 01:43:46 +00003333 // void objc_sync_exit (id)
3334 Params.clear();
3335 Params.push_back(IdType);
3336
3337 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
Daniel Dunbar1c566672009-02-24 01:43:46 +00003338 SyncExitFn = CGM.CreateRuntimeFunction(FTy, "objc_sync_exit");
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003339}
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003340
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003341ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
3342 : ObjCCommonTypesHelper(cgm)
3343{
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003344 // struct _objc_method_description {
3345 // SEL name;
3346 // char *types;
3347 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003348 MethodDescriptionTy =
3349 llvm::StructType::get(SelectorPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003350 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003351 NULL);
3352 CGM.getModule().addTypeName("struct._objc_method_description",
3353 MethodDescriptionTy);
3354
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003355 // struct _objc_method_description_list {
3356 // int count;
3357 // struct _objc_method_description[1];
3358 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003359 MethodDescriptionListTy =
3360 llvm::StructType::get(IntTy,
3361 llvm::ArrayType::get(MethodDescriptionTy, 0),
3362 NULL);
3363 CGM.getModule().addTypeName("struct._objc_method_description_list",
3364 MethodDescriptionListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003365
3366 // struct _objc_method_description_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003367 MethodDescriptionListPtrTy =
3368 llvm::PointerType::getUnqual(MethodDescriptionListTy);
3369
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003370 // Protocol description structures
3371
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003372 // struct _objc_protocol_extension {
3373 // uint32_t size; // sizeof(struct _objc_protocol_extension)
3374 // struct _objc_method_description_list *optional_instance_methods;
3375 // struct _objc_method_description_list *optional_class_methods;
3376 // struct _objc_property_list *instance_properties;
3377 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003378 ProtocolExtensionTy =
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003379 llvm::StructType::get(IntTy,
3380 MethodDescriptionListPtrTy,
3381 MethodDescriptionListPtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003382 PropertyListPtrTy,
3383 NULL);
3384 CGM.getModule().addTypeName("struct._objc_protocol_extension",
3385 ProtocolExtensionTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003386
3387 // struct _objc_protocol_extension *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003388 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
3389
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003390 // Handle recursive construction of Protocol and ProtocolList types
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003391
3392 llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get();
3393 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3394
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003395 const llvm::Type *T =
3396 llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder),
3397 LongTy,
3398 llvm::ArrayType::get(ProtocolTyHolder, 0),
3399 NULL);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003400 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T);
3401
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003402 // struct _objc_protocol {
3403 // struct _objc_protocol_extension *isa;
3404 // char *protocol_name;
3405 // struct _objc_protocol **_objc_protocol_list;
3406 // struct _objc_method_description_list *instance_methods;
3407 // struct _objc_method_description_list *class_methods;
3408 // }
3409 T = llvm::StructType::get(ProtocolExtensionPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003410 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003411 llvm::PointerType::getUnqual(ProtocolListTyHolder),
3412 MethodDescriptionListPtrTy,
3413 MethodDescriptionListPtrTy,
3414 NULL);
3415 cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T);
3416
3417 ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get());
3418 CGM.getModule().addTypeName("struct._objc_protocol_list",
3419 ProtocolListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003420 // struct _objc_protocol_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003421 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
3422
3423 ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get());
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003424 CGM.getModule().addTypeName("struct._objc_protocol", ProtocolTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003425 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003426
3427 // Class description structures
3428
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003429 // struct _objc_ivar {
3430 // char *ivar_name;
3431 // char *ivar_type;
3432 // int ivar_offset;
3433 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003434 IvarTy = llvm::StructType::get(Int8PtrTy,
3435 Int8PtrTy,
3436 IntTy,
3437 NULL);
3438 CGM.getModule().addTypeName("struct._objc_ivar", IvarTy);
3439
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003440 // struct _objc_ivar_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003441 IvarListTy = llvm::OpaqueType::get();
3442 CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy);
3443 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
3444
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003445 // struct _objc_method_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003446 MethodListTy = llvm::OpaqueType::get();
3447 CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy);
3448 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
3449
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003450 // struct _objc_class_extension *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003451 ClassExtensionTy =
3452 llvm::StructType::get(IntTy,
3453 Int8PtrTy,
3454 PropertyListPtrTy,
3455 NULL);
3456 CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy);
3457 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
3458
3459 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3460
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003461 // struct _objc_class {
3462 // Class isa;
3463 // Class super_class;
3464 // char *name;
3465 // long version;
3466 // long info;
3467 // long instance_size;
3468 // struct _objc_ivar_list *ivars;
3469 // struct _objc_method_list *methods;
3470 // struct _objc_cache *cache;
3471 // struct _objc_protocol_list *protocols;
3472 // char *ivar_layout;
3473 // struct _objc_class_ext *ext;
3474 // };
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003475 T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3476 llvm::PointerType::getUnqual(ClassTyHolder),
3477 Int8PtrTy,
3478 LongTy,
3479 LongTy,
3480 LongTy,
3481 IvarListPtrTy,
3482 MethodListPtrTy,
3483 CachePtrTy,
3484 ProtocolListPtrTy,
3485 Int8PtrTy,
3486 ClassExtensionPtrTy,
3487 NULL);
3488 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T);
3489
3490 ClassTy = cast<llvm::StructType>(ClassTyHolder.get());
3491 CGM.getModule().addTypeName("struct._objc_class", ClassTy);
3492 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
3493
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003494 // struct _objc_category {
3495 // char *category_name;
3496 // char *class_name;
3497 // struct _objc_method_list *instance_method;
3498 // struct _objc_method_list *class_method;
3499 // uint32_t size; // sizeof(struct _objc_category)
3500 // struct _objc_property_list *instance_properties;// category's @property
3501 // }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003502 CategoryTy = llvm::StructType::get(Int8PtrTy,
3503 Int8PtrTy,
3504 MethodListPtrTy,
3505 MethodListPtrTy,
3506 ProtocolListPtrTy,
3507 IntTy,
3508 PropertyListPtrTy,
3509 NULL);
3510 CGM.getModule().addTypeName("struct._objc_category", CategoryTy);
3511
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003512 // Global metadata structures
3513
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003514 // struct _objc_symtab {
3515 // long sel_ref_cnt;
3516 // SEL *refs;
3517 // short cls_def_cnt;
3518 // short cat_def_cnt;
3519 // char *defs[cls_def_cnt + cat_def_cnt];
3520 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003521 SymtabTy = llvm::StructType::get(LongTy,
3522 SelectorPtrTy,
3523 ShortTy,
3524 ShortTy,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003525 llvm::ArrayType::get(Int8PtrTy, 0),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003526 NULL);
3527 CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy);
3528 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
3529
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003530 // struct _objc_module {
3531 // long version;
3532 // long size; // sizeof(struct _objc_module)
3533 // char *name;
3534 // struct _objc_symtab* symtab;
3535 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003536 ModuleTy =
3537 llvm::StructType::get(LongTy,
3538 LongTy,
3539 Int8PtrTy,
3540 SymtabPtrTy,
3541 NULL);
3542 CGM.getModule().addTypeName("struct._objc_module", ModuleTy);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003543
Daniel Dunbar49f66022008-09-24 03:38:44 +00003544 // Message send functions.
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003545
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003546 // id objc_msgSend (id, SEL, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003547 std::vector<const llvm::Type*> Params;
3548 Params.push_back(ObjectPtrTy);
3549 Params.push_back(SelectorPtrTy);
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003550 MessageSendFn =
3551 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3552 Params,
3553 true),
3554 "objc_msgSend");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003555
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003556 // id objc_msgSend_stret (id, SEL, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003557 Params.clear();
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003558 Params.push_back(ObjectPtrTy);
3559 Params.push_back(SelectorPtrTy);
3560 MessageSendStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003561 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3562 Params,
3563 true),
3564 "objc_msgSend_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00003565
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003566 //
Daniel Dunbar5669e572008-10-17 03:24:53 +00003567 Params.clear();
3568 Params.push_back(ObjectPtrTy);
3569 Params.push_back(SelectorPtrTy);
3570 // FIXME: This should be long double on x86_64?
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003571 // [double | long double] objc_msgSend_fpret(id self, SEL op, ...)
Daniel Dunbar5669e572008-10-17 03:24:53 +00003572 MessageSendFpretFn =
3573 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::DoubleTy,
3574 Params,
3575 true),
3576 "objc_msgSend_fpret");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003577
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003578 // id objc_msgSendSuper(struct objc_super *super, SEL op, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003579 Params.clear();
3580 Params.push_back(SuperPtrTy);
3581 Params.push_back(SelectorPtrTy);
3582 MessageSendSuperFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003583 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3584 Params,
3585 true),
3586 "objc_msgSendSuper");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003587
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003588 // void objc_msgSendSuper_stret(void * stretAddr, struct objc_super *super,
3589 // SEL op, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003590 Params.clear();
3591 Params.push_back(Int8PtrTy);
3592 Params.push_back(SuperPtrTy);
3593 Params.push_back(SelectorPtrTy);
3594 MessageSendSuperStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003595 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3596 Params,
3597 true),
3598 "objc_msgSendSuper_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00003599
3600 // There is no objc_msgSendSuper_fpret? How can that work?
3601 MessageSendSuperFpretFn = MessageSendSuperFn;
Anders Carlsson2abd89c2008-08-31 04:05:03 +00003602
Anders Carlsson124526b2008-09-09 10:10:21 +00003603 // FIXME: This is the size of the setjmp buffer and should be
3604 // target specific. 18 is what's used on 32-bit X86.
3605 uint64_t SetJmpBufferSize = 18;
3606
3607 // Exceptions
3608 const llvm::Type *StackPtrTy =
Daniel Dunbar10004912008-09-27 06:32:25 +00003609 llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4);
Anders Carlsson124526b2008-09-09 10:10:21 +00003610
3611 ExceptionDataTy =
3612 llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty,
3613 SetJmpBufferSize),
3614 StackPtrTy, NULL);
3615 CGM.getModule().addTypeName("struct._objc_exception_data",
3616 ExceptionDataTy);
3617
3618 Params.clear();
Anders Carlsson124526b2008-09-09 10:10:21 +00003619 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
3620 ExceptionTryEnterFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003621 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3622 Params,
3623 false),
3624 "objc_exception_try_enter");
Anders Carlsson124526b2008-09-09 10:10:21 +00003625 ExceptionTryExitFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003626 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3627 Params,
3628 false),
3629 "objc_exception_try_exit");
Anders Carlsson124526b2008-09-09 10:10:21 +00003630 ExceptionExtractFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003631 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3632 Params,
3633 false),
3634 "objc_exception_extract");
Anders Carlsson124526b2008-09-09 10:10:21 +00003635
3636 Params.clear();
3637 Params.push_back(ClassPtrTy);
3638 Params.push_back(ObjectPtrTy);
3639 ExceptionMatchFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003640 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
3641 Params,
3642 false),
3643 "objc_exception_match");
Chris Lattner10cac6f2008-11-15 21:26:17 +00003644
Anders Carlsson124526b2008-09-09 10:10:21 +00003645 Params.clear();
3646 Params.push_back(llvm::PointerType::getUnqual(llvm::Type::Int32Ty));
3647 SetJmpFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003648 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
3649 Params,
3650 false),
3651 "_setjmp");
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00003652
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003653}
3654
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003655ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003656: ObjCCommonTypesHelper(cgm)
3657{
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003658 // struct _method_list_t {
3659 // uint32_t entsize; // sizeof(struct _objc_method)
3660 // uint32_t method_count;
3661 // struct _objc_method method_list[method_count];
3662 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003663 MethodListnfABITy = llvm::StructType::get(IntTy,
3664 IntTy,
3665 llvm::ArrayType::get(MethodTy, 0),
3666 NULL);
3667 CGM.getModule().addTypeName("struct.__method_list_t",
3668 MethodListnfABITy);
3669 // struct method_list_t *
3670 MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003671
3672 // struct _protocol_t {
3673 // id isa; // NULL
3674 // const char * const protocol_name;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003675 // const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003676 // const struct method_list_t * const instance_methods;
3677 // const struct method_list_t * const class_methods;
3678 // const struct method_list_t *optionalInstanceMethods;
3679 // const struct method_list_t *optionalClassMethods;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003680 // const struct _prop_list_t * properties;
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003681 // const uint32_t size; // sizeof(struct _protocol_t)
3682 // const uint32_t flags; // = 0
3683 // }
3684
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003685 // Holder for struct _protocol_list_t *
3686 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3687
3688 ProtocolnfABITy = llvm::StructType::get(ObjectPtrTy,
3689 Int8PtrTy,
3690 llvm::PointerType::getUnqual(
3691 ProtocolListTyHolder),
3692 MethodListnfABIPtrTy,
3693 MethodListnfABIPtrTy,
3694 MethodListnfABIPtrTy,
3695 MethodListnfABIPtrTy,
3696 PropertyListPtrTy,
3697 IntTy,
3698 IntTy,
3699 NULL);
3700 CGM.getModule().addTypeName("struct._protocol_t",
3701 ProtocolnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003702
3703 // struct _protocol_t*
3704 ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003705
Fariborz Jahanianda320092009-01-29 19:24:30 +00003706 // struct _protocol_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003707 // long protocol_count; // Note, this is 32/64 bit
Daniel Dunbar948e2582009-02-15 07:36:20 +00003708 // struct _protocol_t *[protocol_count];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003709 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003710 ProtocolListnfABITy = llvm::StructType::get(LongTy,
3711 llvm::ArrayType::get(
Daniel Dunbar948e2582009-02-15 07:36:20 +00003712 ProtocolnfABIPtrTy, 0),
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003713 NULL);
3714 CGM.getModule().addTypeName("struct._objc_protocol_list",
3715 ProtocolListnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003716 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(
3717 ProtocolListnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003718
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003719 // struct _objc_protocol_list*
3720 ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003721
3722 // struct _ivar_t {
3723 // unsigned long int *offset; // pointer to ivar offset location
3724 // char *name;
3725 // char *type;
3726 // uint32_t alignment;
3727 // uint32_t size;
3728 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003729 IvarnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(LongTy),
3730 Int8PtrTy,
3731 Int8PtrTy,
3732 IntTy,
3733 IntTy,
3734 NULL);
3735 CGM.getModule().addTypeName("struct._ivar_t", IvarnfABITy);
3736
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003737 // struct _ivar_list_t {
3738 // uint32 entsize; // sizeof(struct _ivar_t)
3739 // uint32 count;
3740 // struct _iver_t list[count];
3741 // }
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003742 IvarListnfABITy = llvm::StructType::get(IntTy,
3743 IntTy,
3744 llvm::ArrayType::get(
3745 IvarnfABITy, 0),
3746 NULL);
3747 CGM.getModule().addTypeName("struct._ivar_list_t", IvarListnfABITy);
3748
3749 IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003750
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003751 // struct _class_ro_t {
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003752 // uint32_t const flags;
3753 // uint32_t const instanceStart;
3754 // uint32_t const instanceSize;
3755 // uint32_t const reserved; // only when building for 64bit targets
3756 // const uint8_t * const ivarLayout;
3757 // const char *const name;
3758 // const struct _method_list_t * const baseMethods;
3759 // const struct _objc_protocol_list *const baseProtocols;
3760 // const struct _ivar_list_t *const ivars;
3761 // const uint8_t * const weakIvarLayout;
3762 // const struct _prop_list_t * const properties;
3763 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003764
3765 // FIXME. Add 'reserved' field in 64bit abi mode!
3766 ClassRonfABITy = llvm::StructType::get(IntTy,
3767 IntTy,
3768 IntTy,
3769 Int8PtrTy,
3770 Int8PtrTy,
3771 MethodListnfABIPtrTy,
3772 ProtocolListnfABIPtrTy,
3773 IvarListnfABIPtrTy,
3774 Int8PtrTy,
3775 PropertyListPtrTy,
3776 NULL);
3777 CGM.getModule().addTypeName("struct._class_ro_t",
3778 ClassRonfABITy);
3779
3780 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
3781 std::vector<const llvm::Type*> Params;
3782 Params.push_back(ObjectPtrTy);
3783 Params.push_back(SelectorPtrTy);
3784 ImpnfABITy = llvm::PointerType::getUnqual(
3785 llvm::FunctionType::get(ObjectPtrTy, Params, false));
3786
3787 // struct _class_t {
3788 // struct _class_t *isa;
3789 // struct _class_t * const superclass;
3790 // void *cache;
3791 // IMP *vtable;
3792 // struct class_ro_t *ro;
3793 // }
3794
3795 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3796 ClassnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3797 llvm::PointerType::getUnqual(ClassTyHolder),
3798 CachePtrTy,
3799 llvm::PointerType::getUnqual(ImpnfABITy),
3800 llvm::PointerType::getUnqual(
3801 ClassRonfABITy),
3802 NULL);
3803 CGM.getModule().addTypeName("struct._class_t", ClassnfABITy);
3804
3805 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(
3806 ClassnfABITy);
3807
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003808 // LLVM for struct _class_t *
3809 ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy);
3810
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003811 // struct _category_t {
3812 // const char * const name;
3813 // struct _class_t *const cls;
3814 // const struct _method_list_t * const instance_methods;
3815 // const struct _method_list_t * const class_methods;
3816 // const struct _protocol_list_t * const protocols;
3817 // const struct _prop_list_t * const properties;
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003818 // }
3819 CategorynfABITy = llvm::StructType::get(Int8PtrTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003820 ClassnfABIPtrTy,
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003821 MethodListnfABIPtrTy,
3822 MethodListnfABIPtrTy,
3823 ProtocolListnfABIPtrTy,
3824 PropertyListPtrTy,
3825 NULL);
3826 CGM.getModule().addTypeName("struct._category_t", CategorynfABITy);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003827
3828 // New types for nonfragile abi messaging.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003829 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3830 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003831
3832 // MessageRefTy - LLVM for:
3833 // struct _message_ref_t {
3834 // IMP messenger;
3835 // SEL name;
3836 // };
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003837
3838 // First the clang type for struct _message_ref_t
3839 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3840 SourceLocation(),
3841 &Ctx.Idents.get("_message_ref_t"));
Douglas Gregor6ab35242009-04-09 21:40:53 +00003842 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3843 Ctx.VoidPtrTy, 0, false));
3844 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3845 Ctx.getObjCSelType(), 0, false));
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003846 RD->completeDefinition(Ctx);
3847
3848 MessageRefCTy = Ctx.getTagDeclType(RD);
3849 MessageRefCPtrTy = Ctx.getPointerType(MessageRefCTy);
3850 MessageRefTy = cast<llvm::StructType>(Types.ConvertType(MessageRefCTy));
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003851
3852 // MessageRefPtrTy - LLVM for struct _message_ref_t*
3853 MessageRefPtrTy = llvm::PointerType::getUnqual(MessageRefTy);
3854
3855 // SuperMessageRefTy - LLVM for:
3856 // struct _super_message_ref_t {
3857 // SUPER_IMP messenger;
3858 // SEL name;
3859 // };
3860 SuperMessageRefTy = llvm::StructType::get(ImpnfABITy,
3861 SelectorPtrTy,
3862 NULL);
3863 CGM.getModule().addTypeName("struct._super_message_ref_t", SuperMessageRefTy);
3864
3865 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
3866 SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy);
3867
3868 // id objc_msgSend_fixup (id, struct message_ref_t*, ...)
3869 Params.clear();
3870 Params.push_back(ObjectPtrTy);
3871 Params.push_back(MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00003872 MessengerTy = llvm::FunctionType::get(ObjectPtrTy,
3873 Params,
3874 true);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003875 MessageSendFixupFn =
Fariborz Jahanianef163782009-02-05 01:13:09 +00003876 CGM.CreateRuntimeFunction(MessengerTy,
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003877 "objc_msgSend_fixup");
3878
3879 // id objc_msgSend_fpret_fixup (id, struct message_ref_t*, ...)
3880 MessageSendFpretFixupFn =
3881 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3882 Params,
3883 true),
3884 "objc_msgSend_fpret_fixup");
3885
3886 // id objc_msgSend_stret_fixup (id, struct message_ref_t*, ...)
3887 MessageSendStretFixupFn =
3888 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3889 Params,
3890 true),
3891 "objc_msgSend_stret_fixup");
3892
3893 // id objc_msgSendId_fixup (id, struct message_ref_t*, ...)
3894 MessageSendIdFixupFn =
3895 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3896 Params,
3897 true),
3898 "objc_msgSendId_fixup");
3899
3900
3901 // id objc_msgSendId_stret_fixup (id, struct message_ref_t*, ...)
3902 MessageSendIdStretFixupFn =
3903 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3904 Params,
3905 true),
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003906 "objc_msgSendId_stret_fixup");
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003907
3908 // id objc_msgSendSuper2_fixup (struct objc_super *,
3909 // struct _super_message_ref_t*, ...)
3910 Params.clear();
3911 Params.push_back(SuperPtrTy);
3912 Params.push_back(SuperMessageRefPtrTy);
3913 MessageSendSuper2FixupFn =
3914 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3915 Params,
3916 true),
3917 "objc_msgSendSuper2_fixup");
3918
3919
3920 // id objc_msgSendSuper2_stret_fixup (struct objc_super *,
3921 // struct _super_message_ref_t*, ...)
3922 MessageSendSuper2StretFixupFn =
3923 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3924 Params,
3925 true),
3926 "objc_msgSendSuper2_stret_fixup");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00003927
3928 Params.clear();
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00003929 Params.push_back(Int8PtrTy);
3930 UnwindResumeOrRethrowFn =
3931 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3932 Params,
3933 false),
3934 "_Unwind_Resume_or_Rethrow");
Daniel Dunbare588b992009-03-01 04:46:24 +00003935 ObjCBeginCatchFn =
3936 CGM.CreateRuntimeFunction(llvm::FunctionType::get(Int8PtrTy,
3937 Params,
3938 false),
3939 "objc_begin_catch");
3940
3941 Params.clear();
3942 ObjCEndCatchFn =
3943 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3944 Params,
3945 false),
3946 "objc_end_catch");
3947
3948 // struct objc_typeinfo {
3949 // const void** vtable; // objc_ehtype_vtable + 2
3950 // const char* name; // c++ typeinfo string
3951 // Class cls;
3952 // };
3953 EHTypeTy = llvm::StructType::get(llvm::PointerType::getUnqual(Int8PtrTy),
3954 Int8PtrTy,
3955 ClassnfABIPtrTy,
3956 NULL);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00003957 CGM.getModule().addTypeName("struct._objc_typeinfo", EHTypeTy);
Daniel Dunbare588b992009-03-01 04:46:24 +00003958 EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy);
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003959}
3960
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003961llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() {
3962 FinishNonFragileABIModule();
3963
3964 return NULL;
3965}
3966
3967void CGObjCNonFragileABIMac::FinishNonFragileABIModule() {
3968 // nonfragile abi has no module definition.
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003969
3970 // Build list of all implemented classe addresses in array
3971 // L_OBJC_LABEL_CLASS_$.
3972 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CLASS_$
3973 // list of 'nonlazy' implementations (defined as those with a +load{}
3974 // method!!).
3975 unsigned NumClasses = DefinedClasses.size();
3976 if (NumClasses) {
3977 std::vector<llvm::Constant*> Symbols(NumClasses);
3978 for (unsigned i=0; i<NumClasses; i++)
3979 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
3980 ObjCTypes.Int8PtrTy);
3981 llvm::Constant* Init =
3982 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
3983 NumClasses),
3984 Symbols);
3985
3986 llvm::GlobalVariable *GV =
3987 new llvm::GlobalVariable(Init->getType(), false,
3988 llvm::GlobalValue::InternalLinkage,
3989 Init,
3990 "\01L_OBJC_LABEL_CLASS_$",
3991 &CGM.getModule());
Daniel Dunbar58a29122009-03-09 22:18:41 +00003992 GV->setAlignment(8);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003993 GV->setSection("__DATA, __objc_classlist, regular, no_dead_strip");
3994 UsedGlobals.push_back(GV);
3995 }
3996
3997 // Build list of all implemented category addresses in array
3998 // L_OBJC_LABEL_CATEGORY_$.
3999 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CATEGORY_$
4000 // list of 'nonlazy' category implementations (defined as those with a +load{}
4001 // method!!).
4002 unsigned NumCategory = DefinedCategories.size();
4003 if (NumCategory) {
4004 std::vector<llvm::Constant*> Symbols(NumCategory);
4005 for (unsigned i=0; i<NumCategory; i++)
4006 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedCategories[i],
4007 ObjCTypes.Int8PtrTy);
4008 llvm::Constant* Init =
4009 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
4010 NumCategory),
4011 Symbols);
4012
4013 llvm::GlobalVariable *GV =
4014 new llvm::GlobalVariable(Init->getType(), false,
4015 llvm::GlobalValue::InternalLinkage,
4016 Init,
4017 "\01L_OBJC_LABEL_CATEGORY_$",
4018 &CGM.getModule());
Daniel Dunbar58a29122009-03-09 22:18:41 +00004019 GV->setAlignment(8);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004020 GV->setSection("__DATA, __objc_catlist, regular, no_dead_strip");
4021 UsedGlobals.push_back(GV);
4022 }
4023
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004024 // static int L_OBJC_IMAGE_INFO[2] = { 0, flags };
4025 // FIXME. flags can be 0 | 1 | 2 | 6. For now just use 0
4026 std::vector<llvm::Constant*> Values(2);
4027 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, 0);
Fariborz Jahanian067986e2009-02-24 21:08:09 +00004028 unsigned int flags = 0;
Fariborz Jahanian66a5c2c2009-02-24 23:34:44 +00004029 // FIXME: Fix and continue?
4030 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
4031 flags |= eImageInfo_GarbageCollected;
4032 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
4033 flags |= eImageInfo_GCOnly;
Fariborz Jahanian067986e2009-02-24 21:08:09 +00004034 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004035 llvm::Constant* Init = llvm::ConstantArray::get(
4036 llvm::ArrayType::get(ObjCTypes.IntTy, 2),
4037 Values);
4038 llvm::GlobalVariable *IMGV =
4039 new llvm::GlobalVariable(Init->getType(), false,
4040 llvm::GlobalValue::InternalLinkage,
4041 Init,
4042 "\01L_OBJC_IMAGE_INFO",
4043 &CGM.getModule());
4044 IMGV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
4045 UsedGlobals.push_back(IMGV);
4046
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004047 std::vector<llvm::Constant*> Used;
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004048
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004049 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
4050 e = UsedGlobals.end(); i != e; ++i) {
4051 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
4052 }
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004053
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004054 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
4055 llvm::GlobalValue *GV =
4056 new llvm::GlobalVariable(AT, false,
4057 llvm::GlobalValue::AppendingLinkage,
4058 llvm::ConstantArray::get(AT, Used),
4059 "llvm.used",
4060 &CGM.getModule());
4061
4062 GV->setSection("llvm.metadata");
4063
4064}
4065
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004066// Metadata flags
4067enum MetaDataDlags {
4068 CLS = 0x0,
4069 CLS_META = 0x1,
4070 CLS_ROOT = 0x2,
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004071 OBJC2_CLS_HIDDEN = 0x10,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004072 CLS_EXCEPTION = 0x20
4073};
4074/// BuildClassRoTInitializer - generate meta-data for:
4075/// struct _class_ro_t {
4076/// uint32_t const flags;
4077/// uint32_t const instanceStart;
4078/// uint32_t const instanceSize;
4079/// uint32_t const reserved; // only when building for 64bit targets
4080/// const uint8_t * const ivarLayout;
4081/// const char *const name;
4082/// const struct _method_list_t * const baseMethods;
Fariborz Jahanianda320092009-01-29 19:24:30 +00004083/// const struct _protocol_list_t *const baseProtocols;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004084/// const struct _ivar_list_t *const ivars;
4085/// const uint8_t * const weakIvarLayout;
4086/// const struct _prop_list_t * const properties;
4087/// }
4088///
4089llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer(
4090 unsigned flags,
4091 unsigned InstanceStart,
4092 unsigned InstanceSize,
4093 const ObjCImplementationDecl *ID) {
4094 std::string ClassName = ID->getNameAsString();
4095 std::vector<llvm::Constant*> Values(10); // 11 for 64bit targets!
4096 Values[ 0] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
4097 Values[ 1] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceStart);
4098 Values[ 2] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceSize);
4099 // FIXME. For 64bit targets add 0 here.
Fariborz Jahanianda320092009-01-29 19:24:30 +00004100 // FIXME. ivarLayout is currently null!
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00004101 Values[ 3] = GetIvarLayoutName(0, ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004102 Values[ 4] = GetClassName(ID->getIdentifier());
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004103 // const struct _method_list_t * const baseMethods;
4104 std::vector<llvm::Constant*> Methods;
4105 std::string MethodListName("\01l_OBJC_$_");
4106 if (flags & CLS_META) {
4107 MethodListName += "CLASS_METHODS_" + ID->getNameAsString();
4108 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
4109 e = ID->classmeth_end(); i != e; ++i) {
4110 // Class methods should always be defined.
4111 Methods.push_back(GetMethodConstant(*i));
4112 }
4113 } else {
4114 MethodListName += "INSTANCE_METHODS_" + ID->getNameAsString();
4115 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
4116 e = ID->instmeth_end(); i != e; ++i) {
4117 // Instance methods should always be defined.
4118 Methods.push_back(GetMethodConstant(*i));
4119 }
Fariborz Jahanian939abce2009-01-28 22:46:49 +00004120 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
4121 e = ID->propimpl_end(); i != e; ++i) {
4122 ObjCPropertyImplDecl *PID = *i;
4123
4124 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize){
4125 ObjCPropertyDecl *PD = PID->getPropertyDecl();
4126
4127 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
4128 if (llvm::Constant *C = GetMethodConstant(MD))
4129 Methods.push_back(C);
4130 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
4131 if (llvm::Constant *C = GetMethodConstant(MD))
4132 Methods.push_back(C);
4133 }
4134 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004135 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004136 Values[ 5] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004137 "__DATA, __objc_const", Methods);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004138
4139 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4140 assert(OID && "CGObjCNonFragileABIMac::BuildClassRoTInitializer");
4141 Values[ 6] = EmitProtocolList("\01l_OBJC_CLASS_PROTOCOLS_$_"
4142 + OID->getNameAsString(),
4143 OID->protocol_begin(),
4144 OID->protocol_end());
4145
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004146 if (flags & CLS_META)
4147 Values[ 7] = llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4148 else
4149 Values[ 7] = EmitIvarList(ID);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004150 // FIXME. weakIvarLayout is currently null.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00004151 Values[ 8] = GetIvarLayoutName(0, ObjCTypes);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004152 if (flags & CLS_META)
4153 Values[ 9] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4154 else
4155 Values[ 9] =
4156 EmitPropertyList(
4157 "\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
4158 ID, ID->getClassInterface(), ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004159 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassRonfABITy,
4160 Values);
4161 llvm::GlobalVariable *CLASS_RO_GV =
4162 new llvm::GlobalVariable(ObjCTypes.ClassRonfABITy, false,
4163 llvm::GlobalValue::InternalLinkage,
4164 Init,
4165 (flags & CLS_META) ?
4166 std::string("\01l_OBJC_METACLASS_RO_$_")+ClassName :
4167 std::string("\01l_OBJC_CLASS_RO_$_")+ClassName,
4168 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004169 CLASS_RO_GV->setAlignment(
4170 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassRonfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004171 CLASS_RO_GV->setSection("__DATA, __objc_const");
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004172 return CLASS_RO_GV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004173
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004174}
4175
4176/// BuildClassMetaData - This routine defines that to-level meta-data
4177/// for the given ClassName for:
4178/// struct _class_t {
4179/// struct _class_t *isa;
4180/// struct _class_t * const superclass;
4181/// void *cache;
4182/// IMP *vtable;
4183/// struct class_ro_t *ro;
4184/// }
4185///
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004186llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassMetaData(
4187 std::string &ClassName,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004188 llvm::Constant *IsAGV,
4189 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004190 llvm::Constant *ClassRoGV,
4191 bool HiddenVisibility) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004192 std::vector<llvm::Constant*> Values(5);
4193 Values[0] = IsAGV;
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004194 Values[1] = SuperClassGV
4195 ? SuperClassGV
4196 : llvm::Constant::getNullValue(ObjCTypes.ClassnfABIPtrTy);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004197 Values[2] = ObjCEmptyCacheVar; // &ObjCEmptyCacheVar
4198 Values[3] = ObjCEmptyVtableVar; // &ObjCEmptyVtableVar
4199 Values[4] = ClassRoGV; // &CLASS_RO_GV
4200 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassnfABITy,
4201 Values);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004202 llvm::GlobalVariable *GV = GetClassGlobal(ClassName);
4203 GV->setInitializer(Init);
Fariborz Jahaniandd0db2a2009-01-31 01:07:39 +00004204 GV->setSection("__DATA, __objc_data");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004205 GV->setAlignment(
4206 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassnfABITy));
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004207 if (HiddenVisibility)
4208 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004209 return GV;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004210}
4211
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004212void CGObjCNonFragileABIMac::GetClassSizeInfo(const ObjCInterfaceDecl *OID,
4213 uint32_t &InstanceStart,
4214 uint32_t &InstanceSize) {
4215 // FIXME. Share this with the one in EmitIvarList.
4216 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID);
4217
4218 RecordDecl::field_iterator firstField, lastField;
4219 const RecordDecl *RD = GetFirstIvarInRecord(OID, firstField, lastField);
4220
4221 for (RecordDecl::field_iterator e = RD->field_end(CGM.getContext()),
4222 ifield = firstField; ifield != e; ++ifield)
4223 lastField = ifield;
4224
4225 InstanceStart = InstanceSize = 0;
4226 if (lastField != RD->field_end(CGM.getContext())) {
4227 FieldDecl *Field = *lastField;
4228 const llvm::Type *FieldTy =
4229 CGM.getTypes().ConvertTypeForMem(Field->getType());
4230 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
4231 InstanceSize = GetIvarBaseOffset(Layout, Field) + Size;
4232 if (firstField == RD->field_end(CGM.getContext()))
4233 InstanceStart = InstanceSize;
4234 else {
4235 Field = *firstField;
4236 InstanceStart = GetIvarBaseOffset(Layout, Field);
4237 }
4238 }
4239}
4240
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004241void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) {
4242 std::string ClassName = ID->getNameAsString();
4243 if (!ObjCEmptyCacheVar) {
4244 ObjCEmptyCacheVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004245 ObjCTypes.CacheTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004246 false,
4247 llvm::GlobalValue::ExternalLinkage,
4248 0,
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004249 "_objc_empty_cache",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004250 &CGM.getModule());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004251
4252 ObjCEmptyVtableVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004253 ObjCTypes.ImpnfABITy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004254 false,
4255 llvm::GlobalValue::ExternalLinkage,
4256 0,
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004257 "_objc_empty_vtable",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004258 &CGM.getModule());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004259 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004260 assert(ID->getClassInterface() &&
4261 "CGObjCNonFragileABIMac::GenerateClass - class is 0");
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004262 // FIXME: Is this correct (That meta class size is never computed)?
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004263 uint32_t InstanceStart =
4264 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassnfABITy);
4265 uint32_t InstanceSize = InstanceStart;
4266 uint32_t flags = CLS_META;
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004267 std::string ObjCMetaClassName(getMetaclassSymbolPrefix());
4268 std::string ObjCClassName(getClassSymbolPrefix());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004269
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004270 llvm::GlobalVariable *SuperClassGV, *IsAGV;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004271
Daniel Dunbar04d40782009-04-14 06:00:08 +00004272 bool classIsHidden =
4273 CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004274 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004275 flags |= OBJC2_CLS_HIDDEN;
4276 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004277 // class is root
4278 flags |= CLS_ROOT;
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004279 SuperClassGV = GetClassGlobal(ObjCClassName + ClassName);
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004280 IsAGV = GetClassGlobal(ObjCMetaClassName + ClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004281 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004282 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004283 const ObjCInterfaceDecl *Root = ID->getClassInterface();
4284 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
4285 Root = Super;
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004286 IsAGV = GetClassGlobal(ObjCMetaClassName + Root->getNameAsString());
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004287 // work on super class metadata symbol.
4288 std::string SuperClassName =
4289 ObjCMetaClassName + ID->getClassInterface()->getSuperClass()->getNameAsString();
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004290 SuperClassGV = GetClassGlobal(SuperClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004291 }
4292 llvm::GlobalVariable *CLASS_RO_GV = BuildClassRoTInitializer(flags,
4293 InstanceStart,
4294 InstanceSize,ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004295 std::string TClassName = ObjCMetaClassName + ClassName;
4296 llvm::GlobalVariable *MetaTClass =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004297 BuildClassMetaData(TClassName, IsAGV, SuperClassGV, CLASS_RO_GV,
4298 classIsHidden);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004299
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004300 // Metadata for the class
4301 flags = CLS;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004302 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004303 flags |= OBJC2_CLS_HIDDEN;
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004304
4305 if (hasObjCExceptionAttribute(ID->getClassInterface()))
4306 flags |= CLS_EXCEPTION;
4307
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004308 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004309 flags |= CLS_ROOT;
4310 SuperClassGV = 0;
Chris Lattnerb7b58b12009-04-19 06:02:28 +00004311 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004312 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004313 std::string RootClassName =
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004314 ID->getClassInterface()->getSuperClass()->getNameAsString();
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004315 SuperClassGV = GetClassGlobal(ObjCClassName + RootClassName);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004316 }
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004317 GetClassSizeInfo(ID->getClassInterface(), InstanceStart, InstanceSize);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004318 CLASS_RO_GV = BuildClassRoTInitializer(flags,
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004319 InstanceStart,
4320 InstanceSize,
4321 ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004322
4323 TClassName = ObjCClassName + ClassName;
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004324 llvm::GlobalVariable *ClassMD =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004325 BuildClassMetaData(TClassName, MetaTClass, SuperClassGV, CLASS_RO_GV,
4326 classIsHidden);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004327 DefinedClasses.push_back(ClassMD);
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004328
4329 // Force the definition of the EHType if necessary.
4330 if (flags & CLS_EXCEPTION)
4331 GetInterfaceEHType(ID->getClassInterface(), true);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004332}
4333
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004334/// GenerateProtocolRef - This routine is called to generate code for
4335/// a protocol reference expression; as in:
4336/// @code
4337/// @protocol(Proto1);
4338/// @endcode
4339/// It generates a weak reference to l_OBJC_PROTOCOL_REFERENCE_$_Proto1
4340/// which will hold address of the protocol meta-data.
4341///
4342llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CGBuilderTy &Builder,
4343 const ObjCProtocolDecl *PD) {
4344
Fariborz Jahanian960cd062009-04-10 18:47:34 +00004345 // This routine is called for @protocol only. So, we must build definition
4346 // of protocol's meta-data (not a reference to it!)
4347 //
4348 llvm::Constant *Init = llvm::ConstantExpr::getBitCast(GetOrEmitProtocol(PD),
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004349 ObjCTypes.ExternalProtocolPtrTy);
4350
4351 std::string ProtocolName("\01l_OBJC_PROTOCOL_REFERENCE_$_");
4352 ProtocolName += PD->getNameAsCString();
4353
4354 llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName);
4355 if (PTGV)
4356 return Builder.CreateLoad(PTGV, false, "tmp");
4357 PTGV = new llvm::GlobalVariable(
4358 Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00004359 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004360 Init,
4361 ProtocolName,
4362 &CGM.getModule());
4363 PTGV->setSection("__DATA, __objc_protorefs, coalesced, no_dead_strip");
4364 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4365 UsedGlobals.push_back(PTGV);
4366 return Builder.CreateLoad(PTGV, false, "tmp");
4367}
4368
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004369/// GenerateCategory - Build metadata for a category implementation.
4370/// struct _category_t {
4371/// const char * const name;
4372/// struct _class_t *const cls;
4373/// const struct _method_list_t * const instance_methods;
4374/// const struct _method_list_t * const class_methods;
4375/// const struct _protocol_list_t * const protocols;
4376/// const struct _prop_list_t * const properties;
4377/// }
4378///
4379void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD)
4380{
4381 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004382 const char *Prefix = "\01l_OBJC_$_CATEGORY_";
4383 std::string ExtCatName(Prefix + Interface->getNameAsString()+
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004384 "_$_" + OCD->getNameAsString());
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004385 std::string ExtClassName(getClassSymbolPrefix() +
4386 Interface->getNameAsString());
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004387
4388 std::vector<llvm::Constant*> Values(6);
4389 Values[0] = GetClassName(OCD->getIdentifier());
4390 // meta-class entry symbol
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004391 llvm::GlobalVariable *ClassGV = GetClassGlobal(ExtClassName);
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004392 Values[1] = ClassGV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004393 std::vector<llvm::Constant*> Methods;
4394 std::string MethodListName(Prefix);
4395 MethodListName += "INSTANCE_METHODS_" + Interface->getNameAsString() +
4396 "_$_" + OCD->getNameAsString();
4397
4398 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
4399 e = OCD->instmeth_end(); i != e; ++i) {
4400 // Instance methods should always be defined.
4401 Methods.push_back(GetMethodConstant(*i));
4402 }
4403
4404 Values[2] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004405 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004406 Methods);
4407
4408 MethodListName = Prefix;
4409 MethodListName += "CLASS_METHODS_" + Interface->getNameAsString() + "_$_" +
4410 OCD->getNameAsString();
4411 Methods.clear();
4412 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
4413 e = OCD->classmeth_end(); i != e; ++i) {
4414 // Class methods should always be defined.
4415 Methods.push_back(GetMethodConstant(*i));
4416 }
4417
4418 Values[3] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004419 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004420 Methods);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004421 const ObjCCategoryDecl *Category =
4422 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Fariborz Jahanian943ed6f2009-02-13 17:52:22 +00004423 if (Category) {
4424 std::string ExtName(Interface->getNameAsString() + "_$_" +
4425 OCD->getNameAsString());
4426 Values[4] = EmitProtocolList("\01l_OBJC_CATEGORY_PROTOCOLS_$_"
4427 + Interface->getNameAsString() + "_$_"
4428 + Category->getNameAsString(),
4429 Category->protocol_begin(),
4430 Category->protocol_end());
4431 Values[5] =
4432 EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
4433 OCD, Category, ObjCTypes);
4434 }
4435 else {
4436 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4437 Values[5] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4438 }
4439
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004440 llvm::Constant *Init =
4441 llvm::ConstantStruct::get(ObjCTypes.CategorynfABITy,
4442 Values);
4443 llvm::GlobalVariable *GCATV
4444 = new llvm::GlobalVariable(ObjCTypes.CategorynfABITy,
4445 false,
4446 llvm::GlobalValue::InternalLinkage,
4447 Init,
4448 ExtCatName,
4449 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004450 GCATV->setAlignment(
4451 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.CategorynfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004452 GCATV->setSection("__DATA, __objc_const");
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004453 UsedGlobals.push_back(GCATV);
4454 DefinedCategories.push_back(GCATV);
4455}
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004456
4457/// GetMethodConstant - Return a struct objc_method constant for the
4458/// given method if it has been defined. The result is null if the
4459/// method has not been defined. The return value has type MethodPtrTy.
4460llvm::Constant *CGObjCNonFragileABIMac::GetMethodConstant(
4461 const ObjCMethodDecl *MD) {
4462 // FIXME: Use DenseMap::lookup
4463 llvm::Function *Fn = MethodDefinitions[MD];
4464 if (!Fn)
4465 return 0;
4466
4467 std::vector<llvm::Constant*> Method(3);
4468 Method[0] =
4469 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4470 ObjCTypes.SelectorPtrTy);
4471 Method[1] = GetMethodVarType(MD);
4472 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
4473 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
4474}
4475
4476/// EmitMethodList - Build meta-data for method declarations
4477/// struct _method_list_t {
4478/// uint32_t entsize; // sizeof(struct _objc_method)
4479/// uint32_t method_count;
4480/// struct _objc_method method_list[method_count];
4481/// }
4482///
4483llvm::Constant *CGObjCNonFragileABIMac::EmitMethodList(
4484 const std::string &Name,
4485 const char *Section,
4486 const ConstantVector &Methods) {
4487 // Return null for empty list.
4488 if (Methods.empty())
4489 return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy);
4490
4491 std::vector<llvm::Constant*> Values(3);
4492 // sizeof(struct _objc_method)
4493 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.MethodTy);
4494 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4495 // method_count
4496 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
4497 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
4498 Methods.size());
4499 Values[2] = llvm::ConstantArray::get(AT, Methods);
4500 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4501
4502 llvm::GlobalVariable *GV =
4503 new llvm::GlobalVariable(Init->getType(), false,
4504 llvm::GlobalValue::InternalLinkage,
4505 Init,
4506 Name,
4507 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004508 GV->setAlignment(
4509 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004510 GV->setSection(Section);
4511 UsedGlobals.push_back(GV);
4512 return llvm::ConstantExpr::getBitCast(GV,
4513 ObjCTypes.MethodListnfABIPtrTy);
4514}
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004515
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004516/// ObjCIvarOffsetVariable - Returns the ivar offset variable for
4517/// the given ivar.
4518///
4519llvm::GlobalVariable * CGObjCNonFragileABIMac::ObjCIvarOffsetVariable(
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004520 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004521 const ObjCIvarDecl *Ivar) {
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00004522 std::string Name = "OBJC_IVAR_$_" +
Douglas Gregor6ab35242009-04-09 21:40:53 +00004523 getInterfaceDeclForIvar(ID, Ivar, CGM.getContext())->getNameAsString() +
4524 '.' + Ivar->getNameAsString();
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004525 llvm::GlobalVariable *IvarOffsetGV =
4526 CGM.getModule().getGlobalVariable(Name);
4527 if (!IvarOffsetGV)
4528 IvarOffsetGV =
4529 new llvm::GlobalVariable(ObjCTypes.LongTy,
4530 false,
4531 llvm::GlobalValue::ExternalLinkage,
4532 0,
4533 Name,
4534 &CGM.getModule());
4535 return IvarOffsetGV;
4536}
4537
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004538llvm::Constant * CGObjCNonFragileABIMac::EmitIvarOffsetVar(
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004539 const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004540 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004541 unsigned long int Offset) {
Daniel Dunbar737c5022009-04-19 00:44:02 +00004542 llvm::GlobalVariable *IvarOffsetGV = ObjCIvarOffsetVariable(ID, Ivar);
4543 IvarOffsetGV->setInitializer(llvm::ConstantInt::get(ObjCTypes.LongTy,
4544 Offset));
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004545 IvarOffsetGV->setAlignment(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004546 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.LongTy));
Daniel Dunbar737c5022009-04-19 00:44:02 +00004547
4548 // FIXME: This matches gcc, but shouldn't the visibility be set on
4549 // the use as well (i.e., in ObjCIvarOffsetVariable).
4550 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
4551 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
4552 CGM.getDeclVisibilityMode(ID) == LangOptions::Hidden)
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004553 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar04d40782009-04-14 06:00:08 +00004554 else
Fariborz Jahanian77c9fd22009-04-06 18:30:00 +00004555 IvarOffsetGV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004556 IvarOffsetGV->setSection("__DATA, __objc_const");
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004557 return IvarOffsetGV;
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004558}
4559
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004560/// EmitIvarList - Emit the ivar list for the given
Daniel Dunbar11394522009-04-18 08:51:00 +00004561/// implementation. The return value has type
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004562/// IvarListnfABIPtrTy.
4563/// struct _ivar_t {
4564/// unsigned long int *offset; // pointer to ivar offset location
4565/// char *name;
4566/// char *type;
4567/// uint32_t alignment;
4568/// uint32_t size;
4569/// }
4570/// struct _ivar_list_t {
4571/// uint32 entsize; // sizeof(struct _ivar_t)
4572/// uint32 count;
4573/// struct _iver_t list[count];
4574/// }
4575///
4576llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList(
4577 const ObjCImplementationDecl *ID) {
4578
4579 std::vector<llvm::Constant*> Ivars, Ivar(5);
4580
4581 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4582 assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface");
4583
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004584 // FIXME. Consolidate this with similar code in GenerateClass.
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00004585 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00004586
4587 RecordDecl::field_iterator i,p;
4588 const RecordDecl *RD = GetFirstIvarInRecord(OID, i,p);
Daniel Dunbar91636d62009-04-20 00:33:43 +00004589 // Collect declared and synthesized ivars in a small vector.
Fariborz Jahanian18191882009-03-31 18:11:23 +00004590 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
4591 for (ObjCInterfaceDecl::ivar_iterator I = OID->ivar_begin(),
4592 E = OID->ivar_end(); I != E; ++I)
4593 OIvars.push_back(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +00004594 for (ObjCInterfaceDecl::prop_iterator I = OID->prop_begin(CGM.getContext()),
4595 E = OID->prop_end(CGM.getContext()); I != E; ++I)
Fariborz Jahanian18191882009-03-31 18:11:23 +00004596 if (ObjCIvarDecl *IV = (*I)->getPropertyIvarDecl())
4597 OIvars.push_back(IV);
Fariborz Jahanian99eee362009-04-01 19:37:34 +00004598
Fariborz Jahanian18191882009-03-31 18:11:23 +00004599 unsigned iv = 0;
Douglas Gregor6ab35242009-04-09 21:40:53 +00004600 for (RecordDecl::field_iterator e = RD->field_end(CGM.getContext());
4601 i != e; ++i) {
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004602 FieldDecl *Field = *i;
Daniel Dunbar48fa0642009-04-19 02:03:42 +00004603 Ivar[0] = EmitIvarOffsetVar(ID->getClassInterface(), OIvars[iv++],
4604 GetIvarBaseOffset(Layout, Field));
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004605 if (Field->getIdentifier())
4606 Ivar[1] = GetMethodVarName(Field->getIdentifier());
4607 else
4608 Ivar[1] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Devang Patel7794bb82009-03-04 18:21:39 +00004609 Ivar[2] = GetMethodVarType(Field);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004610 const llvm::Type *FieldTy =
4611 CGM.getTypes().ConvertTypeForMem(Field->getType());
4612 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
4613 unsigned Align = CGM.getContext().getPreferredTypeAlign(
4614 Field->getType().getTypePtr()) >> 3;
4615 Align = llvm::Log2_32(Align);
4616 Ivar[3] = llvm::ConstantInt::get(ObjCTypes.IntTy, Align);
Daniel Dunbar91636d62009-04-20 00:33:43 +00004617 // NOTE. Size of a bitfield does not match gcc's, because of the
4618 // way bitfields are treated special in each. But I am told that
4619 // 'size' for bitfield ivars is ignored by the runtime so it does
4620 // not matter. If it matters, there is enough info to get the
4621 // bitfield right!
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004622 Ivar[4] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4623 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarnfABITy, Ivar));
4624 }
4625 // Return null for empty list.
4626 if (Ivars.empty())
4627 return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4628 std::vector<llvm::Constant*> Values(3);
4629 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.IvarnfABITy);
4630 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4631 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
4632 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarnfABITy,
4633 Ivars.size());
4634 Values[2] = llvm::ConstantArray::get(AT, Ivars);
4635 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4636 const char *Prefix = "\01l_OBJC_$_INSTANCE_VARIABLES_";
4637 llvm::GlobalVariable *GV =
4638 new llvm::GlobalVariable(Init->getType(), false,
4639 llvm::GlobalValue::InternalLinkage,
4640 Init,
4641 Prefix + OID->getNameAsString(),
4642 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004643 GV->setAlignment(
4644 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004645 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004646
4647 UsedGlobals.push_back(GV);
4648 return llvm::ConstantExpr::getBitCast(GV,
4649 ObjCTypes.IvarListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004650}
4651
4652llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef(
4653 const ObjCProtocolDecl *PD) {
4654 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4655
4656 if (!Entry) {
4657 // We use the initializer as a marker of whether this is a forward
4658 // reference or not. At module finalization we add the empty
4659 // contents for protocols which were referenced but never defined.
4660 Entry =
4661 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
4662 llvm::GlobalValue::ExternalLinkage,
4663 0,
4664 "\01l_OBJC_PROTOCOL_$_" + PD->getNameAsString(),
4665 &CGM.getModule());
4666 Entry->setSection("__DATA,__datacoal_nt,coalesced");
4667 UsedGlobals.push_back(Entry);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004668 }
4669
4670 return Entry;
4671}
4672
4673/// GetOrEmitProtocol - Generate the protocol meta-data:
4674/// @code
4675/// struct _protocol_t {
4676/// id isa; // NULL
4677/// const char * const protocol_name;
4678/// const struct _protocol_list_t * protocol_list; // super protocols
4679/// const struct method_list_t * const instance_methods;
4680/// const struct method_list_t * const class_methods;
4681/// const struct method_list_t *optionalInstanceMethods;
4682/// const struct method_list_t *optionalClassMethods;
4683/// const struct _prop_list_t * properties;
4684/// const uint32_t size; // sizeof(struct _protocol_t)
4685/// const uint32_t flags; // = 0
4686/// }
4687/// @endcode
4688///
4689
4690llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol(
4691 const ObjCProtocolDecl *PD) {
4692 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4693
4694 // Early exit if a defining object has already been generated.
4695 if (Entry && Entry->hasInitializer())
4696 return Entry;
4697
4698 const char *ProtocolName = PD->getNameAsCString();
4699
4700 // Construct method lists.
4701 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
4702 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregor6ab35242009-04-09 21:40:53 +00004703 for (ObjCProtocolDecl::instmeth_iterator
4704 i = PD->instmeth_begin(CGM.getContext()),
4705 e = PD->instmeth_end(CGM.getContext());
4706 i != e; ++i) {
Fariborz Jahanianda320092009-01-29 19:24:30 +00004707 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004708 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004709 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4710 OptInstanceMethods.push_back(C);
4711 } else {
4712 InstanceMethods.push_back(C);
4713 }
4714 }
4715
Douglas Gregor6ab35242009-04-09 21:40:53 +00004716 for (ObjCProtocolDecl::classmeth_iterator
4717 i = PD->classmeth_begin(CGM.getContext()),
4718 e = PD->classmeth_end(CGM.getContext());
4719 i != e; ++i) {
Fariborz Jahanianda320092009-01-29 19:24:30 +00004720 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004721 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004722 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4723 OptClassMethods.push_back(C);
4724 } else {
4725 ClassMethods.push_back(C);
4726 }
4727 }
4728
4729 std::vector<llvm::Constant*> Values(10);
4730 // isa is NULL
4731 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ObjectPtrTy);
4732 Values[1] = GetClassName(PD->getIdentifier());
4733 Values[2] = EmitProtocolList(
4734 "\01l_OBJC_$_PROTOCOL_REFS_" + PD->getNameAsString(),
4735 PD->protocol_begin(),
4736 PD->protocol_end());
4737
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004738 Values[3] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004739 + PD->getNameAsString(),
4740 "__DATA, __objc_const",
4741 InstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004742 Values[4] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004743 + PD->getNameAsString(),
4744 "__DATA, __objc_const",
4745 ClassMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004746 Values[5] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004747 + PD->getNameAsString(),
4748 "__DATA, __objc_const",
4749 OptInstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004750 Values[6] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004751 + PD->getNameAsString(),
4752 "__DATA, __objc_const",
4753 OptClassMethods);
4754 Values[7] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + PD->getNameAsString(),
4755 0, PD, ObjCTypes);
4756 uint32_t Size =
4757 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolnfABITy);
4758 Values[8] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4759 Values[9] = llvm::Constant::getNullValue(ObjCTypes.IntTy);
4760 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolnfABITy,
4761 Values);
4762
4763 if (Entry) {
4764 // Already created, fix the linkage and update the initializer.
Mike Stump286acbd2009-03-07 16:33:28 +00004765 Entry->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004766 Entry->setInitializer(Init);
4767 } else {
4768 Entry =
4769 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004770 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004771 Init,
4772 std::string("\01l_OBJC_PROTOCOL_$_")+ProtocolName,
4773 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004774 Entry->setAlignment(
4775 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABITy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004776 Entry->setSection("__DATA,__datacoal_nt,coalesced");
Fariborz Jahanianda320092009-01-29 19:24:30 +00004777 }
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004778 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
4779
4780 // Use this protocol meta-data to build protocol list table in section
4781 // __DATA, __objc_protolist
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004782 llvm::GlobalVariable *PTGV = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004783 ObjCTypes.ProtocolnfABIPtrTy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004784 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004785 Entry,
4786 std::string("\01l_OBJC_LABEL_PROTOCOL_$_")
4787 +ProtocolName,
4788 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004789 PTGV->setAlignment(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004790 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABIPtrTy));
Daniel Dunbar0bf21992009-04-15 02:56:18 +00004791 PTGV->setSection("__DATA, __objc_protolist, coalesced, no_dead_strip");
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004792 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4793 UsedGlobals.push_back(PTGV);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004794 return Entry;
4795}
4796
4797/// EmitProtocolList - Generate protocol list meta-data:
4798/// @code
4799/// struct _protocol_list_t {
4800/// long protocol_count; // Note, this is 32/64 bit
4801/// struct _protocol_t[protocol_count];
4802/// }
4803/// @endcode
4804///
4805llvm::Constant *
4806CGObjCNonFragileABIMac::EmitProtocolList(const std::string &Name,
4807 ObjCProtocolDecl::protocol_iterator begin,
4808 ObjCProtocolDecl::protocol_iterator end) {
4809 std::vector<llvm::Constant*> ProtocolRefs;
4810
Fariborz Jahanianda320092009-01-29 19:24:30 +00004811 // Just return null for empty protocol lists
Daniel Dunbar948e2582009-02-15 07:36:20 +00004812 if (begin == end)
Fariborz Jahanianda320092009-01-29 19:24:30 +00004813 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4814
Daniel Dunbar948e2582009-02-15 07:36:20 +00004815 // FIXME: We shouldn't need to do this lookup here, should we?
Fariborz Jahanianda320092009-01-29 19:24:30 +00004816 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
4817 if (GV)
Daniel Dunbar948e2582009-02-15 07:36:20 +00004818 return llvm::ConstantExpr::getBitCast(GV,
4819 ObjCTypes.ProtocolListnfABIPtrTy);
4820
4821 for (; begin != end; ++begin)
4822 ProtocolRefs.push_back(GetProtocolRef(*begin)); // Implemented???
4823
Fariborz Jahanianda320092009-01-29 19:24:30 +00004824 // This list is null terminated.
4825 ProtocolRefs.push_back(llvm::Constant::getNullValue(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004826 ObjCTypes.ProtocolnfABIPtrTy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004827
4828 std::vector<llvm::Constant*> Values(2);
4829 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
4830 Values[1] =
Daniel Dunbar948e2582009-02-15 07:36:20 +00004831 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolnfABIPtrTy,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004832 ProtocolRefs.size()),
4833 ProtocolRefs);
4834
4835 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4836 GV = new llvm::GlobalVariable(Init->getType(), false,
4837 llvm::GlobalValue::InternalLinkage,
4838 Init,
4839 Name,
4840 &CGM.getModule());
4841 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004842 GV->setAlignment(
4843 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004844 UsedGlobals.push_back(GV);
Daniel Dunbar948e2582009-02-15 07:36:20 +00004845 return llvm::ConstantExpr::getBitCast(GV,
4846 ObjCTypes.ProtocolListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004847}
4848
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004849/// GetMethodDescriptionConstant - This routine build following meta-data:
4850/// struct _objc_method {
4851/// SEL _cmd;
4852/// char *method_type;
4853/// char *_imp;
4854/// }
4855
4856llvm::Constant *
4857CGObjCNonFragileABIMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
4858 std::vector<llvm::Constant*> Desc(3);
4859 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4860 ObjCTypes.SelectorPtrTy);
4861 Desc[1] = GetMethodVarType(MD);
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004862 // Protocol methods have no implementation. So, this entry is always NULL.
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004863 Desc[2] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
4864 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Desc);
4865}
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004866
4867/// EmitObjCValueForIvar - Code Gen for nonfragile ivar reference.
4868/// This code gen. amounts to generating code for:
4869/// @code
4870/// (type *)((char *)base + _OBJC_IVAR_$_.ivar;
4871/// @encode
4872///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004873LValue CGObjCNonFragileABIMac::EmitObjCValueForIvar(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004874 CodeGen::CodeGenFunction &CGF,
4875 QualType ObjectTy,
4876 llvm::Value *BaseValue,
4877 const ObjCIvarDecl *Ivar,
4878 const FieldDecl *Field,
4879 unsigned CVRQualifiers) {
4880 assert(ObjectTy->isObjCInterfaceType() &&
4881 "CGObjCNonFragileABIMac::EmitObjCValueForIvar");
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004882 ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00004883 llvm::GlobalVariable *IvarOffsetGV = ObjCIvarOffsetVariable(ID, Ivar);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004884
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004885 // (char *) BaseValue
Chris Lattner51123fe2009-04-17 17:46:19 +00004886 llvm::Value *V = CGF.Builder.CreateBitCast(BaseValue, ObjCTypes.Int8PtrTy);
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004887 llvm::Value *Offset = CGF.Builder.CreateLoad(IvarOffsetGV);
4888 // (char*)BaseValue + Offset_symbol
4889 V = CGF.Builder.CreateGEP(V, Offset, "add.ptr");
4890 // (type *)((char*)BaseValue + Offset_symbol)
4891 const llvm::Type *IvarTy =
Chris Lattner51123fe2009-04-17 17:46:19 +00004892 CGM.getTypes().ConvertTypeForMem(Ivar->getType());
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004893 llvm::Type *ptrIvarTy = llvm::PointerType::getUnqual(IvarTy);
4894 V = CGF.Builder.CreateBitCast(V, ptrIvarTy);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004895
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00004896 if (Ivar->isBitField()) {
Chris Lattner51123fe2009-04-17 17:46:19 +00004897 QualType FieldTy = Field->getType();
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00004898 CodeGenTypes::BitFieldInfo bitFieldInfo =
4899 CGM.getTypes().getBitFieldInfo(Field);
4900 return LValue::MakeBitfield(V, bitFieldInfo.Begin, bitFieldInfo.Size,
Chris Lattner51123fe2009-04-17 17:46:19 +00004901 FieldTy->isSignedIntegerType(),
4902 FieldTy.getCVRQualifiers()|CVRQualifiers);
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00004903 }
4904
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004905 LValue LV = LValue::MakeAddr(V,
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004906 Ivar->getType().getCVRQualifiers()|CVRQualifiers,
4907 CGM.getContext().getObjCGCAttrKind(Ivar->getType()));
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004908 LValue::SetObjCIvar(LV, true);
4909 return LV;
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004910}
4911
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004912llvm::Value *CGObjCNonFragileABIMac::EmitIvarOffset(
4913 CodeGen::CodeGenFunction &CGF,
4914 ObjCInterfaceDecl *Interface,
4915 const ObjCIvarDecl *Ivar) {
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00004916 return CGF.Builder.CreateLoad(ObjCIvarOffsetVariable(Interface, Ivar),
4917 false, "ivar");
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004918}
4919
Fariborz Jahanian46551122009-02-04 00:22:57 +00004920CodeGen::RValue CGObjCNonFragileABIMac::EmitMessageSend(
4921 CodeGen::CodeGenFunction &CGF,
4922 QualType ResultType,
4923 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004924 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +00004925 QualType Arg0Ty,
4926 bool IsSuper,
4927 const CallArgList &CallArgs) {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004928 // FIXME. Even though IsSuper is passes. This function doese not
4929 // handle calls to 'super' receivers.
4930 CodeGenTypes &Types = CGM.getTypes();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004931 llvm::Value *Arg0 = Receiver;
4932 if (!IsSuper)
4933 Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy, "tmp");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004934
4935 // Find the message function name.
Fariborz Jahanianef163782009-02-05 01:13:09 +00004936 // FIXME. This is too much work to get the ABI-specific result type
4937 // needed to find the message name.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004938 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType,
4939 llvm::SmallVector<QualType, 16>());
4940 llvm::Constant *Fn;
4941 std::string Name("\01l_");
4942 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004943#if 0
4944 // unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004945 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
4946 Fn = ObjCTypes.MessageSendIdStretFixupFn;
4947 // FIXME. Is there a better way of getting these names.
4948 // They are available in RuntimeFunctions vector pair.
4949 Name += "objc_msgSendId_stret_fixup";
4950 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004951 else
4952#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004953 if (IsSuper) {
4954 Fn = ObjCTypes.MessageSendSuper2StretFixupFn;
4955 Name += "objc_msgSendSuper2_stret_fixup";
4956 }
4957 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004958 {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004959 Fn = ObjCTypes.MessageSendStretFixupFn;
4960 Name += "objc_msgSend_stret_fixup";
4961 }
4962 }
Fariborz Jahanian1a6b3682009-02-05 19:35:43 +00004963 else if (ResultType->isFloatingType() &&
4964 // Selection of frret API only happens in 32bit nonfragile ABI.
4965 CGM.getTargetData().getTypePaddedSize(ObjCTypes.LongTy) == 4) {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004966 Fn = ObjCTypes.MessageSendFpretFixupFn;
4967 Name += "objc_msgSend_fpret_fixup";
4968 }
4969 else {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004970#if 0
4971// unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004972 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
4973 Fn = ObjCTypes.MessageSendIdFixupFn;
4974 Name += "objc_msgSendId_fixup";
4975 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004976 else
4977#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004978 if (IsSuper) {
4979 Fn = ObjCTypes.MessageSendSuper2FixupFn;
4980 Name += "objc_msgSendSuper2_fixup";
4981 }
4982 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004983 {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004984 Fn = ObjCTypes.MessageSendFixupFn;
4985 Name += "objc_msgSend_fixup";
4986 }
4987 }
4988 Name += '_';
4989 std::string SelName(Sel.getAsString());
4990 // Replace all ':' in selector name with '_' ouch!
4991 for(unsigned i = 0; i < SelName.size(); i++)
4992 if (SelName[i] == ':')
4993 SelName[i] = '_';
4994 Name += SelName;
4995 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
4996 if (!GV) {
Daniel Dunbar33af70f2009-04-15 19:03:14 +00004997 // Build message ref table entry.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004998 std::vector<llvm::Constant*> Values(2);
4999 Values[0] = Fn;
5000 Values[1] = GetMethodVarName(Sel);
5001 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
5002 GV = new llvm::GlobalVariable(Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00005003 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005004 Init,
5005 Name,
5006 &CGM.getModule());
5007 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbarf59c1a62009-04-15 19:04:46 +00005008 GV->setAlignment(16);
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005009 GV->setSection("__DATA, __objc_msgrefs, coalesced");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005010 }
5011 llvm::Value *Arg1 = CGF.Builder.CreateBitCast(GV, ObjCTypes.MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00005012
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005013 CallArgList ActualArgs;
5014 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
5015 ActualArgs.push_back(std::make_pair(RValue::get(Arg1),
5016 ObjCTypes.MessageRefCPtrTy));
5017 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Fariborz Jahanianef163782009-02-05 01:13:09 +00005018 const CGFunctionInfo &FnInfo1 = Types.getFunctionInfo(ResultType, ActualArgs);
5019 llvm::Value *Callee = CGF.Builder.CreateStructGEP(Arg1, 0);
5020 Callee = CGF.Builder.CreateLoad(Callee);
Fariborz Jahanian3ab75bd2009-02-14 21:25:36 +00005021 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo1, true);
Fariborz Jahanianef163782009-02-05 01:13:09 +00005022 Callee = CGF.Builder.CreateBitCast(Callee,
5023 llvm::PointerType::getUnqual(FTy));
5024 return CGF.EmitCall(FnInfo1, Callee, ActualArgs);
Fariborz Jahanian46551122009-02-04 00:22:57 +00005025}
5026
5027/// Generate code for a message send expression in the nonfragile abi.
5028CodeGen::RValue CGObjCNonFragileABIMac::GenerateMessageSend(
5029 CodeGen::CodeGenFunction &CGF,
5030 QualType ResultType,
5031 Selector Sel,
5032 llvm::Value *Receiver,
5033 bool IsClassMessage,
5034 const CallArgList &CallArgs) {
Fariborz Jahanian46551122009-02-04 00:22:57 +00005035 return EmitMessageSend(CGF, ResultType, Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005036 Receiver, CGF.getContext().getObjCIdType(),
Fariborz Jahanian46551122009-02-04 00:22:57 +00005037 false, CallArgs);
5038}
5039
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005040llvm::GlobalVariable *
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005041CGObjCNonFragileABIMac::GetClassGlobal(const std::string &Name) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005042 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5043
Daniel Dunbardfff2302009-03-02 05:18:14 +00005044 if (!GV) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005045 GV = new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
5046 llvm::GlobalValue::ExternalLinkage,
5047 0, Name, &CGM.getModule());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005048 }
5049
5050 return GV;
5051}
5052
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005053llvm::Value *CGObjCNonFragileABIMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar11394522009-04-18 08:51:00 +00005054 const ObjCInterfaceDecl *ID) {
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005055 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
5056
5057 if (!Entry) {
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005058 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005059 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005060 Entry =
5061 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5062 llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005063 ClassGV,
Daniel Dunbar11394522009-04-18 08:51:00 +00005064 "\01L_OBJC_CLASSLIST_REFERENCES_$_",
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005065 &CGM.getModule());
5066 Entry->setAlignment(
5067 CGM.getTargetData().getPrefTypeAlignment(
5068 ObjCTypes.ClassnfABIPtrTy));
Daniel Dunbar11394522009-04-18 08:51:00 +00005069 Entry->setSection("__DATA, __objc_classrefs, regular, no_dead_strip");
5070 UsedGlobals.push_back(Entry);
5071 }
5072
5073 return Builder.CreateLoad(Entry, false, "tmp");
5074}
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005075
Daniel Dunbar11394522009-04-18 08:51:00 +00005076llvm::Value *
5077CGObjCNonFragileABIMac::EmitSuperClassRef(CGBuilderTy &Builder,
5078 const ObjCInterfaceDecl *ID) {
5079 llvm::GlobalVariable *&Entry = SuperClassReferences[ID->getIdentifier()];
5080
5081 if (!Entry) {
5082 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
5083 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
5084 Entry =
5085 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5086 llvm::GlobalValue::InternalLinkage,
5087 ClassGV,
5088 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5089 &CGM.getModule());
5090 Entry->setAlignment(
5091 CGM.getTargetData().getPrefTypeAlignment(
5092 ObjCTypes.ClassnfABIPtrTy));
5093 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005094 UsedGlobals.push_back(Entry);
5095 }
5096
5097 return Builder.CreateLoad(Entry, false, "tmp");
5098}
5099
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005100/// EmitMetaClassRef - Return a Value * of the address of _class_t
5101/// meta-data
5102///
5103llvm::Value *CGObjCNonFragileABIMac::EmitMetaClassRef(CGBuilderTy &Builder,
5104 const ObjCInterfaceDecl *ID) {
5105 llvm::GlobalVariable * &Entry = MetaClassReferences[ID->getIdentifier()];
5106 if (Entry)
5107 return Builder.CreateLoad(Entry, false, "tmp");
5108
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005109 std::string MetaClassName(getMetaclassSymbolPrefix() + ID->getNameAsString());
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005110 llvm::GlobalVariable *MetaClassGV = GetClassGlobal(MetaClassName);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005111 Entry =
5112 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5113 llvm::GlobalValue::InternalLinkage,
5114 MetaClassGV,
5115 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5116 &CGM.getModule());
5117 Entry->setAlignment(
5118 CGM.getTargetData().getPrefTypeAlignment(
5119 ObjCTypes.ClassnfABIPtrTy));
5120
Daniel Dunbar33af70f2009-04-15 19:03:14 +00005121 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005122 UsedGlobals.push_back(Entry);
5123
5124 return Builder.CreateLoad(Entry, false, "tmp");
5125}
5126
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005127/// GetClass - Return a reference to the class for the given interface
5128/// decl.
5129llvm::Value *CGObjCNonFragileABIMac::GetClass(CGBuilderTy &Builder,
5130 const ObjCInterfaceDecl *ID) {
5131 return EmitClassRef(Builder, ID);
5132}
5133
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005134/// Generates a message send where the super is the receiver. This is
5135/// a message send to self with special delivery semantics indicating
5136/// which class's method should be called.
5137CodeGen::RValue
5138CGObjCNonFragileABIMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
5139 QualType ResultType,
5140 Selector Sel,
5141 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005142 bool isCategoryImpl,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005143 llvm::Value *Receiver,
5144 bool IsClassMessage,
5145 const CodeGen::CallArgList &CallArgs) {
5146 // ...
5147 // Create and init a super structure; this is a (receiver, class)
5148 // pair we will pass to objc_msgSendSuper.
5149 llvm::Value *ObjCSuper =
5150 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
5151
5152 llvm::Value *ReceiverAsObject =
5153 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
5154 CGF.Builder.CreateStore(ReceiverAsObject,
5155 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
5156
5157 // If this is a class message the metaclass is passed as the target.
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005158 llvm::Value *Target;
5159 if (IsClassMessage) {
5160 if (isCategoryImpl) {
5161 // Message sent to "super' in a class method defined in
5162 // a category implementation.
Daniel Dunbar11394522009-04-18 08:51:00 +00005163 Target = EmitClassRef(CGF.Builder, Class);
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005164 Target = CGF.Builder.CreateStructGEP(Target, 0);
5165 Target = CGF.Builder.CreateLoad(Target);
5166 }
5167 else
5168 Target = EmitMetaClassRef(CGF.Builder, Class);
5169 }
5170 else
Daniel Dunbar11394522009-04-18 08:51:00 +00005171 Target = EmitSuperClassRef(CGF.Builder, Class);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005172
5173 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
5174 // and ObjCTypes types.
5175 const llvm::Type *ClassTy =
5176 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
5177 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
5178 CGF.Builder.CreateStore(Target,
5179 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
5180
5181 return EmitMessageSend(CGF, ResultType, Sel,
5182 ObjCSuper, ObjCTypes.SuperPtrCTy,
5183 true, CallArgs);
5184}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005185
5186llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CGBuilderTy &Builder,
5187 Selector Sel) {
5188 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
5189
5190 if (!Entry) {
5191 llvm::Constant *Casted =
5192 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
5193 ObjCTypes.SelectorPtrTy);
5194 Entry =
5195 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
5196 llvm::GlobalValue::InternalLinkage,
5197 Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
5198 &CGM.getModule());
5199 Entry->setSection("__DATA,__objc_selrefs,literal_pointers,no_dead_strip");
5200 UsedGlobals.push_back(Entry);
5201 }
5202
5203 return Builder.CreateLoad(Entry, false, "tmp");
5204}
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005205/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
5206/// objc_assign_ivar (id src, id *dst)
5207///
5208void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
5209 llvm::Value *src, llvm::Value *dst)
5210{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005211 const llvm::Type * SrcTy = src->getType();
5212 if (!isa<llvm::PointerType>(SrcTy)) {
5213 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5214 assert(Size <= 8 && "does not support size > 8");
5215 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5216 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005217 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5218 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005219 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5220 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5221 CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn,
5222 src, dst, "assignivar");
5223 return;
5224}
5225
5226/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
5227/// objc_assign_strongCast (id src, id *dst)
5228///
5229void CGObjCNonFragileABIMac::EmitObjCStrongCastAssign(
5230 CodeGen::CodeGenFunction &CGF,
5231 llvm::Value *src, llvm::Value *dst)
5232{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005233 const llvm::Type * SrcTy = src->getType();
5234 if (!isa<llvm::PointerType>(SrcTy)) {
5235 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5236 assert(Size <= 8 && "does not support size > 8");
5237 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5238 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005239 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5240 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005241 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5242 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5243 CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn,
5244 src, dst, "weakassign");
5245 return;
5246}
5247
5248/// EmitObjCWeakRead - Code gen for loading value of a __weak
5249/// object: objc_read_weak (id *src)
5250///
5251llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead(
5252 CodeGen::CodeGenFunction &CGF,
5253 llvm::Value *AddrWeakObj)
5254{
Eli Friedman8339b352009-03-07 03:57:15 +00005255 const llvm::Type* DestTy =
5256 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005257 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
5258 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
5259 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00005260 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005261 return read_weak;
5262}
5263
5264/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
5265/// objc_assign_weak (id src, id *dst)
5266///
5267void CGObjCNonFragileABIMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
5268 llvm::Value *src, llvm::Value *dst)
5269{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005270 const llvm::Type * SrcTy = src->getType();
5271 if (!isa<llvm::PointerType>(SrcTy)) {
5272 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5273 assert(Size <= 8 && "does not support size > 8");
5274 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5275 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005276 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5277 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005278 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5279 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattner96508e12009-04-17 22:12:36 +00005280 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005281 src, dst, "weakassign");
5282 return;
5283}
5284
5285/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
5286/// objc_assign_global (id src, id *dst)
5287///
5288void CGObjCNonFragileABIMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
5289 llvm::Value *src, llvm::Value *dst)
5290{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005291 const llvm::Type * SrcTy = src->getType();
5292 if (!isa<llvm::PointerType>(SrcTy)) {
5293 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5294 assert(Size <= 8 && "does not support size > 8");
5295 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5296 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005297 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5298 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005299 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5300 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5301 CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn,
5302 src, dst, "globalassign");
5303 return;
5304}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005305
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005306void
5307CGObjCNonFragileABIMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
5308 const Stmt &S) {
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005309 bool isTry = isa<ObjCAtTryStmt>(S);
5310 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
5311 llvm::BasicBlock *PrevLandingPad = CGF.getInvokeDest();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005312 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005313 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005314 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005315 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
5316
5317 // For @synchronized, call objc_sync_enter(sync.expr). The
5318 // evaluation of the expression must occur before we enter the
5319 // @synchronized. We can safely avoid a temp here because jumps into
5320 // @synchronized are illegal & this will dominate uses.
5321 llvm::Value *SyncArg = 0;
5322 if (!isTry) {
5323 SyncArg =
5324 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
5325 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005326 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005327 }
5328
5329 // Push an EH context entry, used for handling rethrows and jumps
5330 // through finally.
5331 CGF.PushCleanupBlock(FinallyBlock);
5332
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005333 CGF.setInvokeDest(TryHandler);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005334
5335 CGF.EmitBlock(TryBlock);
5336 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
5337 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
5338 CGF.EmitBranchThroughCleanup(FinallyEnd);
5339
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005340 // Emit the exception handler.
5341
5342 CGF.EmitBlock(TryHandler);
5343
5344 llvm::Value *llvm_eh_exception =
5345 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_exception);
5346 llvm::Value *llvm_eh_selector_i64 =
5347 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector_i64);
5348 llvm::Value *llvm_eh_typeid_for_i64 =
5349 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for_i64);
5350 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5351 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(Exc->getType(), "_rethrow");
5352
5353 llvm::SmallVector<llvm::Value*, 8> SelectorArgs;
5354 SelectorArgs.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005355 SelectorArgs.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005356
5357 // Construct the lists of (type, catch body) to handle.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005358 llvm::SmallVector<std::pair<const ParmVarDecl*, const Stmt*>, 8> Handlers;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005359 bool HasCatchAll = false;
5360 if (isTry) {
5361 if (const ObjCAtCatchStmt* CatchStmt =
5362 cast<ObjCAtTryStmt>(S).getCatchStmts()) {
5363 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005364 const ParmVarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
Steve Naroff7ba138a2009-03-03 19:52:17 +00005365 Handlers.push_back(std::make_pair(CatchDecl, CatchStmt->getCatchBody()));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005366
5367 // catch(...) always matches.
Steve Naroff7ba138a2009-03-03 19:52:17 +00005368 if (!CatchDecl) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005369 // Use i8* null here to signal this is a catch all, not a cleanup.
5370 llvm::Value *Null = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
5371 SelectorArgs.push_back(Null);
5372 HasCatchAll = true;
5373 break;
5374 }
5375
Daniel Dunbarede8de92009-03-06 00:01:21 +00005376 if (CGF.getContext().isObjCIdType(CatchDecl->getType()) ||
5377 CatchDecl->getType()->isObjCQualifiedIdType()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005378 llvm::Value *IDEHType =
5379 CGM.getModule().getGlobalVariable("OBJC_EHTYPE_id");
5380 if (!IDEHType)
5381 IDEHType =
5382 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5383 llvm::GlobalValue::ExternalLinkage,
5384 0, "OBJC_EHTYPE_id", &CGM.getModule());
5385 SelectorArgs.push_back(IDEHType);
5386 HasCatchAll = true;
5387 break;
5388 }
5389
5390 // All other types should be Objective-C interface pointer types.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005391 const PointerType *PT = CatchDecl->getType()->getAsPointerType();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005392 assert(PT && "Invalid @catch type.");
5393 const ObjCInterfaceType *IT =
5394 PT->getPointeeType()->getAsObjCInterfaceType();
5395 assert(IT && "Invalid @catch type.");
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005396 llvm::Value *EHType = GetInterfaceEHType(IT->getDecl(), false);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005397 SelectorArgs.push_back(EHType);
5398 }
5399 }
5400 }
5401
5402 // We use a cleanup unless there was already a catch all.
5403 if (!HasCatchAll) {
5404 SelectorArgs.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
Daniel Dunbarede8de92009-03-06 00:01:21 +00005405 Handlers.push_back(std::make_pair((const ParmVarDecl*) 0, (const Stmt*) 0));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005406 }
5407
5408 llvm::Value *Selector =
5409 CGF.Builder.CreateCall(llvm_eh_selector_i64,
5410 SelectorArgs.begin(), SelectorArgs.end(),
5411 "selector");
5412 for (unsigned i = 0, e = Handlers.size(); i != e; ++i) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005413 const ParmVarDecl *CatchParam = Handlers[i].first;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005414 const Stmt *CatchBody = Handlers[i].second;
5415
5416 llvm::BasicBlock *Next = 0;
5417
5418 // The last handler always matches.
5419 if (i + 1 != e) {
5420 assert(CatchParam && "Only last handler can be a catch all.");
5421
5422 llvm::BasicBlock *Match = CGF.createBasicBlock("match");
5423 Next = CGF.createBasicBlock("catch.next");
5424 llvm::Value *Id =
5425 CGF.Builder.CreateCall(llvm_eh_typeid_for_i64,
5426 CGF.Builder.CreateBitCast(SelectorArgs[i+2],
5427 ObjCTypes.Int8PtrTy));
5428 CGF.Builder.CreateCondBr(CGF.Builder.CreateICmpEQ(Selector, Id),
5429 Match, Next);
5430
5431 CGF.EmitBlock(Match);
5432 }
5433
5434 if (CatchBody) {
5435 llvm::BasicBlock *MatchEnd = CGF.createBasicBlock("match.end");
5436 llvm::BasicBlock *MatchHandler = CGF.createBasicBlock("match.handler");
5437
5438 // Cleanups must call objc_end_catch.
5439 //
5440 // FIXME: It seems incorrect for objc_begin_catch to be inside
5441 // this context, but this matches gcc.
5442 CGF.PushCleanupBlock(MatchEnd);
5443 CGF.setInvokeDest(MatchHandler);
5444
5445 llvm::Value *ExcObject =
5446 CGF.Builder.CreateCall(ObjCTypes.ObjCBeginCatchFn, Exc);
5447
5448 // Bind the catch parameter if it exists.
5449 if (CatchParam) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005450 ExcObject =
5451 CGF.Builder.CreateBitCast(ExcObject,
5452 CGF.ConvertType(CatchParam->getType()));
5453 // CatchParam is a ParmVarDecl because of the grammar
5454 // construction used to handle this, but for codegen purposes
5455 // we treat this as a local decl.
5456 CGF.EmitLocalBlockVarDecl(*CatchParam);
5457 CGF.Builder.CreateStore(ExcObject, CGF.GetAddrOfLocalVar(CatchParam));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005458 }
5459
5460 CGF.ObjCEHValueStack.push_back(ExcObject);
5461 CGF.EmitStmt(CatchBody);
5462 CGF.ObjCEHValueStack.pop_back();
5463
5464 CGF.EmitBranchThroughCleanup(FinallyEnd);
5465
5466 CGF.EmitBlock(MatchHandler);
5467
5468 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5469 // We are required to emit this call to satisfy LLVM, even
5470 // though we don't use the result.
5471 llvm::SmallVector<llvm::Value*, 8> Args;
5472 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005473 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005474 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5475 0));
5476 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5477 CGF.Builder.CreateStore(Exc, RethrowPtr);
5478 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5479
5480 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5481
5482 CGF.EmitBlock(MatchEnd);
5483
5484 // Unfortunately, we also have to generate another EH frame here
5485 // in case this throws.
5486 llvm::BasicBlock *MatchEndHandler =
5487 CGF.createBasicBlock("match.end.handler");
5488 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
5489 CGF.Builder.CreateInvoke(ObjCTypes.ObjCEndCatchFn,
5490 Cont, MatchEndHandler,
5491 Args.begin(), Args.begin());
5492
5493 CGF.EmitBlock(Cont);
5494 if (Info.SwitchBlock)
5495 CGF.EmitBlock(Info.SwitchBlock);
5496 if (Info.EndBlock)
5497 CGF.EmitBlock(Info.EndBlock);
5498
5499 CGF.EmitBlock(MatchEndHandler);
5500 Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5501 // We are required to emit this call to satisfy LLVM, even
5502 // though we don't use the result.
5503 Args.clear();
5504 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005505 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005506 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5507 0));
5508 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5509 CGF.Builder.CreateStore(Exc, RethrowPtr);
5510 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5511
5512 if (Next)
5513 CGF.EmitBlock(Next);
5514 } else {
5515 assert(!Next && "catchup should be last handler.");
5516
5517 CGF.Builder.CreateStore(Exc, RethrowPtr);
5518 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5519 }
5520 }
5521
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005522 // Pop the cleanup entry, the @finally is outside this cleanup
5523 // scope.
5524 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5525 CGF.setInvokeDest(PrevLandingPad);
5526
5527 CGF.EmitBlock(FinallyBlock);
5528
5529 if (isTry) {
5530 if (const ObjCAtFinallyStmt* FinallyStmt =
5531 cast<ObjCAtTryStmt>(S).getFinallyStmt())
5532 CGF.EmitStmt(FinallyStmt->getFinallyBody());
5533 } else {
5534 // Emit 'objc_sync_exit(expr)' as finally's sole statement for
5535 // @synchronized.
5536 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, SyncArg);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005537 }
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005538
5539 if (Info.SwitchBlock)
5540 CGF.EmitBlock(Info.SwitchBlock);
5541 if (Info.EndBlock)
5542 CGF.EmitBlock(Info.EndBlock);
5543
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005544 // Branch around the rethrow code.
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005545 CGF.EmitBranch(FinallyEnd);
5546
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005547 CGF.EmitBlock(FinallyRethrow);
5548 CGF.Builder.CreateCall(ObjCTypes.UnwindResumeOrRethrowFn,
5549 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005550 CGF.Builder.CreateUnreachable();
5551
5552 CGF.EmitBlock(FinallyEnd);
5553}
5554
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005555/// EmitThrowStmt - Generate code for a throw statement.
5556void CGObjCNonFragileABIMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
5557 const ObjCAtThrowStmt &S) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005558 llvm::Value *Exception;
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005559 if (const Expr *ThrowExpr = S.getThrowExpr()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005560 Exception = CGF.EmitScalarExpr(ThrowExpr);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005561 } else {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005562 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
5563 "Unexpected rethrow outside @catch block.");
5564 Exception = CGF.ObjCEHValueStack.back();
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005565 }
5566
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005567 llvm::Value *ExceptionAsObject =
5568 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
5569 llvm::BasicBlock *InvokeDest = CGF.getInvokeDest();
5570 if (InvokeDest) {
5571 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
5572 CGF.Builder.CreateInvoke(ObjCTypes.ExceptionThrowFn,
5573 Cont, InvokeDest,
5574 &ExceptionAsObject, &ExceptionAsObject + 1);
5575 CGF.EmitBlock(Cont);
5576 } else
5577 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
5578 CGF.Builder.CreateUnreachable();
5579
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005580 // Clear the insertion point to indicate we are in unreachable code.
5581 CGF.Builder.ClearInsertionPoint();
5582}
Daniel Dunbare588b992009-03-01 04:46:24 +00005583
5584llvm::Value *
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005585CGObjCNonFragileABIMac::GetInterfaceEHType(const ObjCInterfaceDecl *ID,
5586 bool ForDefinition) {
Daniel Dunbare588b992009-03-01 04:46:24 +00005587 llvm::GlobalVariable * &Entry = EHTypeReferences[ID->getIdentifier()];
Daniel Dunbare588b992009-03-01 04:46:24 +00005588
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005589 // If we don't need a definition, return the entry if found or check
5590 // if we use an external reference.
5591 if (!ForDefinition) {
5592 if (Entry)
5593 return Entry;
Daniel Dunbar7e075cb2009-04-07 06:43:45 +00005594
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005595 // If this type (or a super class) has the __objc_exception__
5596 // attribute, emit an external reference.
5597 if (hasObjCExceptionAttribute(ID))
5598 return Entry =
5599 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5600 llvm::GlobalValue::ExternalLinkage,
5601 0,
5602 (std::string("OBJC_EHTYPE_$_") +
5603 ID->getIdentifier()->getName()),
5604 &CGM.getModule());
5605 }
5606
5607 // Otherwise we need to either make a new entry or fill in the
5608 // initializer.
5609 assert((!Entry || !Entry->hasInitializer()) && "Duplicate EHType definition");
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005610 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbare588b992009-03-01 04:46:24 +00005611 std::string VTableName = "objc_ehtype_vtable";
5612 llvm::GlobalVariable *VTableGV =
5613 CGM.getModule().getGlobalVariable(VTableName);
5614 if (!VTableGV)
5615 VTableGV = new llvm::GlobalVariable(ObjCTypes.Int8PtrTy, false,
5616 llvm::GlobalValue::ExternalLinkage,
5617 0, VTableName, &CGM.getModule());
5618
5619 llvm::Value *VTableIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, 2);
5620
5621 std::vector<llvm::Constant*> Values(3);
5622 Values[0] = llvm::ConstantExpr::getGetElementPtr(VTableGV, &VTableIdx, 1);
5623 Values[1] = GetClassName(ID->getIdentifier());
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005624 Values[2] = GetClassGlobal(ClassName);
Daniel Dunbare588b992009-03-01 04:46:24 +00005625 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.EHTypeTy, Values);
5626
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005627 if (Entry) {
5628 Entry->setInitializer(Init);
5629 } else {
5630 Entry = new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5631 llvm::GlobalValue::WeakAnyLinkage,
5632 Init,
5633 (std::string("OBJC_EHTYPE_$_") +
5634 ID->getIdentifier()->getName()),
5635 &CGM.getModule());
5636 }
5637
Daniel Dunbar04d40782009-04-14 06:00:08 +00005638 if (CGM.getLangOptions().getVisibilityMode() == LangOptions::Hidden)
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005639 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005640 Entry->setAlignment(8);
5641
5642 if (ForDefinition) {
5643 Entry->setSection("__DATA,__objc_const");
5644 Entry->setLinkage(llvm::GlobalValue::ExternalLinkage);
5645 } else {
5646 Entry->setSection("__DATA,__datacoal_nt,coalesced");
5647 }
Daniel Dunbare588b992009-03-01 04:46:24 +00005648
5649 return Entry;
5650}
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005651
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00005652/* *** */
5653
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00005654CodeGen::CGObjCRuntime *
5655CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00005656 return new CGObjCMac(CGM);
5657}
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005658
5659CodeGen::CGObjCRuntime *
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00005660CodeGen::CreateMacNonFragileABIObjCRuntime(CodeGen::CodeGenModule &CGM) {
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00005661 return new CGObjCNonFragileABIMac(CGM);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005662}