blob: 0c7b6f6160fb8ce4bb99b512dcb35ad45dfc6e47 [file] [log] [blame]
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001//===------- CGObjCMac.cpp - Interface to Apple Objective-C Runtime -------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This provides Objective-C code generation targetting the Apple runtime.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CGObjCRuntime.h"
Daniel Dunbarf77ac862008-08-11 21:35:06 +000015
16#include "CodeGenModule.h"
Daniel Dunbarb7ec2462008-08-16 03:19:19 +000017#include "CodeGenFunction.h"
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000018#include "clang/AST/ASTContext.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000019#include "clang/AST/Decl.h"
Daniel Dunbar6efc0c52008-08-13 03:21:16 +000020#include "clang/AST/DeclObjC.h"
Daniel Dunbarf77ac862008-08-11 21:35:06 +000021#include "clang/Basic/LangOptions.h"
22
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +000023#include "llvm/Intrinsics.h"
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000024#include "llvm/Module.h"
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +000025#include "llvm/ADT/DenseSet.h"
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +000026#include "llvm/Target/TargetData.h"
Daniel Dunbarb7ec2462008-08-16 03:19:19 +000027#include <sstream>
Daniel Dunbarc17a4d32008-08-11 02:45:11 +000028
29using namespace clang;
Daniel Dunbar46f45b92008-09-09 01:06:48 +000030using namespace CodeGen;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +000031
32namespace {
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000033
Daniel Dunbarae226fa2008-08-27 02:31:56 +000034 typedef std::vector<llvm::Constant*> ConstantVector;
35
Daniel Dunbar6efc0c52008-08-13 03:21:16 +000036 // FIXME: We should find a nicer way to make the labels for
37 // metadata, string concatenation is lame.
38
Fariborz Jahanianee0af742009-01-21 22:04:16 +000039class ObjCCommonTypesHelper {
40protected:
41 CodeGen::CodeGenModule &CGM;
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000042
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000043public:
Fariborz Jahanian0a855d02009-03-23 19:10:40 +000044 const llvm::Type *ShortTy, *IntTy, *LongTy, *LongLongTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +000045 const llvm::Type *Int8PtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +000046
Daniel Dunbar2bedbf82008-08-12 05:28:47 +000047 /// ObjectPtrTy - LLVM type for object handles (typeof(id))
48 const llvm::Type *ObjectPtrTy;
Fariborz Jahanian6d657c42008-11-18 20:18:11 +000049
50 /// PtrObjectPtrTy - LLVM type for id *
51 const llvm::Type *PtrObjectPtrTy;
52
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +000053 /// SelectorPtrTy - LLVM type for selector handles (typeof(SEL))
Daniel Dunbar2bedbf82008-08-12 05:28:47 +000054 const llvm::Type *SelectorPtrTy;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +000055 /// ProtocolPtrTy - LLVM type for external protocol handles
56 /// (typeof(Protocol))
57 const llvm::Type *ExternalProtocolPtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +000058
Daniel Dunbar19cd87e2008-08-30 03:02:31 +000059 // SuperCTy - clang type for struct objc_super.
60 QualType SuperCTy;
61 // SuperPtrCTy - clang type for struct objc_super *.
62 QualType SuperPtrCTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +000063
Daniel Dunbare8b470d2008-08-23 04:28:29 +000064 /// SuperTy - LLVM type for struct objc_super.
65 const llvm::StructType *SuperTy;
Daniel Dunbar14c80b72008-08-23 09:25:55 +000066 /// SuperPtrTy - LLVM type for struct objc_super *.
67 const llvm::Type *SuperPtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +000068
Fariborz Jahanian30bc5712009-01-22 23:02:58 +000069 /// PropertyTy - LLVM type for struct objc_property (struct _prop_t
70 /// in GCC parlance).
71 const llvm::StructType *PropertyTy;
72
73 /// PropertyListTy - LLVM type for struct objc_property_list
74 /// (_prop_list_t in GCC parlance).
75 const llvm::StructType *PropertyListTy;
76 /// PropertyListPtrTy - LLVM type for struct objc_property_list*.
77 const llvm::Type *PropertyListPtrTy;
78
79 // MethodTy - LLVM type for struct objc_method.
80 const llvm::StructType *MethodTy;
81
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +000082 /// CacheTy - LLVM type for struct objc_cache.
83 const llvm::Type *CacheTy;
84 /// CachePtrTy - LLVM type for struct objc_cache *.
85 const llvm::Type *CachePtrTy;
86
Chris Lattner74391b42009-03-22 21:03:39 +000087 llvm::Constant *GetPropertyFn, *SetPropertyFn;
Fariborz Jahaniandb286862009-01-22 00:37:21 +000088
Chris Lattner74391b42009-03-22 21:03:39 +000089 llvm::Constant *EnumerationMutationFn;
Fariborz Jahaniandb286862009-01-22 00:37:21 +000090
91 /// GcReadWeakFn -- LLVM objc_read_weak (id *src) function.
Chris Lattner74391b42009-03-22 21:03:39 +000092 llvm::Constant *GcReadWeakFn;
Fariborz Jahaniandb286862009-01-22 00:37:21 +000093
94 /// GcAssignWeakFn -- LLVM objc_assign_weak function.
Chris Lattner96508e12009-04-17 22:12:36 +000095 llvm::Constant *getGcAssignWeakFn() {
96 // id objc_assign_weak (id, id *)
97 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
98 Args.push_back(ObjectPtrTy->getPointerTo());
99 llvm::FunctionType *FTy =
100 llvm::FunctionType::get(ObjectPtrTy, Args, false);
101 return CGM.CreateRuntimeFunction(FTy, "objc_assign_weak");
102 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000103
104 /// GcAssignGlobalFn -- LLVM objc_assign_global function.
Chris Lattner74391b42009-03-22 21:03:39 +0000105 llvm::Constant *GcAssignGlobalFn;
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000106
107 /// GcAssignIvarFn -- LLVM objc_assign_ivar function.
Chris Lattner74391b42009-03-22 21:03:39 +0000108 llvm::Constant *GcAssignIvarFn;
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000109
110 /// GcAssignStrongCastFn -- LLVM objc_assign_strongCast function.
Chris Lattner74391b42009-03-22 21:03:39 +0000111 llvm::Constant *GcAssignStrongCastFn;
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000112
113 /// ExceptionThrowFn - LLVM objc_exception_throw function.
Chris Lattner74391b42009-03-22 21:03:39 +0000114 llvm::Constant *ExceptionThrowFn;
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000115
Daniel Dunbar1c566672009-02-24 01:43:46 +0000116 /// SyncEnterFn - LLVM object_sync_enter function.
Chris Lattnerb02e53b2009-04-06 16:53:45 +0000117 llvm::Constant *getSyncEnterFn() {
118 // void objc_sync_enter (id)
119 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
120 llvm::FunctionType *FTy =
121 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
122 return CGM.CreateRuntimeFunction(FTy, "objc_sync_enter");
123 }
Daniel Dunbar1c566672009-02-24 01:43:46 +0000124
125 /// SyncExitFn - LLVM object_sync_exit function.
Chris Lattner74391b42009-03-22 21:03:39 +0000126 llvm::Constant *SyncExitFn;
Daniel Dunbar1c566672009-02-24 01:43:46 +0000127
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000128 ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm);
129 ~ObjCCommonTypesHelper(){}
130};
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000131
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000132/// ObjCTypesHelper - Helper class that encapsulates lazy
133/// construction of varies types used during ObjC generation.
134class ObjCTypesHelper : public ObjCCommonTypesHelper {
135private:
136
Chris Lattner74391b42009-03-22 21:03:39 +0000137 llvm::Constant *MessageSendFn, *MessageSendStretFn, *MessageSendFpretFn;
138 llvm::Constant *MessageSendSuperFn, *MessageSendSuperStretFn,
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000139 *MessageSendSuperFpretFn;
140
141public:
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000142 /// SymtabTy - LLVM type for struct objc_symtab.
143 const llvm::StructType *SymtabTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000144 /// SymtabPtrTy - LLVM type for struct objc_symtab *.
145 const llvm::Type *SymtabPtrTy;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000146 /// ModuleTy - LLVM type for struct objc_module.
147 const llvm::StructType *ModuleTy;
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000148
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000149 /// ProtocolTy - LLVM type for struct objc_protocol.
150 const llvm::StructType *ProtocolTy;
151 /// ProtocolPtrTy - LLVM type for struct objc_protocol *.
152 const llvm::Type *ProtocolPtrTy;
153 /// ProtocolExtensionTy - LLVM type for struct
154 /// objc_protocol_extension.
155 const llvm::StructType *ProtocolExtensionTy;
156 /// ProtocolExtensionTy - LLVM type for struct
157 /// objc_protocol_extension *.
158 const llvm::Type *ProtocolExtensionPtrTy;
159 /// MethodDescriptionTy - LLVM type for struct
160 /// objc_method_description.
161 const llvm::StructType *MethodDescriptionTy;
162 /// MethodDescriptionListTy - LLVM type for struct
163 /// objc_method_description_list.
164 const llvm::StructType *MethodDescriptionListTy;
165 /// MethodDescriptionListPtrTy - LLVM type for struct
166 /// objc_method_description_list *.
167 const llvm::Type *MethodDescriptionListPtrTy;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000168 /// ProtocolListTy - LLVM type for struct objc_property_list.
169 const llvm::Type *ProtocolListTy;
170 /// ProtocolListPtrTy - LLVM type for struct objc_property_list*.
171 const llvm::Type *ProtocolListPtrTy;
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000172 /// CategoryTy - LLVM type for struct objc_category.
173 const llvm::StructType *CategoryTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000174 /// ClassTy - LLVM type for struct objc_class.
175 const llvm::StructType *ClassTy;
176 /// ClassPtrTy - LLVM type for struct objc_class *.
177 const llvm::Type *ClassPtrTy;
178 /// ClassExtensionTy - LLVM type for struct objc_class_ext.
179 const llvm::StructType *ClassExtensionTy;
180 /// ClassExtensionPtrTy - LLVM type for struct objc_class_ext *.
181 const llvm::Type *ClassExtensionPtrTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000182 // IvarTy - LLVM type for struct objc_ivar.
183 const llvm::StructType *IvarTy;
184 /// IvarListTy - LLVM type for struct objc_ivar_list.
185 const llvm::Type *IvarListTy;
186 /// IvarListPtrTy - LLVM type for struct objc_ivar_list *.
187 const llvm::Type *IvarListPtrTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000188 /// MethodListTy - LLVM type for struct objc_method_list.
189 const llvm::Type *MethodListTy;
190 /// MethodListPtrTy - LLVM type for struct objc_method_list *.
191 const llvm::Type *MethodListPtrTy;
Anders Carlsson124526b2008-09-09 10:10:21 +0000192
193 /// ExceptionDataTy - LLVM type for struct _objc_exception_data.
194 const llvm::Type *ExceptionDataTy;
195
Anders Carlsson124526b2008-09-09 10:10:21 +0000196 /// ExceptionTryEnterFn - LLVM objc_exception_try_enter function.
Chris Lattner74391b42009-03-22 21:03:39 +0000197 llvm::Constant *ExceptionTryEnterFn;
Anders Carlsson124526b2008-09-09 10:10:21 +0000198
199 /// ExceptionTryExitFn - LLVM objc_exception_try_exit function.
Chris Lattner74391b42009-03-22 21:03:39 +0000200 llvm::Constant *ExceptionTryExitFn;
Anders Carlsson124526b2008-09-09 10:10:21 +0000201
202 /// ExceptionExtractFn - LLVM objc_exception_extract function.
Chris Lattner74391b42009-03-22 21:03:39 +0000203 llvm::Constant *ExceptionExtractFn;
Anders Carlsson124526b2008-09-09 10:10:21 +0000204
205 /// ExceptionMatchFn - LLVM objc_exception_match function.
Chris Lattner74391b42009-03-22 21:03:39 +0000206 llvm::Constant *ExceptionMatchFn;
Anders Carlsson124526b2008-09-09 10:10:21 +0000207
208 /// SetJmpFn - LLVM _setjmp function.
Chris Lattner74391b42009-03-22 21:03:39 +0000209 llvm::Constant *SetJmpFn;
Chris Lattner10cac6f2008-11-15 21:26:17 +0000210
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000211public:
212 ObjCTypesHelper(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000213 ~ObjCTypesHelper() {}
Daniel Dunbar5669e572008-10-17 03:24:53 +0000214
215
Chris Lattner74391b42009-03-22 21:03:39 +0000216 llvm::Constant *getSendFn(bool IsSuper) {
Daniel Dunbar5669e572008-10-17 03:24:53 +0000217 return IsSuper ? MessageSendSuperFn : MessageSendFn;
218 }
219
Chris Lattner74391b42009-03-22 21:03:39 +0000220 llvm::Constant *getSendStretFn(bool IsSuper) {
Daniel Dunbar5669e572008-10-17 03:24:53 +0000221 return IsSuper ? MessageSendSuperStretFn : MessageSendStretFn;
222 }
223
Chris Lattner74391b42009-03-22 21:03:39 +0000224 llvm::Constant *getSendFpretFn(bool IsSuper) {
Daniel Dunbar5669e572008-10-17 03:24:53 +0000225 return IsSuper ? MessageSendSuperFpretFn : MessageSendFpretFn;
226 }
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000227};
228
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000229/// ObjCNonFragileABITypesHelper - will have all types needed by objective-c's
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000230/// modern abi
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000231class ObjCNonFragileABITypesHelper : public ObjCCommonTypesHelper {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000232public:
Chris Lattner74391b42009-03-22 21:03:39 +0000233 llvm::Constant *MessageSendFixupFn, *MessageSendFpretFixupFn,
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000234 *MessageSendStretFixupFn, *MessageSendIdFixupFn,
235 *MessageSendIdStretFixupFn, *MessageSendSuper2FixupFn,
236 *MessageSendSuper2StretFixupFn;
237
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000238 // MethodListnfABITy - LLVM for struct _method_list_t
239 const llvm::StructType *MethodListnfABITy;
240
241 // MethodListnfABIPtrTy - LLVM for struct _method_list_t*
242 const llvm::Type *MethodListnfABIPtrTy;
243
244 // ProtocolnfABITy = LLVM for struct _protocol_t
245 const llvm::StructType *ProtocolnfABITy;
246
Daniel Dunbar948e2582009-02-15 07:36:20 +0000247 // ProtocolnfABIPtrTy = LLVM for struct _protocol_t*
248 const llvm::Type *ProtocolnfABIPtrTy;
249
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000250 // ProtocolListnfABITy - LLVM for struct _objc_protocol_list
251 const llvm::StructType *ProtocolListnfABITy;
252
253 // ProtocolListnfABIPtrTy - LLVM for struct _objc_protocol_list*
254 const llvm::Type *ProtocolListnfABIPtrTy;
255
256 // ClassnfABITy - LLVM for struct _class_t
257 const llvm::StructType *ClassnfABITy;
258
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000259 // ClassnfABIPtrTy - LLVM for struct _class_t*
260 const llvm::Type *ClassnfABIPtrTy;
261
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000262 // IvarnfABITy - LLVM for struct _ivar_t
263 const llvm::StructType *IvarnfABITy;
264
265 // IvarListnfABITy - LLVM for struct _ivar_list_t
266 const llvm::StructType *IvarListnfABITy;
267
268 // IvarListnfABIPtrTy = LLVM for struct _ivar_list_t*
269 const llvm::Type *IvarListnfABIPtrTy;
270
271 // ClassRonfABITy - LLVM for struct _class_ro_t
272 const llvm::StructType *ClassRonfABITy;
273
274 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
275 const llvm::Type *ImpnfABITy;
276
277 // CategorynfABITy - LLVM for struct _category_t
278 const llvm::StructType *CategorynfABITy;
279
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000280 // New types for nonfragile abi messaging.
281
282 // MessageRefTy - LLVM for:
283 // struct _message_ref_t {
284 // IMP messenger;
285 // SEL name;
286 // };
287 const llvm::StructType *MessageRefTy;
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000288 // MessageRefCTy - clang type for struct _message_ref_t
289 QualType MessageRefCTy;
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000290
291 // MessageRefPtrTy - LLVM for struct _message_ref_t*
292 const llvm::Type *MessageRefPtrTy;
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000293 // MessageRefCPtrTy - clang type for struct _message_ref_t*
294 QualType MessageRefCPtrTy;
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000295
Fariborz Jahanianef163782009-02-05 01:13:09 +0000296 // MessengerTy - Type of the messenger (shown as IMP above)
297 const llvm::FunctionType *MessengerTy;
298
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000299 // SuperMessageRefTy - LLVM for:
300 // struct _super_message_ref_t {
301 // SUPER_IMP messenger;
302 // SEL name;
303 // };
304 const llvm::StructType *SuperMessageRefTy;
305
306 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
307 const llvm::Type *SuperMessageRefPtrTy;
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000308
309 /// EHPersonalityPtr - LLVM value for an i8* to the Objective-C
310 /// exception personality function.
Chris Lattnerb02e53b2009-04-06 16:53:45 +0000311 llvm::Value *getEHPersonalityPtr() {
312 llvm::Constant *Personality =
313 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
314 std::vector<const llvm::Type*>(),
315 true),
316 "__objc_personality_v0");
317 return llvm::ConstantExpr::getBitCast(Personality, Int8PtrTy);
318 }
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000319
Chris Lattner74391b42009-03-22 21:03:39 +0000320 llvm::Constant *UnwindResumeOrRethrowFn, *ObjCBeginCatchFn, *ObjCEndCatchFn;
Daniel Dunbare588b992009-03-01 04:46:24 +0000321
322 const llvm::StructType *EHTypeTy;
323 const llvm::Type *EHTypePtrTy;
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000324
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000325 ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm);
326 ~ObjCNonFragileABITypesHelper(){}
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000327};
328
329class CGObjCCommonMac : public CodeGen::CGObjCRuntime {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000330public:
331 // FIXME - accessibility
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000332 class GC_IVAR {
Fariborz Jahanian820e0202009-03-11 00:07:04 +0000333 public:
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000334 unsigned int ivar_bytepos;
335 unsigned int ivar_size;
336 GC_IVAR() : ivar_bytepos(0), ivar_size(0) {}
337 };
338
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000339 class SKIP_SCAN {
340 public:
341 unsigned int skip;
342 unsigned int scan;
343 SKIP_SCAN() : skip(0), scan(0) {}
344 };
345
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000346protected:
347 CodeGen::CodeGenModule &CGM;
348 // FIXME! May not be needing this after all.
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000349 unsigned ObjCABI;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000350
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000351 // gc ivar layout bitmap calculation helper caches.
352 llvm::SmallVector<GC_IVAR, 16> SkipIvars;
353 llvm::SmallVector<GC_IVAR, 16> IvarsInfo;
354 llvm::SmallVector<SKIP_SCAN, 32> SkipScanIvars;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000355
Daniel Dunbar242d4dc2008-08-25 06:02:07 +0000356 /// LazySymbols - Symbols to generate a lazy reference for. See
357 /// DefinedSymbols and FinishModule().
358 std::set<IdentifierInfo*> LazySymbols;
359
360 /// DefinedSymbols - External symbols which are defined by this
361 /// module. The symbols in this list and LazySymbols are used to add
362 /// special linker symbols which ensure that Objective-C modules are
363 /// linked properly.
364 std::set<IdentifierInfo*> DefinedSymbols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000365
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000366 /// ClassNames - uniqued class names.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000367 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000368
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000369 /// MethodVarNames - uniqued method variable names.
370 llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000371
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000372 /// MethodVarTypes - uniqued method type signatures. We have to use
373 /// a StringMap here because have no other unique reference.
374 llvm::StringMap<llvm::GlobalVariable*> MethodVarTypes;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000375
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000376 /// MethodDefinitions - map of methods which have been defined in
377 /// this translation unit.
378 llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> MethodDefinitions;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000379
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000380 /// PropertyNames - uniqued method variable names.
381 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000382
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000383 /// ClassReferences - uniqued class references.
384 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000385
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000386 /// SelectorReferences - uniqued selector references.
387 llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000388
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000389 /// Protocols - Protocols for which an objc_protocol structure has
390 /// been emitted. Forward declarations are handled by creating an
391 /// empty structure whose initializer is filled in when/if defined.
392 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> Protocols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000393
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000394 /// DefinedProtocols - Protocols which have actually been
395 /// defined. We should not need this, see FIXME in GenerateProtocol.
396 llvm::DenseSet<IdentifierInfo*> DefinedProtocols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000397
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000398 /// DefinedClasses - List of defined classes.
399 std::vector<llvm::GlobalValue*> DefinedClasses;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000400
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000401 /// DefinedCategories - List of defined categories.
402 std::vector<llvm::GlobalValue*> DefinedCategories;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000403
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000404 /// UsedGlobals - List of globals to pack into the llvm.used metadata
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000405 /// to prevent them from being clobbered.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000406 std::vector<llvm::GlobalVariable*> UsedGlobals;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000407
Fariborz Jahanian56210f72009-01-21 23:34:32 +0000408 /// GetNameForMethod - Return a name for the given method.
409 /// \param[out] NameOut - The return value.
410 void GetNameForMethod(const ObjCMethodDecl *OMD,
411 const ObjCContainerDecl *CD,
412 std::string &NameOut);
413
414 /// GetMethodVarName - Return a unique constant for the given
415 /// selector's name. The return value has type char *.
416 llvm::Constant *GetMethodVarName(Selector Sel);
417 llvm::Constant *GetMethodVarName(IdentifierInfo *Ident);
418 llvm::Constant *GetMethodVarName(const std::string &Name);
419
420 /// GetMethodVarType - Return a unique constant for the given
421 /// selector's name. The return value has type char *.
422
423 // FIXME: This is a horrible name.
424 llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D);
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +0000425 llvm::Constant *GetMethodVarType(const FieldDecl *D);
Fariborz Jahanian56210f72009-01-21 23:34:32 +0000426
427 /// GetPropertyName - Return a unique constant for the given
428 /// name. The return value has type char *.
429 llvm::Constant *GetPropertyName(IdentifierInfo *Ident);
430
431 // FIXME: This can be dropped once string functions are unified.
432 llvm::Constant *GetPropertyTypeString(const ObjCPropertyDecl *PD,
433 const Decl *Container);
434
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000435 /// GetClassName - Return a unique constant for the given selector's
436 /// name. The return value has type char *.
437 llvm::Constant *GetClassName(IdentifierInfo *Ident);
438
Fariborz Jahanian21e6f172009-03-11 21:42:00 +0000439 /// GetInterfaceDeclStructLayout - Get layout for ivars of given
440 /// interface declaration.
441 const llvm::StructLayout *GetInterfaceDeclStructLayout(
442 const ObjCInterfaceDecl *ID) const;
443
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000444 /// BuildIvarLayout - Builds ivar layout bitmap for the class
445 /// implementation for the __strong or __weak case.
446 ///
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000447 llvm::Constant *BuildIvarLayout(const ObjCImplementationDecl *OI,
448 bool ForStrongLayout);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000449
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000450 void BuildAggrIvarLayout(const ObjCInterfaceDecl *OI,
451 const llvm::StructLayout *Layout,
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000452 const RecordDecl *RD,
Chris Lattnerf1690852009-03-31 08:48:01 +0000453 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000454 unsigned int BytePos, bool ForStrongLayout,
455 int &Index, int &SkIndex, bool &HasUnion);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000456
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +0000457 /// GetIvarLayoutName - Returns a unique constant for the given
458 /// ivar layout bitmap.
459 llvm::Constant *GetIvarLayoutName(IdentifierInfo *Ident,
460 const ObjCCommonTypesHelper &ObjCTypes);
461
Fariborz Jahanian46b86c62009-01-28 19:12:34 +0000462 const RecordDecl *GetFirstIvarInRecord(const ObjCInterfaceDecl *OID,
463 RecordDecl::field_iterator &FIV,
464 RecordDecl::field_iterator &PIV);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +0000465 /// EmitPropertyList - Emit the given property list. The return
466 /// value has type PropertyListPtrTy.
467 llvm::Constant *EmitPropertyList(const std::string &Name,
468 const Decl *Container,
469 const ObjCContainerDecl *OCD,
470 const ObjCCommonTypesHelper &ObjCTypes);
471
Fariborz Jahanianda320092009-01-29 19:24:30 +0000472 /// GetProtocolRef - Return a reference to the internal protocol
473 /// description, creating an empty one if it has not been
474 /// defined. The return value has type ProtocolPtrTy.
475 llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +0000476
477 /// GetIvarBaseOffset - returns ivars byte offset.
478 uint64_t GetIvarBaseOffset(const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +0000479 const FieldDecl *Field);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000480
Chris Lattnercd0ee142009-03-31 08:33:16 +0000481 /// GetFieldBaseOffset - return's field byte offset.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000482 uint64_t GetFieldBaseOffset(const ObjCInterfaceDecl *OI,
483 const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +0000484 const FieldDecl *Field);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000485
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000486 /// CreateMetadataVar - Create a global variable with internal
487 /// linkage for use by the Objective-C runtime.
488 ///
489 /// This is a convenience wrapper which not only creates the
490 /// variable, but also sets the section and alignment and adds the
491 /// global to the UsedGlobals list.
Daniel Dunbar35bd7632009-03-09 20:50:13 +0000492 ///
493 /// \param Name - The variable name.
494 /// \param Init - The variable initializer; this is also used to
495 /// define the type of the variable.
496 /// \param Section - The section the variable should go into, or 0.
497 /// \param Align - The alignment for the variable, or 0.
498 /// \param AddToUsed - Whether the variable should be added to
Daniel Dunbarc1583062009-04-14 17:42:51 +0000499 /// "llvm.used".
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000500 llvm::GlobalVariable *CreateMetadataVar(const std::string &Name,
501 llvm::Constant *Init,
502 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +0000503 unsigned Align,
504 bool AddToUsed);
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000505
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +0000506 /// GetNamedIvarList - Return the list of ivars in the interface
507 /// itself (not including super classes and not including unnamed
508 /// bitfields).
509 ///
510 /// For the non-fragile ABI, this also includes synthesized property
511 /// ivars.
512 void GetNamedIvarList(const ObjCInterfaceDecl *OID,
513 llvm::SmallVector<ObjCIvarDecl*, 16> &Res) const;
514
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000515public:
516 CGObjCCommonMac(CodeGen::CodeGenModule &cgm) : CGM(cgm)
517 { }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000518
Steve Naroff33fdb732009-03-31 16:53:37 +0000519 virtual llvm::Constant *GenerateConstantString(const ObjCStringLiteral *SL);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000520
521 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
522 const ObjCContainerDecl *CD=0);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000523
524 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
525
526 /// GetOrEmitProtocol - Get the protocol object for the given
527 /// declaration, emitting it if necessary. The return value has type
528 /// ProtocolPtrTy.
529 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD)=0;
530
531 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
532 /// object for the given declaration, emitting it if needed. These
533 /// forward references will be filled in with empty bodies if no
534 /// definition is seen. The return value has type ProtocolPtrTy.
535 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD)=0;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000536};
537
538class CGObjCMac : public CGObjCCommonMac {
539private:
540 ObjCTypesHelper ObjCTypes;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000541 /// EmitImageInfo - Emit the image info marker used to encode some module
542 /// level information.
543 void EmitImageInfo();
544
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000545 /// EmitModuleInfo - Another marker encoding module level
546 /// information.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000547 void EmitModuleInfo();
548
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000549 /// EmitModuleSymols - Emit module symbols, the list of defined
550 /// classes and categories. The result has type SymtabPtrTy.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000551 llvm::Constant *EmitModuleSymbols();
552
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000553 /// FinishModule - Write out global data structures at the end of
554 /// processing a translation unit.
555 void FinishModule();
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000556
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000557 /// EmitClassExtension - Generate the class extension structure used
558 /// to store the weak ivar layout and properties. The return value
559 /// has type ClassExtensionPtrTy.
560 llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID);
561
562 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
563 /// for the given class.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000564 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000565 const ObjCInterfaceDecl *ID);
566
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000567 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000568 QualType ResultType,
569 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000570 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000571 QualType Arg0Ty,
572 bool IsSuper,
573 const CallArgList &CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000574
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000575 /// EmitIvarList - Emit the ivar list for the given
576 /// implementation. If ForClass is true the list of class ivars
577 /// (i.e. metaclass ivars) is emitted, otherwise the list of
578 /// interface ivars will be emitted. The return value has type
579 /// IvarListPtrTy.
580 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +0000581 bool ForClass);
582
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000583 /// EmitMetaClass - Emit a forward reference to the class structure
584 /// for the metaclass of the given interface. The return value has
585 /// type ClassPtrTy.
586 llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
587
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000588 /// EmitMetaClass - Emit a class structure for the metaclass of the
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000589 /// given implementation. The return value has type ClassPtrTy.
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000590 llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
591 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000592 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000593 const ConstantVector &Methods);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000594
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000595 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000596
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000597 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000598
599 /// EmitMethodList - Emit the method list for the given
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000600 /// implementation. The return value has type MethodListPtrTy.
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000601 llvm::Constant *EmitMethodList(const std::string &Name,
602 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000603 const ConstantVector &Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000604
605 /// EmitMethodDescList - Emit a method description list for a list of
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000606 /// method declarations.
607 /// - TypeName: The name for the type containing the methods.
608 /// - IsProtocol: True iff these methods are for a protocol.
609 /// - ClassMethds: True iff these are class methods.
610 /// - Required: When true, only "required" methods are
611 /// listed. Similarly, when false only "optional" methods are
612 /// listed. For classes this should always be true.
613 /// - begin, end: The method list to output.
614 ///
615 /// The return value has type MethodDescriptionListPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000616 llvm::Constant *EmitMethodDescList(const std::string &Name,
617 const char *Section,
618 const ConstantVector &Methods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000619
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000620 /// GetOrEmitProtocol - Get the protocol object for the given
621 /// declaration, emitting it if necessary. The return value has type
622 /// ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +0000623 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000624
625 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
626 /// object for the given declaration, emitting it if needed. These
627 /// forward references will be filled in with empty bodies if no
628 /// definition is seen. The return value has type ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +0000629 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000630
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000631 /// EmitProtocolExtension - Generate the protocol extension
632 /// structure used to store optional instance and class methods, and
633 /// protocol properties. The return value has type
634 /// ProtocolExtensionPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000635 llvm::Constant *
636 EmitProtocolExtension(const ObjCProtocolDecl *PD,
637 const ConstantVector &OptInstanceMethods,
638 const ConstantVector &OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000639
640 /// EmitProtocolList - Generate the list of referenced
641 /// protocols. The return value has type ProtocolListPtrTy.
Daniel Dunbardbc933702008-08-21 21:57:41 +0000642 llvm::Constant *EmitProtocolList(const std::string &Name,
643 ObjCProtocolDecl::protocol_iterator begin,
644 ObjCProtocolDecl::protocol_iterator end);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000645
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000646 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
647 /// for the given selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000648 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000649
Fariborz Jahanianda320092009-01-29 19:24:30 +0000650 public:
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000651 CGObjCMac(CodeGen::CodeGenModule &cgm);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000652
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000653 virtual llvm::Function *ModuleInitFunction();
654
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000655 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000656 QualType ResultType,
657 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000658 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000659 bool IsClassMessage,
660 const CallArgList &CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000661
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000662 virtual CodeGen::RValue
663 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000664 QualType ResultType,
665 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000666 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000667 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000668 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000669 bool IsClassMessage,
670 const CallArgList &CallArgs);
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000671
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000672 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000673 const ObjCInterfaceDecl *ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000674
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000675 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000676
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000677 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000678
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000679 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000680
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000681 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000682 const ObjCProtocolDecl *PD);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000683
Chris Lattner74391b42009-03-22 21:03:39 +0000684 virtual llvm::Constant *GetPropertyGetFunction();
685 virtual llvm::Constant *GetPropertySetFunction();
686 virtual llvm::Constant *EnumerationMutationFunction();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000687
Fariborz Jahanianbd71be42008-11-21 00:49:24 +0000688 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
689 const Stmt &S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000690 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
691 const ObjCAtThrowStmt &S);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000692 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +0000693 llvm::Value *AddrWeakObj);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000694 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
695 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000696 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
697 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian7eda8362008-11-20 19:23:36 +0000698 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
699 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000700 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
701 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian0bb20362009-02-02 20:02:29 +0000702
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000703 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
704 QualType ObjectTy,
705 llvm::Value *BaseValue,
706 const ObjCIvarDecl *Ivar,
707 const FieldDecl *Field,
708 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000709 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
710 ObjCInterfaceDecl *Interface,
711 const ObjCIvarDecl *Ivar);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000712};
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000713
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000714class CGObjCNonFragileABIMac : public CGObjCCommonMac {
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000715private:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000716 ObjCNonFragileABITypesHelper ObjCTypes;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000717 llvm::GlobalVariable* ObjCEmptyCacheVar;
718 llvm::GlobalVariable* ObjCEmptyVtableVar;
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000719
Daniel Dunbar11394522009-04-18 08:51:00 +0000720 /// SuperClassReferences - uniqued super class references.
721 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> SuperClassReferences;
722
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000723 /// MetaClassReferences - uniqued meta class references.
724 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> MetaClassReferences;
Daniel Dunbare588b992009-03-01 04:46:24 +0000725
726 /// EHTypeReferences - uniqued class ehtype references.
727 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> EHTypeReferences;
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000728
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000729 /// FinishNonFragileABIModule - Write out global data structures at the end of
730 /// processing a translation unit.
731 void FinishNonFragileABIModule();
Daniel Dunbar8158a2f2009-04-08 04:21:03 +0000732
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000733 llvm::GlobalVariable * BuildClassRoTInitializer(unsigned flags,
734 unsigned InstanceStart,
735 unsigned InstanceSize,
736 const ObjCImplementationDecl *ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +0000737 llvm::GlobalVariable * BuildClassMetaData(std::string &ClassName,
738 llvm::Constant *IsAGV,
739 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +0000740 llvm::Constant *ClassRoGV,
741 bool HiddenVisibility);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000742
743 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
744
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +0000745 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
746
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000747 /// EmitMethodList - Emit the method list for the given
748 /// implementation. The return value has type MethodListnfABITy.
749 llvm::Constant *EmitMethodList(const std::string &Name,
750 const char *Section,
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +0000751 const ConstantVector &Methods);
752 /// EmitIvarList - Emit the ivar list for the given
753 /// implementation. If ForClass is true the list of class ivars
754 /// (i.e. metaclass ivars) is emitted, otherwise the list of
755 /// interface ivars will be emitted. The return value has type
756 /// IvarListnfABIPtrTy.
757 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000758
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000759 llvm::Constant *EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +0000760 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +0000761 unsigned long int offset);
762
Fariborz Jahanianda320092009-01-29 19:24:30 +0000763 /// GetOrEmitProtocol - Get the protocol object for the given
764 /// declaration, emitting it if necessary. The return value has type
765 /// ProtocolPtrTy.
766 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
767
768 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
769 /// object for the given declaration, emitting it if needed. These
770 /// forward references will be filled in with empty bodies if no
771 /// definition is seen. The return value has type ProtocolPtrTy.
772 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
773
774 /// EmitProtocolList - Generate the list of referenced
775 /// protocols. The return value has type ProtocolListPtrTy.
776 llvm::Constant *EmitProtocolList(const std::string &Name,
777 ObjCProtocolDecl::protocol_iterator begin,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000778 ObjCProtocolDecl::protocol_iterator end);
779
780 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
781 QualType ResultType,
782 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000783 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000784 QualType Arg0Ty,
785 bool IsSuper,
786 const CallArgList &CallArgs);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +0000787
788 /// GetClassGlobal - Return the global variable for the Objective-C
789 /// class of the given name.
Fariborz Jahanian0f902942009-04-14 18:41:56 +0000790 llvm::GlobalVariable *GetClassGlobal(const std::string &Name);
791
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000792 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
Daniel Dunbar11394522009-04-18 08:51:00 +0000793 /// for the given class reference.
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000794 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar11394522009-04-18 08:51:00 +0000795 const ObjCInterfaceDecl *ID);
796
797 /// EmitSuperClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
798 /// for the given super class reference.
799 llvm::Value *EmitSuperClassRef(CGBuilderTy &Builder,
800 const ObjCInterfaceDecl *ID);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000801
802 /// EmitMetaClassRef - Return a Value * of the address of _class_t
803 /// meta-data
804 llvm::Value *EmitMetaClassRef(CGBuilderTy &Builder,
805 const ObjCInterfaceDecl *ID);
806
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000807 /// ObjCIvarOffsetVariable - Returns the ivar offset variable for
808 /// the given ivar.
809 ///
Daniel Dunbar5e88bea2009-04-19 00:31:15 +0000810 llvm::GlobalVariable * ObjCIvarOffsetVariable(
Fariborz Jahanian01a0c362009-02-12 18:51:23 +0000811 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000812 const ObjCIvarDecl *Ivar);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000813
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +0000814 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
815 /// for the given selector.
816 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbare588b992009-03-01 04:46:24 +0000817
Daniel Dunbar8158a2f2009-04-08 04:21:03 +0000818 /// GetInterfaceEHType - Get the cached ehtype for the given Objective-C
Daniel Dunbare588b992009-03-01 04:46:24 +0000819 /// interface. The return value has type EHTypePtrTy.
Daniel Dunbar8158a2f2009-04-08 04:21:03 +0000820 llvm::Value *GetInterfaceEHType(const ObjCInterfaceDecl *ID,
821 bool ForDefinition);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +0000822
823 const char *getMetaclassSymbolPrefix() const {
824 return "OBJC_METACLASS_$_";
825 }
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000826
Daniel Dunbar6ab187a2009-04-07 05:48:37 +0000827 const char *getClassSymbolPrefix() const {
828 return "OBJC_CLASS_$_";
829 }
830
Daniel Dunbarb02532a2009-04-19 23:41:48 +0000831 void GetClassSizeInfo(const ObjCInterfaceDecl *OID,
832 uint32_t &InstanceStart,
833 uint32_t &InstanceSize);
834
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000835public:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000836 CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000837 // FIXME. All stubs for now!
838 virtual llvm::Function *ModuleInitFunction();
839
840 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
841 QualType ResultType,
842 Selector Sel,
843 llvm::Value *Receiver,
844 bool IsClassMessage,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000845 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000846
847 virtual CodeGen::RValue
848 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
849 QualType ResultType,
850 Selector Sel,
851 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000852 bool isCategoryImpl,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000853 llvm::Value *Receiver,
854 bool IsClassMessage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000855 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000856
857 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000858 const ObjCInterfaceDecl *ID);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000859
860 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel)
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +0000861 { return EmitSelector(Builder, Sel); }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000862
Fariborz Jahanianeb062d92009-01-26 18:32:24 +0000863 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000864
865 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000866 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +0000867 const ObjCProtocolDecl *PD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000868
Chris Lattner74391b42009-03-22 21:03:39 +0000869 virtual llvm::Constant *GetPropertyGetFunction() {
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000870 return ObjCTypes.GetPropertyFn;
871 }
Chris Lattner74391b42009-03-22 21:03:39 +0000872 virtual llvm::Constant *GetPropertySetFunction() {
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000873 return ObjCTypes.SetPropertyFn;
874 }
Chris Lattner74391b42009-03-22 21:03:39 +0000875 virtual llvm::Constant *EnumerationMutationFunction() {
Daniel Dunbar28ed0842009-02-16 18:48:45 +0000876 return ObjCTypes.EnumerationMutationFn;
877 }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000878
879 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000880 const Stmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000881 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000882 const ObjCAtThrowStmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000883 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000884 llvm::Value *AddrWeakObj);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000885 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000886 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000887 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000888 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000889 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000890 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000891 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000892 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000893 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
894 QualType ObjectTy,
895 llvm::Value *BaseValue,
896 const ObjCIvarDecl *Ivar,
897 const FieldDecl *Field,
898 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000899 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
900 ObjCInterfaceDecl *Interface,
901 const ObjCIvarDecl *Ivar);
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000902};
903
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000904} // end anonymous namespace
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000905
906/* *** Helper Functions *** */
907
908/// getConstantGEP() - Help routine to construct simple GEPs.
909static llvm::Constant *getConstantGEP(llvm::Constant *C,
910 unsigned idx0,
911 unsigned idx1) {
912 llvm::Value *Idxs[] = {
913 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx0),
914 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx1)
915 };
916 return llvm::ConstantExpr::getGetElementPtr(C, Idxs, 2);
917}
918
Daniel Dunbar8158a2f2009-04-08 04:21:03 +0000919/// hasObjCExceptionAttribute - Return true if this class or any super
920/// class has the __objc_exception__ attribute.
921static bool hasObjCExceptionAttribute(const ObjCInterfaceDecl *OID) {
Daniel Dunbarb11fa0d2009-04-13 21:08:27 +0000922 if (OID->hasAttr<ObjCExceptionAttr>())
Daniel Dunbar8158a2f2009-04-08 04:21:03 +0000923 return true;
924 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
925 return hasObjCExceptionAttribute(Super);
926 return false;
927}
928
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000929/* *** CGObjCMac Public Interface *** */
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000930
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000931CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm),
932 ObjCTypes(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000933{
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000934 ObjCABI = 1;
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000935 EmitImageInfo();
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000936}
937
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000938/// GetClass - Return a reference to the class for the given interface
939/// decl.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000940llvm::Value *CGObjCMac::GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000941 const ObjCInterfaceDecl *ID) {
942 return EmitClassRef(Builder, ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000943}
944
945/// GetSelector - Return the pointer to the unique'd string for this selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000946llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000947 return EmitSelector(Builder, Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000948}
949
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000950/// Generate a constant CFString object.
951/*
952 struct __builtin_CFString {
953 const int *isa; // point to __CFConstantStringClassReference
954 int flags;
955 const char *str;
956 long length;
957 };
958*/
959
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000960llvm::Constant *CGObjCCommonMac::GenerateConstantString(
Steve Naroff33fdb732009-03-31 16:53:37 +0000961 const ObjCStringLiteral *SL) {
Steve Naroff8d4141f2009-04-01 13:55:36 +0000962 return CGM.GetAddrOfConstantCFString(SL->getString());
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000963}
964
965/// Generates a message send where the super is the receiver. This is
966/// a message send to self with special delivery semantics indicating
967/// which class's method should be called.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000968CodeGen::RValue
969CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000970 QualType ResultType,
971 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000972 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000973 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000974 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000975 bool IsClassMessage,
Daniel Dunbar46f45b92008-09-09 01:06:48 +0000976 const CodeGen::CallArgList &CallArgs) {
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000977 // Create and init a super structure; this is a (receiver, class)
978 // pair we will pass to objc_msgSendSuper.
979 llvm::Value *ObjCSuper =
980 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
981 llvm::Value *ReceiverAsObject =
982 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
983 CGF.Builder.CreateStore(ReceiverAsObject,
984 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000985
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000986 // If this is a class message the metaclass is passed as the target.
987 llvm::Value *Target;
988 if (IsClassMessage) {
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000989 if (isCategoryImpl) {
990 // Message sent to 'super' in a class method defined in a category
991 // implementation requires an odd treatment.
992 // If we are in a class method, we must retrieve the
993 // _metaclass_ for the current class, pointed at by
994 // the class's "isa" pointer. The following assumes that
995 // isa" is the first ivar in a class (which it must be).
996 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
997 Target = CGF.Builder.CreateStructGEP(Target, 0);
998 Target = CGF.Builder.CreateLoad(Target);
999 }
1000 else {
1001 llvm::Value *MetaClassPtr = EmitMetaClassRef(Class);
1002 llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1);
1003 llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr);
1004 Target = Super;
1005 }
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001006 } else {
1007 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
1008 }
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001009 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
1010 // and ObjCTypes types.
1011 const llvm::Type *ClassTy =
1012 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001013 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001014 CGF.Builder.CreateStore(Target,
1015 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
1016
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001017 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001018 ObjCSuper, ObjCTypes.SuperPtrCTy,
1019 true, CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001020}
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001021
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001022/// Generate code for a message send expression.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +00001023CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001024 QualType ResultType,
1025 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001026 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001027 bool IsClassMessage,
1028 const CallArgList &CallArgs) {
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001029 llvm::Value *Arg0 =
1030 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy, "tmp");
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001031 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001032 Arg0, CGF.getContext().getObjCIdType(),
1033 false, CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001034}
1035
1036CodeGen::RValue CGObjCMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001037 QualType ResultType,
1038 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001039 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001040 QualType Arg0Ty,
1041 bool IsSuper,
1042 const CallArgList &CallArgs) {
1043 CallArgList ActualArgs;
Daniel Dunbar46f45b92008-09-09 01:06:48 +00001044 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
1045 ActualArgs.push_back(std::make_pair(RValue::get(EmitSelector(CGF.Builder,
1046 Sel)),
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001047 CGF.getContext().getObjCSelType()));
1048 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001049
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001050 CodeGenTypes &Types = CGM.getTypes();
1051 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs);
1052 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo, false);
Daniel Dunbar5669e572008-10-17 03:24:53 +00001053
1054 llvm::Constant *Fn;
Daniel Dunbar88b53962009-02-02 22:03:45 +00001055 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Daniel Dunbar5669e572008-10-17 03:24:53 +00001056 Fn = ObjCTypes.getSendStretFn(IsSuper);
1057 } else if (ResultType->isFloatingType()) {
1058 // FIXME: Sadly, this is wrong. This actually depends on the
1059 // architecture. This happens to be right for x86-32 though.
1060 Fn = ObjCTypes.getSendFpretFn(IsSuper);
1061 } else {
1062 Fn = ObjCTypes.getSendFn(IsSuper);
1063 }
Daniel Dunbar62d5c1b2008-09-10 07:00:50 +00001064 Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy));
Daniel Dunbar88b53962009-02-02 22:03:45 +00001065 return CGF.EmitCall(FnInfo, Fn, ActualArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001066}
1067
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001068llvm::Value *CGObjCMac::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001069 const ObjCProtocolDecl *PD) {
Daniel Dunbarc67876d2008-09-04 04:33:15 +00001070 // FIXME: I don't understand why gcc generates this, or where it is
1071 // resolved. Investigate. Its also wasteful to look this up over and
1072 // over.
1073 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1074
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001075 return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
1076 ObjCTypes.ExternalProtocolPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001077}
1078
Fariborz Jahanianda320092009-01-29 19:24:30 +00001079void CGObjCCommonMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001080 // FIXME: We shouldn't need this, the protocol decl should contain
1081 // enough information to tell us whether this was a declaration or a
1082 // definition.
1083 DefinedProtocols.insert(PD->getIdentifier());
1084
1085 // If we have generated a forward reference to this protocol, emit
1086 // it now. Otherwise do nothing, the protocol objects are lazily
1087 // emitted.
1088 if (Protocols.count(PD->getIdentifier()))
1089 GetOrEmitProtocol(PD);
1090}
1091
Fariborz Jahanianda320092009-01-29 19:24:30 +00001092llvm::Constant *CGObjCCommonMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001093 if (DefinedProtocols.count(PD->getIdentifier()))
1094 return GetOrEmitProtocol(PD);
1095 return GetOrEmitProtocolRef(PD);
1096}
1097
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001098/*
1099 // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions
1100 struct _objc_protocol {
1101 struct _objc_protocol_extension *isa;
1102 char *protocol_name;
1103 struct _objc_protocol_list *protocol_list;
1104 struct _objc__method_prototype_list *instance_methods;
1105 struct _objc__method_prototype_list *class_methods
1106 };
1107
1108 See EmitProtocolExtension().
1109*/
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001110llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
1111 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1112
1113 // Early exit if a defining object has already been generated.
1114 if (Entry && Entry->hasInitializer())
1115 return Entry;
1116
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001117 // FIXME: I don't understand why gcc generates this, or where it is
1118 // resolved. Investigate. Its also wasteful to look this up over and
1119 // over.
1120 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1121
Chris Lattner8ec03f52008-11-24 03:54:41 +00001122 const char *ProtocolName = PD->getNameAsCString();
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001123
1124 // Construct method lists.
1125 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1126 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregor6ab35242009-04-09 21:40:53 +00001127 for (ObjCProtocolDecl::instmeth_iterator
1128 i = PD->instmeth_begin(CGM.getContext()),
1129 e = PD->instmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001130 ObjCMethodDecl *MD = *i;
1131 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1132 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1133 OptInstanceMethods.push_back(C);
1134 } else {
1135 InstanceMethods.push_back(C);
1136 }
1137 }
1138
Douglas Gregor6ab35242009-04-09 21:40:53 +00001139 for (ObjCProtocolDecl::classmeth_iterator
1140 i = PD->classmeth_begin(CGM.getContext()),
1141 e = PD->classmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001142 ObjCMethodDecl *MD = *i;
1143 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1144 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1145 OptClassMethods.push_back(C);
1146 } else {
1147 ClassMethods.push_back(C);
1148 }
1149 }
1150
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001151 std::vector<llvm::Constant*> Values(5);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001152 Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001153 Values[1] = GetClassName(PD->getIdentifier());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001154 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001155 EmitProtocolList("\01L_OBJC_PROTOCOL_REFS_" + PD->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001156 PD->protocol_begin(),
1157 PD->protocol_end());
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001158 Values[3] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001159 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_"
1160 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001161 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1162 InstanceMethods);
1163 Values[4] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001164 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_"
1165 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001166 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1167 ClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001168 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
1169 Values);
1170
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001171 if (Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001172 // Already created, fix the linkage and update the initializer.
1173 Entry->setLinkage(llvm::GlobalValue::InternalLinkage);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001174 Entry->setInitializer(Init);
1175 } else {
1176 Entry =
1177 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
1178 llvm::GlobalValue::InternalLinkage,
1179 Init,
1180 std::string("\01L_OBJC_PROTOCOL_")+ProtocolName,
1181 &CGM.getModule());
1182 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001183 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001184 UsedGlobals.push_back(Entry);
1185 // FIXME: Is this necessary? Why only for protocol?
1186 Entry->setAlignment(4);
1187 }
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001188
1189 return Entry;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001190}
1191
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001192llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001193 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1194
1195 if (!Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001196 // We use the initializer as a marker of whether this is a forward
1197 // reference or not. At module finalization we add the empty
1198 // contents for protocols which were referenced but never defined.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001199 Entry =
1200 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001201 llvm::GlobalValue::ExternalLinkage,
1202 0,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001203 "\01L_OBJC_PROTOCOL_" + PD->getNameAsString(),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001204 &CGM.getModule());
1205 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001206 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001207 UsedGlobals.push_back(Entry);
1208 // FIXME: Is this necessary? Why only for protocol?
1209 Entry->setAlignment(4);
1210 }
1211
1212 return Entry;
1213}
1214
1215/*
1216 struct _objc_protocol_extension {
1217 uint32_t size;
1218 struct objc_method_description_list *optional_instance_methods;
1219 struct objc_method_description_list *optional_class_methods;
1220 struct objc_property_list *instance_properties;
1221 };
1222*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001223llvm::Constant *
1224CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
1225 const ConstantVector &OptInstanceMethods,
1226 const ConstantVector &OptClassMethods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001227 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001228 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolExtensionTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001229 std::vector<llvm::Constant*> Values(4);
1230 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001231 Values[1] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001232 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_"
1233 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001234 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1235 OptInstanceMethods);
1236 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001237 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_"
1238 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001239 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1240 OptClassMethods);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001241 Values[3] = EmitPropertyList("\01L_OBJC_$_PROP_PROTO_LIST_" +
1242 PD->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001243 0, PD, ObjCTypes);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001244
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001245 // Return null if no extension bits are used.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001246 if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
1247 Values[3]->isNullValue())
1248 return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
1249
1250 llvm::Constant *Init =
1251 llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001252
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001253 // No special section, but goes in llvm.used
1254 return CreateMetadataVar("\01L_OBJC_PROTOCOLEXT_" + PD->getNameAsString(),
1255 Init,
1256 0, 0, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001257}
1258
1259/*
1260 struct objc_protocol_list {
1261 struct objc_protocol_list *next;
1262 long count;
1263 Protocol *list[];
1264 };
1265*/
Daniel Dunbardbc933702008-08-21 21:57:41 +00001266llvm::Constant *
1267CGObjCMac::EmitProtocolList(const std::string &Name,
1268 ObjCProtocolDecl::protocol_iterator begin,
1269 ObjCProtocolDecl::protocol_iterator end) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001270 std::vector<llvm::Constant*> ProtocolRefs;
1271
Daniel Dunbardbc933702008-08-21 21:57:41 +00001272 for (; begin != end; ++begin)
1273 ProtocolRefs.push_back(GetProtocolRef(*begin));
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001274
1275 // Just return null for empty protocol lists
1276 if (ProtocolRefs.empty())
1277 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1278
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001279 // This list is null terminated.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001280 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
1281
1282 std::vector<llvm::Constant*> Values(3);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001283 // This field is only used by the runtime.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001284 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1285 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
1286 Values[2] =
1287 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
1288 ProtocolRefs.size()),
1289 ProtocolRefs);
1290
1291 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1292 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001293 CreateMetadataVar(Name, Init, "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001294 4, false);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001295 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
1296}
1297
1298/*
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001299 struct _objc_property {
1300 const char * const name;
1301 const char * const attributes;
1302 };
1303
1304 struct _objc_property_list {
1305 uint32_t entsize; // sizeof (struct _objc_property)
1306 uint32_t prop_count;
1307 struct _objc_property[prop_count];
1308 };
1309*/
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001310llvm::Constant *CGObjCCommonMac::EmitPropertyList(const std::string &Name,
1311 const Decl *Container,
1312 const ObjCContainerDecl *OCD,
1313 const ObjCCommonTypesHelper &ObjCTypes) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001314 std::vector<llvm::Constant*> Properties, Prop(2);
Douglas Gregor6ab35242009-04-09 21:40:53 +00001315 for (ObjCContainerDecl::prop_iterator I = OCD->prop_begin(CGM.getContext()),
1316 E = OCD->prop_end(CGM.getContext()); I != E; ++I) {
Steve Naroff93983f82009-01-11 12:47:58 +00001317 const ObjCPropertyDecl *PD = *I;
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001318 Prop[0] = GetPropertyName(PD->getIdentifier());
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00001319 Prop[1] = GetPropertyTypeString(PD, Container);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001320 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
1321 Prop));
1322 }
1323
1324 // Return null for empty list.
1325 if (Properties.empty())
1326 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1327
1328 unsigned PropertySize =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001329 CGM.getTargetData().getTypePaddedSize(ObjCTypes.PropertyTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001330 std::vector<llvm::Constant*> Values(3);
1331 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
1332 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
1333 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
1334 Properties.size());
1335 Values[2] = llvm::ConstantArray::get(AT, Properties);
1336 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1337
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001338 llvm::GlobalVariable *GV =
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001339 CreateMetadataVar(Name, Init,
1340 (ObjCABI == 2) ? "__DATA, __objc_const" :
1341 "__OBJC,__property,regular,no_dead_strip",
1342 (ObjCABI == 2) ? 8 : 4,
1343 true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001344 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.PropertyListPtrTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001345}
1346
1347/*
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001348 struct objc_method_description_list {
1349 int count;
1350 struct objc_method_description list[];
1351 };
1352*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001353llvm::Constant *
1354CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
1355 std::vector<llvm::Constant*> Desc(2);
1356 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1357 ObjCTypes.SelectorPtrTy);
1358 Desc[1] = GetMethodVarType(MD);
1359 return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
1360 Desc);
1361}
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001362
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001363llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name,
1364 const char *Section,
1365 const ConstantVector &Methods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001366 // Return null for empty list.
1367 if (Methods.empty())
1368 return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
1369
1370 std::vector<llvm::Constant*> Values(2);
1371 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1372 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
1373 Methods.size());
1374 Values[1] = llvm::ConstantArray::get(AT, Methods);
1375 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1376
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001377 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001378 return llvm::ConstantExpr::getBitCast(GV,
1379 ObjCTypes.MethodDescriptionListPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001380}
1381
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001382/*
1383 struct _objc_category {
1384 char *category_name;
1385 char *class_name;
1386 struct _objc_method_list *instance_methods;
1387 struct _objc_method_list *class_methods;
1388 struct _objc_protocol_list *protocols;
1389 uint32_t size; // <rdar://4585769>
1390 struct _objc_property_list *instance_properties;
1391 };
1392 */
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001393void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001394 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.CategoryTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001395
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001396 // FIXME: This is poor design, the OCD should have a pointer to the
1397 // category decl. Additionally, note that Category can be null for
1398 // the @implementation w/o an @interface case. Sema should just
1399 // create one for us as it does for @implementation so everyone else
1400 // can live life under a clear blue sky.
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001401 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001402 const ObjCCategoryDecl *Category =
1403 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001404 std::string ExtName(Interface->getNameAsString() + "_" +
1405 OCD->getNameAsString());
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001406
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001407 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1408 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
1409 e = OCD->instmeth_end(); i != e; ++i) {
1410 // Instance methods should always be defined.
1411 InstanceMethods.push_back(GetMethodConstant(*i));
1412 }
1413 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
1414 e = OCD->classmeth_end(); i != e; ++i) {
1415 // Class methods should always be defined.
1416 ClassMethods.push_back(GetMethodConstant(*i));
1417 }
1418
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001419 std::vector<llvm::Constant*> Values(7);
1420 Values[0] = GetClassName(OCD->getIdentifier());
1421 Values[1] = GetClassName(Interface->getIdentifier());
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001422 Values[2] =
1423 EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") +
1424 ExtName,
1425 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001426 InstanceMethods);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001427 Values[3] =
1428 EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName,
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001429 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001430 ClassMethods);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001431 if (Category) {
1432 Values[4] =
1433 EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName,
1434 Category->protocol_begin(),
1435 Category->protocol_end());
1436 } else {
1437 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1438 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001439 Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001440
1441 // If there is no category @interface then there can be no properties.
1442 if (Category) {
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001443 Values[6] = EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001444 OCD, Category, ObjCTypes);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001445 } else {
1446 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1447 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001448
1449 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
1450 Values);
1451
1452 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001453 CreateMetadataVar(std::string("\01L_OBJC_CATEGORY_")+ExtName, Init,
1454 "__OBJC,__category,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001455 4, true);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001456 DefinedCategories.push_back(GV);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001457}
1458
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001459// FIXME: Get from somewhere?
1460enum ClassFlags {
1461 eClassFlags_Factory = 0x00001,
1462 eClassFlags_Meta = 0x00002,
1463 // <rdr://5142207>
1464 eClassFlags_HasCXXStructors = 0x02000,
1465 eClassFlags_Hidden = 0x20000,
1466 eClassFlags_ABI2_Hidden = 0x00010,
1467 eClassFlags_ABI2_HasCXXStructors = 0x00004 // <rdr://4923634>
1468};
1469
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001470/*
1471 struct _objc_class {
1472 Class isa;
1473 Class super_class;
1474 const char *name;
1475 long version;
1476 long info;
1477 long instance_size;
1478 struct _objc_ivar_list *ivars;
1479 struct _objc_method_list *methods;
1480 struct _objc_cache *cache;
1481 struct _objc_protocol_list *protocols;
1482 // Objective-C 1.0 extensions (<rdr://4585769>)
1483 const char *ivar_layout;
1484 struct _objc_class_ext *ext;
1485 };
1486
1487 See EmitClassExtension();
1488 */
1489void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001490 DefinedSymbols.insert(ID->getIdentifier());
1491
Chris Lattner8ec03f52008-11-24 03:54:41 +00001492 std::string ClassName = ID->getNameAsString();
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001493 // FIXME: Gross
1494 ObjCInterfaceDecl *Interface =
1495 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001496 llvm::Constant *Protocols =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001497 EmitProtocolList("\01L_OBJC_CLASS_PROTOCOLS_" + ID->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001498 Interface->protocol_begin(),
1499 Interface->protocol_end());
Chris Lattnerb7b58b12009-04-19 06:02:28 +00001500 const llvm::Type *InterfaceTy;
1501 if (Interface->isForwardDecl())
1502 InterfaceTy = llvm::StructType::get(NULL, NULL);
1503 else
1504 InterfaceTy =
Chris Lattner03d9f342009-04-01 06:23:52 +00001505 CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(Interface));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001506 unsigned Flags = eClassFlags_Factory;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001507 unsigned Size = CGM.getTargetData().getTypePaddedSize(InterfaceTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001508
1509 // FIXME: Set CXX-structors flag.
Daniel Dunbar04d40782009-04-14 06:00:08 +00001510 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001511 Flags |= eClassFlags_Hidden;
1512
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001513 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1514 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
1515 e = ID->instmeth_end(); i != e; ++i) {
1516 // Instance methods should always be defined.
1517 InstanceMethods.push_back(GetMethodConstant(*i));
1518 }
1519 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
1520 e = ID->classmeth_end(); i != e; ++i) {
1521 // Class methods should always be defined.
1522 ClassMethods.push_back(GetMethodConstant(*i));
1523 }
1524
1525 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
1526 e = ID->propimpl_end(); i != e; ++i) {
1527 ObjCPropertyImplDecl *PID = *i;
1528
1529 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1530 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1531
1532 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
1533 if (llvm::Constant *C = GetMethodConstant(MD))
1534 InstanceMethods.push_back(C);
1535 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
1536 if (llvm::Constant *C = GetMethodConstant(MD))
1537 InstanceMethods.push_back(C);
1538 }
1539 }
1540
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001541 std::vector<llvm::Constant*> Values(12);
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001542 Values[ 0] = EmitMetaClass(ID, Protocols, InterfaceTy, ClassMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001543 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001544 // Record a reference to the super class.
1545 LazySymbols.insert(Super->getIdentifier());
1546
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001547 Values[ 1] =
1548 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1549 ObjCTypes.ClassPtrTy);
1550 } else {
1551 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1552 }
1553 Values[ 2] = GetClassName(ID->getIdentifier());
1554 // Version is always 0.
1555 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1556 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1557 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001558 Values[ 6] = EmitIvarList(ID, false);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001559 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001560 EmitMethodList("\01L_OBJC_INSTANCE_METHODS_" + ID->getNameAsString(),
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001561 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001562 InstanceMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001563 // cache is always NULL.
1564 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1565 Values[ 9] = Protocols;
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001566 // FIXME: Set ivar_layout
Fariborz Jahanian667423a2009-03-25 22:36:49 +00001567 // Values[10] = BuildIvarLayout(ID, true);
1568 Values[10] = GetIvarLayoutName(0, ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001569 Values[11] = EmitClassExtension(ID);
1570 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1571 Values);
1572
1573 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001574 CreateMetadataVar(std::string("\01L_OBJC_CLASS_")+ClassName, Init,
1575 "__OBJC,__class,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001576 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001577 DefinedClasses.push_back(GV);
1578}
1579
1580llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
1581 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001582 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001583 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001584 unsigned Flags = eClassFlags_Meta;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001585 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001586
Daniel Dunbar04d40782009-04-14 06:00:08 +00001587 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001588 Flags |= eClassFlags_Hidden;
1589
1590 std::vector<llvm::Constant*> Values(12);
1591 // The isa for the metaclass is the root of the hierarchy.
1592 const ObjCInterfaceDecl *Root = ID->getClassInterface();
1593 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
1594 Root = Super;
1595 Values[ 0] =
1596 llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
1597 ObjCTypes.ClassPtrTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001598 // The super class for the metaclass is emitted as the name of the
1599 // super class. The runtime fixes this up to point to the
1600 // *metaclass* for the super class.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001601 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
1602 Values[ 1] =
1603 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1604 ObjCTypes.ClassPtrTy);
1605 } else {
1606 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1607 }
1608 Values[ 2] = GetClassName(ID->getIdentifier());
1609 // Version is always 0.
1610 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1611 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1612 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001613 Values[ 6] = EmitIvarList(ID, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001614 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001615 EmitMethodList("\01L_OBJC_CLASS_METHODS_" + ID->getNameAsString(),
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001616 "__OBJC,__cls_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001617 Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001618 // cache is always NULL.
1619 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1620 Values[ 9] = Protocols;
1621 // ivar_layout for metaclass is always NULL.
1622 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1623 // The class extension is always unused for metaclasses.
1624 Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1625 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1626 Values);
1627
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001628 std::string Name("\01L_OBJC_METACLASS_");
Chris Lattner8ec03f52008-11-24 03:54:41 +00001629 Name += ID->getNameAsCString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001630
1631 // Check for a forward reference.
1632 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
1633 if (GV) {
1634 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1635 "Forward metaclass reference has incorrect type.");
1636 GV->setLinkage(llvm::GlobalValue::InternalLinkage);
1637 GV->setInitializer(Init);
1638 } else {
1639 GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1640 llvm::GlobalValue::InternalLinkage,
1641 Init, Name,
1642 &CGM.getModule());
1643 }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001644 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001645 GV->setAlignment(4);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001646 UsedGlobals.push_back(GV);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001647
1648 return GV;
1649}
1650
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001651llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001652 std::string Name = "\01L_OBJC_METACLASS_" + ID->getNameAsString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001653
1654 // FIXME: Should we look these up somewhere other than the
1655 // module. Its a bit silly since we only generate these while
1656 // processing an implementation, so exactly one pointer would work
1657 // if know when we entered/exitted an implementation block.
1658
1659 // Check for an existing forward reference.
Fariborz Jahanianb0d27942009-01-07 20:11:22 +00001660 // Previously, metaclass with internal linkage may have been defined.
1661 // pass 'true' as 2nd argument so it is returned.
1662 if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true)) {
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001663 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1664 "Forward metaclass reference has incorrect type.");
1665 return GV;
1666 } else {
1667 // Generate as an external reference to keep a consistent
1668 // module. This will be patched up when we emit the metaclass.
1669 return new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1670 llvm::GlobalValue::ExternalLinkage,
1671 0,
1672 Name,
1673 &CGM.getModule());
1674 }
1675}
1676
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001677/*
1678 struct objc_class_ext {
1679 uint32_t size;
1680 const char *weak_ivar_layout;
1681 struct _objc_property_list *properties;
1682 };
1683*/
1684llvm::Constant *
1685CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
1686 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001687 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassExtensionTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001688
1689 std::vector<llvm::Constant*> Values(3);
1690 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001691 // FIXME: Output weak_ivar_layout string.
Fariborz Jahanian667423a2009-03-25 22:36:49 +00001692 // Values[1] = BuildIvarLayout(ID, false);
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00001693 Values[1] = GetIvarLayoutName(0, ObjCTypes);
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001694 Values[2] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001695 ID, ID->getClassInterface(), ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001696
1697 // Return null if no extension bits are used.
1698 if (Values[1]->isNullValue() && Values[2]->isNullValue())
1699 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1700
1701 llvm::Constant *Init =
1702 llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001703 return CreateMetadataVar("\01L_OBJC_CLASSEXT_" + ID->getNameAsString(),
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001704 Init, "__OBJC,__class_ext,regular,no_dead_strip",
1705 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001706}
1707
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001708/// countInheritedIvars - count number of ivars in class and its super class(s)
1709///
Douglas Gregor6ab35242009-04-09 21:40:53 +00001710static int countInheritedIvars(const ObjCInterfaceDecl *OI,
1711 ASTContext &Context) {
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001712 int count = 0;
1713 if (!OI)
1714 return 0;
1715 const ObjCInterfaceDecl *SuperClass = OI->getSuperClass();
1716 if (SuperClass)
Douglas Gregor6ab35242009-04-09 21:40:53 +00001717 count += countInheritedIvars(SuperClass, Context);
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001718 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1719 E = OI->ivar_end(); I != E; ++I)
1720 ++count;
Fariborz Jahanian18191882009-03-31 18:11:23 +00001721 // look into properties.
Douglas Gregor6ab35242009-04-09 21:40:53 +00001722 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(Context),
1723 E = OI->prop_end(Context); I != E; ++I) {
Fariborz Jahanian18191882009-03-31 18:11:23 +00001724 if ((*I)->getPropertyIvarDecl())
1725 ++count;
1726 }
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001727 return count;
1728}
1729
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001730/// getInterfaceDeclForIvar - Get the interface declaration node where
1731/// this ivar is declared in.
1732/// FIXME. Ideally, this info should be in the ivar node. But currently
1733/// it is not and prevailing wisdom is that ASTs should not have more
1734/// info than is absolutely needed, even though this info reflects the
1735/// source language.
1736///
1737static const ObjCInterfaceDecl *getInterfaceDeclForIvar(
1738 const ObjCInterfaceDecl *OI,
Douglas Gregor6ab35242009-04-09 21:40:53 +00001739 const ObjCIvarDecl *IVD,
1740 ASTContext &Context) {
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001741 if (!OI)
1742 return 0;
1743 assert(isa<ObjCInterfaceDecl>(OI) && "OI is not an interface");
1744 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1745 E = OI->ivar_end(); I != E; ++I)
1746 if ((*I)->getIdentifier() == IVD->getIdentifier())
1747 return OI;
Fariborz Jahanian5a4b4532009-03-31 17:00:52 +00001748 // look into properties.
Douglas Gregor6ab35242009-04-09 21:40:53 +00001749 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(Context),
1750 E = OI->prop_end(Context); I != E; ++I) {
Fariborz Jahanian5a4b4532009-03-31 17:00:52 +00001751 ObjCPropertyDecl *PDecl = (*I);
1752 if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl())
1753 if (IV->getIdentifier() == IVD->getIdentifier())
1754 return OI;
1755 }
Douglas Gregor6ab35242009-04-09 21:40:53 +00001756 return getInterfaceDeclForIvar(OI->getSuperClass(), IVD, Context);
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001757}
1758
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001759/*
1760 struct objc_ivar {
1761 char *ivar_name;
1762 char *ivar_type;
1763 int ivar_offset;
1764 };
1765
1766 struct objc_ivar_list {
1767 int ivar_count;
1768 struct objc_ivar list[count];
1769 };
1770 */
1771llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001772 bool ForClass) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001773 std::vector<llvm::Constant*> Ivars, Ivar(3);
1774
1775 // When emitting the root class GCC emits ivar entries for the
1776 // actual class structure. It is not clear if we need to follow this
1777 // behavior; for now lets try and get away with not doing it. If so,
1778 // the cleanest solution would be to make up an ObjCInterfaceDecl
1779 // for the class.
1780 if (ForClass)
1781 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001782
1783 ObjCInterfaceDecl *OID =
1784 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00001785 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001786
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00001787 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
1788 GetNamedIvarList(OID, OIvars);
1789
1790 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
1791 ObjCIvarDecl *IVD = OIvars[i];
1792 const FieldDecl *Field = OID->lookupFieldDeclForIvar(CGM.getContext(), IVD);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00001793 uint64_t Offset = GetIvarBaseOffset(Layout, Field);
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00001794 Ivar[0] = GetMethodVarName(Field->getIdentifier());
Devang Patel7794bb82009-03-04 18:21:39 +00001795 Ivar[1] = GetMethodVarType(Field);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001796 Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy, Offset);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001797 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001798 }
1799
1800 // Return null for empty list.
1801 if (Ivars.empty())
1802 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
1803
1804 std::vector<llvm::Constant*> Values(2);
1805 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
1806 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
1807 Ivars.size());
1808 Values[1] = llvm::ConstantArray::get(AT, Ivars);
1809 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1810
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001811 llvm::GlobalVariable *GV;
1812 if (ForClass)
1813 GV = CreateMetadataVar("\01L_OBJC_CLASS_VARIABLES_" + ID->getNameAsString(),
Daniel Dunbar58a29122009-03-09 22:18:41 +00001814 Init, "__OBJC,__class_vars,regular,no_dead_strip",
1815 4, true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001816 else
1817 GV = CreateMetadataVar("\01L_OBJC_INSTANCE_VARIABLES_"
1818 + ID->getNameAsString(),
1819 Init, "__OBJC,__instance_vars,regular,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001820 4, true);
1821 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.IvarListPtrTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001822}
1823
1824/*
1825 struct objc_method {
1826 SEL method_name;
1827 char *method_types;
1828 void *method;
1829 };
1830
1831 struct objc_method_list {
1832 struct objc_method_list *obsolete;
1833 int count;
1834 struct objc_method methods_list[count];
1835 };
1836*/
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001837
1838/// GetMethodConstant - Return a struct objc_method constant for the
1839/// given method if it has been defined. The result is null if the
1840/// method has not been defined. The return value has type MethodPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001841llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001842 // FIXME: Use DenseMap::lookup
1843 llvm::Function *Fn = MethodDefinitions[MD];
1844 if (!Fn)
1845 return 0;
1846
1847 std::vector<llvm::Constant*> Method(3);
1848 Method[0] =
1849 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1850 ObjCTypes.SelectorPtrTy);
1851 Method[1] = GetMethodVarType(MD);
1852 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
1853 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
1854}
1855
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001856llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name,
1857 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001858 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001859 // Return null for empty list.
1860 if (Methods.empty())
1861 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
1862
1863 std::vector<llvm::Constant*> Values(3);
1864 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1865 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1866 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
1867 Methods.size());
1868 Values[2] = llvm::ConstantArray::get(AT, Methods);
1869 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1870
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001871 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001872 return llvm::ConstantExpr::getBitCast(GV,
1873 ObjCTypes.MethodListPtrTy);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001874}
1875
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001876llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD,
Daniel Dunbarbb36d332009-02-02 21:43:58 +00001877 const ObjCContainerDecl *CD) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001878 std::string Name;
Fariborz Jahanian679a5022009-01-10 21:06:09 +00001879 GetNameForMethod(OMD, CD, Name);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001880
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001881 CodeGenTypes &Types = CGM.getTypes();
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001882 const llvm::FunctionType *MethodTy =
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001883 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001884 llvm::Function *Method =
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001885 llvm::Function::Create(MethodTy,
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001886 llvm::GlobalValue::InternalLinkage,
1887 Name,
1888 &CGM.getModule());
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001889 MethodDefinitions.insert(std::make_pair(OMD, Method));
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001890
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001891 return Method;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001892}
1893
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00001894uint64_t CGObjCCommonMac::GetIvarBaseOffset(const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +00001895 const FieldDecl *Field) {
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00001896 if (!Field->isBitField())
Daniel Dunbar48fa0642009-04-19 02:03:42 +00001897 return Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(Field));
1898
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00001899 // FIXME. Must be a better way of getting a bitfield base offset.
Daniel Dunbar48fa0642009-04-19 02:03:42 +00001900 CodeGenTypes::BitFieldInfo BFI = CGM.getTypes().getBitFieldInfo(Field);
1901 // FIXME: The "field no" for bitfields is something completely
1902 // different; it is the offset in multiples of the base type size!
1903 uint64_t Offset = CGM.getTypes().getLLVMFieldNo(Field);
1904 const llvm::Type *Ty =
1905 CGM.getTypes().ConvertTypeForMemRecursive(Field->getType());
1906 Offset *= CGM.getTypes().getTargetData().getTypePaddedSizeInBits(Ty);
1907 return (Offset + BFI.Begin) / 8;
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00001908}
1909
Daniel Dunbar48fa0642009-04-19 02:03:42 +00001910/// GetFieldBaseOffset - return the field's byte offset.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00001911uint64_t CGObjCCommonMac::GetFieldBaseOffset(const ObjCInterfaceDecl *OI,
1912 const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +00001913 const FieldDecl *Field) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00001914 const ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
Chris Lattnercd0ee142009-03-31 08:33:16 +00001915 const FieldDecl *FD = OI->lookupFieldDeclForIvar(CGM.getContext(), Ivar);
1916 return GetIvarBaseOffset(Layout, FD);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00001917}
1918
Daniel Dunbarfd65d372009-03-09 20:09:19 +00001919llvm::GlobalVariable *
1920CGObjCCommonMac::CreateMetadataVar(const std::string &Name,
1921 llvm::Constant *Init,
1922 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +00001923 unsigned Align,
1924 bool AddToUsed) {
Daniel Dunbarfd65d372009-03-09 20:09:19 +00001925 const llvm::Type *Ty = Init->getType();
1926 llvm::GlobalVariable *GV =
1927 new llvm::GlobalVariable(Ty, false,
1928 llvm::GlobalValue::InternalLinkage,
1929 Init,
1930 Name,
1931 &CGM.getModule());
1932 if (Section)
1933 GV->setSection(Section);
Daniel Dunbar35bd7632009-03-09 20:50:13 +00001934 if (Align)
1935 GV->setAlignment(Align);
1936 if (AddToUsed)
Daniel Dunbarfd65d372009-03-09 20:09:19 +00001937 UsedGlobals.push_back(GV);
1938 return GV;
1939}
1940
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001941llvm::Function *CGObjCMac::ModuleInitFunction() {
Daniel Dunbarf77ac862008-08-11 21:35:06 +00001942 // Abuse this interface function as a place to finalize.
1943 FinishModule();
1944
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001945 return NULL;
1946}
1947
Chris Lattner74391b42009-03-22 21:03:39 +00001948llvm::Constant *CGObjCMac::GetPropertyGetFunction() {
Daniel Dunbar49f66022008-09-24 03:38:44 +00001949 return ObjCTypes.GetPropertyFn;
1950}
1951
Chris Lattner74391b42009-03-22 21:03:39 +00001952llvm::Constant *CGObjCMac::GetPropertySetFunction() {
Daniel Dunbar49f66022008-09-24 03:38:44 +00001953 return ObjCTypes.SetPropertyFn;
1954}
1955
Chris Lattner74391b42009-03-22 21:03:39 +00001956llvm::Constant *CGObjCMac::EnumerationMutationFunction() {
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001957 return ObjCTypes.EnumerationMutationFn;
1958}
1959
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001960/*
1961
1962Objective-C setjmp-longjmp (sjlj) Exception Handling
1963--
1964
1965The basic framework for a @try-catch-finally is as follows:
1966{
1967 objc_exception_data d;
1968 id _rethrow = null;
Anders Carlsson190d00e2009-02-07 21:26:04 +00001969 bool _call_try_exit = true;
1970
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001971 objc_exception_try_enter(&d);
1972 if (!setjmp(d.jmp_buf)) {
1973 ... try body ...
1974 } else {
1975 // exception path
1976 id _caught = objc_exception_extract(&d);
1977
1978 // enter new try scope for handlers
1979 if (!setjmp(d.jmp_buf)) {
1980 ... match exception and execute catch blocks ...
1981
1982 // fell off end, rethrow.
1983 _rethrow = _caught;
Daniel Dunbar898d5082008-09-30 01:06:03 +00001984 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001985 } else {
1986 // exception in catch block
1987 _rethrow = objc_exception_extract(&d);
Anders Carlsson190d00e2009-02-07 21:26:04 +00001988 _call_try_exit = false;
1989 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001990 }
1991 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00001992 ... jump-through-finally to finally_end ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001993
1994finally:
Anders Carlsson190d00e2009-02-07 21:26:04 +00001995 if (_call_try_exit)
1996 objc_exception_try_exit(&d);
1997
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001998 ... finally block ....
Daniel Dunbar898d5082008-09-30 01:06:03 +00001999 ... dispatch to finally destination ...
2000
2001finally_rethrow:
2002 objc_exception_throw(_rethrow);
2003
2004finally_end:
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002005}
2006
2007This framework differs slightly from the one gcc uses, in that gcc
Daniel Dunbar898d5082008-09-30 01:06:03 +00002008uses _rethrow to determine if objc_exception_try_exit should be called
2009and if the object should be rethrown. This breaks in the face of
2010throwing nil and introduces unnecessary branches.
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002011
2012We specialize this framework for a few particular circumstances:
2013
2014 - If there are no catch blocks, then we avoid emitting the second
2015 exception handling context.
2016
2017 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
2018 e)) we avoid emitting the code to rethrow an uncaught exception.
2019
2020 - FIXME: If there is no @finally block we can do a few more
2021 simplifications.
2022
2023Rethrows and Jumps-Through-Finally
2024--
2025
2026Support for implicit rethrows and jumping through the finally block is
2027handled by storing the current exception-handling context in
2028ObjCEHStack.
2029
Daniel Dunbar898d5082008-09-30 01:06:03 +00002030In order to implement proper @finally semantics, we support one basic
2031mechanism for jumping through the finally block to an arbitrary
2032destination. Constructs which generate exits from a @try or @catch
2033block use this mechanism to implement the proper semantics by chaining
2034jumps, as necessary.
2035
2036This mechanism works like the one used for indirect goto: we
2037arbitrarily assign an ID to each destination and store the ID for the
2038destination in a variable prior to entering the finally block. At the
2039end of the finally block we simply create a switch to the proper
2040destination.
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002041
2042Code gen for @synchronized(expr) stmt;
2043Effectively generating code for:
2044objc_sync_enter(expr);
2045@try stmt @finally { objc_sync_exit(expr); }
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002046*/
2047
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002048void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
2049 const Stmt &S) {
2050 bool isTry = isa<ObjCAtTryStmt>(S);
Daniel Dunbar898d5082008-09-30 01:06:03 +00002051 // Create various blocks we refer to for handling @finally.
Daniel Dunbar55e87422008-11-11 02:29:29 +00002052 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002053 llvm::BasicBlock *FinallyExit = CGF.createBasicBlock("finally.exit");
Daniel Dunbar55e87422008-11-11 02:29:29 +00002054 llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
2055 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
2056 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
Daniel Dunbar1c566672009-02-24 01:43:46 +00002057
2058 // For @synchronized, call objc_sync_enter(sync.expr). The
2059 // evaluation of the expression must occur before we enter the
2060 // @synchronized. We can safely avoid a temp here because jumps into
2061 // @synchronized are illegal & this will dominate uses.
2062 llvm::Value *SyncArg = 0;
2063 if (!isTry) {
2064 SyncArg =
2065 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
2066 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00002067 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar1c566672009-02-24 01:43:46 +00002068 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00002069
2070 // Push an EH context entry, used for handling rethrows and jumps
2071 // through finally.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002072 CGF.PushCleanupBlock(FinallyBlock);
2073
Anders Carlsson273558f2009-02-07 21:37:21 +00002074 CGF.ObjCEHValueStack.push_back(0);
2075
Daniel Dunbar898d5082008-09-30 01:06:03 +00002076 // Allocate memory for the exception data and rethrow pointer.
Anders Carlsson80f25672008-09-09 17:59:25 +00002077 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
2078 "exceptiondata.ptr");
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002079 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
2080 "_rethrow");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002081 llvm::Value *CallTryExitPtr = CGF.CreateTempAlloca(llvm::Type::Int1Ty,
2082 "_call_try_exit");
2083 CGF.Builder.CreateStore(llvm::ConstantInt::getTrue(), CallTryExitPtr);
2084
Anders Carlsson80f25672008-09-09 17:59:25 +00002085 // Enter a new try block and call setjmp.
2086 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
2087 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
2088 "jmpbufarray");
2089 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
2090 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
2091 JmpBufPtr, "result");
Daniel Dunbar898d5082008-09-30 01:06:03 +00002092
Daniel Dunbar55e87422008-11-11 02:29:29 +00002093 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
2094 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002095 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002096 TryHandler, TryBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002097
2098 // Emit the @try block.
2099 CGF.EmitBlock(TryBlock);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002100 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
2101 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002102 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002103
2104 // Emit the "exception in @try" block.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002105 CGF.EmitBlock(TryHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002106
2107 // Retrieve the exception object. We may emit multiple blocks but
2108 // nothing can cross this so the value is already in SSA form.
2109 llvm::Value *Caught = CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
2110 ExceptionData,
2111 "caught");
Anders Carlsson273558f2009-02-07 21:37:21 +00002112 CGF.ObjCEHValueStack.back() = Caught;
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002113 if (!isTry)
2114 {
2115 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002116 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002117 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002118 }
2119 else if (const ObjCAtCatchStmt* CatchStmt =
2120 cast<ObjCAtTryStmt>(S).getCatchStmts())
2121 {
Daniel Dunbar55e40722008-09-27 07:03:52 +00002122 // Enter a new exception try block (in case a @catch block throws
2123 // an exception).
Anders Carlsson80f25672008-09-09 17:59:25 +00002124 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002125
Anders Carlsson80f25672008-09-09 17:59:25 +00002126 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
2127 JmpBufPtr, "result");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002128 llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw");
Anders Carlsson80f25672008-09-09 17:59:25 +00002129
Daniel Dunbar55e87422008-11-11 02:29:29 +00002130 llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch");
2131 llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler");
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002132 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002133
2134 CGF.EmitBlock(CatchBlock);
2135
Daniel Dunbar55e40722008-09-27 07:03:52 +00002136 // Handle catch list. As a special case we check if everything is
2137 // matched and avoid generating code for falling off the end if
2138 // so.
2139 bool AllMatched = false;
Anders Carlsson80f25672008-09-09 17:59:25 +00002140 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbar55e87422008-11-11 02:29:29 +00002141 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch");
Anders Carlsson80f25672008-09-09 17:59:25 +00002142
Steve Naroff7ba138a2009-03-03 19:52:17 +00002143 const ParmVarDecl *CatchParam = CatchStmt->getCatchParamDecl();
Daniel Dunbar129271a2008-09-27 07:36:24 +00002144 const PointerType *PT = 0;
2145
Anders Carlsson80f25672008-09-09 17:59:25 +00002146 // catch(...) always matches.
Daniel Dunbar55e40722008-09-27 07:03:52 +00002147 if (!CatchParam) {
2148 AllMatched = true;
2149 } else {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002150 PT = CatchParam->getType()->getAsPointerType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002151
Daniel Dunbar97f61d12008-09-27 22:21:14 +00002152 // catch(id e) always matches.
2153 // FIXME: For the time being we also match id<X>; this should
2154 // be rejected by Sema instead.
Steve Naroff389bf462009-02-12 17:52:19 +00002155 if ((PT && CGF.getContext().isObjCIdStructType(PT->getPointeeType())) ||
Steve Naroff7ba138a2009-03-03 19:52:17 +00002156 CatchParam->getType()->isObjCQualifiedIdType())
Daniel Dunbar55e40722008-09-27 07:03:52 +00002157 AllMatched = true;
Anders Carlsson80f25672008-09-09 17:59:25 +00002158 }
2159
Daniel Dunbar55e40722008-09-27 07:03:52 +00002160 if (AllMatched) {
Anders Carlssondde0a942008-09-11 09:15:33 +00002161 if (CatchParam) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002162 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002163 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002164 CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002165 }
Anders Carlsson1452f552008-09-11 08:21:54 +00002166
Anders Carlssondde0a942008-09-11 09:15:33 +00002167 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002168 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002169 break;
2170 }
2171
Daniel Dunbar129271a2008-09-27 07:36:24 +00002172 assert(PT && "Unexpected non-pointer type in @catch");
2173 QualType T = PT->getPointeeType();
Anders Carlsson4b7ff6e2008-09-11 06:35:14 +00002174 const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002175 assert(ObjCType && "Catch parameter must have Objective-C type!");
2176
2177 // Check if the @catch block matches the exception object.
2178 llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl());
2179
Anders Carlsson80f25672008-09-09 17:59:25 +00002180 llvm::Value *Match = CGF.Builder.CreateCall2(ObjCTypes.ExceptionMatchFn,
2181 Class, Caught, "match");
Anders Carlsson80f25672008-09-09 17:59:25 +00002182
Daniel Dunbar55e87422008-11-11 02:29:29 +00002183 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched");
Anders Carlsson80f25672008-09-09 17:59:25 +00002184
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002185 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002186 MatchedBlock, NextCatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002187
2188 // Emit the @catch block.
2189 CGF.EmitBlock(MatchedBlock);
Steve Naroff7ba138a2009-03-03 19:52:17 +00002190 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002191 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002192
2193 llvm::Value *Tmp =
Steve Naroff7ba138a2009-03-03 19:52:17 +00002194 CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(CatchParam->getType()),
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002195 "tmp");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002196 CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002197
2198 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002199 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002200
2201 CGF.EmitBlock(NextCatchBlock);
2202 }
2203
Daniel Dunbar55e40722008-09-27 07:03:52 +00002204 if (!AllMatched) {
2205 // None of the handlers caught the exception, so store it to be
2206 // rethrown at the end of the @finally block.
2207 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002208 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002209 }
2210
2211 // Emit the exception handler for the @catch blocks.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002212 CGF.EmitBlock(CatchHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002213 CGF.Builder.CreateStore(CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
2214 ExceptionData),
2215 RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002216 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002217 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002218 } else {
Anders Carlsson80f25672008-09-09 17:59:25 +00002219 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002220 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002221 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Anders Carlsson80f25672008-09-09 17:59:25 +00002222 }
2223
Daniel Dunbar898d5082008-09-30 01:06:03 +00002224 // Pop the exception-handling stack entry. It is important to do
2225 // this now, because the code in the @finally block is not in this
2226 // context.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002227 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
2228
Anders Carlsson273558f2009-02-07 21:37:21 +00002229 CGF.ObjCEHValueStack.pop_back();
2230
Anders Carlsson80f25672008-09-09 17:59:25 +00002231 // Emit the @finally block.
2232 CGF.EmitBlock(FinallyBlock);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002233 llvm::Value* CallTryExit = CGF.Builder.CreateLoad(CallTryExitPtr, "tmp");
2234
2235 CGF.Builder.CreateCondBr(CallTryExit, FinallyExit, FinallyNoExit);
2236
2237 CGF.EmitBlock(FinallyExit);
Anders Carlsson80f25672008-09-09 17:59:25 +00002238 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryExitFn, ExceptionData);
Daniel Dunbar129271a2008-09-27 07:36:24 +00002239
2240 CGF.EmitBlock(FinallyNoExit);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002241 if (isTry) {
2242 if (const ObjCAtFinallyStmt* FinallyStmt =
2243 cast<ObjCAtTryStmt>(S).getFinallyStmt())
2244 CGF.EmitStmt(FinallyStmt->getFinallyBody());
Daniel Dunbar1c566672009-02-24 01:43:46 +00002245 } else {
2246 // Emit objc_sync_exit(expr); as finally's sole statement for
2247 // @synchronized.
2248 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, SyncArg);
Fariborz Jahanianf2878e52008-11-21 19:21:53 +00002249 }
Anders Carlsson80f25672008-09-09 17:59:25 +00002250
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002251 // Emit the switch block
2252 if (Info.SwitchBlock)
2253 CGF.EmitBlock(Info.SwitchBlock);
2254 if (Info.EndBlock)
2255 CGF.EmitBlock(Info.EndBlock);
2256
Daniel Dunbar898d5082008-09-30 01:06:03 +00002257 CGF.EmitBlock(FinallyRethrow);
2258 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn,
2259 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002260 CGF.Builder.CreateUnreachable();
Daniel Dunbar898d5082008-09-30 01:06:03 +00002261
2262 CGF.EmitBlock(FinallyEnd);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002263}
2264
2265void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar898d5082008-09-30 01:06:03 +00002266 const ObjCAtThrowStmt &S) {
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002267 llvm::Value *ExceptionAsObject;
2268
2269 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2270 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
2271 ExceptionAsObject =
2272 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
2273 } else {
Anders Carlsson273558f2009-02-07 21:37:21 +00002274 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002275 "Unexpected rethrow outside @catch block.");
Anders Carlsson273558f2009-02-07 21:37:21 +00002276 ExceptionAsObject = CGF.ObjCEHValueStack.back();
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002277 }
2278
2279 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
Anders Carlsson80f25672008-09-09 17:59:25 +00002280 CGF.Builder.CreateUnreachable();
Daniel Dunbara448fb22008-11-11 23:11:34 +00002281
2282 // Clear the insertion point to indicate we are in unreachable code.
2283 CGF.Builder.ClearInsertionPoint();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002284}
2285
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002286/// EmitObjCWeakRead - Code gen for loading value of a __weak
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002287/// object: objc_read_weak (id *src)
2288///
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002289llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002290 llvm::Value *AddrWeakObj)
2291{
Eli Friedman8339b352009-03-07 03:57:15 +00002292 const llvm::Type* DestTy =
2293 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002294 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002295 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002296 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00002297 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002298 return read_weak;
2299}
2300
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002301/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
2302/// objc_assign_weak (id src, id *dst)
2303///
2304void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
2305 llvm::Value *src, llvm::Value *dst)
2306{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002307 const llvm::Type * SrcTy = src->getType();
2308 if (!isa<llvm::PointerType>(SrcTy)) {
2309 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2310 assert(Size <= 8 && "does not support size > 8");
2311 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2312 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002313 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2314 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002315 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2316 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattner96508e12009-04-17 22:12:36 +00002317 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002318 src, dst, "weakassign");
2319 return;
2320}
2321
Fariborz Jahanian58626502008-11-19 00:59:10 +00002322/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
2323/// objc_assign_global (id src, id *dst)
2324///
2325void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
2326 llvm::Value *src, llvm::Value *dst)
2327{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002328 const llvm::Type * SrcTy = src->getType();
2329 if (!isa<llvm::PointerType>(SrcTy)) {
2330 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2331 assert(Size <= 8 && "does not support size > 8");
2332 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2333 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002334 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2335 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002336 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2337 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian58626502008-11-19 00:59:10 +00002338 CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn,
2339 src, dst, "globalassign");
2340 return;
2341}
2342
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002343/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
2344/// objc_assign_ivar (id src, id *dst)
2345///
2346void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
2347 llvm::Value *src, llvm::Value *dst)
2348{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002349 const llvm::Type * SrcTy = src->getType();
2350 if (!isa<llvm::PointerType>(SrcTy)) {
2351 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2352 assert(Size <= 8 && "does not support size > 8");
2353 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2354 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002355 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2356 }
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002357 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2358 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
2359 CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn,
2360 src, dst, "assignivar");
2361 return;
2362}
2363
Fariborz Jahanian58626502008-11-19 00:59:10 +00002364/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
2365/// objc_assign_strongCast (id src, id *dst)
2366///
2367void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
2368 llvm::Value *src, llvm::Value *dst)
2369{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002370 const llvm::Type * SrcTy = src->getType();
2371 if (!isa<llvm::PointerType>(SrcTy)) {
2372 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2373 assert(Size <= 8 && "does not support size > 8");
2374 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2375 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002376 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2377 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002378 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2379 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian58626502008-11-19 00:59:10 +00002380 CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn,
2381 src, dst, "weakassign");
2382 return;
2383}
2384
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002385/// EmitObjCValueForIvar - Code Gen for ivar reference.
2386///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002387LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
2388 QualType ObjectTy,
2389 llvm::Value *BaseValue,
2390 const ObjCIvarDecl *Ivar,
2391 const FieldDecl *Field,
2392 unsigned CVRQualifiers) {
2393 if (Ivar->isBitField())
2394 return CGF.EmitLValueForBitfield(BaseValue, const_cast<FieldDecl *>(Field),
2395 CVRQualifiers);
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002396 // TODO: Add a special case for isa (index 0)
2397 unsigned Index = CGM.getTypes().getLLVMFieldNo(Field);
2398 llvm::Value *V = CGF.Builder.CreateStructGEP(BaseValue, Index, "tmp");
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002399 LValue LV = LValue::MakeAddr(V,
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00002400 Ivar->getType().getCVRQualifiers()|CVRQualifiers,
2401 CGM.getContext().getObjCGCAttrKind(Ivar->getType()));
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002402 LValue::SetObjCIvar(LV, true);
2403 return LV;
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002404}
2405
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002406llvm::Value *CGObjCMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
2407 ObjCInterfaceDecl *Interface,
2408 const ObjCIvarDecl *Ivar) {
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002409 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(Interface);
Daniel Dunbar60952f92009-04-20 00:37:55 +00002410 const FieldDecl *Field =
2411 Interface->lookupFieldDeclForIvar(CGM.getContext(), Ivar);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00002412 uint64_t Offset = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002413 return llvm::ConstantInt::get(
2414 CGM.getTypes().ConvertType(CGM.getContext().LongTy),
2415 Offset);
2416}
2417
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002418/* *** Private Interface *** */
2419
2420/// EmitImageInfo - Emit the image info marker used to encode some module
2421/// level information.
2422///
2423/// See: <rdr://4810609&4810587&4810587>
2424/// struct IMAGE_INFO {
2425/// unsigned version;
2426/// unsigned flags;
2427/// };
2428enum ImageInfoFlags {
2429 eImageInfo_FixAndContinue = (1 << 0), // FIXME: Not sure what this implies
2430 eImageInfo_GarbageCollected = (1 << 1),
2431 eImageInfo_GCOnly = (1 << 2)
2432};
2433
2434void CGObjCMac::EmitImageInfo() {
2435 unsigned version = 0; // Version is unused?
2436 unsigned flags = 0;
2437
2438 // FIXME: Fix and continue?
2439 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
2440 flags |= eImageInfo_GarbageCollected;
2441 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
2442 flags |= eImageInfo_GCOnly;
2443
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002444 // Emitted as int[2];
2445 llvm::Constant *values[2] = {
2446 llvm::ConstantInt::get(llvm::Type::Int32Ty, version),
2447 llvm::ConstantInt::get(llvm::Type::Int32Ty, flags)
2448 };
2449 llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002450
2451 const char *Section;
2452 if (ObjCABI == 1)
2453 Section = "__OBJC, __image_info,regular";
2454 else
2455 Section = "__DATA, __objc_imageinfo, regular, no_dead_strip";
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002456 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002457 CreateMetadataVar("\01L_OBJC_IMAGE_INFO",
2458 llvm::ConstantArray::get(AT, values, 2),
2459 Section,
2460 0,
2461 true);
2462 GV->setConstant(true);
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002463}
2464
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002465
2466// struct objc_module {
2467// unsigned long version;
2468// unsigned long size;
2469// const char *name;
2470// Symtab symtab;
2471// };
2472
2473// FIXME: Get from somewhere
2474static const int ModuleVersion = 7;
2475
2476void CGObjCMac::EmitModuleInfo() {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00002477 uint64_t Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ModuleTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002478
2479 std::vector<llvm::Constant*> Values(4);
2480 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
2481 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002482 // This used to be the filename, now it is unused. <rdr://4327263>
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002483 Values[2] = GetClassName(&CGM.getContext().Idents.get(""));
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002484 Values[3] = EmitModuleSymbols();
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002485 CreateMetadataVar("\01L_OBJC_MODULES",
2486 llvm::ConstantStruct::get(ObjCTypes.ModuleTy, Values),
2487 "__OBJC,__module_info,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00002488 4, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002489}
2490
2491llvm::Constant *CGObjCMac::EmitModuleSymbols() {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002492 unsigned NumClasses = DefinedClasses.size();
2493 unsigned NumCategories = DefinedCategories.size();
2494
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002495 // Return null if no symbols were defined.
2496 if (!NumClasses && !NumCategories)
2497 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
2498
2499 std::vector<llvm::Constant*> Values(5);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002500 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2501 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
2502 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
2503 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
2504
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002505 // The runtime expects exactly the list of defined classes followed
2506 // by the list of defined categories, in a single array.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002507 std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002508 for (unsigned i=0; i<NumClasses; i++)
2509 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
2510 ObjCTypes.Int8PtrTy);
2511 for (unsigned i=0; i<NumCategories; i++)
2512 Symbols[NumClasses + i] =
2513 llvm::ConstantExpr::getBitCast(DefinedCategories[i],
2514 ObjCTypes.Int8PtrTy);
2515
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002516 Values[4] =
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002517 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002518 NumClasses + NumCategories),
2519 Symbols);
2520
2521 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2522
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002523 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002524 CreateMetadataVar("\01L_OBJC_SYMBOLS", Init,
2525 "__OBJC,__symbols,regular,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002526 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002527 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
2528}
2529
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002530llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002531 const ObjCInterfaceDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002532 LazySymbols.insert(ID->getIdentifier());
2533
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002534 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
2535
2536 if (!Entry) {
2537 llvm::Constant *Casted =
2538 llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()),
2539 ObjCTypes.ClassPtrTy);
2540 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002541 CreateMetadataVar("\01L_OBJC_CLASS_REFERENCES_", Casted,
2542 "__OBJC,__cls_refs,literal_pointers,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002543 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002544 }
2545
2546 return Builder.CreateLoad(Entry, false, "tmp");
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002547}
2548
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002549llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002550 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
2551
2552 if (!Entry) {
2553 llvm::Constant *Casted =
2554 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
2555 ObjCTypes.SelectorPtrTy);
2556 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002557 CreateMetadataVar("\01L_OBJC_SELECTOR_REFERENCES_", Casted,
2558 "__OBJC,__message_refs,literal_pointers,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002559 4, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002560 }
2561
2562 return Builder.CreateLoad(Entry, false, "tmp");
2563}
2564
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00002565llvm::Constant *CGObjCCommonMac::GetClassName(IdentifierInfo *Ident) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002566 llvm::GlobalVariable *&Entry = ClassNames[Ident];
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002567
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002568 if (!Entry)
2569 Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
2570 llvm::ConstantArray::get(Ident->getName()),
2571 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00002572 1, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002573
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002574 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002575}
2576
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002577/// GetInterfaceDeclStructLayout - Get layout for ivars of given
2578/// interface declaration.
2579const llvm::StructLayout *CGObjCCommonMac::GetInterfaceDeclStructLayout(
2580 const ObjCInterfaceDecl *OID) const {
Chris Lattnerb7b58b12009-04-19 06:02:28 +00002581 const llvm::Type *InterfaceTy;
2582
Daniel Dunbarb02532a2009-04-19 23:41:48 +00002583 // FIXME: When does this happen? It seems pretty bad to do this...
Chris Lattnerb7b58b12009-04-19 06:02:28 +00002584 if (OID->isForwardDecl()) {
2585 InterfaceTy = llvm::StructType::get(NULL, NULL);
2586 } else {
2587 QualType T = CGM.getContext().getObjCInterfaceType(
2588 const_cast<ObjCInterfaceDecl*>(OID));
2589 InterfaceTy = CGM.getTypes().ConvertType(T);
2590 }
2591
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002592 const llvm::StructLayout *Layout =
2593 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceTy));
2594 return Layout;
2595}
2596
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00002597/// GetIvarLayoutName - Returns a unique constant for the given
2598/// ivar layout bitmap.
2599llvm::Constant *CGObjCCommonMac::GetIvarLayoutName(IdentifierInfo *Ident,
2600 const ObjCCommonTypesHelper &ObjCTypes) {
2601 return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2602}
2603
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002604void CGObjCCommonMac::BuildAggrIvarLayout(const ObjCInterfaceDecl *OI,
2605 const llvm::StructLayout *Layout,
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002606 const RecordDecl *RD,
Chris Lattnerf1690852009-03-31 08:48:01 +00002607 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002608 unsigned int BytePos, bool ForStrongLayout,
2609 int &Index, int &SkIndex, bool &HasUnion) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002610 bool IsUnion = (RD && RD->isUnion());
2611 uint64_t MaxUnionIvarSize = 0;
2612 uint64_t MaxSkippedUnionIvarSize = 0;
2613 FieldDecl *MaxField = 0;
2614 FieldDecl *MaxSkippedField = 0;
Chris Lattnerf1690852009-03-31 08:48:01 +00002615 unsigned base = 0;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002616 if (RecFields.empty())
2617 return;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002618 if (IsUnion)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002619 base = BytePos + GetFieldBaseOffset(OI, Layout, RecFields[0]);
Chris Lattnerf1690852009-03-31 08:48:01 +00002620 unsigned WordSizeInBits = CGM.getContext().Target.getPointerWidth(0);
2621 unsigned ByteSizeInBits = CGM.getContext().Target.getCharWidth();
2622
2623 llvm::SmallVector<FieldDecl*, 16> TmpRecFields;
2624
2625 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002626 FieldDecl *Field = RecFields[i];
2627 // Skip over unnamed or bitfields
2628 if (!Field->getIdentifier() || Field->isBitField())
2629 continue;
2630 QualType FQT = Field->getType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002631 if (FQT->isRecordType() || FQT->isUnionType()) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002632 if (FQT->isUnionType())
2633 HasUnion = true;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002634 else
2635 assert(FQT->isRecordType() &&
2636 "only union/record is supported for ivar layout bitmap");
2637
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002638 const RecordType *RT = FQT->getAsRecordType();
2639 const RecordDecl *RD = RT->getDecl();
Daniel Dunbarb02532a2009-04-19 23:41:48 +00002640 // FIXME - Find a more efficient way of passing records down.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002641 TmpRecFields.append(RD->field_begin(CGM.getContext()),
2642 RD->field_end(CGM.getContext()));
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002643 // FIXME - Is Layout correct?
Chris Lattnerf1690852009-03-31 08:48:01 +00002644 BuildAggrIvarLayout(OI, Layout, RD, TmpRecFields,
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002645 BytePos + GetFieldBaseOffset(OI, Layout, Field),
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002646 ForStrongLayout, Index, SkIndex,
2647 HasUnion);
Chris Lattnerf1690852009-03-31 08:48:01 +00002648 TmpRecFields.clear();
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002649 continue;
2650 }
Chris Lattnerf1690852009-03-31 08:48:01 +00002651
2652 if (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002653 const ConstantArrayType *CArray =
2654 dyn_cast_or_null<ConstantArrayType>(Array);
2655 assert(CArray && "only array with know element size is supported");
2656 FQT = CArray->getElementType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002657 while (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
2658 const ConstantArrayType *CArray =
2659 dyn_cast_or_null<ConstantArrayType>(Array);
2660 FQT = CArray->getElementType();
2661 }
2662
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002663 assert(!FQT->isUnionType() &&
2664 "layout for array of unions not supported");
2665 if (FQT->isRecordType()) {
2666 uint64_t ElCount = CArray->getSize().getZExtValue();
2667 int OldIndex = Index;
2668 int OldSkIndex = SkIndex;
2669
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002670 // FIXME - Use a common routine with the above!
2671 const RecordType *RT = FQT->getAsRecordType();
2672 const RecordDecl *RD = RT->getDecl();
2673 // FIXME - Find a more efficiant way of passing records down.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002674 TmpRecFields.append(RD->field_begin(CGM.getContext()),
2675 RD->field_end(CGM.getContext()));
Chris Lattnerf1690852009-03-31 08:48:01 +00002676
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002677 BuildAggrIvarLayout(OI, Layout, RD,
Chris Lattnerf1690852009-03-31 08:48:01 +00002678 TmpRecFields,
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002679 BytePos + GetFieldBaseOffset(OI, Layout, Field),
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002680 ForStrongLayout, Index, SkIndex,
2681 HasUnion);
Chris Lattnerf1690852009-03-31 08:48:01 +00002682 TmpRecFields.clear();
2683
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002684 // Replicate layout information for each array element. Note that
2685 // one element is already done.
2686 uint64_t ElIx = 1;
2687 for (int FirstIndex = Index, FirstSkIndex = SkIndex;
2688 ElIx < ElCount; ElIx++) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002689 uint64_t Size = CGM.getContext().getTypeSize(RT)/ByteSizeInBits;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002690 for (int i = OldIndex+1; i <= FirstIndex; ++i)
2691 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002692 GC_IVAR gcivar;
2693 gcivar.ivar_bytepos = IvarsInfo[i].ivar_bytepos + Size*ElIx;
2694 gcivar.ivar_size = IvarsInfo[i].ivar_size;
2695 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002696 }
2697
Chris Lattnerf1690852009-03-31 08:48:01 +00002698 for (int i = OldSkIndex+1; i <= FirstSkIndex; ++i) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002699 GC_IVAR skivar;
2700 skivar.ivar_bytepos = SkipIvars[i].ivar_bytepos + Size*ElIx;
2701 skivar.ivar_size = SkipIvars[i].ivar_size;
2702 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002703 }
2704 }
2705 continue;
2706 }
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002707 }
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002708 // At this point, we are done with Record/Union and array there of.
2709 // For other arrays we are down to its element type.
2710 QualType::GCAttrTypes GCAttr = QualType::GCNone;
2711 do {
2712 if (FQT.isObjCGCStrong() || FQT.isObjCGCWeak()) {
2713 GCAttr = FQT.isObjCGCStrong() ? QualType::Strong : QualType::Weak;
2714 break;
2715 }
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002716 else if (CGM.getContext().isObjCObjectPointerType(FQT)) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002717 GCAttr = QualType::Strong;
2718 break;
2719 }
2720 else if (const PointerType *PT = FQT->getAsPointerType()) {
2721 FQT = PT->getPointeeType();
2722 }
2723 else {
2724 break;
2725 }
2726 } while (true);
Chris Lattnerf1690852009-03-31 08:48:01 +00002727
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002728 if ((ForStrongLayout && GCAttr == QualType::Strong)
2729 || (!ForStrongLayout && GCAttr == QualType::Weak)) {
2730 if (IsUnion)
2731 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002732 uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType())
2733 / WordSizeInBits;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002734 if (UnionIvarSize > MaxUnionIvarSize)
2735 {
2736 MaxUnionIvarSize = UnionIvarSize;
2737 MaxField = Field;
2738 }
2739 }
2740 else
2741 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002742 GC_IVAR gcivar;
2743 gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field);
2744 gcivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) /
2745 WordSizeInBits;
2746 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002747 }
2748 }
2749 else if ((ForStrongLayout &&
2750 (GCAttr == QualType::GCNone || GCAttr == QualType::Weak))
2751 || (!ForStrongLayout && GCAttr != QualType::Weak)) {
2752 if (IsUnion)
2753 {
2754 uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType());
2755 if (UnionIvarSize > MaxSkippedUnionIvarSize)
2756 {
2757 MaxSkippedUnionIvarSize = UnionIvarSize;
2758 MaxSkippedField = Field;
2759 }
2760 }
2761 else
2762 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002763 GC_IVAR skivar;
2764 skivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field);
2765 skivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) /
2766 WordSizeInBits;
2767 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002768 }
2769 }
2770 }
Chris Lattnerf1690852009-03-31 08:48:01 +00002771 if (MaxField) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002772 GC_IVAR gcivar;
2773 gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, MaxField);
2774 gcivar.ivar_size = MaxUnionIvarSize;
2775 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002776 }
Chris Lattnerf1690852009-03-31 08:48:01 +00002777
2778 if (MaxSkippedField) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002779 GC_IVAR skivar;
2780 skivar.ivar_bytepos = BytePos +
2781 GetFieldBaseOffset(OI, Layout, MaxSkippedField);
2782 skivar.ivar_size = MaxSkippedUnionIvarSize;
2783 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002784 }
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002785}
2786
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002787static int
Chris Lattnerf1690852009-03-31 08:48:01 +00002788IvarBytePosCompare(const void *a, const void *b)
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002789{
2790 unsigned int sa = ((CGObjCCommonMac::GC_IVAR *)a)->ivar_bytepos;
2791 unsigned int sb = ((CGObjCCommonMac::GC_IVAR *)b)->ivar_bytepos;
2792
2793 if (sa < sb)
2794 return -1;
2795 if (sa > sb)
2796 return 1;
2797 return 0;
2798}
2799
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002800/// BuildIvarLayout - Builds ivar layout bitmap for the class
2801/// implementation for the __strong or __weak case.
2802/// The layout map displays which words in ivar list must be skipped
2803/// and which must be scanned by GC (see below). String is built of bytes.
2804/// Each byte is divided up in two nibbles (4-bit each). Left nibble is count
2805/// of words to skip and right nibble is count of words to scan. So, each
2806/// nibble represents up to 15 workds to skip or scan. Skipping the rest is
2807/// represented by a 0x00 byte which also ends the string.
2808/// 1. when ForStrongLayout is true, following ivars are scanned:
2809/// - id, Class
2810/// - object *
2811/// - __strong anything
2812///
2813/// 2. When ForStrongLayout is false, following ivars are scanned:
2814/// - __weak anything
2815///
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002816llvm::Constant *CGObjCCommonMac::BuildIvarLayout(
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002817 const ObjCImplementationDecl *OMD,
2818 bool ForStrongLayout) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002819 int Index = -1;
2820 int SkIndex = -1;
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002821 bool hasUnion = false;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002822 int SkipScan;
2823 unsigned int WordsToScan, WordsToSkip;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002824 const llvm::Type *PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
2825 if (CGM.getLangOptions().getGCMode() == LangOptions::NonGC)
2826 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002827
Chris Lattnerf1690852009-03-31 08:48:01 +00002828 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002829 const ObjCInterfaceDecl *OI = OMD->getClassInterface();
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002830 CGM.getContext().CollectObjCIvars(OI, RecFields);
2831 if (RecFields.empty())
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002832 return llvm::Constant::getNullValue(PtrTy);
Chris Lattnerf1690852009-03-31 08:48:01 +00002833
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002834 SkipIvars.clear();
2835 IvarsInfo.clear();
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002836
2837 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OI);
Chris Lattnerf1690852009-03-31 08:48:01 +00002838 BuildAggrIvarLayout(OI, Layout, 0, RecFields, 0, ForStrongLayout,
2839 Index, SkIndex, hasUnion);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002840 if (Index == -1)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002841 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002842
2843 // Sort on byte position in case we encounterred a union nested in
2844 // the ivar list.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002845 if (hasUnion && !IvarsInfo.empty())
2846 qsort(&IvarsInfo[0], Index+1, sizeof(GC_IVAR), IvarBytePosCompare);
2847 if (hasUnion && !SkipIvars.empty())
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002848 qsort(&SkipIvars[0], Index+1, sizeof(GC_IVAR), IvarBytePosCompare);
2849
2850 // Build the string of skip/scan nibbles
2851 SkipScan = -1;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002852 SkipScanIvars.clear();
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002853 unsigned int WordSize =
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002854 CGM.getTypes().getTargetData().getTypePaddedSize(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002855 if (IvarsInfo[0].ivar_bytepos == 0) {
2856 WordsToSkip = 0;
2857 WordsToScan = IvarsInfo[0].ivar_size;
2858 }
2859 else {
2860 WordsToSkip = IvarsInfo[0].ivar_bytepos/WordSize;
2861 WordsToScan = IvarsInfo[0].ivar_size;
2862 }
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002863 for (unsigned int i=1, Last=IvarsInfo.size(); i != Last; i++)
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002864 {
2865 unsigned int TailPrevGCObjC =
2866 IvarsInfo[i-1].ivar_bytepos + IvarsInfo[i-1].ivar_size * WordSize;
2867 if (IvarsInfo[i].ivar_bytepos == TailPrevGCObjC)
2868 {
2869 // consecutive 'scanned' object pointers.
2870 WordsToScan += IvarsInfo[i].ivar_size;
2871 }
2872 else
2873 {
2874 // Skip over 'gc'able object pointer which lay over each other.
2875 if (TailPrevGCObjC > IvarsInfo[i].ivar_bytepos)
2876 continue;
2877 // Must skip over 1 or more words. We save current skip/scan values
2878 // and start a new pair.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002879 SKIP_SCAN SkScan;
2880 SkScan.skip = WordsToSkip;
2881 SkScan.scan = WordsToScan;
2882 SkipScanIvars.push_back(SkScan); ++SkipScan;
2883
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002884 // Skip the hole.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002885 SkScan.skip = (IvarsInfo[i].ivar_bytepos - TailPrevGCObjC) / WordSize;
2886 SkScan.scan = 0;
2887 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002888 WordsToSkip = 0;
2889 WordsToScan = IvarsInfo[i].ivar_size;
2890 }
2891 }
2892 if (WordsToScan > 0)
2893 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002894 SKIP_SCAN SkScan;
2895 SkScan.skip = WordsToSkip;
2896 SkScan.scan = WordsToScan;
2897 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002898 }
2899
2900 bool BytesSkipped = false;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002901 if (!SkipIvars.empty())
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002902 {
2903 int LastByteSkipped =
2904 SkipIvars[SkIndex].ivar_bytepos + SkipIvars[SkIndex].ivar_size;
2905 int LastByteScanned =
2906 IvarsInfo[Index].ivar_bytepos + IvarsInfo[Index].ivar_size * WordSize;
2907 BytesSkipped = (LastByteSkipped > LastByteScanned);
2908 // Compute number of bytes to skip at the tail end of the last ivar scanned.
2909 if (BytesSkipped)
2910 {
2911 unsigned int TotalWords = (LastByteSkipped + (WordSize -1)) / WordSize;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002912 SKIP_SCAN SkScan;
2913 SkScan.skip = TotalWords - (LastByteScanned/WordSize);
2914 SkScan.scan = 0;
2915 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002916 }
2917 }
2918 // Mini optimization of nibbles such that an 0xM0 followed by 0x0N is produced
2919 // as 0xMN.
2920 for (int i = 0; i <= SkipScan; i++)
2921 {
2922 if ((i < SkipScan) && SkipScanIvars[i].skip && SkipScanIvars[i].scan == 0
2923 && SkipScanIvars[i+1].skip == 0 && SkipScanIvars[i+1].scan) {
2924 // 0xM0 followed by 0x0N detected.
2925 SkipScanIvars[i].scan = SkipScanIvars[i+1].scan;
2926 for (int j = i+1; j < SkipScan; j++)
2927 SkipScanIvars[j] = SkipScanIvars[j+1];
2928 --SkipScan;
2929 }
2930 }
2931
2932 // Generate the string.
2933 std::string BitMap;
2934 for (int i = 0; i <= SkipScan; i++)
2935 {
2936 unsigned char byte;
2937 unsigned int skip_small = SkipScanIvars[i].skip % 0xf;
2938 unsigned int scan_small = SkipScanIvars[i].scan % 0xf;
2939 unsigned int skip_big = SkipScanIvars[i].skip / 0xf;
2940 unsigned int scan_big = SkipScanIvars[i].scan / 0xf;
2941
2942 if (skip_small > 0 || skip_big > 0)
2943 BytesSkipped = true;
2944 // first skip big.
2945 for (unsigned int ix = 0; ix < skip_big; ix++)
2946 BitMap += (unsigned char)(0xf0);
2947
2948 // next (skip small, scan)
2949 if (skip_small)
2950 {
2951 byte = skip_small << 4;
2952 if (scan_big > 0)
2953 {
2954 byte |= 0xf;
2955 --scan_big;
2956 }
2957 else if (scan_small)
2958 {
2959 byte |= scan_small;
2960 scan_small = 0;
2961 }
2962 BitMap += byte;
2963 }
2964 // next scan big
2965 for (unsigned int ix = 0; ix < scan_big; ix++)
2966 BitMap += (unsigned char)(0x0f);
2967 // last scan small
2968 if (scan_small)
2969 {
2970 byte = scan_small;
2971 BitMap += byte;
2972 }
2973 }
2974 // null terminate string.
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002975 unsigned char zero = 0;
2976 BitMap += zero;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002977 // if ivar_layout bitmap is all 1 bits (nothing skipped) then use NULL as
2978 // final layout.
2979 if (ForStrongLayout && !BytesSkipped)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002980 return llvm::Constant::getNullValue(PtrTy);
2981 llvm::GlobalVariable * Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
2982 llvm::ConstantArray::get(BitMap.c_str()),
2983 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00002984 1, true);
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002985 // FIXME. Need a commomand-line option for this eventually.
2986 if (ForStrongLayout)
2987 printf("\nstrong ivar layout: ");
2988 else
2989 printf("\nweak ivar layout: ");
2990 const unsigned char *s = (unsigned char*)BitMap.c_str();
2991 for (unsigned i = 0; i < BitMap.size(); i++)
Fariborz Jahaniandbf15cb2009-03-26 19:10:36 +00002992 if (!(s[i] & 0xf0))
2993 printf("0x0%x%s", s[i], s[i] != 0 ? ", " : "");
2994 else
2995 printf("0x%x%s", s[i], s[i] != 0 ? ", " : "");
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002996 printf("\n");
2997
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002998 return getConstantGEP(Entry, 0, 0);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002999}
3000
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003001llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003002 llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
3003
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003004 // FIXME: Avoid std::string copying.
3005 if (!Entry)
3006 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_NAME_",
3007 llvm::ConstantArray::get(Sel.getAsString()),
3008 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003009 1, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003010
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003011 return getConstantGEP(Entry, 0, 0);
3012}
3013
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003014// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003015llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003016 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
3017}
3018
3019// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003020llvm::Constant *CGObjCCommonMac::GetMethodVarName(const std::string &Name) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003021 return GetMethodVarName(&CGM.getContext().Idents.get(Name));
3022}
3023
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00003024llvm::Constant *CGObjCCommonMac::GetMethodVarType(const FieldDecl *Field) {
Devang Patel7794bb82009-03-04 18:21:39 +00003025 std::string TypeStr;
3026 CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
3027
3028 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003029
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003030 if (!Entry)
3031 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3032 llvm::ConstantArray::get(TypeStr),
3033 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003034 1, true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003035
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003036 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003037}
3038
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003039llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003040 std::string TypeStr;
Daniel Dunbarc45ef602008-08-26 21:51:14 +00003041 CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D),
3042 TypeStr);
Devang Patel7794bb82009-03-04 18:21:39 +00003043
3044 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
3045
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003046 if (!Entry)
3047 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3048 llvm::ConstantArray::get(TypeStr),
3049 "__TEXT,__cstring,cstring_literals",
3050 1, true);
Devang Patel7794bb82009-03-04 18:21:39 +00003051
3052 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003053}
3054
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003055// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003056llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003057 llvm::GlobalVariable *&Entry = PropertyNames[Ident];
3058
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003059 if (!Entry)
3060 Entry = CreateMetadataVar("\01L_OBJC_PROP_NAME_ATTR_",
3061 llvm::ConstantArray::get(Ident->getName()),
3062 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003063 1, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003064
3065 return getConstantGEP(Entry, 0, 0);
3066}
3067
3068// FIXME: Merge into a single cstring creation function.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003069// FIXME: This Decl should be more precise.
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003070llvm::Constant *
3071 CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
3072 const Decl *Container) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003073 std::string TypeStr;
3074 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003075 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
3076}
3077
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003078void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D,
3079 const ObjCContainerDecl *CD,
3080 std::string &NameOut) {
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00003081 NameOut = '\01';
3082 NameOut += (D->isInstanceMethod() ? '-' : '+');
Chris Lattner077bf5e2008-11-24 03:33:13 +00003083 NameOut += '[';
Fariborz Jahanian679a5022009-01-10 21:06:09 +00003084 assert (CD && "Missing container decl in GetNameForMethod");
3085 NameOut += CD->getNameAsString();
Fariborz Jahanian1e9aef32009-04-16 18:34:20 +00003086 if (const ObjCCategoryImplDecl *CID =
3087 dyn_cast<ObjCCategoryImplDecl>(D->getDeclContext())) {
3088 NameOut += '(';
3089 NameOut += CID->getNameAsString();
3090 NameOut+= ')';
3091 }
Chris Lattner077bf5e2008-11-24 03:33:13 +00003092 NameOut += ' ';
3093 NameOut += D->getSelector().getAsString();
3094 NameOut += ']';
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00003095}
3096
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00003097/// GetFirstIvarInRecord - This routine returns the record for the
3098/// implementation of the fiven class OID. It also returns field
3099/// corresponding to the first ivar in the class in FIV. It also
3100/// returns the one before the first ivar.
3101///
3102const RecordDecl *CGObjCCommonMac::GetFirstIvarInRecord(
3103 const ObjCInterfaceDecl *OID,
3104 RecordDecl::field_iterator &FIV,
3105 RecordDecl::field_iterator &PIV) {
Douglas Gregor6ab35242009-04-09 21:40:53 +00003106 int countSuperClassIvars = countInheritedIvars(OID->getSuperClass(),
3107 CGM.getContext());
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00003108 const RecordDecl *RD = CGM.getContext().addRecordToClass(OID);
Douglas Gregor6ab35242009-04-09 21:40:53 +00003109 RecordDecl::field_iterator ifield = RD->field_begin(CGM.getContext());
3110 RecordDecl::field_iterator pfield = RD->field_end(CGM.getContext());
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00003111 while (countSuperClassIvars-- > 0) {
3112 pfield = ifield;
3113 ++ifield;
3114 }
3115 FIV = ifield;
3116 PIV = pfield;
3117 return RD;
3118}
3119
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003120void CGObjCMac::FinishModule() {
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003121 EmitModuleInfo();
3122
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003123 // Emit the dummy bodies for any protocols which were referenced but
3124 // never defined.
3125 for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
3126 i = Protocols.begin(), e = Protocols.end(); i != e; ++i) {
3127 if (i->second->hasInitializer())
3128 continue;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003129
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003130 std::vector<llvm::Constant*> Values(5);
3131 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
3132 Values[1] = GetClassName(i->first);
3133 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
3134 Values[3] = Values[4] =
3135 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
3136 i->second->setLinkage(llvm::GlobalValue::InternalLinkage);
3137 i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
3138 Values));
3139 }
3140
3141 std::vector<llvm::Constant*> Used;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003142 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003143 e = UsedGlobals.end(); i != e; ++i) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003144 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003145 }
3146
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003147 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003148 llvm::GlobalValue *GV =
3149 new llvm::GlobalVariable(AT, false,
3150 llvm::GlobalValue::AppendingLinkage,
3151 llvm::ConstantArray::get(AT, Used),
3152 "llvm.used",
3153 &CGM.getModule());
3154
3155 GV->setSection("llvm.metadata");
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003156
3157 // Add assembler directives to add lazy undefined symbol references
3158 // for classes which are referenced but not defined. This is
3159 // important for correct linker interaction.
3160
3161 // FIXME: Uh, this isn't particularly portable.
3162 std::stringstream s;
Anders Carlsson565c99f2008-12-10 02:21:04 +00003163
3164 if (!CGM.getModule().getModuleInlineAsm().empty())
3165 s << "\n";
3166
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003167 for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(),
3168 e = LazySymbols.end(); i != e; ++i) {
3169 s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n";
3170 }
3171 for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(),
3172 e = DefinedSymbols.end(); i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003173 s << "\t.objc_class_name_" << (*i)->getName() << "=0\n"
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003174 << "\t.globl .objc_class_name_" << (*i)->getName() << "\n";
3175 }
Anders Carlsson565c99f2008-12-10 02:21:04 +00003176
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003177 CGM.getModule().appendModuleInlineAsm(s.str());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003178}
3179
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003180CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003181 : CGObjCCommonMac(cgm),
3182 ObjCTypes(cgm)
3183{
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003184 ObjCEmptyCacheVar = ObjCEmptyVtableVar = NULL;
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003185 ObjCABI = 2;
3186}
3187
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003188/* *** */
3189
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003190ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm)
3191: CGM(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003192{
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003193 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3194 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003195
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003196 ShortTy = Types.ConvertType(Ctx.ShortTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003197 IntTy = Types.ConvertType(Ctx.IntTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003198 LongTy = Types.ConvertType(Ctx.LongTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00003199 LongLongTy = Types.ConvertType(Ctx.LongLongTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003200 Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3201
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003202 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00003203 PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003204 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003205
3206 // FIXME: It would be nice to unify this with the opaque type, so
3207 // that the IR comes out a bit cleaner.
3208 const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
3209 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003210
3211 // I'm not sure I like this. The implicit coordination is a bit
3212 // gross. We should solve this in a reasonable fashion because this
3213 // is a pretty common task (match some runtime data structure with
3214 // an LLVM data structure).
3215
3216 // FIXME: This is leaked.
3217 // FIXME: Merge with rewriter code?
3218
3219 // struct _objc_super {
3220 // id self;
3221 // Class cls;
3222 // }
3223 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3224 SourceLocation(),
3225 &Ctx.Idents.get("_objc_super"));
Douglas Gregor6ab35242009-04-09 21:40:53 +00003226 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3227 Ctx.getObjCIdType(), 0, false));
3228 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3229 Ctx.getObjCClassType(), 0, false));
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003230 RD->completeDefinition(Ctx);
3231
3232 SuperCTy = Ctx.getTagDeclType(RD);
3233 SuperPtrCTy = Ctx.getPointerType(SuperCTy);
3234
3235 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003236 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
3237
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003238 // struct _prop_t {
3239 // char *name;
3240 // char *attributes;
3241 // }
3242 PropertyTy = llvm::StructType::get(Int8PtrTy,
3243 Int8PtrTy,
3244 NULL);
3245 CGM.getModule().addTypeName("struct._prop_t",
3246 PropertyTy);
3247
3248 // struct _prop_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003249 // uint32_t entsize; // sizeof(struct _prop_t)
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003250 // uint32_t count_of_properties;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003251 // struct _prop_t prop_list[count_of_properties];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003252 // }
3253 PropertyListTy = llvm::StructType::get(IntTy,
3254 IntTy,
3255 llvm::ArrayType::get(PropertyTy, 0),
3256 NULL);
3257 CGM.getModule().addTypeName("struct._prop_list_t",
3258 PropertyListTy);
3259 // struct _prop_list_t *
3260 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
3261
3262 // struct _objc_method {
3263 // SEL _cmd;
3264 // char *method_type;
3265 // char *_imp;
3266 // }
3267 MethodTy = llvm::StructType::get(SelectorPtrTy,
3268 Int8PtrTy,
3269 Int8PtrTy,
3270 NULL);
3271 CGM.getModule().addTypeName("struct._objc_method", MethodTy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003272
3273 // struct _objc_cache *
3274 CacheTy = llvm::OpaqueType::get();
3275 CGM.getModule().addTypeName("struct._objc_cache", CacheTy);
3276 CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003277
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003278 // Property manipulation functions.
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003279
3280 QualType IdType = Ctx.getObjCIdType();
3281 QualType SelType = Ctx.getObjCSelType();
3282 llvm::SmallVector<QualType,16> Params;
3283 const llvm::FunctionType *FTy;
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003284
3285 // id objc_getProperty (id, SEL, ptrdiff_t, bool)
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003286 Params.push_back(IdType);
3287 Params.push_back(SelType);
3288 Params.push_back(Ctx.LongTy);
3289 Params.push_back(Ctx.BoolTy);
3290 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params),
3291 false);
3292 GetPropertyFn = CGM.CreateRuntimeFunction(FTy, "objc_getProperty");
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003293
3294 // void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool)
3295 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003296 Params.push_back(IdType);
3297 Params.push_back(SelType);
3298 Params.push_back(Ctx.LongTy);
3299 Params.push_back(IdType);
3300 Params.push_back(Ctx.BoolTy);
3301 Params.push_back(Ctx.BoolTy);
3302 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
3303 SetPropertyFn = CGM.CreateRuntimeFunction(FTy, "objc_setProperty");
3304
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003305 // Enumeration mutation.
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003306
3307 // void objc_enumerationMutation (id)
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003308 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003309 Params.push_back(IdType);
3310 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
3311 EnumerationMutationFn = CGM.CreateRuntimeFunction(FTy,
3312 "objc_enumerationMutation");
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003313
3314 // gc's API
3315 // id objc_read_weak (id *)
3316 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003317 Params.push_back(Ctx.getPointerType(IdType));
3318 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
3319 GcReadWeakFn = CGM.CreateRuntimeFunction(FTy, "objc_read_weak");
3320
Chris Lattner96508e12009-04-17 22:12:36 +00003321 // id objc_assign_global (id, id *)
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003322 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003323 Params.push_back(IdType);
3324 Params.push_back(Ctx.getPointerType(IdType));
3325
3326 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003327 GcAssignGlobalFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_global");
3328 GcAssignIvarFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_ivar");
3329 GcAssignStrongCastFn =
3330 CGM.CreateRuntimeFunction(FTy, "objc_assign_strongCast");
Anders Carlssonf57c5b22009-02-16 22:59:18 +00003331
3332 // void objc_exception_throw(id)
3333 Params.clear();
3334 Params.push_back(IdType);
3335
3336 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00003337 ExceptionThrowFn =
3338 CGM.CreateRuntimeFunction(FTy, "objc_exception_throw");
Daniel Dunbar1c566672009-02-24 01:43:46 +00003339
3340 // synchronized APIs
Daniel Dunbar1c566672009-02-24 01:43:46 +00003341 // void objc_sync_exit (id)
3342 Params.clear();
3343 Params.push_back(IdType);
3344
3345 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
Daniel Dunbar1c566672009-02-24 01:43:46 +00003346 SyncExitFn = CGM.CreateRuntimeFunction(FTy, "objc_sync_exit");
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003347}
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003348
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003349ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
3350 : ObjCCommonTypesHelper(cgm)
3351{
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003352 // struct _objc_method_description {
3353 // SEL name;
3354 // char *types;
3355 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003356 MethodDescriptionTy =
3357 llvm::StructType::get(SelectorPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003358 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003359 NULL);
3360 CGM.getModule().addTypeName("struct._objc_method_description",
3361 MethodDescriptionTy);
3362
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003363 // struct _objc_method_description_list {
3364 // int count;
3365 // struct _objc_method_description[1];
3366 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003367 MethodDescriptionListTy =
3368 llvm::StructType::get(IntTy,
3369 llvm::ArrayType::get(MethodDescriptionTy, 0),
3370 NULL);
3371 CGM.getModule().addTypeName("struct._objc_method_description_list",
3372 MethodDescriptionListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003373
3374 // struct _objc_method_description_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003375 MethodDescriptionListPtrTy =
3376 llvm::PointerType::getUnqual(MethodDescriptionListTy);
3377
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003378 // Protocol description structures
3379
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003380 // struct _objc_protocol_extension {
3381 // uint32_t size; // sizeof(struct _objc_protocol_extension)
3382 // struct _objc_method_description_list *optional_instance_methods;
3383 // struct _objc_method_description_list *optional_class_methods;
3384 // struct _objc_property_list *instance_properties;
3385 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003386 ProtocolExtensionTy =
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003387 llvm::StructType::get(IntTy,
3388 MethodDescriptionListPtrTy,
3389 MethodDescriptionListPtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003390 PropertyListPtrTy,
3391 NULL);
3392 CGM.getModule().addTypeName("struct._objc_protocol_extension",
3393 ProtocolExtensionTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003394
3395 // struct _objc_protocol_extension *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003396 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
3397
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003398 // Handle recursive construction of Protocol and ProtocolList types
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003399
3400 llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get();
3401 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3402
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003403 const llvm::Type *T =
3404 llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder),
3405 LongTy,
3406 llvm::ArrayType::get(ProtocolTyHolder, 0),
3407 NULL);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003408 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T);
3409
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003410 // struct _objc_protocol {
3411 // struct _objc_protocol_extension *isa;
3412 // char *protocol_name;
3413 // struct _objc_protocol **_objc_protocol_list;
3414 // struct _objc_method_description_list *instance_methods;
3415 // struct _objc_method_description_list *class_methods;
3416 // }
3417 T = llvm::StructType::get(ProtocolExtensionPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003418 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003419 llvm::PointerType::getUnqual(ProtocolListTyHolder),
3420 MethodDescriptionListPtrTy,
3421 MethodDescriptionListPtrTy,
3422 NULL);
3423 cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T);
3424
3425 ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get());
3426 CGM.getModule().addTypeName("struct._objc_protocol_list",
3427 ProtocolListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003428 // struct _objc_protocol_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003429 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
3430
3431 ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get());
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003432 CGM.getModule().addTypeName("struct._objc_protocol", ProtocolTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003433 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003434
3435 // Class description structures
3436
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003437 // struct _objc_ivar {
3438 // char *ivar_name;
3439 // char *ivar_type;
3440 // int ivar_offset;
3441 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003442 IvarTy = llvm::StructType::get(Int8PtrTy,
3443 Int8PtrTy,
3444 IntTy,
3445 NULL);
3446 CGM.getModule().addTypeName("struct._objc_ivar", IvarTy);
3447
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003448 // struct _objc_ivar_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003449 IvarListTy = llvm::OpaqueType::get();
3450 CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy);
3451 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
3452
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003453 // struct _objc_method_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003454 MethodListTy = llvm::OpaqueType::get();
3455 CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy);
3456 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
3457
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003458 // struct _objc_class_extension *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003459 ClassExtensionTy =
3460 llvm::StructType::get(IntTy,
3461 Int8PtrTy,
3462 PropertyListPtrTy,
3463 NULL);
3464 CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy);
3465 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
3466
3467 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3468
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003469 // struct _objc_class {
3470 // Class isa;
3471 // Class super_class;
3472 // char *name;
3473 // long version;
3474 // long info;
3475 // long instance_size;
3476 // struct _objc_ivar_list *ivars;
3477 // struct _objc_method_list *methods;
3478 // struct _objc_cache *cache;
3479 // struct _objc_protocol_list *protocols;
3480 // char *ivar_layout;
3481 // struct _objc_class_ext *ext;
3482 // };
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003483 T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3484 llvm::PointerType::getUnqual(ClassTyHolder),
3485 Int8PtrTy,
3486 LongTy,
3487 LongTy,
3488 LongTy,
3489 IvarListPtrTy,
3490 MethodListPtrTy,
3491 CachePtrTy,
3492 ProtocolListPtrTy,
3493 Int8PtrTy,
3494 ClassExtensionPtrTy,
3495 NULL);
3496 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T);
3497
3498 ClassTy = cast<llvm::StructType>(ClassTyHolder.get());
3499 CGM.getModule().addTypeName("struct._objc_class", ClassTy);
3500 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
3501
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003502 // struct _objc_category {
3503 // char *category_name;
3504 // char *class_name;
3505 // struct _objc_method_list *instance_method;
3506 // struct _objc_method_list *class_method;
3507 // uint32_t size; // sizeof(struct _objc_category)
3508 // struct _objc_property_list *instance_properties;// category's @property
3509 // }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003510 CategoryTy = llvm::StructType::get(Int8PtrTy,
3511 Int8PtrTy,
3512 MethodListPtrTy,
3513 MethodListPtrTy,
3514 ProtocolListPtrTy,
3515 IntTy,
3516 PropertyListPtrTy,
3517 NULL);
3518 CGM.getModule().addTypeName("struct._objc_category", CategoryTy);
3519
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003520 // Global metadata structures
3521
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003522 // struct _objc_symtab {
3523 // long sel_ref_cnt;
3524 // SEL *refs;
3525 // short cls_def_cnt;
3526 // short cat_def_cnt;
3527 // char *defs[cls_def_cnt + cat_def_cnt];
3528 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003529 SymtabTy = llvm::StructType::get(LongTy,
3530 SelectorPtrTy,
3531 ShortTy,
3532 ShortTy,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003533 llvm::ArrayType::get(Int8PtrTy, 0),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003534 NULL);
3535 CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy);
3536 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
3537
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003538 // struct _objc_module {
3539 // long version;
3540 // long size; // sizeof(struct _objc_module)
3541 // char *name;
3542 // struct _objc_symtab* symtab;
3543 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003544 ModuleTy =
3545 llvm::StructType::get(LongTy,
3546 LongTy,
3547 Int8PtrTy,
3548 SymtabPtrTy,
3549 NULL);
3550 CGM.getModule().addTypeName("struct._objc_module", ModuleTy);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003551
Daniel Dunbar49f66022008-09-24 03:38:44 +00003552 // Message send functions.
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003553
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003554 // id objc_msgSend (id, SEL, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003555 std::vector<const llvm::Type*> Params;
3556 Params.push_back(ObjectPtrTy);
3557 Params.push_back(SelectorPtrTy);
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003558 MessageSendFn =
3559 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3560 Params,
3561 true),
3562 "objc_msgSend");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003563
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003564 // id objc_msgSend_stret (id, SEL, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003565 Params.clear();
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003566 Params.push_back(ObjectPtrTy);
3567 Params.push_back(SelectorPtrTy);
3568 MessageSendStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003569 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3570 Params,
3571 true),
3572 "objc_msgSend_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00003573
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003574 //
Daniel Dunbar5669e572008-10-17 03:24:53 +00003575 Params.clear();
3576 Params.push_back(ObjectPtrTy);
3577 Params.push_back(SelectorPtrTy);
3578 // FIXME: This should be long double on x86_64?
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003579 // [double | long double] objc_msgSend_fpret(id self, SEL op, ...)
Daniel Dunbar5669e572008-10-17 03:24:53 +00003580 MessageSendFpretFn =
3581 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::DoubleTy,
3582 Params,
3583 true),
3584 "objc_msgSend_fpret");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003585
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003586 // id objc_msgSendSuper(struct objc_super *super, SEL op, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003587 Params.clear();
3588 Params.push_back(SuperPtrTy);
3589 Params.push_back(SelectorPtrTy);
3590 MessageSendSuperFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003591 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3592 Params,
3593 true),
3594 "objc_msgSendSuper");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003595
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003596 // void objc_msgSendSuper_stret(void * stretAddr, struct objc_super *super,
3597 // SEL op, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003598 Params.clear();
3599 Params.push_back(Int8PtrTy);
3600 Params.push_back(SuperPtrTy);
3601 Params.push_back(SelectorPtrTy);
3602 MessageSendSuperStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003603 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3604 Params,
3605 true),
3606 "objc_msgSendSuper_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00003607
3608 // There is no objc_msgSendSuper_fpret? How can that work?
3609 MessageSendSuperFpretFn = MessageSendSuperFn;
Anders Carlsson2abd89c2008-08-31 04:05:03 +00003610
Anders Carlsson124526b2008-09-09 10:10:21 +00003611 // FIXME: This is the size of the setjmp buffer and should be
3612 // target specific. 18 is what's used on 32-bit X86.
3613 uint64_t SetJmpBufferSize = 18;
3614
3615 // Exceptions
3616 const llvm::Type *StackPtrTy =
Daniel Dunbar10004912008-09-27 06:32:25 +00003617 llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4);
Anders Carlsson124526b2008-09-09 10:10:21 +00003618
3619 ExceptionDataTy =
3620 llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty,
3621 SetJmpBufferSize),
3622 StackPtrTy, NULL);
3623 CGM.getModule().addTypeName("struct._objc_exception_data",
3624 ExceptionDataTy);
3625
3626 Params.clear();
Anders Carlsson124526b2008-09-09 10:10:21 +00003627 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
3628 ExceptionTryEnterFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003629 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3630 Params,
3631 false),
3632 "objc_exception_try_enter");
Anders Carlsson124526b2008-09-09 10:10:21 +00003633 ExceptionTryExitFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003634 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3635 Params,
3636 false),
3637 "objc_exception_try_exit");
Anders Carlsson124526b2008-09-09 10:10:21 +00003638 ExceptionExtractFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003639 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3640 Params,
3641 false),
3642 "objc_exception_extract");
Anders Carlsson124526b2008-09-09 10:10:21 +00003643
3644 Params.clear();
3645 Params.push_back(ClassPtrTy);
3646 Params.push_back(ObjectPtrTy);
3647 ExceptionMatchFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003648 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
3649 Params,
3650 false),
3651 "objc_exception_match");
Chris Lattner10cac6f2008-11-15 21:26:17 +00003652
Anders Carlsson124526b2008-09-09 10:10:21 +00003653 Params.clear();
3654 Params.push_back(llvm::PointerType::getUnqual(llvm::Type::Int32Ty));
3655 SetJmpFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003656 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
3657 Params,
3658 false),
3659 "_setjmp");
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00003660
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003661}
3662
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003663ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003664: ObjCCommonTypesHelper(cgm)
3665{
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003666 // struct _method_list_t {
3667 // uint32_t entsize; // sizeof(struct _objc_method)
3668 // uint32_t method_count;
3669 // struct _objc_method method_list[method_count];
3670 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003671 MethodListnfABITy = llvm::StructType::get(IntTy,
3672 IntTy,
3673 llvm::ArrayType::get(MethodTy, 0),
3674 NULL);
3675 CGM.getModule().addTypeName("struct.__method_list_t",
3676 MethodListnfABITy);
3677 // struct method_list_t *
3678 MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003679
3680 // struct _protocol_t {
3681 // id isa; // NULL
3682 // const char * const protocol_name;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003683 // const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003684 // const struct method_list_t * const instance_methods;
3685 // const struct method_list_t * const class_methods;
3686 // const struct method_list_t *optionalInstanceMethods;
3687 // const struct method_list_t *optionalClassMethods;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003688 // const struct _prop_list_t * properties;
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003689 // const uint32_t size; // sizeof(struct _protocol_t)
3690 // const uint32_t flags; // = 0
3691 // }
3692
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003693 // Holder for struct _protocol_list_t *
3694 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3695
3696 ProtocolnfABITy = llvm::StructType::get(ObjectPtrTy,
3697 Int8PtrTy,
3698 llvm::PointerType::getUnqual(
3699 ProtocolListTyHolder),
3700 MethodListnfABIPtrTy,
3701 MethodListnfABIPtrTy,
3702 MethodListnfABIPtrTy,
3703 MethodListnfABIPtrTy,
3704 PropertyListPtrTy,
3705 IntTy,
3706 IntTy,
3707 NULL);
3708 CGM.getModule().addTypeName("struct._protocol_t",
3709 ProtocolnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003710
3711 // struct _protocol_t*
3712 ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003713
Fariborz Jahanianda320092009-01-29 19:24:30 +00003714 // struct _protocol_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003715 // long protocol_count; // Note, this is 32/64 bit
Daniel Dunbar948e2582009-02-15 07:36:20 +00003716 // struct _protocol_t *[protocol_count];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003717 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003718 ProtocolListnfABITy = llvm::StructType::get(LongTy,
3719 llvm::ArrayType::get(
Daniel Dunbar948e2582009-02-15 07:36:20 +00003720 ProtocolnfABIPtrTy, 0),
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003721 NULL);
3722 CGM.getModule().addTypeName("struct._objc_protocol_list",
3723 ProtocolListnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003724 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(
3725 ProtocolListnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003726
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003727 // struct _objc_protocol_list*
3728 ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003729
3730 // struct _ivar_t {
3731 // unsigned long int *offset; // pointer to ivar offset location
3732 // char *name;
3733 // char *type;
3734 // uint32_t alignment;
3735 // uint32_t size;
3736 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003737 IvarnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(LongTy),
3738 Int8PtrTy,
3739 Int8PtrTy,
3740 IntTy,
3741 IntTy,
3742 NULL);
3743 CGM.getModule().addTypeName("struct._ivar_t", IvarnfABITy);
3744
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003745 // struct _ivar_list_t {
3746 // uint32 entsize; // sizeof(struct _ivar_t)
3747 // uint32 count;
3748 // struct _iver_t list[count];
3749 // }
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003750 IvarListnfABITy = llvm::StructType::get(IntTy,
3751 IntTy,
3752 llvm::ArrayType::get(
3753 IvarnfABITy, 0),
3754 NULL);
3755 CGM.getModule().addTypeName("struct._ivar_list_t", IvarListnfABITy);
3756
3757 IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003758
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003759 // struct _class_ro_t {
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003760 // uint32_t const flags;
3761 // uint32_t const instanceStart;
3762 // uint32_t const instanceSize;
3763 // uint32_t const reserved; // only when building for 64bit targets
3764 // const uint8_t * const ivarLayout;
3765 // const char *const name;
3766 // const struct _method_list_t * const baseMethods;
3767 // const struct _objc_protocol_list *const baseProtocols;
3768 // const struct _ivar_list_t *const ivars;
3769 // const uint8_t * const weakIvarLayout;
3770 // const struct _prop_list_t * const properties;
3771 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003772
3773 // FIXME. Add 'reserved' field in 64bit abi mode!
3774 ClassRonfABITy = llvm::StructType::get(IntTy,
3775 IntTy,
3776 IntTy,
3777 Int8PtrTy,
3778 Int8PtrTy,
3779 MethodListnfABIPtrTy,
3780 ProtocolListnfABIPtrTy,
3781 IvarListnfABIPtrTy,
3782 Int8PtrTy,
3783 PropertyListPtrTy,
3784 NULL);
3785 CGM.getModule().addTypeName("struct._class_ro_t",
3786 ClassRonfABITy);
3787
3788 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
3789 std::vector<const llvm::Type*> Params;
3790 Params.push_back(ObjectPtrTy);
3791 Params.push_back(SelectorPtrTy);
3792 ImpnfABITy = llvm::PointerType::getUnqual(
3793 llvm::FunctionType::get(ObjectPtrTy, Params, false));
3794
3795 // struct _class_t {
3796 // struct _class_t *isa;
3797 // struct _class_t * const superclass;
3798 // void *cache;
3799 // IMP *vtable;
3800 // struct class_ro_t *ro;
3801 // }
3802
3803 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3804 ClassnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3805 llvm::PointerType::getUnqual(ClassTyHolder),
3806 CachePtrTy,
3807 llvm::PointerType::getUnqual(ImpnfABITy),
3808 llvm::PointerType::getUnqual(
3809 ClassRonfABITy),
3810 NULL);
3811 CGM.getModule().addTypeName("struct._class_t", ClassnfABITy);
3812
3813 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(
3814 ClassnfABITy);
3815
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003816 // LLVM for struct _class_t *
3817 ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy);
3818
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003819 // struct _category_t {
3820 // const char * const name;
3821 // struct _class_t *const cls;
3822 // const struct _method_list_t * const instance_methods;
3823 // const struct _method_list_t * const class_methods;
3824 // const struct _protocol_list_t * const protocols;
3825 // const struct _prop_list_t * const properties;
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003826 // }
3827 CategorynfABITy = llvm::StructType::get(Int8PtrTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003828 ClassnfABIPtrTy,
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003829 MethodListnfABIPtrTy,
3830 MethodListnfABIPtrTy,
3831 ProtocolListnfABIPtrTy,
3832 PropertyListPtrTy,
3833 NULL);
3834 CGM.getModule().addTypeName("struct._category_t", CategorynfABITy);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003835
3836 // New types for nonfragile abi messaging.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003837 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3838 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003839
3840 // MessageRefTy - LLVM for:
3841 // struct _message_ref_t {
3842 // IMP messenger;
3843 // SEL name;
3844 // };
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003845
3846 // First the clang type for struct _message_ref_t
3847 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3848 SourceLocation(),
3849 &Ctx.Idents.get("_message_ref_t"));
Douglas Gregor6ab35242009-04-09 21:40:53 +00003850 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3851 Ctx.VoidPtrTy, 0, false));
3852 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3853 Ctx.getObjCSelType(), 0, false));
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003854 RD->completeDefinition(Ctx);
3855
3856 MessageRefCTy = Ctx.getTagDeclType(RD);
3857 MessageRefCPtrTy = Ctx.getPointerType(MessageRefCTy);
3858 MessageRefTy = cast<llvm::StructType>(Types.ConvertType(MessageRefCTy));
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003859
3860 // MessageRefPtrTy - LLVM for struct _message_ref_t*
3861 MessageRefPtrTy = llvm::PointerType::getUnqual(MessageRefTy);
3862
3863 // SuperMessageRefTy - LLVM for:
3864 // struct _super_message_ref_t {
3865 // SUPER_IMP messenger;
3866 // SEL name;
3867 // };
3868 SuperMessageRefTy = llvm::StructType::get(ImpnfABITy,
3869 SelectorPtrTy,
3870 NULL);
3871 CGM.getModule().addTypeName("struct._super_message_ref_t", SuperMessageRefTy);
3872
3873 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
3874 SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy);
3875
3876 // id objc_msgSend_fixup (id, struct message_ref_t*, ...)
3877 Params.clear();
3878 Params.push_back(ObjectPtrTy);
3879 Params.push_back(MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00003880 MessengerTy = llvm::FunctionType::get(ObjectPtrTy,
3881 Params,
3882 true);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003883 MessageSendFixupFn =
Fariborz Jahanianef163782009-02-05 01:13:09 +00003884 CGM.CreateRuntimeFunction(MessengerTy,
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003885 "objc_msgSend_fixup");
3886
3887 // id objc_msgSend_fpret_fixup (id, struct message_ref_t*, ...)
3888 MessageSendFpretFixupFn =
3889 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3890 Params,
3891 true),
3892 "objc_msgSend_fpret_fixup");
3893
3894 // id objc_msgSend_stret_fixup (id, struct message_ref_t*, ...)
3895 MessageSendStretFixupFn =
3896 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3897 Params,
3898 true),
3899 "objc_msgSend_stret_fixup");
3900
3901 // id objc_msgSendId_fixup (id, struct message_ref_t*, ...)
3902 MessageSendIdFixupFn =
3903 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3904 Params,
3905 true),
3906 "objc_msgSendId_fixup");
3907
3908
3909 // id objc_msgSendId_stret_fixup (id, struct message_ref_t*, ...)
3910 MessageSendIdStretFixupFn =
3911 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3912 Params,
3913 true),
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003914 "objc_msgSendId_stret_fixup");
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003915
3916 // id objc_msgSendSuper2_fixup (struct objc_super *,
3917 // struct _super_message_ref_t*, ...)
3918 Params.clear();
3919 Params.push_back(SuperPtrTy);
3920 Params.push_back(SuperMessageRefPtrTy);
3921 MessageSendSuper2FixupFn =
3922 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3923 Params,
3924 true),
3925 "objc_msgSendSuper2_fixup");
3926
3927
3928 // id objc_msgSendSuper2_stret_fixup (struct objc_super *,
3929 // struct _super_message_ref_t*, ...)
3930 MessageSendSuper2StretFixupFn =
3931 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3932 Params,
3933 true),
3934 "objc_msgSendSuper2_stret_fixup");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00003935
3936 Params.clear();
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00003937 Params.push_back(Int8PtrTy);
3938 UnwindResumeOrRethrowFn =
3939 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3940 Params,
3941 false),
3942 "_Unwind_Resume_or_Rethrow");
Daniel Dunbare588b992009-03-01 04:46:24 +00003943 ObjCBeginCatchFn =
3944 CGM.CreateRuntimeFunction(llvm::FunctionType::get(Int8PtrTy,
3945 Params,
3946 false),
3947 "objc_begin_catch");
3948
3949 Params.clear();
3950 ObjCEndCatchFn =
3951 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3952 Params,
3953 false),
3954 "objc_end_catch");
3955
3956 // struct objc_typeinfo {
3957 // const void** vtable; // objc_ehtype_vtable + 2
3958 // const char* name; // c++ typeinfo string
3959 // Class cls;
3960 // };
3961 EHTypeTy = llvm::StructType::get(llvm::PointerType::getUnqual(Int8PtrTy),
3962 Int8PtrTy,
3963 ClassnfABIPtrTy,
3964 NULL);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00003965 CGM.getModule().addTypeName("struct._objc_typeinfo", EHTypeTy);
Daniel Dunbare588b992009-03-01 04:46:24 +00003966 EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy);
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003967}
3968
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003969llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() {
3970 FinishNonFragileABIModule();
3971
3972 return NULL;
3973}
3974
3975void CGObjCNonFragileABIMac::FinishNonFragileABIModule() {
3976 // nonfragile abi has no module definition.
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003977
3978 // Build list of all implemented classe addresses in array
3979 // L_OBJC_LABEL_CLASS_$.
3980 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CLASS_$
3981 // list of 'nonlazy' implementations (defined as those with a +load{}
3982 // method!!).
3983 unsigned NumClasses = DefinedClasses.size();
3984 if (NumClasses) {
3985 std::vector<llvm::Constant*> Symbols(NumClasses);
3986 for (unsigned i=0; i<NumClasses; i++)
3987 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
3988 ObjCTypes.Int8PtrTy);
3989 llvm::Constant* Init =
3990 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
3991 NumClasses),
3992 Symbols);
3993
3994 llvm::GlobalVariable *GV =
3995 new llvm::GlobalVariable(Init->getType(), false,
3996 llvm::GlobalValue::InternalLinkage,
3997 Init,
3998 "\01L_OBJC_LABEL_CLASS_$",
3999 &CGM.getModule());
Daniel Dunbar58a29122009-03-09 22:18:41 +00004000 GV->setAlignment(8);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004001 GV->setSection("__DATA, __objc_classlist, regular, no_dead_strip");
4002 UsedGlobals.push_back(GV);
4003 }
4004
4005 // Build list of all implemented category addresses in array
4006 // L_OBJC_LABEL_CATEGORY_$.
4007 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CATEGORY_$
4008 // list of 'nonlazy' category implementations (defined as those with a +load{}
4009 // method!!).
4010 unsigned NumCategory = DefinedCategories.size();
4011 if (NumCategory) {
4012 std::vector<llvm::Constant*> Symbols(NumCategory);
4013 for (unsigned i=0; i<NumCategory; i++)
4014 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedCategories[i],
4015 ObjCTypes.Int8PtrTy);
4016 llvm::Constant* Init =
4017 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
4018 NumCategory),
4019 Symbols);
4020
4021 llvm::GlobalVariable *GV =
4022 new llvm::GlobalVariable(Init->getType(), false,
4023 llvm::GlobalValue::InternalLinkage,
4024 Init,
4025 "\01L_OBJC_LABEL_CATEGORY_$",
4026 &CGM.getModule());
Daniel Dunbar58a29122009-03-09 22:18:41 +00004027 GV->setAlignment(8);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004028 GV->setSection("__DATA, __objc_catlist, regular, no_dead_strip");
4029 UsedGlobals.push_back(GV);
4030 }
4031
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004032 // static int L_OBJC_IMAGE_INFO[2] = { 0, flags };
4033 // FIXME. flags can be 0 | 1 | 2 | 6. For now just use 0
4034 std::vector<llvm::Constant*> Values(2);
4035 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, 0);
Fariborz Jahanian067986e2009-02-24 21:08:09 +00004036 unsigned int flags = 0;
Fariborz Jahanian66a5c2c2009-02-24 23:34:44 +00004037 // FIXME: Fix and continue?
4038 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
4039 flags |= eImageInfo_GarbageCollected;
4040 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
4041 flags |= eImageInfo_GCOnly;
Fariborz Jahanian067986e2009-02-24 21:08:09 +00004042 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004043 llvm::Constant* Init = llvm::ConstantArray::get(
4044 llvm::ArrayType::get(ObjCTypes.IntTy, 2),
4045 Values);
4046 llvm::GlobalVariable *IMGV =
4047 new llvm::GlobalVariable(Init->getType(), false,
4048 llvm::GlobalValue::InternalLinkage,
4049 Init,
4050 "\01L_OBJC_IMAGE_INFO",
4051 &CGM.getModule());
4052 IMGV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
4053 UsedGlobals.push_back(IMGV);
4054
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004055 std::vector<llvm::Constant*> Used;
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004056
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004057 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
4058 e = UsedGlobals.end(); i != e; ++i) {
4059 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
4060 }
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004061
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004062 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
4063 llvm::GlobalValue *GV =
4064 new llvm::GlobalVariable(AT, false,
4065 llvm::GlobalValue::AppendingLinkage,
4066 llvm::ConstantArray::get(AT, Used),
4067 "llvm.used",
4068 &CGM.getModule());
4069
4070 GV->setSection("llvm.metadata");
4071
4072}
4073
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004074// Metadata flags
4075enum MetaDataDlags {
4076 CLS = 0x0,
4077 CLS_META = 0x1,
4078 CLS_ROOT = 0x2,
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004079 OBJC2_CLS_HIDDEN = 0x10,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004080 CLS_EXCEPTION = 0x20
4081};
4082/// BuildClassRoTInitializer - generate meta-data for:
4083/// struct _class_ro_t {
4084/// uint32_t const flags;
4085/// uint32_t const instanceStart;
4086/// uint32_t const instanceSize;
4087/// uint32_t const reserved; // only when building for 64bit targets
4088/// const uint8_t * const ivarLayout;
4089/// const char *const name;
4090/// const struct _method_list_t * const baseMethods;
Fariborz Jahanianda320092009-01-29 19:24:30 +00004091/// const struct _protocol_list_t *const baseProtocols;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004092/// const struct _ivar_list_t *const ivars;
4093/// const uint8_t * const weakIvarLayout;
4094/// const struct _prop_list_t * const properties;
4095/// }
4096///
4097llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer(
4098 unsigned flags,
4099 unsigned InstanceStart,
4100 unsigned InstanceSize,
4101 const ObjCImplementationDecl *ID) {
4102 std::string ClassName = ID->getNameAsString();
4103 std::vector<llvm::Constant*> Values(10); // 11 for 64bit targets!
4104 Values[ 0] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
4105 Values[ 1] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceStart);
4106 Values[ 2] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceSize);
4107 // FIXME. For 64bit targets add 0 here.
Fariborz Jahanianda320092009-01-29 19:24:30 +00004108 // FIXME. ivarLayout is currently null!
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00004109 Values[ 3] = GetIvarLayoutName(0, ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004110 Values[ 4] = GetClassName(ID->getIdentifier());
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004111 // const struct _method_list_t * const baseMethods;
4112 std::vector<llvm::Constant*> Methods;
4113 std::string MethodListName("\01l_OBJC_$_");
4114 if (flags & CLS_META) {
4115 MethodListName += "CLASS_METHODS_" + ID->getNameAsString();
4116 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
4117 e = ID->classmeth_end(); i != e; ++i) {
4118 // Class methods should always be defined.
4119 Methods.push_back(GetMethodConstant(*i));
4120 }
4121 } else {
4122 MethodListName += "INSTANCE_METHODS_" + ID->getNameAsString();
4123 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
4124 e = ID->instmeth_end(); i != e; ++i) {
4125 // Instance methods should always be defined.
4126 Methods.push_back(GetMethodConstant(*i));
4127 }
Fariborz Jahanian939abce2009-01-28 22:46:49 +00004128 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
4129 e = ID->propimpl_end(); i != e; ++i) {
4130 ObjCPropertyImplDecl *PID = *i;
4131
4132 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize){
4133 ObjCPropertyDecl *PD = PID->getPropertyDecl();
4134
4135 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
4136 if (llvm::Constant *C = GetMethodConstant(MD))
4137 Methods.push_back(C);
4138 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
4139 if (llvm::Constant *C = GetMethodConstant(MD))
4140 Methods.push_back(C);
4141 }
4142 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004143 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004144 Values[ 5] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004145 "__DATA, __objc_const", Methods);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004146
4147 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4148 assert(OID && "CGObjCNonFragileABIMac::BuildClassRoTInitializer");
4149 Values[ 6] = EmitProtocolList("\01l_OBJC_CLASS_PROTOCOLS_$_"
4150 + OID->getNameAsString(),
4151 OID->protocol_begin(),
4152 OID->protocol_end());
4153
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004154 if (flags & CLS_META)
4155 Values[ 7] = llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4156 else
4157 Values[ 7] = EmitIvarList(ID);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004158 // FIXME. weakIvarLayout is currently null.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00004159 Values[ 8] = GetIvarLayoutName(0, ObjCTypes);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004160 if (flags & CLS_META)
4161 Values[ 9] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4162 else
4163 Values[ 9] =
4164 EmitPropertyList(
4165 "\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
4166 ID, ID->getClassInterface(), ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004167 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassRonfABITy,
4168 Values);
4169 llvm::GlobalVariable *CLASS_RO_GV =
4170 new llvm::GlobalVariable(ObjCTypes.ClassRonfABITy, false,
4171 llvm::GlobalValue::InternalLinkage,
4172 Init,
4173 (flags & CLS_META) ?
4174 std::string("\01l_OBJC_METACLASS_RO_$_")+ClassName :
4175 std::string("\01l_OBJC_CLASS_RO_$_")+ClassName,
4176 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004177 CLASS_RO_GV->setAlignment(
4178 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassRonfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004179 CLASS_RO_GV->setSection("__DATA, __objc_const");
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004180 return CLASS_RO_GV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004181
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004182}
4183
4184/// BuildClassMetaData - This routine defines that to-level meta-data
4185/// for the given ClassName for:
4186/// struct _class_t {
4187/// struct _class_t *isa;
4188/// struct _class_t * const superclass;
4189/// void *cache;
4190/// IMP *vtable;
4191/// struct class_ro_t *ro;
4192/// }
4193///
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004194llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassMetaData(
4195 std::string &ClassName,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004196 llvm::Constant *IsAGV,
4197 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004198 llvm::Constant *ClassRoGV,
4199 bool HiddenVisibility) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004200 std::vector<llvm::Constant*> Values(5);
4201 Values[0] = IsAGV;
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004202 Values[1] = SuperClassGV
4203 ? SuperClassGV
4204 : llvm::Constant::getNullValue(ObjCTypes.ClassnfABIPtrTy);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004205 Values[2] = ObjCEmptyCacheVar; // &ObjCEmptyCacheVar
4206 Values[3] = ObjCEmptyVtableVar; // &ObjCEmptyVtableVar
4207 Values[4] = ClassRoGV; // &CLASS_RO_GV
4208 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassnfABITy,
4209 Values);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004210 llvm::GlobalVariable *GV = GetClassGlobal(ClassName);
4211 GV->setInitializer(Init);
Fariborz Jahaniandd0db2a2009-01-31 01:07:39 +00004212 GV->setSection("__DATA, __objc_data");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004213 GV->setAlignment(
4214 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassnfABITy));
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004215 if (HiddenVisibility)
4216 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004217 return GV;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004218}
4219
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004220void CGObjCNonFragileABIMac::GetClassSizeInfo(const ObjCInterfaceDecl *OID,
4221 uint32_t &InstanceStart,
4222 uint32_t &InstanceSize) {
4223 // FIXME. Share this with the one in EmitIvarList.
4224 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID);
4225
4226 RecordDecl::field_iterator firstField, lastField;
4227 const RecordDecl *RD = GetFirstIvarInRecord(OID, firstField, lastField);
4228
4229 for (RecordDecl::field_iterator e = RD->field_end(CGM.getContext()),
4230 ifield = firstField; ifield != e; ++ifield)
4231 lastField = ifield;
4232
4233 InstanceStart = InstanceSize = 0;
4234 if (lastField != RD->field_end(CGM.getContext())) {
4235 FieldDecl *Field = *lastField;
4236 const llvm::Type *FieldTy =
4237 CGM.getTypes().ConvertTypeForMem(Field->getType());
4238 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
4239 InstanceSize = GetIvarBaseOffset(Layout, Field) + Size;
4240 if (firstField == RD->field_end(CGM.getContext()))
4241 InstanceStart = InstanceSize;
4242 else {
4243 Field = *firstField;
4244 InstanceStart = GetIvarBaseOffset(Layout, Field);
4245 }
4246 }
4247}
4248
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004249void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) {
4250 std::string ClassName = ID->getNameAsString();
4251 if (!ObjCEmptyCacheVar) {
4252 ObjCEmptyCacheVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004253 ObjCTypes.CacheTy,
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_cache",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004258 &CGM.getModule());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004259
4260 ObjCEmptyVtableVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004261 ObjCTypes.ImpnfABITy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004262 false,
4263 llvm::GlobalValue::ExternalLinkage,
4264 0,
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004265 "_objc_empty_vtable",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004266 &CGM.getModule());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004267 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004268 assert(ID->getClassInterface() &&
4269 "CGObjCNonFragileABIMac::GenerateClass - class is 0");
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004270 // FIXME: Is this correct (That meta class size is never computed)?
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004271 uint32_t InstanceStart =
4272 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassnfABITy);
4273 uint32_t InstanceSize = InstanceStart;
4274 uint32_t flags = CLS_META;
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004275 std::string ObjCMetaClassName(getMetaclassSymbolPrefix());
4276 std::string ObjCClassName(getClassSymbolPrefix());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004277
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004278 llvm::GlobalVariable *SuperClassGV, *IsAGV;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004279
Daniel Dunbar04d40782009-04-14 06:00:08 +00004280 bool classIsHidden =
4281 CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004282 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004283 flags |= OBJC2_CLS_HIDDEN;
4284 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004285 // class is root
4286 flags |= CLS_ROOT;
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004287 SuperClassGV = GetClassGlobal(ObjCClassName + ClassName);
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004288 IsAGV = GetClassGlobal(ObjCMetaClassName + ClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004289 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004290 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004291 const ObjCInterfaceDecl *Root = ID->getClassInterface();
4292 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
4293 Root = Super;
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004294 IsAGV = GetClassGlobal(ObjCMetaClassName + Root->getNameAsString());
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004295 // work on super class metadata symbol.
4296 std::string SuperClassName =
4297 ObjCMetaClassName + ID->getClassInterface()->getSuperClass()->getNameAsString();
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004298 SuperClassGV = GetClassGlobal(SuperClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004299 }
4300 llvm::GlobalVariable *CLASS_RO_GV = BuildClassRoTInitializer(flags,
4301 InstanceStart,
4302 InstanceSize,ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004303 std::string TClassName = ObjCMetaClassName + ClassName;
4304 llvm::GlobalVariable *MetaTClass =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004305 BuildClassMetaData(TClassName, IsAGV, SuperClassGV, CLASS_RO_GV,
4306 classIsHidden);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004307
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004308 // Metadata for the class
4309 flags = CLS;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004310 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004311 flags |= OBJC2_CLS_HIDDEN;
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004312
4313 if (hasObjCExceptionAttribute(ID->getClassInterface()))
4314 flags |= CLS_EXCEPTION;
4315
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004316 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004317 flags |= CLS_ROOT;
4318 SuperClassGV = 0;
Chris Lattnerb7b58b12009-04-19 06:02:28 +00004319 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004320 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004321 std::string RootClassName =
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004322 ID->getClassInterface()->getSuperClass()->getNameAsString();
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004323 SuperClassGV = GetClassGlobal(ObjCClassName + RootClassName);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004324 }
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004325 GetClassSizeInfo(ID->getClassInterface(), InstanceStart, InstanceSize);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004326 CLASS_RO_GV = BuildClassRoTInitializer(flags,
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004327 InstanceStart,
4328 InstanceSize,
4329 ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004330
4331 TClassName = ObjCClassName + ClassName;
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004332 llvm::GlobalVariable *ClassMD =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004333 BuildClassMetaData(TClassName, MetaTClass, SuperClassGV, CLASS_RO_GV,
4334 classIsHidden);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004335 DefinedClasses.push_back(ClassMD);
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004336
4337 // Force the definition of the EHType if necessary.
4338 if (flags & CLS_EXCEPTION)
4339 GetInterfaceEHType(ID->getClassInterface(), true);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004340}
4341
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004342/// GenerateProtocolRef - This routine is called to generate code for
4343/// a protocol reference expression; as in:
4344/// @code
4345/// @protocol(Proto1);
4346/// @endcode
4347/// It generates a weak reference to l_OBJC_PROTOCOL_REFERENCE_$_Proto1
4348/// which will hold address of the protocol meta-data.
4349///
4350llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CGBuilderTy &Builder,
4351 const ObjCProtocolDecl *PD) {
4352
Fariborz Jahanian960cd062009-04-10 18:47:34 +00004353 // This routine is called for @protocol only. So, we must build definition
4354 // of protocol's meta-data (not a reference to it!)
4355 //
4356 llvm::Constant *Init = llvm::ConstantExpr::getBitCast(GetOrEmitProtocol(PD),
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004357 ObjCTypes.ExternalProtocolPtrTy);
4358
4359 std::string ProtocolName("\01l_OBJC_PROTOCOL_REFERENCE_$_");
4360 ProtocolName += PD->getNameAsCString();
4361
4362 llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName);
4363 if (PTGV)
4364 return Builder.CreateLoad(PTGV, false, "tmp");
4365 PTGV = new llvm::GlobalVariable(
4366 Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00004367 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004368 Init,
4369 ProtocolName,
4370 &CGM.getModule());
4371 PTGV->setSection("__DATA, __objc_protorefs, coalesced, no_dead_strip");
4372 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4373 UsedGlobals.push_back(PTGV);
4374 return Builder.CreateLoad(PTGV, false, "tmp");
4375}
4376
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004377/// GenerateCategory - Build metadata for a category implementation.
4378/// struct _category_t {
4379/// const char * const name;
4380/// struct _class_t *const cls;
4381/// const struct _method_list_t * const instance_methods;
4382/// const struct _method_list_t * const class_methods;
4383/// const struct _protocol_list_t * const protocols;
4384/// const struct _prop_list_t * const properties;
4385/// }
4386///
4387void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD)
4388{
4389 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004390 const char *Prefix = "\01l_OBJC_$_CATEGORY_";
4391 std::string ExtCatName(Prefix + Interface->getNameAsString()+
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004392 "_$_" + OCD->getNameAsString());
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004393 std::string ExtClassName(getClassSymbolPrefix() +
4394 Interface->getNameAsString());
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004395
4396 std::vector<llvm::Constant*> Values(6);
4397 Values[0] = GetClassName(OCD->getIdentifier());
4398 // meta-class entry symbol
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004399 llvm::GlobalVariable *ClassGV = GetClassGlobal(ExtClassName);
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004400 Values[1] = ClassGV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004401 std::vector<llvm::Constant*> Methods;
4402 std::string MethodListName(Prefix);
4403 MethodListName += "INSTANCE_METHODS_" + Interface->getNameAsString() +
4404 "_$_" + OCD->getNameAsString();
4405
4406 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
4407 e = OCD->instmeth_end(); i != e; ++i) {
4408 // Instance methods should always be defined.
4409 Methods.push_back(GetMethodConstant(*i));
4410 }
4411
4412 Values[2] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004413 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004414 Methods);
4415
4416 MethodListName = Prefix;
4417 MethodListName += "CLASS_METHODS_" + Interface->getNameAsString() + "_$_" +
4418 OCD->getNameAsString();
4419 Methods.clear();
4420 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
4421 e = OCD->classmeth_end(); i != e; ++i) {
4422 // Class methods should always be defined.
4423 Methods.push_back(GetMethodConstant(*i));
4424 }
4425
4426 Values[3] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004427 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004428 Methods);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004429 const ObjCCategoryDecl *Category =
4430 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Fariborz Jahanian943ed6f2009-02-13 17:52:22 +00004431 if (Category) {
4432 std::string ExtName(Interface->getNameAsString() + "_$_" +
4433 OCD->getNameAsString());
4434 Values[4] = EmitProtocolList("\01l_OBJC_CATEGORY_PROTOCOLS_$_"
4435 + Interface->getNameAsString() + "_$_"
4436 + Category->getNameAsString(),
4437 Category->protocol_begin(),
4438 Category->protocol_end());
4439 Values[5] =
4440 EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
4441 OCD, Category, ObjCTypes);
4442 }
4443 else {
4444 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4445 Values[5] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4446 }
4447
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004448 llvm::Constant *Init =
4449 llvm::ConstantStruct::get(ObjCTypes.CategorynfABITy,
4450 Values);
4451 llvm::GlobalVariable *GCATV
4452 = new llvm::GlobalVariable(ObjCTypes.CategorynfABITy,
4453 false,
4454 llvm::GlobalValue::InternalLinkage,
4455 Init,
4456 ExtCatName,
4457 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004458 GCATV->setAlignment(
4459 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.CategorynfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004460 GCATV->setSection("__DATA, __objc_const");
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004461 UsedGlobals.push_back(GCATV);
4462 DefinedCategories.push_back(GCATV);
4463}
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004464
4465/// GetMethodConstant - Return a struct objc_method constant for the
4466/// given method if it has been defined. The result is null if the
4467/// method has not been defined. The return value has type MethodPtrTy.
4468llvm::Constant *CGObjCNonFragileABIMac::GetMethodConstant(
4469 const ObjCMethodDecl *MD) {
4470 // FIXME: Use DenseMap::lookup
4471 llvm::Function *Fn = MethodDefinitions[MD];
4472 if (!Fn)
4473 return 0;
4474
4475 std::vector<llvm::Constant*> Method(3);
4476 Method[0] =
4477 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4478 ObjCTypes.SelectorPtrTy);
4479 Method[1] = GetMethodVarType(MD);
4480 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
4481 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
4482}
4483
4484/// EmitMethodList - Build meta-data for method declarations
4485/// struct _method_list_t {
4486/// uint32_t entsize; // sizeof(struct _objc_method)
4487/// uint32_t method_count;
4488/// struct _objc_method method_list[method_count];
4489/// }
4490///
4491llvm::Constant *CGObjCNonFragileABIMac::EmitMethodList(
4492 const std::string &Name,
4493 const char *Section,
4494 const ConstantVector &Methods) {
4495 // Return null for empty list.
4496 if (Methods.empty())
4497 return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy);
4498
4499 std::vector<llvm::Constant*> Values(3);
4500 // sizeof(struct _objc_method)
4501 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.MethodTy);
4502 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4503 // method_count
4504 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
4505 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
4506 Methods.size());
4507 Values[2] = llvm::ConstantArray::get(AT, Methods);
4508 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4509
4510 llvm::GlobalVariable *GV =
4511 new llvm::GlobalVariable(Init->getType(), false,
4512 llvm::GlobalValue::InternalLinkage,
4513 Init,
4514 Name,
4515 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004516 GV->setAlignment(
4517 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004518 GV->setSection(Section);
4519 UsedGlobals.push_back(GV);
4520 return llvm::ConstantExpr::getBitCast(GV,
4521 ObjCTypes.MethodListnfABIPtrTy);
4522}
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004523
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004524/// ObjCIvarOffsetVariable - Returns the ivar offset variable for
4525/// the given ivar.
4526///
4527llvm::GlobalVariable * CGObjCNonFragileABIMac::ObjCIvarOffsetVariable(
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004528 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004529 const ObjCIvarDecl *Ivar) {
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00004530 std::string Name = "OBJC_IVAR_$_" +
Douglas Gregor6ab35242009-04-09 21:40:53 +00004531 getInterfaceDeclForIvar(ID, Ivar, CGM.getContext())->getNameAsString() +
4532 '.' + Ivar->getNameAsString();
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004533 llvm::GlobalVariable *IvarOffsetGV =
4534 CGM.getModule().getGlobalVariable(Name);
4535 if (!IvarOffsetGV)
4536 IvarOffsetGV =
4537 new llvm::GlobalVariable(ObjCTypes.LongTy,
4538 false,
4539 llvm::GlobalValue::ExternalLinkage,
4540 0,
4541 Name,
4542 &CGM.getModule());
4543 return IvarOffsetGV;
4544}
4545
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004546llvm::Constant * CGObjCNonFragileABIMac::EmitIvarOffsetVar(
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004547 const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004548 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004549 unsigned long int Offset) {
Daniel Dunbar737c5022009-04-19 00:44:02 +00004550 llvm::GlobalVariable *IvarOffsetGV = ObjCIvarOffsetVariable(ID, Ivar);
4551 IvarOffsetGV->setInitializer(llvm::ConstantInt::get(ObjCTypes.LongTy,
4552 Offset));
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004553 IvarOffsetGV->setAlignment(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004554 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.LongTy));
Daniel Dunbar737c5022009-04-19 00:44:02 +00004555
4556 // FIXME: This matches gcc, but shouldn't the visibility be set on
4557 // the use as well (i.e., in ObjCIvarOffsetVariable).
4558 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
4559 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
4560 CGM.getDeclVisibilityMode(ID) == LangOptions::Hidden)
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004561 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar04d40782009-04-14 06:00:08 +00004562 else
Fariborz Jahanian77c9fd22009-04-06 18:30:00 +00004563 IvarOffsetGV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004564 IvarOffsetGV->setSection("__DATA, __objc_const");
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004565 return IvarOffsetGV;
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004566}
4567
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004568/// EmitIvarList - Emit the ivar list for the given
Daniel Dunbar11394522009-04-18 08:51:00 +00004569/// implementation. The return value has type
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004570/// IvarListnfABIPtrTy.
4571/// struct _ivar_t {
4572/// unsigned long int *offset; // pointer to ivar offset location
4573/// char *name;
4574/// char *type;
4575/// uint32_t alignment;
4576/// uint32_t size;
4577/// }
4578/// struct _ivar_list_t {
4579/// uint32 entsize; // sizeof(struct _ivar_t)
4580/// uint32 count;
4581/// struct _iver_t list[count];
4582/// }
4583///
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004584
4585void CGObjCCommonMac::GetNamedIvarList(const ObjCInterfaceDecl *OID,
4586 llvm::SmallVector<ObjCIvarDecl*, 16> &Res) const {
4587 for (ObjCInterfaceDecl::ivar_iterator I = OID->ivar_begin(),
4588 E = OID->ivar_end(); I != E; ++I) {
4589 // Ignore unnamed bit-fields.
4590 if (!(*I)->getDeclName())
4591 continue;
4592
4593 Res.push_back(*I);
4594 }
4595
4596 for (ObjCInterfaceDecl::prop_iterator I = OID->prop_begin(CGM.getContext()),
4597 E = OID->prop_end(CGM.getContext()); I != E; ++I)
4598 if (ObjCIvarDecl *IV = (*I)->getPropertyIvarDecl())
4599 Res.push_back(IV);
4600}
4601
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004602llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList(
4603 const ObjCImplementationDecl *ID) {
4604
4605 std::vector<llvm::Constant*> Ivars, Ivar(5);
4606
4607 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4608 assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface");
4609
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004610 // FIXME. Consolidate this with similar code in GenerateClass.
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00004611 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00004612
Daniel Dunbar91636d62009-04-20 00:33:43 +00004613 // Collect declared and synthesized ivars in a small vector.
Fariborz Jahanian18191882009-03-31 18:11:23 +00004614 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004615 GetNamedIvarList(OID, OIvars);
Fariborz Jahanian99eee362009-04-01 19:37:34 +00004616
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004617 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
4618 ObjCIvarDecl *IVD = OIvars[i];
4619 const FieldDecl *Field = OID->lookupFieldDeclForIvar(CGM.getContext(), IVD);
Daniel Dunbar3eec8aa2009-04-20 05:53:40 +00004620 Ivar[0] = EmitIvarOffsetVar(ID->getClassInterface(), IVD,
Daniel Dunbar48fa0642009-04-19 02:03:42 +00004621 GetIvarBaseOffset(Layout, Field));
Daniel Dunbar3eec8aa2009-04-20 05:53:40 +00004622 Ivar[1] = GetMethodVarName(Field->getIdentifier());
Devang Patel7794bb82009-03-04 18:21:39 +00004623 Ivar[2] = GetMethodVarType(Field);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004624 const llvm::Type *FieldTy =
4625 CGM.getTypes().ConvertTypeForMem(Field->getType());
4626 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
4627 unsigned Align = CGM.getContext().getPreferredTypeAlign(
4628 Field->getType().getTypePtr()) >> 3;
4629 Align = llvm::Log2_32(Align);
4630 Ivar[3] = llvm::ConstantInt::get(ObjCTypes.IntTy, Align);
Daniel Dunbar91636d62009-04-20 00:33:43 +00004631 // NOTE. Size of a bitfield does not match gcc's, because of the
4632 // way bitfields are treated special in each. But I am told that
4633 // 'size' for bitfield ivars is ignored by the runtime so it does
4634 // not matter. If it matters, there is enough info to get the
4635 // bitfield right!
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004636 Ivar[4] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4637 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarnfABITy, Ivar));
4638 }
4639 // Return null for empty list.
4640 if (Ivars.empty())
4641 return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4642 std::vector<llvm::Constant*> Values(3);
4643 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.IvarnfABITy);
4644 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4645 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
4646 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarnfABITy,
4647 Ivars.size());
4648 Values[2] = llvm::ConstantArray::get(AT, Ivars);
4649 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4650 const char *Prefix = "\01l_OBJC_$_INSTANCE_VARIABLES_";
4651 llvm::GlobalVariable *GV =
4652 new llvm::GlobalVariable(Init->getType(), false,
4653 llvm::GlobalValue::InternalLinkage,
4654 Init,
4655 Prefix + OID->getNameAsString(),
4656 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004657 GV->setAlignment(
4658 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004659 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004660
4661 UsedGlobals.push_back(GV);
4662 return llvm::ConstantExpr::getBitCast(GV,
4663 ObjCTypes.IvarListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004664}
4665
4666llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef(
4667 const ObjCProtocolDecl *PD) {
4668 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4669
4670 if (!Entry) {
4671 // We use the initializer as a marker of whether this is a forward
4672 // reference or not. At module finalization we add the empty
4673 // contents for protocols which were referenced but never defined.
4674 Entry =
4675 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
4676 llvm::GlobalValue::ExternalLinkage,
4677 0,
4678 "\01l_OBJC_PROTOCOL_$_" + PD->getNameAsString(),
4679 &CGM.getModule());
4680 Entry->setSection("__DATA,__datacoal_nt,coalesced");
4681 UsedGlobals.push_back(Entry);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004682 }
4683
4684 return Entry;
4685}
4686
4687/// GetOrEmitProtocol - Generate the protocol meta-data:
4688/// @code
4689/// struct _protocol_t {
4690/// id isa; // NULL
4691/// const char * const protocol_name;
4692/// const struct _protocol_list_t * protocol_list; // super protocols
4693/// const struct method_list_t * const instance_methods;
4694/// const struct method_list_t * const class_methods;
4695/// const struct method_list_t *optionalInstanceMethods;
4696/// const struct method_list_t *optionalClassMethods;
4697/// const struct _prop_list_t * properties;
4698/// const uint32_t size; // sizeof(struct _protocol_t)
4699/// const uint32_t flags; // = 0
4700/// }
4701/// @endcode
4702///
4703
4704llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol(
4705 const ObjCProtocolDecl *PD) {
4706 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4707
4708 // Early exit if a defining object has already been generated.
4709 if (Entry && Entry->hasInitializer())
4710 return Entry;
4711
4712 const char *ProtocolName = PD->getNameAsCString();
4713
4714 // Construct method lists.
4715 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
4716 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregor6ab35242009-04-09 21:40:53 +00004717 for (ObjCProtocolDecl::instmeth_iterator
4718 i = PD->instmeth_begin(CGM.getContext()),
4719 e = PD->instmeth_end(CGM.getContext());
4720 i != e; ++i) {
Fariborz Jahanianda320092009-01-29 19:24:30 +00004721 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004722 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004723 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4724 OptInstanceMethods.push_back(C);
4725 } else {
4726 InstanceMethods.push_back(C);
4727 }
4728 }
4729
Douglas Gregor6ab35242009-04-09 21:40:53 +00004730 for (ObjCProtocolDecl::classmeth_iterator
4731 i = PD->classmeth_begin(CGM.getContext()),
4732 e = PD->classmeth_end(CGM.getContext());
4733 i != e; ++i) {
Fariborz Jahanianda320092009-01-29 19:24:30 +00004734 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004735 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004736 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4737 OptClassMethods.push_back(C);
4738 } else {
4739 ClassMethods.push_back(C);
4740 }
4741 }
4742
4743 std::vector<llvm::Constant*> Values(10);
4744 // isa is NULL
4745 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ObjectPtrTy);
4746 Values[1] = GetClassName(PD->getIdentifier());
4747 Values[2] = EmitProtocolList(
4748 "\01l_OBJC_$_PROTOCOL_REFS_" + PD->getNameAsString(),
4749 PD->protocol_begin(),
4750 PD->protocol_end());
4751
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004752 Values[3] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004753 + PD->getNameAsString(),
4754 "__DATA, __objc_const",
4755 InstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004756 Values[4] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004757 + PD->getNameAsString(),
4758 "__DATA, __objc_const",
4759 ClassMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004760 Values[5] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004761 + PD->getNameAsString(),
4762 "__DATA, __objc_const",
4763 OptInstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004764 Values[6] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004765 + PD->getNameAsString(),
4766 "__DATA, __objc_const",
4767 OptClassMethods);
4768 Values[7] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + PD->getNameAsString(),
4769 0, PD, ObjCTypes);
4770 uint32_t Size =
4771 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolnfABITy);
4772 Values[8] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4773 Values[9] = llvm::Constant::getNullValue(ObjCTypes.IntTy);
4774 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolnfABITy,
4775 Values);
4776
4777 if (Entry) {
4778 // Already created, fix the linkage and update the initializer.
Mike Stump286acbd2009-03-07 16:33:28 +00004779 Entry->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004780 Entry->setInitializer(Init);
4781 } else {
4782 Entry =
4783 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004784 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004785 Init,
4786 std::string("\01l_OBJC_PROTOCOL_$_")+ProtocolName,
4787 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004788 Entry->setAlignment(
4789 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABITy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004790 Entry->setSection("__DATA,__datacoal_nt,coalesced");
Fariborz Jahanianda320092009-01-29 19:24:30 +00004791 }
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004792 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
4793
4794 // Use this protocol meta-data to build protocol list table in section
4795 // __DATA, __objc_protolist
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004796 llvm::GlobalVariable *PTGV = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004797 ObjCTypes.ProtocolnfABIPtrTy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004798 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004799 Entry,
4800 std::string("\01l_OBJC_LABEL_PROTOCOL_$_")
4801 +ProtocolName,
4802 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004803 PTGV->setAlignment(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004804 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABIPtrTy));
Daniel Dunbar0bf21992009-04-15 02:56:18 +00004805 PTGV->setSection("__DATA, __objc_protolist, coalesced, no_dead_strip");
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004806 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4807 UsedGlobals.push_back(PTGV);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004808 return Entry;
4809}
4810
4811/// EmitProtocolList - Generate protocol list meta-data:
4812/// @code
4813/// struct _protocol_list_t {
4814/// long protocol_count; // Note, this is 32/64 bit
4815/// struct _protocol_t[protocol_count];
4816/// }
4817/// @endcode
4818///
4819llvm::Constant *
4820CGObjCNonFragileABIMac::EmitProtocolList(const std::string &Name,
4821 ObjCProtocolDecl::protocol_iterator begin,
4822 ObjCProtocolDecl::protocol_iterator end) {
4823 std::vector<llvm::Constant*> ProtocolRefs;
4824
Fariborz Jahanianda320092009-01-29 19:24:30 +00004825 // Just return null for empty protocol lists
Daniel Dunbar948e2582009-02-15 07:36:20 +00004826 if (begin == end)
Fariborz Jahanianda320092009-01-29 19:24:30 +00004827 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4828
Daniel Dunbar948e2582009-02-15 07:36:20 +00004829 // FIXME: We shouldn't need to do this lookup here, should we?
Fariborz Jahanianda320092009-01-29 19:24:30 +00004830 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
4831 if (GV)
Daniel Dunbar948e2582009-02-15 07:36:20 +00004832 return llvm::ConstantExpr::getBitCast(GV,
4833 ObjCTypes.ProtocolListnfABIPtrTy);
4834
4835 for (; begin != end; ++begin)
4836 ProtocolRefs.push_back(GetProtocolRef(*begin)); // Implemented???
4837
Fariborz Jahanianda320092009-01-29 19:24:30 +00004838 // This list is null terminated.
4839 ProtocolRefs.push_back(llvm::Constant::getNullValue(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004840 ObjCTypes.ProtocolnfABIPtrTy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004841
4842 std::vector<llvm::Constant*> Values(2);
4843 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
4844 Values[1] =
Daniel Dunbar948e2582009-02-15 07:36:20 +00004845 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolnfABIPtrTy,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004846 ProtocolRefs.size()),
4847 ProtocolRefs);
4848
4849 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4850 GV = new llvm::GlobalVariable(Init->getType(), false,
4851 llvm::GlobalValue::InternalLinkage,
4852 Init,
4853 Name,
4854 &CGM.getModule());
4855 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004856 GV->setAlignment(
4857 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004858 UsedGlobals.push_back(GV);
Daniel Dunbar948e2582009-02-15 07:36:20 +00004859 return llvm::ConstantExpr::getBitCast(GV,
4860 ObjCTypes.ProtocolListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004861}
4862
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004863/// GetMethodDescriptionConstant - This routine build following meta-data:
4864/// struct _objc_method {
4865/// SEL _cmd;
4866/// char *method_type;
4867/// char *_imp;
4868/// }
4869
4870llvm::Constant *
4871CGObjCNonFragileABIMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
4872 std::vector<llvm::Constant*> Desc(3);
4873 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4874 ObjCTypes.SelectorPtrTy);
4875 Desc[1] = GetMethodVarType(MD);
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004876 // Protocol methods have no implementation. So, this entry is always NULL.
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004877 Desc[2] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
4878 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Desc);
4879}
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004880
4881/// EmitObjCValueForIvar - Code Gen for nonfragile ivar reference.
4882/// This code gen. amounts to generating code for:
4883/// @code
4884/// (type *)((char *)base + _OBJC_IVAR_$_.ivar;
4885/// @encode
4886///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004887LValue CGObjCNonFragileABIMac::EmitObjCValueForIvar(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004888 CodeGen::CodeGenFunction &CGF,
4889 QualType ObjectTy,
4890 llvm::Value *BaseValue,
4891 const ObjCIvarDecl *Ivar,
4892 const FieldDecl *Field,
4893 unsigned CVRQualifiers) {
4894 assert(ObjectTy->isObjCInterfaceType() &&
4895 "CGObjCNonFragileABIMac::EmitObjCValueForIvar");
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004896 ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00004897 llvm::GlobalVariable *IvarOffsetGV = ObjCIvarOffsetVariable(ID, Ivar);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004898
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004899 // (char *) BaseValue
Chris Lattner51123fe2009-04-17 17:46:19 +00004900 llvm::Value *V = CGF.Builder.CreateBitCast(BaseValue, ObjCTypes.Int8PtrTy);
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004901 llvm::Value *Offset = CGF.Builder.CreateLoad(IvarOffsetGV);
4902 // (char*)BaseValue + Offset_symbol
4903 V = CGF.Builder.CreateGEP(V, Offset, "add.ptr");
4904 // (type *)((char*)BaseValue + Offset_symbol)
4905 const llvm::Type *IvarTy =
Chris Lattner51123fe2009-04-17 17:46:19 +00004906 CGM.getTypes().ConvertTypeForMem(Ivar->getType());
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004907 llvm::Type *ptrIvarTy = llvm::PointerType::getUnqual(IvarTy);
4908 V = CGF.Builder.CreateBitCast(V, ptrIvarTy);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004909
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00004910 if (Ivar->isBitField()) {
Chris Lattner51123fe2009-04-17 17:46:19 +00004911 QualType FieldTy = Field->getType();
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00004912 CodeGenTypes::BitFieldInfo bitFieldInfo =
4913 CGM.getTypes().getBitFieldInfo(Field);
4914 return LValue::MakeBitfield(V, bitFieldInfo.Begin, bitFieldInfo.Size,
Chris Lattner51123fe2009-04-17 17:46:19 +00004915 FieldTy->isSignedIntegerType(),
4916 FieldTy.getCVRQualifiers()|CVRQualifiers);
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00004917 }
4918
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004919 LValue LV = LValue::MakeAddr(V,
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004920 Ivar->getType().getCVRQualifiers()|CVRQualifiers,
4921 CGM.getContext().getObjCGCAttrKind(Ivar->getType()));
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004922 LValue::SetObjCIvar(LV, true);
4923 return LV;
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004924}
4925
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004926llvm::Value *CGObjCNonFragileABIMac::EmitIvarOffset(
4927 CodeGen::CodeGenFunction &CGF,
4928 ObjCInterfaceDecl *Interface,
4929 const ObjCIvarDecl *Ivar) {
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00004930 return CGF.Builder.CreateLoad(ObjCIvarOffsetVariable(Interface, Ivar),
4931 false, "ivar");
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004932}
4933
Fariborz Jahanian46551122009-02-04 00:22:57 +00004934CodeGen::RValue CGObjCNonFragileABIMac::EmitMessageSend(
4935 CodeGen::CodeGenFunction &CGF,
4936 QualType ResultType,
4937 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004938 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +00004939 QualType Arg0Ty,
4940 bool IsSuper,
4941 const CallArgList &CallArgs) {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004942 // FIXME. Even though IsSuper is passes. This function doese not
4943 // handle calls to 'super' receivers.
4944 CodeGenTypes &Types = CGM.getTypes();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004945 llvm::Value *Arg0 = Receiver;
4946 if (!IsSuper)
4947 Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy, "tmp");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004948
4949 // Find the message function name.
Fariborz Jahanianef163782009-02-05 01:13:09 +00004950 // FIXME. This is too much work to get the ABI-specific result type
4951 // needed to find the message name.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004952 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType,
4953 llvm::SmallVector<QualType, 16>());
4954 llvm::Constant *Fn;
4955 std::string Name("\01l_");
4956 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004957#if 0
4958 // unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004959 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
4960 Fn = ObjCTypes.MessageSendIdStretFixupFn;
4961 // FIXME. Is there a better way of getting these names.
4962 // They are available in RuntimeFunctions vector pair.
4963 Name += "objc_msgSendId_stret_fixup";
4964 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004965 else
4966#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004967 if (IsSuper) {
4968 Fn = ObjCTypes.MessageSendSuper2StretFixupFn;
4969 Name += "objc_msgSendSuper2_stret_fixup";
4970 }
4971 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004972 {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004973 Fn = ObjCTypes.MessageSendStretFixupFn;
4974 Name += "objc_msgSend_stret_fixup";
4975 }
4976 }
Fariborz Jahanian1a6b3682009-02-05 19:35:43 +00004977 else if (ResultType->isFloatingType() &&
4978 // Selection of frret API only happens in 32bit nonfragile ABI.
4979 CGM.getTargetData().getTypePaddedSize(ObjCTypes.LongTy) == 4) {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004980 Fn = ObjCTypes.MessageSendFpretFixupFn;
4981 Name += "objc_msgSend_fpret_fixup";
4982 }
4983 else {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004984#if 0
4985// unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004986 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
4987 Fn = ObjCTypes.MessageSendIdFixupFn;
4988 Name += "objc_msgSendId_fixup";
4989 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004990 else
4991#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004992 if (IsSuper) {
4993 Fn = ObjCTypes.MessageSendSuper2FixupFn;
4994 Name += "objc_msgSendSuper2_fixup";
4995 }
4996 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004997 {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004998 Fn = ObjCTypes.MessageSendFixupFn;
4999 Name += "objc_msgSend_fixup";
5000 }
5001 }
5002 Name += '_';
5003 std::string SelName(Sel.getAsString());
5004 // Replace all ':' in selector name with '_' ouch!
5005 for(unsigned i = 0; i < SelName.size(); i++)
5006 if (SelName[i] == ':')
5007 SelName[i] = '_';
5008 Name += SelName;
5009 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5010 if (!GV) {
Daniel Dunbar33af70f2009-04-15 19:03:14 +00005011 // Build message ref table entry.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005012 std::vector<llvm::Constant*> Values(2);
5013 Values[0] = Fn;
5014 Values[1] = GetMethodVarName(Sel);
5015 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
5016 GV = new llvm::GlobalVariable(Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00005017 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005018 Init,
5019 Name,
5020 &CGM.getModule());
5021 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbarf59c1a62009-04-15 19:04:46 +00005022 GV->setAlignment(16);
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005023 GV->setSection("__DATA, __objc_msgrefs, coalesced");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005024 }
5025 llvm::Value *Arg1 = CGF.Builder.CreateBitCast(GV, ObjCTypes.MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00005026
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005027 CallArgList ActualArgs;
5028 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
5029 ActualArgs.push_back(std::make_pair(RValue::get(Arg1),
5030 ObjCTypes.MessageRefCPtrTy));
5031 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Fariborz Jahanianef163782009-02-05 01:13:09 +00005032 const CGFunctionInfo &FnInfo1 = Types.getFunctionInfo(ResultType, ActualArgs);
5033 llvm::Value *Callee = CGF.Builder.CreateStructGEP(Arg1, 0);
5034 Callee = CGF.Builder.CreateLoad(Callee);
Fariborz Jahanian3ab75bd2009-02-14 21:25:36 +00005035 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo1, true);
Fariborz Jahanianef163782009-02-05 01:13:09 +00005036 Callee = CGF.Builder.CreateBitCast(Callee,
5037 llvm::PointerType::getUnqual(FTy));
5038 return CGF.EmitCall(FnInfo1, Callee, ActualArgs);
Fariborz Jahanian46551122009-02-04 00:22:57 +00005039}
5040
5041/// Generate code for a message send expression in the nonfragile abi.
5042CodeGen::RValue CGObjCNonFragileABIMac::GenerateMessageSend(
5043 CodeGen::CodeGenFunction &CGF,
5044 QualType ResultType,
5045 Selector Sel,
5046 llvm::Value *Receiver,
5047 bool IsClassMessage,
5048 const CallArgList &CallArgs) {
Fariborz Jahanian46551122009-02-04 00:22:57 +00005049 return EmitMessageSend(CGF, ResultType, Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005050 Receiver, CGF.getContext().getObjCIdType(),
Fariborz Jahanian46551122009-02-04 00:22:57 +00005051 false, CallArgs);
5052}
5053
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005054llvm::GlobalVariable *
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005055CGObjCNonFragileABIMac::GetClassGlobal(const std::string &Name) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005056 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5057
Daniel Dunbardfff2302009-03-02 05:18:14 +00005058 if (!GV) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005059 GV = new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
5060 llvm::GlobalValue::ExternalLinkage,
5061 0, Name, &CGM.getModule());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005062 }
5063
5064 return GV;
5065}
5066
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005067llvm::Value *CGObjCNonFragileABIMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar11394522009-04-18 08:51:00 +00005068 const ObjCInterfaceDecl *ID) {
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005069 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
5070
5071 if (!Entry) {
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005072 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005073 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005074 Entry =
5075 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5076 llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005077 ClassGV,
Daniel Dunbar11394522009-04-18 08:51:00 +00005078 "\01L_OBJC_CLASSLIST_REFERENCES_$_",
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005079 &CGM.getModule());
5080 Entry->setAlignment(
5081 CGM.getTargetData().getPrefTypeAlignment(
5082 ObjCTypes.ClassnfABIPtrTy));
Daniel Dunbar11394522009-04-18 08:51:00 +00005083 Entry->setSection("__DATA, __objc_classrefs, regular, no_dead_strip");
5084 UsedGlobals.push_back(Entry);
5085 }
5086
5087 return Builder.CreateLoad(Entry, false, "tmp");
5088}
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005089
Daniel Dunbar11394522009-04-18 08:51:00 +00005090llvm::Value *
5091CGObjCNonFragileABIMac::EmitSuperClassRef(CGBuilderTy &Builder,
5092 const ObjCInterfaceDecl *ID) {
5093 llvm::GlobalVariable *&Entry = SuperClassReferences[ID->getIdentifier()];
5094
5095 if (!Entry) {
5096 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
5097 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
5098 Entry =
5099 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5100 llvm::GlobalValue::InternalLinkage,
5101 ClassGV,
5102 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5103 &CGM.getModule());
5104 Entry->setAlignment(
5105 CGM.getTargetData().getPrefTypeAlignment(
5106 ObjCTypes.ClassnfABIPtrTy));
5107 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005108 UsedGlobals.push_back(Entry);
5109 }
5110
5111 return Builder.CreateLoad(Entry, false, "tmp");
5112}
5113
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005114/// EmitMetaClassRef - Return a Value * of the address of _class_t
5115/// meta-data
5116///
5117llvm::Value *CGObjCNonFragileABIMac::EmitMetaClassRef(CGBuilderTy &Builder,
5118 const ObjCInterfaceDecl *ID) {
5119 llvm::GlobalVariable * &Entry = MetaClassReferences[ID->getIdentifier()];
5120 if (Entry)
5121 return Builder.CreateLoad(Entry, false, "tmp");
5122
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005123 std::string MetaClassName(getMetaclassSymbolPrefix() + ID->getNameAsString());
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005124 llvm::GlobalVariable *MetaClassGV = GetClassGlobal(MetaClassName);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005125 Entry =
5126 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5127 llvm::GlobalValue::InternalLinkage,
5128 MetaClassGV,
5129 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5130 &CGM.getModule());
5131 Entry->setAlignment(
5132 CGM.getTargetData().getPrefTypeAlignment(
5133 ObjCTypes.ClassnfABIPtrTy));
5134
Daniel Dunbar33af70f2009-04-15 19:03:14 +00005135 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005136 UsedGlobals.push_back(Entry);
5137
5138 return Builder.CreateLoad(Entry, false, "tmp");
5139}
5140
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005141/// GetClass - Return a reference to the class for the given interface
5142/// decl.
5143llvm::Value *CGObjCNonFragileABIMac::GetClass(CGBuilderTy &Builder,
5144 const ObjCInterfaceDecl *ID) {
5145 return EmitClassRef(Builder, ID);
5146}
5147
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005148/// Generates a message send where the super is the receiver. This is
5149/// a message send to self with special delivery semantics indicating
5150/// which class's method should be called.
5151CodeGen::RValue
5152CGObjCNonFragileABIMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
5153 QualType ResultType,
5154 Selector Sel,
5155 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005156 bool isCategoryImpl,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005157 llvm::Value *Receiver,
5158 bool IsClassMessage,
5159 const CodeGen::CallArgList &CallArgs) {
5160 // ...
5161 // Create and init a super structure; this is a (receiver, class)
5162 // pair we will pass to objc_msgSendSuper.
5163 llvm::Value *ObjCSuper =
5164 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
5165
5166 llvm::Value *ReceiverAsObject =
5167 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
5168 CGF.Builder.CreateStore(ReceiverAsObject,
5169 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
5170
5171 // If this is a class message the metaclass is passed as the target.
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005172 llvm::Value *Target;
5173 if (IsClassMessage) {
5174 if (isCategoryImpl) {
5175 // Message sent to "super' in a class method defined in
5176 // a category implementation.
Daniel Dunbar11394522009-04-18 08:51:00 +00005177 Target = EmitClassRef(CGF.Builder, Class);
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005178 Target = CGF.Builder.CreateStructGEP(Target, 0);
5179 Target = CGF.Builder.CreateLoad(Target);
5180 }
5181 else
5182 Target = EmitMetaClassRef(CGF.Builder, Class);
5183 }
5184 else
Daniel Dunbar11394522009-04-18 08:51:00 +00005185 Target = EmitSuperClassRef(CGF.Builder, Class);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005186
5187 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
5188 // and ObjCTypes types.
5189 const llvm::Type *ClassTy =
5190 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
5191 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
5192 CGF.Builder.CreateStore(Target,
5193 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
5194
5195 return EmitMessageSend(CGF, ResultType, Sel,
5196 ObjCSuper, ObjCTypes.SuperPtrCTy,
5197 true, CallArgs);
5198}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005199
5200llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CGBuilderTy &Builder,
5201 Selector Sel) {
5202 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
5203
5204 if (!Entry) {
5205 llvm::Constant *Casted =
5206 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
5207 ObjCTypes.SelectorPtrTy);
5208 Entry =
5209 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
5210 llvm::GlobalValue::InternalLinkage,
5211 Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
5212 &CGM.getModule());
5213 Entry->setSection("__DATA,__objc_selrefs,literal_pointers,no_dead_strip");
5214 UsedGlobals.push_back(Entry);
5215 }
5216
5217 return Builder.CreateLoad(Entry, false, "tmp");
5218}
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005219/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
5220/// objc_assign_ivar (id src, id *dst)
5221///
5222void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
5223 llvm::Value *src, llvm::Value *dst)
5224{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005225 const llvm::Type * SrcTy = src->getType();
5226 if (!isa<llvm::PointerType>(SrcTy)) {
5227 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5228 assert(Size <= 8 && "does not support size > 8");
5229 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5230 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005231 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5232 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005233 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5234 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5235 CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn,
5236 src, dst, "assignivar");
5237 return;
5238}
5239
5240/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
5241/// objc_assign_strongCast (id src, id *dst)
5242///
5243void CGObjCNonFragileABIMac::EmitObjCStrongCastAssign(
5244 CodeGen::CodeGenFunction &CGF,
5245 llvm::Value *src, llvm::Value *dst)
5246{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005247 const llvm::Type * SrcTy = src->getType();
5248 if (!isa<llvm::PointerType>(SrcTy)) {
5249 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5250 assert(Size <= 8 && "does not support size > 8");
5251 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5252 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005253 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5254 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005255 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5256 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5257 CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn,
5258 src, dst, "weakassign");
5259 return;
5260}
5261
5262/// EmitObjCWeakRead - Code gen for loading value of a __weak
5263/// object: objc_read_weak (id *src)
5264///
5265llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead(
5266 CodeGen::CodeGenFunction &CGF,
5267 llvm::Value *AddrWeakObj)
5268{
Eli Friedman8339b352009-03-07 03:57:15 +00005269 const llvm::Type* DestTy =
5270 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005271 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
5272 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
5273 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00005274 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005275 return read_weak;
5276}
5277
5278/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
5279/// objc_assign_weak (id src, id *dst)
5280///
5281void CGObjCNonFragileABIMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
5282 llvm::Value *src, llvm::Value *dst)
5283{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005284 const llvm::Type * SrcTy = src->getType();
5285 if (!isa<llvm::PointerType>(SrcTy)) {
5286 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5287 assert(Size <= 8 && "does not support size > 8");
5288 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5289 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005290 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5291 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005292 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5293 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattner96508e12009-04-17 22:12:36 +00005294 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005295 src, dst, "weakassign");
5296 return;
5297}
5298
5299/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
5300/// objc_assign_global (id src, id *dst)
5301///
5302void CGObjCNonFragileABIMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
5303 llvm::Value *src, llvm::Value *dst)
5304{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005305 const llvm::Type * SrcTy = src->getType();
5306 if (!isa<llvm::PointerType>(SrcTy)) {
5307 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5308 assert(Size <= 8 && "does not support size > 8");
5309 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5310 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005311 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5312 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005313 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5314 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5315 CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn,
5316 src, dst, "globalassign");
5317 return;
5318}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005319
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005320void
5321CGObjCNonFragileABIMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
5322 const Stmt &S) {
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005323 bool isTry = isa<ObjCAtTryStmt>(S);
5324 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
5325 llvm::BasicBlock *PrevLandingPad = CGF.getInvokeDest();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005326 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005327 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005328 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005329 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
5330
5331 // For @synchronized, call objc_sync_enter(sync.expr). The
5332 // evaluation of the expression must occur before we enter the
5333 // @synchronized. We can safely avoid a temp here because jumps into
5334 // @synchronized are illegal & this will dominate uses.
5335 llvm::Value *SyncArg = 0;
5336 if (!isTry) {
5337 SyncArg =
5338 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
5339 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005340 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005341 }
5342
5343 // Push an EH context entry, used for handling rethrows and jumps
5344 // through finally.
5345 CGF.PushCleanupBlock(FinallyBlock);
5346
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005347 CGF.setInvokeDest(TryHandler);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005348
5349 CGF.EmitBlock(TryBlock);
5350 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
5351 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
5352 CGF.EmitBranchThroughCleanup(FinallyEnd);
5353
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005354 // Emit the exception handler.
5355
5356 CGF.EmitBlock(TryHandler);
5357
5358 llvm::Value *llvm_eh_exception =
5359 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_exception);
5360 llvm::Value *llvm_eh_selector_i64 =
5361 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector_i64);
5362 llvm::Value *llvm_eh_typeid_for_i64 =
5363 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for_i64);
5364 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5365 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(Exc->getType(), "_rethrow");
5366
5367 llvm::SmallVector<llvm::Value*, 8> SelectorArgs;
5368 SelectorArgs.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005369 SelectorArgs.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005370
5371 // Construct the lists of (type, catch body) to handle.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005372 llvm::SmallVector<std::pair<const ParmVarDecl*, const Stmt*>, 8> Handlers;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005373 bool HasCatchAll = false;
5374 if (isTry) {
5375 if (const ObjCAtCatchStmt* CatchStmt =
5376 cast<ObjCAtTryStmt>(S).getCatchStmts()) {
5377 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005378 const ParmVarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
Steve Naroff7ba138a2009-03-03 19:52:17 +00005379 Handlers.push_back(std::make_pair(CatchDecl, CatchStmt->getCatchBody()));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005380
5381 // catch(...) always matches.
Steve Naroff7ba138a2009-03-03 19:52:17 +00005382 if (!CatchDecl) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005383 // Use i8* null here to signal this is a catch all, not a cleanup.
5384 llvm::Value *Null = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
5385 SelectorArgs.push_back(Null);
5386 HasCatchAll = true;
5387 break;
5388 }
5389
Daniel Dunbarede8de92009-03-06 00:01:21 +00005390 if (CGF.getContext().isObjCIdType(CatchDecl->getType()) ||
5391 CatchDecl->getType()->isObjCQualifiedIdType()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005392 llvm::Value *IDEHType =
5393 CGM.getModule().getGlobalVariable("OBJC_EHTYPE_id");
5394 if (!IDEHType)
5395 IDEHType =
5396 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5397 llvm::GlobalValue::ExternalLinkage,
5398 0, "OBJC_EHTYPE_id", &CGM.getModule());
5399 SelectorArgs.push_back(IDEHType);
5400 HasCatchAll = true;
5401 break;
5402 }
5403
5404 // All other types should be Objective-C interface pointer types.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005405 const PointerType *PT = CatchDecl->getType()->getAsPointerType();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005406 assert(PT && "Invalid @catch type.");
5407 const ObjCInterfaceType *IT =
5408 PT->getPointeeType()->getAsObjCInterfaceType();
5409 assert(IT && "Invalid @catch type.");
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005410 llvm::Value *EHType = GetInterfaceEHType(IT->getDecl(), false);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005411 SelectorArgs.push_back(EHType);
5412 }
5413 }
5414 }
5415
5416 // We use a cleanup unless there was already a catch all.
5417 if (!HasCatchAll) {
5418 SelectorArgs.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
Daniel Dunbarede8de92009-03-06 00:01:21 +00005419 Handlers.push_back(std::make_pair((const ParmVarDecl*) 0, (const Stmt*) 0));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005420 }
5421
5422 llvm::Value *Selector =
5423 CGF.Builder.CreateCall(llvm_eh_selector_i64,
5424 SelectorArgs.begin(), SelectorArgs.end(),
5425 "selector");
5426 for (unsigned i = 0, e = Handlers.size(); i != e; ++i) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005427 const ParmVarDecl *CatchParam = Handlers[i].first;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005428 const Stmt *CatchBody = Handlers[i].second;
5429
5430 llvm::BasicBlock *Next = 0;
5431
5432 // The last handler always matches.
5433 if (i + 1 != e) {
5434 assert(CatchParam && "Only last handler can be a catch all.");
5435
5436 llvm::BasicBlock *Match = CGF.createBasicBlock("match");
5437 Next = CGF.createBasicBlock("catch.next");
5438 llvm::Value *Id =
5439 CGF.Builder.CreateCall(llvm_eh_typeid_for_i64,
5440 CGF.Builder.CreateBitCast(SelectorArgs[i+2],
5441 ObjCTypes.Int8PtrTy));
5442 CGF.Builder.CreateCondBr(CGF.Builder.CreateICmpEQ(Selector, Id),
5443 Match, Next);
5444
5445 CGF.EmitBlock(Match);
5446 }
5447
5448 if (CatchBody) {
5449 llvm::BasicBlock *MatchEnd = CGF.createBasicBlock("match.end");
5450 llvm::BasicBlock *MatchHandler = CGF.createBasicBlock("match.handler");
5451
5452 // Cleanups must call objc_end_catch.
5453 //
5454 // FIXME: It seems incorrect for objc_begin_catch to be inside
5455 // this context, but this matches gcc.
5456 CGF.PushCleanupBlock(MatchEnd);
5457 CGF.setInvokeDest(MatchHandler);
5458
5459 llvm::Value *ExcObject =
5460 CGF.Builder.CreateCall(ObjCTypes.ObjCBeginCatchFn, Exc);
5461
5462 // Bind the catch parameter if it exists.
5463 if (CatchParam) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005464 ExcObject =
5465 CGF.Builder.CreateBitCast(ExcObject,
5466 CGF.ConvertType(CatchParam->getType()));
5467 // CatchParam is a ParmVarDecl because of the grammar
5468 // construction used to handle this, but for codegen purposes
5469 // we treat this as a local decl.
5470 CGF.EmitLocalBlockVarDecl(*CatchParam);
5471 CGF.Builder.CreateStore(ExcObject, CGF.GetAddrOfLocalVar(CatchParam));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005472 }
5473
5474 CGF.ObjCEHValueStack.push_back(ExcObject);
5475 CGF.EmitStmt(CatchBody);
5476 CGF.ObjCEHValueStack.pop_back();
5477
5478 CGF.EmitBranchThroughCleanup(FinallyEnd);
5479
5480 CGF.EmitBlock(MatchHandler);
5481
5482 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5483 // We are required to emit this call to satisfy LLVM, even
5484 // though we don't use the result.
5485 llvm::SmallVector<llvm::Value*, 8> Args;
5486 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005487 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005488 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5489 0));
5490 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5491 CGF.Builder.CreateStore(Exc, RethrowPtr);
5492 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5493
5494 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5495
5496 CGF.EmitBlock(MatchEnd);
5497
5498 // Unfortunately, we also have to generate another EH frame here
5499 // in case this throws.
5500 llvm::BasicBlock *MatchEndHandler =
5501 CGF.createBasicBlock("match.end.handler");
5502 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
5503 CGF.Builder.CreateInvoke(ObjCTypes.ObjCEndCatchFn,
5504 Cont, MatchEndHandler,
5505 Args.begin(), Args.begin());
5506
5507 CGF.EmitBlock(Cont);
5508 if (Info.SwitchBlock)
5509 CGF.EmitBlock(Info.SwitchBlock);
5510 if (Info.EndBlock)
5511 CGF.EmitBlock(Info.EndBlock);
5512
5513 CGF.EmitBlock(MatchEndHandler);
5514 Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5515 // We are required to emit this call to satisfy LLVM, even
5516 // though we don't use the result.
5517 Args.clear();
5518 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005519 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005520 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5521 0));
5522 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5523 CGF.Builder.CreateStore(Exc, RethrowPtr);
5524 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5525
5526 if (Next)
5527 CGF.EmitBlock(Next);
5528 } else {
5529 assert(!Next && "catchup should be last handler.");
5530
5531 CGF.Builder.CreateStore(Exc, RethrowPtr);
5532 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5533 }
5534 }
5535
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005536 // Pop the cleanup entry, the @finally is outside this cleanup
5537 // scope.
5538 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5539 CGF.setInvokeDest(PrevLandingPad);
5540
5541 CGF.EmitBlock(FinallyBlock);
5542
5543 if (isTry) {
5544 if (const ObjCAtFinallyStmt* FinallyStmt =
5545 cast<ObjCAtTryStmt>(S).getFinallyStmt())
5546 CGF.EmitStmt(FinallyStmt->getFinallyBody());
5547 } else {
5548 // Emit 'objc_sync_exit(expr)' as finally's sole statement for
5549 // @synchronized.
5550 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, SyncArg);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005551 }
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005552
5553 if (Info.SwitchBlock)
5554 CGF.EmitBlock(Info.SwitchBlock);
5555 if (Info.EndBlock)
5556 CGF.EmitBlock(Info.EndBlock);
5557
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005558 // Branch around the rethrow code.
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005559 CGF.EmitBranch(FinallyEnd);
5560
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005561 CGF.EmitBlock(FinallyRethrow);
5562 CGF.Builder.CreateCall(ObjCTypes.UnwindResumeOrRethrowFn,
5563 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005564 CGF.Builder.CreateUnreachable();
5565
5566 CGF.EmitBlock(FinallyEnd);
5567}
5568
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005569/// EmitThrowStmt - Generate code for a throw statement.
5570void CGObjCNonFragileABIMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
5571 const ObjCAtThrowStmt &S) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005572 llvm::Value *Exception;
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005573 if (const Expr *ThrowExpr = S.getThrowExpr()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005574 Exception = CGF.EmitScalarExpr(ThrowExpr);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005575 } else {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005576 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
5577 "Unexpected rethrow outside @catch block.");
5578 Exception = CGF.ObjCEHValueStack.back();
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005579 }
5580
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005581 llvm::Value *ExceptionAsObject =
5582 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
5583 llvm::BasicBlock *InvokeDest = CGF.getInvokeDest();
5584 if (InvokeDest) {
5585 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
5586 CGF.Builder.CreateInvoke(ObjCTypes.ExceptionThrowFn,
5587 Cont, InvokeDest,
5588 &ExceptionAsObject, &ExceptionAsObject + 1);
5589 CGF.EmitBlock(Cont);
5590 } else
5591 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
5592 CGF.Builder.CreateUnreachable();
5593
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005594 // Clear the insertion point to indicate we are in unreachable code.
5595 CGF.Builder.ClearInsertionPoint();
5596}
Daniel Dunbare588b992009-03-01 04:46:24 +00005597
5598llvm::Value *
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005599CGObjCNonFragileABIMac::GetInterfaceEHType(const ObjCInterfaceDecl *ID,
5600 bool ForDefinition) {
Daniel Dunbare588b992009-03-01 04:46:24 +00005601 llvm::GlobalVariable * &Entry = EHTypeReferences[ID->getIdentifier()];
Daniel Dunbare588b992009-03-01 04:46:24 +00005602
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005603 // If we don't need a definition, return the entry if found or check
5604 // if we use an external reference.
5605 if (!ForDefinition) {
5606 if (Entry)
5607 return Entry;
Daniel Dunbar7e075cb2009-04-07 06:43:45 +00005608
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005609 // If this type (or a super class) has the __objc_exception__
5610 // attribute, emit an external reference.
5611 if (hasObjCExceptionAttribute(ID))
5612 return Entry =
5613 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5614 llvm::GlobalValue::ExternalLinkage,
5615 0,
5616 (std::string("OBJC_EHTYPE_$_") +
5617 ID->getIdentifier()->getName()),
5618 &CGM.getModule());
5619 }
5620
5621 // Otherwise we need to either make a new entry or fill in the
5622 // initializer.
5623 assert((!Entry || !Entry->hasInitializer()) && "Duplicate EHType definition");
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005624 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbare588b992009-03-01 04:46:24 +00005625 std::string VTableName = "objc_ehtype_vtable";
5626 llvm::GlobalVariable *VTableGV =
5627 CGM.getModule().getGlobalVariable(VTableName);
5628 if (!VTableGV)
5629 VTableGV = new llvm::GlobalVariable(ObjCTypes.Int8PtrTy, false,
5630 llvm::GlobalValue::ExternalLinkage,
5631 0, VTableName, &CGM.getModule());
5632
5633 llvm::Value *VTableIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, 2);
5634
5635 std::vector<llvm::Constant*> Values(3);
5636 Values[0] = llvm::ConstantExpr::getGetElementPtr(VTableGV, &VTableIdx, 1);
5637 Values[1] = GetClassName(ID->getIdentifier());
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005638 Values[2] = GetClassGlobal(ClassName);
Daniel Dunbare588b992009-03-01 04:46:24 +00005639 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.EHTypeTy, Values);
5640
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005641 if (Entry) {
5642 Entry->setInitializer(Init);
5643 } else {
5644 Entry = new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5645 llvm::GlobalValue::WeakAnyLinkage,
5646 Init,
5647 (std::string("OBJC_EHTYPE_$_") +
5648 ID->getIdentifier()->getName()),
5649 &CGM.getModule());
5650 }
5651
Daniel Dunbar04d40782009-04-14 06:00:08 +00005652 if (CGM.getLangOptions().getVisibilityMode() == LangOptions::Hidden)
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005653 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005654 Entry->setAlignment(8);
5655
5656 if (ForDefinition) {
5657 Entry->setSection("__DATA,__objc_const");
5658 Entry->setLinkage(llvm::GlobalValue::ExternalLinkage);
5659 } else {
5660 Entry->setSection("__DATA,__datacoal_nt,coalesced");
5661 }
Daniel Dunbare588b992009-03-01 04:46:24 +00005662
5663 return Entry;
5664}
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005665
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00005666/* *** */
5667
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00005668CodeGen::CGObjCRuntime *
5669CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00005670 return new CGObjCMac(CGM);
5671}
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005672
5673CodeGen::CGObjCRuntime *
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00005674CodeGen::CreateMacNonFragileABIObjCRuntime(CodeGen::CodeGenModule &CGM) {
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00005675 return new CGObjCNonFragileABIMac(CGM);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005676}