blob: 3bc1365e49bbd8997ae827bc964793ca5152501b [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 Jahanian5de14dc2009-01-28 22:18:42 +0000462 /// EmitPropertyList - Emit the given property list. The return
463 /// value has type PropertyListPtrTy.
464 llvm::Constant *EmitPropertyList(const std::string &Name,
465 const Decl *Container,
466 const ObjCContainerDecl *OCD,
467 const ObjCCommonTypesHelper &ObjCTypes);
468
Fariborz Jahanianda320092009-01-29 19:24:30 +0000469 /// GetProtocolRef - Return a reference to the internal protocol
470 /// description, creating an empty one if it has not been
471 /// defined. The return value has type ProtocolPtrTy.
472 llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +0000473
474 /// GetIvarBaseOffset - returns ivars byte offset.
475 uint64_t GetIvarBaseOffset(const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +0000476 const FieldDecl *Field);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000477
Chris Lattnercd0ee142009-03-31 08:33:16 +0000478 /// GetFieldBaseOffset - return's field byte offset.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000479 uint64_t GetFieldBaseOffset(const ObjCInterfaceDecl *OI,
480 const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +0000481 const FieldDecl *Field);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000482
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000483 /// CreateMetadataVar - Create a global variable with internal
484 /// linkage for use by the Objective-C runtime.
485 ///
486 /// This is a convenience wrapper which not only creates the
487 /// variable, but also sets the section and alignment and adds the
488 /// global to the UsedGlobals list.
Daniel Dunbar35bd7632009-03-09 20:50:13 +0000489 ///
490 /// \param Name - The variable name.
491 /// \param Init - The variable initializer; this is also used to
492 /// define the type of the variable.
493 /// \param Section - The section the variable should go into, or 0.
494 /// \param Align - The alignment for the variable, or 0.
495 /// \param AddToUsed - Whether the variable should be added to
Daniel Dunbarc1583062009-04-14 17:42:51 +0000496 /// "llvm.used".
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000497 llvm::GlobalVariable *CreateMetadataVar(const std::string &Name,
498 llvm::Constant *Init,
499 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +0000500 unsigned Align,
501 bool AddToUsed);
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000502
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +0000503 /// GetNamedIvarList - Return the list of ivars in the interface
504 /// itself (not including super classes and not including unnamed
505 /// bitfields).
506 ///
507 /// For the non-fragile ABI, this also includes synthesized property
508 /// ivars.
509 void GetNamedIvarList(const ObjCInterfaceDecl *OID,
510 llvm::SmallVector<ObjCIvarDecl*, 16> &Res) const;
511
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000512public:
513 CGObjCCommonMac(CodeGen::CodeGenModule &cgm) : CGM(cgm)
514 { }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000515
Steve Naroff33fdb732009-03-31 16:53:37 +0000516 virtual llvm::Constant *GenerateConstantString(const ObjCStringLiteral *SL);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000517
518 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
519 const ObjCContainerDecl *CD=0);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000520
521 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
522
523 /// GetOrEmitProtocol - Get the protocol object for the given
524 /// declaration, emitting it if necessary. The return value has type
525 /// ProtocolPtrTy.
526 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD)=0;
527
528 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
529 /// object for the given declaration, emitting it if needed. These
530 /// forward references will be filled in with empty bodies if no
531 /// definition is seen. The return value has type ProtocolPtrTy.
532 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD)=0;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000533};
534
535class CGObjCMac : public CGObjCCommonMac {
536private:
537 ObjCTypesHelper ObjCTypes;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000538 /// EmitImageInfo - Emit the image info marker used to encode some module
539 /// level information.
540 void EmitImageInfo();
541
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000542 /// EmitModuleInfo - Another marker encoding module level
543 /// information.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000544 void EmitModuleInfo();
545
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000546 /// EmitModuleSymols - Emit module symbols, the list of defined
547 /// classes and categories. The result has type SymtabPtrTy.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000548 llvm::Constant *EmitModuleSymbols();
549
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000550 /// FinishModule - Write out global data structures at the end of
551 /// processing a translation unit.
552 void FinishModule();
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000553
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000554 /// EmitClassExtension - Generate the class extension structure used
555 /// to store the weak ivar layout and properties. The return value
556 /// has type ClassExtensionPtrTy.
557 llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID);
558
559 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
560 /// for the given class.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000561 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000562 const ObjCInterfaceDecl *ID);
563
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000564 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000565 QualType ResultType,
566 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000567 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000568 QualType Arg0Ty,
569 bool IsSuper,
570 const CallArgList &CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000571
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000572 /// EmitIvarList - Emit the ivar list for the given
573 /// implementation. If ForClass is true the list of class ivars
574 /// (i.e. metaclass ivars) is emitted, otherwise the list of
575 /// interface ivars will be emitted. The return value has type
576 /// IvarListPtrTy.
577 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +0000578 bool ForClass);
579
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000580 /// EmitMetaClass - Emit a forward reference to the class structure
581 /// for the metaclass of the given interface. The return value has
582 /// type ClassPtrTy.
583 llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
584
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000585 /// EmitMetaClass - Emit a class structure for the metaclass of the
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000586 /// given implementation. The return value has type ClassPtrTy.
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000587 llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
588 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000589 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000590 const ConstantVector &Methods);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000591
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000592 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000593
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000594 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000595
596 /// EmitMethodList - Emit the method list for the given
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000597 /// implementation. The return value has type MethodListPtrTy.
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000598 llvm::Constant *EmitMethodList(const std::string &Name,
599 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000600 const ConstantVector &Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000601
602 /// EmitMethodDescList - Emit a method description list for a list of
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000603 /// method declarations.
604 /// - TypeName: The name for the type containing the methods.
605 /// - IsProtocol: True iff these methods are for a protocol.
606 /// - ClassMethds: True iff these are class methods.
607 /// - Required: When true, only "required" methods are
608 /// listed. Similarly, when false only "optional" methods are
609 /// listed. For classes this should always be true.
610 /// - begin, end: The method list to output.
611 ///
612 /// The return value has type MethodDescriptionListPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000613 llvm::Constant *EmitMethodDescList(const std::string &Name,
614 const char *Section,
615 const ConstantVector &Methods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000616
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000617 /// GetOrEmitProtocol - Get the protocol object for the given
618 /// declaration, emitting it if necessary. The return value has type
619 /// ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +0000620 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000621
622 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
623 /// object for the given declaration, emitting it if needed. These
624 /// forward references will be filled in with empty bodies if no
625 /// definition is seen. The return value has type ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +0000626 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000627
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000628 /// EmitProtocolExtension - Generate the protocol extension
629 /// structure used to store optional instance and class methods, and
630 /// protocol properties. The return value has type
631 /// ProtocolExtensionPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000632 llvm::Constant *
633 EmitProtocolExtension(const ObjCProtocolDecl *PD,
634 const ConstantVector &OptInstanceMethods,
635 const ConstantVector &OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000636
637 /// EmitProtocolList - Generate the list of referenced
638 /// protocols. The return value has type ProtocolListPtrTy.
Daniel Dunbardbc933702008-08-21 21:57:41 +0000639 llvm::Constant *EmitProtocolList(const std::string &Name,
640 ObjCProtocolDecl::protocol_iterator begin,
641 ObjCProtocolDecl::protocol_iterator end);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000642
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000643 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
644 /// for the given selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000645 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000646
Fariborz Jahanianda320092009-01-29 19:24:30 +0000647 public:
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000648 CGObjCMac(CodeGen::CodeGenModule &cgm);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000649
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000650 virtual llvm::Function *ModuleInitFunction();
651
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000652 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000653 QualType ResultType,
654 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000655 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000656 bool IsClassMessage,
657 const CallArgList &CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000658
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000659 virtual CodeGen::RValue
660 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000661 QualType ResultType,
662 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000663 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000664 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000665 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000666 bool IsClassMessage,
667 const CallArgList &CallArgs);
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000668
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000669 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000670 const ObjCInterfaceDecl *ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000671
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000672 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000673
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000674 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000675
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000676 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000677
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000678 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000679 const ObjCProtocolDecl *PD);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000680
Chris Lattner74391b42009-03-22 21:03:39 +0000681 virtual llvm::Constant *GetPropertyGetFunction();
682 virtual llvm::Constant *GetPropertySetFunction();
683 virtual llvm::Constant *EnumerationMutationFunction();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000684
Fariborz Jahanianbd71be42008-11-21 00:49:24 +0000685 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
686 const Stmt &S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000687 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
688 const ObjCAtThrowStmt &S);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000689 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +0000690 llvm::Value *AddrWeakObj);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000691 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
692 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000693 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
694 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian7eda8362008-11-20 19:23:36 +0000695 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
696 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000697 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
698 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian0bb20362009-02-02 20:02:29 +0000699
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000700 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
701 QualType ObjectTy,
702 llvm::Value *BaseValue,
703 const ObjCIvarDecl *Ivar,
704 const FieldDecl *Field,
705 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000706 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
707 ObjCInterfaceDecl *Interface,
708 const ObjCIvarDecl *Ivar);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000709};
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000710
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000711class CGObjCNonFragileABIMac : public CGObjCCommonMac {
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000712private:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000713 ObjCNonFragileABITypesHelper ObjCTypes;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000714 llvm::GlobalVariable* ObjCEmptyCacheVar;
715 llvm::GlobalVariable* ObjCEmptyVtableVar;
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000716
Daniel Dunbar11394522009-04-18 08:51:00 +0000717 /// SuperClassReferences - uniqued super class references.
718 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> SuperClassReferences;
719
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000720 /// MetaClassReferences - uniqued meta class references.
721 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> MetaClassReferences;
Daniel Dunbare588b992009-03-01 04:46:24 +0000722
723 /// EHTypeReferences - uniqued class ehtype references.
724 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> EHTypeReferences;
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000725
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000726 /// FinishNonFragileABIModule - Write out global data structures at the end of
727 /// processing a translation unit.
728 void FinishNonFragileABIModule();
Daniel Dunbar8158a2f2009-04-08 04:21:03 +0000729
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000730 llvm::GlobalVariable * BuildClassRoTInitializer(unsigned flags,
731 unsigned InstanceStart,
732 unsigned InstanceSize,
733 const ObjCImplementationDecl *ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +0000734 llvm::GlobalVariable * BuildClassMetaData(std::string &ClassName,
735 llvm::Constant *IsAGV,
736 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +0000737 llvm::Constant *ClassRoGV,
738 bool HiddenVisibility);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000739
740 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
741
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +0000742 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
743
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000744 /// EmitMethodList - Emit the method list for the given
745 /// implementation. The return value has type MethodListnfABITy.
746 llvm::Constant *EmitMethodList(const std::string &Name,
747 const char *Section,
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +0000748 const ConstantVector &Methods);
749 /// EmitIvarList - Emit the ivar list for the given
750 /// implementation. If ForClass is true the list of class ivars
751 /// (i.e. metaclass ivars) is emitted, otherwise the list of
752 /// interface ivars will be emitted. The return value has type
753 /// IvarListnfABIPtrTy.
754 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000755
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000756 llvm::Constant *EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +0000757 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +0000758 unsigned long int offset);
759
Fariborz Jahanianda320092009-01-29 19:24:30 +0000760 /// GetOrEmitProtocol - Get the protocol object for the given
761 /// declaration, emitting it if necessary. The return value has type
762 /// ProtocolPtrTy.
763 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
764
765 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
766 /// object for the given declaration, emitting it if needed. These
767 /// forward references will be filled in with empty bodies if no
768 /// definition is seen. The return value has type ProtocolPtrTy.
769 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
770
771 /// EmitProtocolList - Generate the list of referenced
772 /// protocols. The return value has type ProtocolListPtrTy.
773 llvm::Constant *EmitProtocolList(const std::string &Name,
774 ObjCProtocolDecl::protocol_iterator begin,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000775 ObjCProtocolDecl::protocol_iterator end);
776
777 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
778 QualType ResultType,
779 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000780 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000781 QualType Arg0Ty,
782 bool IsSuper,
783 const CallArgList &CallArgs);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +0000784
785 /// GetClassGlobal - Return the global variable for the Objective-C
786 /// class of the given name.
Fariborz Jahanian0f902942009-04-14 18:41:56 +0000787 llvm::GlobalVariable *GetClassGlobal(const std::string &Name);
788
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000789 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
Daniel Dunbar11394522009-04-18 08:51:00 +0000790 /// for the given class reference.
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000791 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar11394522009-04-18 08:51:00 +0000792 const ObjCInterfaceDecl *ID);
793
794 /// EmitSuperClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
795 /// for the given super class reference.
796 llvm::Value *EmitSuperClassRef(CGBuilderTy &Builder,
797 const ObjCInterfaceDecl *ID);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000798
799 /// EmitMetaClassRef - Return a Value * of the address of _class_t
800 /// meta-data
801 llvm::Value *EmitMetaClassRef(CGBuilderTy &Builder,
802 const ObjCInterfaceDecl *ID);
803
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000804 /// ObjCIvarOffsetVariable - Returns the ivar offset variable for
805 /// the given ivar.
806 ///
Daniel Dunbar5e88bea2009-04-19 00:31:15 +0000807 llvm::GlobalVariable * ObjCIvarOffsetVariable(
Fariborz Jahanian01a0c362009-02-12 18:51:23 +0000808 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000809 const ObjCIvarDecl *Ivar);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000810
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +0000811 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
812 /// for the given selector.
813 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbare588b992009-03-01 04:46:24 +0000814
Daniel Dunbar8158a2f2009-04-08 04:21:03 +0000815 /// GetInterfaceEHType - Get the cached ehtype for the given Objective-C
Daniel Dunbare588b992009-03-01 04:46:24 +0000816 /// interface. The return value has type EHTypePtrTy.
Daniel Dunbar8158a2f2009-04-08 04:21:03 +0000817 llvm::Value *GetInterfaceEHType(const ObjCInterfaceDecl *ID,
818 bool ForDefinition);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +0000819
820 const char *getMetaclassSymbolPrefix() const {
821 return "OBJC_METACLASS_$_";
822 }
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000823
Daniel Dunbar6ab187a2009-04-07 05:48:37 +0000824 const char *getClassSymbolPrefix() const {
825 return "OBJC_CLASS_$_";
826 }
827
Daniel Dunbarb02532a2009-04-19 23:41:48 +0000828 void GetClassSizeInfo(const ObjCInterfaceDecl *OID,
829 uint32_t &InstanceStart,
830 uint32_t &InstanceSize);
831
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000832public:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000833 CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000834 // FIXME. All stubs for now!
835 virtual llvm::Function *ModuleInitFunction();
836
837 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
838 QualType ResultType,
839 Selector Sel,
840 llvm::Value *Receiver,
841 bool IsClassMessage,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000842 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000843
844 virtual CodeGen::RValue
845 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
846 QualType ResultType,
847 Selector Sel,
848 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000849 bool isCategoryImpl,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000850 llvm::Value *Receiver,
851 bool IsClassMessage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000852 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000853
854 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000855 const ObjCInterfaceDecl *ID);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000856
857 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel)
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +0000858 { return EmitSelector(Builder, Sel); }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000859
Fariborz Jahanianeb062d92009-01-26 18:32:24 +0000860 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000861
862 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000863 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +0000864 const ObjCProtocolDecl *PD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000865
Chris Lattner74391b42009-03-22 21:03:39 +0000866 virtual llvm::Constant *GetPropertyGetFunction() {
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000867 return ObjCTypes.GetPropertyFn;
868 }
Chris Lattner74391b42009-03-22 21:03:39 +0000869 virtual llvm::Constant *GetPropertySetFunction() {
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000870 return ObjCTypes.SetPropertyFn;
871 }
Chris Lattner74391b42009-03-22 21:03:39 +0000872 virtual llvm::Constant *EnumerationMutationFunction() {
Daniel Dunbar28ed0842009-02-16 18:48:45 +0000873 return ObjCTypes.EnumerationMutationFn;
874 }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000875
876 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000877 const Stmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000878 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000879 const ObjCAtThrowStmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000880 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000881 llvm::Value *AddrWeakObj);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000882 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000883 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000884 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000885 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000886 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000887 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000888 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000889 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000890 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
891 QualType ObjectTy,
892 llvm::Value *BaseValue,
893 const ObjCIvarDecl *Ivar,
894 const FieldDecl *Field,
895 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000896 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
897 ObjCInterfaceDecl *Interface,
898 const ObjCIvarDecl *Ivar);
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000899};
900
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000901} // end anonymous namespace
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000902
903/* *** Helper Functions *** */
904
905/// getConstantGEP() - Help routine to construct simple GEPs.
906static llvm::Constant *getConstantGEP(llvm::Constant *C,
907 unsigned idx0,
908 unsigned idx1) {
909 llvm::Value *Idxs[] = {
910 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx0),
911 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx1)
912 };
913 return llvm::ConstantExpr::getGetElementPtr(C, Idxs, 2);
914}
915
Daniel Dunbar8158a2f2009-04-08 04:21:03 +0000916/// hasObjCExceptionAttribute - Return true if this class or any super
917/// class has the __objc_exception__ attribute.
918static bool hasObjCExceptionAttribute(const ObjCInterfaceDecl *OID) {
Daniel Dunbarb11fa0d2009-04-13 21:08:27 +0000919 if (OID->hasAttr<ObjCExceptionAttr>())
Daniel Dunbar8158a2f2009-04-08 04:21:03 +0000920 return true;
921 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
922 return hasObjCExceptionAttribute(Super);
923 return false;
924}
925
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000926/* *** CGObjCMac Public Interface *** */
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000927
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000928CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm),
929 ObjCTypes(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000930{
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000931 ObjCABI = 1;
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000932 EmitImageInfo();
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000933}
934
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000935/// GetClass - Return a reference to the class for the given interface
936/// decl.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000937llvm::Value *CGObjCMac::GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000938 const ObjCInterfaceDecl *ID) {
939 return EmitClassRef(Builder, ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000940}
941
942/// GetSelector - Return the pointer to the unique'd string for this selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000943llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000944 return EmitSelector(Builder, Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000945}
946
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000947/// Generate a constant CFString object.
948/*
949 struct __builtin_CFString {
950 const int *isa; // point to __CFConstantStringClassReference
951 int flags;
952 const char *str;
953 long length;
954 };
955*/
956
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000957llvm::Constant *CGObjCCommonMac::GenerateConstantString(
Steve Naroff33fdb732009-03-31 16:53:37 +0000958 const ObjCStringLiteral *SL) {
Steve Naroff8d4141f2009-04-01 13:55:36 +0000959 return CGM.GetAddrOfConstantCFString(SL->getString());
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000960}
961
962/// Generates a message send where the super is the receiver. This is
963/// a message send to self with special delivery semantics indicating
964/// which class's method should be called.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000965CodeGen::RValue
966CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000967 QualType ResultType,
968 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000969 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000970 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000971 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000972 bool IsClassMessage,
Daniel Dunbar46f45b92008-09-09 01:06:48 +0000973 const CodeGen::CallArgList &CallArgs) {
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000974 // Create and init a super structure; this is a (receiver, class)
975 // pair we will pass to objc_msgSendSuper.
976 llvm::Value *ObjCSuper =
977 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
978 llvm::Value *ReceiverAsObject =
979 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
980 CGF.Builder.CreateStore(ReceiverAsObject,
981 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000982
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000983 // If this is a class message the metaclass is passed as the target.
984 llvm::Value *Target;
985 if (IsClassMessage) {
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000986 if (isCategoryImpl) {
987 // Message sent to 'super' in a class method defined in a category
988 // implementation requires an odd treatment.
989 // If we are in a class method, we must retrieve the
990 // _metaclass_ for the current class, pointed at by
991 // the class's "isa" pointer. The following assumes that
992 // isa" is the first ivar in a class (which it must be).
993 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
994 Target = CGF.Builder.CreateStructGEP(Target, 0);
995 Target = CGF.Builder.CreateLoad(Target);
996 }
997 else {
998 llvm::Value *MetaClassPtr = EmitMetaClassRef(Class);
999 llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1);
1000 llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr);
1001 Target = Super;
1002 }
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001003 } else {
1004 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
1005 }
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001006 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
1007 // and ObjCTypes types.
1008 const llvm::Type *ClassTy =
1009 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001010 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001011 CGF.Builder.CreateStore(Target,
1012 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
1013
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001014 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001015 ObjCSuper, ObjCTypes.SuperPtrCTy,
1016 true, CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001017}
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001018
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001019/// Generate code for a message send expression.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +00001020CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001021 QualType ResultType,
1022 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001023 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001024 bool IsClassMessage,
1025 const CallArgList &CallArgs) {
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001026 llvm::Value *Arg0 =
1027 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy, "tmp");
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001028 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001029 Arg0, CGF.getContext().getObjCIdType(),
1030 false, CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001031}
1032
1033CodeGen::RValue CGObjCMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001034 QualType ResultType,
1035 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001036 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001037 QualType Arg0Ty,
1038 bool IsSuper,
1039 const CallArgList &CallArgs) {
1040 CallArgList ActualArgs;
Daniel Dunbar46f45b92008-09-09 01:06:48 +00001041 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
1042 ActualArgs.push_back(std::make_pair(RValue::get(EmitSelector(CGF.Builder,
1043 Sel)),
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001044 CGF.getContext().getObjCSelType()));
1045 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001046
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001047 CodeGenTypes &Types = CGM.getTypes();
1048 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs);
1049 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo, false);
Daniel Dunbar5669e572008-10-17 03:24:53 +00001050
1051 llvm::Constant *Fn;
Daniel Dunbar88b53962009-02-02 22:03:45 +00001052 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Daniel Dunbar5669e572008-10-17 03:24:53 +00001053 Fn = ObjCTypes.getSendStretFn(IsSuper);
1054 } else if (ResultType->isFloatingType()) {
1055 // FIXME: Sadly, this is wrong. This actually depends on the
1056 // architecture. This happens to be right for x86-32 though.
1057 Fn = ObjCTypes.getSendFpretFn(IsSuper);
1058 } else {
1059 Fn = ObjCTypes.getSendFn(IsSuper);
1060 }
Daniel Dunbar62d5c1b2008-09-10 07:00:50 +00001061 Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy));
Daniel Dunbar88b53962009-02-02 22:03:45 +00001062 return CGF.EmitCall(FnInfo, Fn, ActualArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001063}
1064
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001065llvm::Value *CGObjCMac::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001066 const ObjCProtocolDecl *PD) {
Daniel Dunbarc67876d2008-09-04 04:33:15 +00001067 // FIXME: I don't understand why gcc generates this, or where it is
1068 // resolved. Investigate. Its also wasteful to look this up over and
1069 // over.
1070 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1071
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001072 return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
1073 ObjCTypes.ExternalProtocolPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001074}
1075
Fariborz Jahanianda320092009-01-29 19:24:30 +00001076void CGObjCCommonMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001077 // FIXME: We shouldn't need this, the protocol decl should contain
1078 // enough information to tell us whether this was a declaration or a
1079 // definition.
1080 DefinedProtocols.insert(PD->getIdentifier());
1081
1082 // If we have generated a forward reference to this protocol, emit
1083 // it now. Otherwise do nothing, the protocol objects are lazily
1084 // emitted.
1085 if (Protocols.count(PD->getIdentifier()))
1086 GetOrEmitProtocol(PD);
1087}
1088
Fariborz Jahanianda320092009-01-29 19:24:30 +00001089llvm::Constant *CGObjCCommonMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001090 if (DefinedProtocols.count(PD->getIdentifier()))
1091 return GetOrEmitProtocol(PD);
1092 return GetOrEmitProtocolRef(PD);
1093}
1094
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001095/*
1096 // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions
1097 struct _objc_protocol {
1098 struct _objc_protocol_extension *isa;
1099 char *protocol_name;
1100 struct _objc_protocol_list *protocol_list;
1101 struct _objc__method_prototype_list *instance_methods;
1102 struct _objc__method_prototype_list *class_methods
1103 };
1104
1105 See EmitProtocolExtension().
1106*/
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001107llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
1108 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1109
1110 // Early exit if a defining object has already been generated.
1111 if (Entry && Entry->hasInitializer())
1112 return Entry;
1113
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001114 // FIXME: I don't understand why gcc generates this, or where it is
1115 // resolved. Investigate. Its also wasteful to look this up over and
1116 // over.
1117 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1118
Chris Lattner8ec03f52008-11-24 03:54:41 +00001119 const char *ProtocolName = PD->getNameAsCString();
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001120
1121 // Construct method lists.
1122 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1123 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregor6ab35242009-04-09 21:40:53 +00001124 for (ObjCProtocolDecl::instmeth_iterator
1125 i = PD->instmeth_begin(CGM.getContext()),
1126 e = PD->instmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001127 ObjCMethodDecl *MD = *i;
1128 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1129 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1130 OptInstanceMethods.push_back(C);
1131 } else {
1132 InstanceMethods.push_back(C);
1133 }
1134 }
1135
Douglas Gregor6ab35242009-04-09 21:40:53 +00001136 for (ObjCProtocolDecl::classmeth_iterator
1137 i = PD->classmeth_begin(CGM.getContext()),
1138 e = PD->classmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001139 ObjCMethodDecl *MD = *i;
1140 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1141 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1142 OptClassMethods.push_back(C);
1143 } else {
1144 ClassMethods.push_back(C);
1145 }
1146 }
1147
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001148 std::vector<llvm::Constant*> Values(5);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001149 Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001150 Values[1] = GetClassName(PD->getIdentifier());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001151 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001152 EmitProtocolList("\01L_OBJC_PROTOCOL_REFS_" + PD->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001153 PD->protocol_begin(),
1154 PD->protocol_end());
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001155 Values[3] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001156 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_"
1157 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001158 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1159 InstanceMethods);
1160 Values[4] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001161 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_"
1162 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001163 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1164 ClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001165 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
1166 Values);
1167
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001168 if (Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001169 // Already created, fix the linkage and update the initializer.
1170 Entry->setLinkage(llvm::GlobalValue::InternalLinkage);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001171 Entry->setInitializer(Init);
1172 } else {
1173 Entry =
1174 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
1175 llvm::GlobalValue::InternalLinkage,
1176 Init,
1177 std::string("\01L_OBJC_PROTOCOL_")+ProtocolName,
1178 &CGM.getModule());
1179 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001180 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001181 UsedGlobals.push_back(Entry);
1182 // FIXME: Is this necessary? Why only for protocol?
1183 Entry->setAlignment(4);
1184 }
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001185
1186 return Entry;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001187}
1188
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001189llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001190 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1191
1192 if (!Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001193 // We use the initializer as a marker of whether this is a forward
1194 // reference or not. At module finalization we add the empty
1195 // contents for protocols which were referenced but never defined.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001196 Entry =
1197 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001198 llvm::GlobalValue::ExternalLinkage,
1199 0,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001200 "\01L_OBJC_PROTOCOL_" + PD->getNameAsString(),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001201 &CGM.getModule());
1202 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001203 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001204 UsedGlobals.push_back(Entry);
1205 // FIXME: Is this necessary? Why only for protocol?
1206 Entry->setAlignment(4);
1207 }
1208
1209 return Entry;
1210}
1211
1212/*
1213 struct _objc_protocol_extension {
1214 uint32_t size;
1215 struct objc_method_description_list *optional_instance_methods;
1216 struct objc_method_description_list *optional_class_methods;
1217 struct objc_property_list *instance_properties;
1218 };
1219*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001220llvm::Constant *
1221CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
1222 const ConstantVector &OptInstanceMethods,
1223 const ConstantVector &OptClassMethods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001224 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001225 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolExtensionTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001226 std::vector<llvm::Constant*> Values(4);
1227 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001228 Values[1] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001229 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_"
1230 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001231 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1232 OptInstanceMethods);
1233 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001234 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_"
1235 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001236 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1237 OptClassMethods);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001238 Values[3] = EmitPropertyList("\01L_OBJC_$_PROP_PROTO_LIST_" +
1239 PD->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001240 0, PD, ObjCTypes);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001241
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001242 // Return null if no extension bits are used.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001243 if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
1244 Values[3]->isNullValue())
1245 return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
1246
1247 llvm::Constant *Init =
1248 llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001249
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001250 // No special section, but goes in llvm.used
1251 return CreateMetadataVar("\01L_OBJC_PROTOCOLEXT_" + PD->getNameAsString(),
1252 Init,
1253 0, 0, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001254}
1255
1256/*
1257 struct objc_protocol_list {
1258 struct objc_protocol_list *next;
1259 long count;
1260 Protocol *list[];
1261 };
1262*/
Daniel Dunbardbc933702008-08-21 21:57:41 +00001263llvm::Constant *
1264CGObjCMac::EmitProtocolList(const std::string &Name,
1265 ObjCProtocolDecl::protocol_iterator begin,
1266 ObjCProtocolDecl::protocol_iterator end) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001267 std::vector<llvm::Constant*> ProtocolRefs;
1268
Daniel Dunbardbc933702008-08-21 21:57:41 +00001269 for (; begin != end; ++begin)
1270 ProtocolRefs.push_back(GetProtocolRef(*begin));
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001271
1272 // Just return null for empty protocol lists
1273 if (ProtocolRefs.empty())
1274 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1275
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001276 // This list is null terminated.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001277 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
1278
1279 std::vector<llvm::Constant*> Values(3);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001280 // This field is only used by the runtime.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001281 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1282 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
1283 Values[2] =
1284 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
1285 ProtocolRefs.size()),
1286 ProtocolRefs);
1287
1288 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1289 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001290 CreateMetadataVar(Name, Init, "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001291 4, false);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001292 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
1293}
1294
1295/*
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001296 struct _objc_property {
1297 const char * const name;
1298 const char * const attributes;
1299 };
1300
1301 struct _objc_property_list {
1302 uint32_t entsize; // sizeof (struct _objc_property)
1303 uint32_t prop_count;
1304 struct _objc_property[prop_count];
1305 };
1306*/
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001307llvm::Constant *CGObjCCommonMac::EmitPropertyList(const std::string &Name,
1308 const Decl *Container,
1309 const ObjCContainerDecl *OCD,
1310 const ObjCCommonTypesHelper &ObjCTypes) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001311 std::vector<llvm::Constant*> Properties, Prop(2);
Douglas Gregor6ab35242009-04-09 21:40:53 +00001312 for (ObjCContainerDecl::prop_iterator I = OCD->prop_begin(CGM.getContext()),
1313 E = OCD->prop_end(CGM.getContext()); I != E; ++I) {
Steve Naroff93983f82009-01-11 12:47:58 +00001314 const ObjCPropertyDecl *PD = *I;
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001315 Prop[0] = GetPropertyName(PD->getIdentifier());
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00001316 Prop[1] = GetPropertyTypeString(PD, Container);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001317 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
1318 Prop));
1319 }
1320
1321 // Return null for empty list.
1322 if (Properties.empty())
1323 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1324
1325 unsigned PropertySize =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001326 CGM.getTargetData().getTypePaddedSize(ObjCTypes.PropertyTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001327 std::vector<llvm::Constant*> Values(3);
1328 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
1329 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
1330 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
1331 Properties.size());
1332 Values[2] = llvm::ConstantArray::get(AT, Properties);
1333 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1334
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001335 llvm::GlobalVariable *GV =
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001336 CreateMetadataVar(Name, Init,
1337 (ObjCABI == 2) ? "__DATA, __objc_const" :
1338 "__OBJC,__property,regular,no_dead_strip",
1339 (ObjCABI == 2) ? 8 : 4,
1340 true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001341 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.PropertyListPtrTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001342}
1343
1344/*
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001345 struct objc_method_description_list {
1346 int count;
1347 struct objc_method_description list[];
1348 };
1349*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001350llvm::Constant *
1351CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
1352 std::vector<llvm::Constant*> Desc(2);
1353 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1354 ObjCTypes.SelectorPtrTy);
1355 Desc[1] = GetMethodVarType(MD);
1356 return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
1357 Desc);
1358}
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001359
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001360llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name,
1361 const char *Section,
1362 const ConstantVector &Methods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001363 // Return null for empty list.
1364 if (Methods.empty())
1365 return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
1366
1367 std::vector<llvm::Constant*> Values(2);
1368 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1369 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
1370 Methods.size());
1371 Values[1] = llvm::ConstantArray::get(AT, Methods);
1372 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1373
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001374 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001375 return llvm::ConstantExpr::getBitCast(GV,
1376 ObjCTypes.MethodDescriptionListPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001377}
1378
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001379/*
1380 struct _objc_category {
1381 char *category_name;
1382 char *class_name;
1383 struct _objc_method_list *instance_methods;
1384 struct _objc_method_list *class_methods;
1385 struct _objc_protocol_list *protocols;
1386 uint32_t size; // <rdar://4585769>
1387 struct _objc_property_list *instance_properties;
1388 };
1389 */
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001390void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001391 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.CategoryTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001392
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001393 // FIXME: This is poor design, the OCD should have a pointer to the
1394 // category decl. Additionally, note that Category can be null for
1395 // the @implementation w/o an @interface case. Sema should just
1396 // create one for us as it does for @implementation so everyone else
1397 // can live life under a clear blue sky.
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001398 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001399 const ObjCCategoryDecl *Category =
1400 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001401 std::string ExtName(Interface->getNameAsString() + "_" +
1402 OCD->getNameAsString());
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001403
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001404 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1405 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
1406 e = OCD->instmeth_end(); i != e; ++i) {
1407 // Instance methods should always be defined.
1408 InstanceMethods.push_back(GetMethodConstant(*i));
1409 }
1410 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
1411 e = OCD->classmeth_end(); i != e; ++i) {
1412 // Class methods should always be defined.
1413 ClassMethods.push_back(GetMethodConstant(*i));
1414 }
1415
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001416 std::vector<llvm::Constant*> Values(7);
1417 Values[0] = GetClassName(OCD->getIdentifier());
1418 Values[1] = GetClassName(Interface->getIdentifier());
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001419 Values[2] =
1420 EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") +
1421 ExtName,
1422 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001423 InstanceMethods);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001424 Values[3] =
1425 EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName,
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001426 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001427 ClassMethods);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001428 if (Category) {
1429 Values[4] =
1430 EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName,
1431 Category->protocol_begin(),
1432 Category->protocol_end());
1433 } else {
1434 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1435 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001436 Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001437
1438 // If there is no category @interface then there can be no properties.
1439 if (Category) {
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001440 Values[6] = EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001441 OCD, Category, ObjCTypes);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001442 } else {
1443 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1444 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001445
1446 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
1447 Values);
1448
1449 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001450 CreateMetadataVar(std::string("\01L_OBJC_CATEGORY_")+ExtName, Init,
1451 "__OBJC,__category,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001452 4, true);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001453 DefinedCategories.push_back(GV);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001454}
1455
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001456// FIXME: Get from somewhere?
1457enum ClassFlags {
1458 eClassFlags_Factory = 0x00001,
1459 eClassFlags_Meta = 0x00002,
1460 // <rdr://5142207>
1461 eClassFlags_HasCXXStructors = 0x02000,
1462 eClassFlags_Hidden = 0x20000,
1463 eClassFlags_ABI2_Hidden = 0x00010,
1464 eClassFlags_ABI2_HasCXXStructors = 0x00004 // <rdr://4923634>
1465};
1466
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001467/*
1468 struct _objc_class {
1469 Class isa;
1470 Class super_class;
1471 const char *name;
1472 long version;
1473 long info;
1474 long instance_size;
1475 struct _objc_ivar_list *ivars;
1476 struct _objc_method_list *methods;
1477 struct _objc_cache *cache;
1478 struct _objc_protocol_list *protocols;
1479 // Objective-C 1.0 extensions (<rdr://4585769>)
1480 const char *ivar_layout;
1481 struct _objc_class_ext *ext;
1482 };
1483
1484 See EmitClassExtension();
1485 */
1486void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001487 DefinedSymbols.insert(ID->getIdentifier());
1488
Chris Lattner8ec03f52008-11-24 03:54:41 +00001489 std::string ClassName = ID->getNameAsString();
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001490 // FIXME: Gross
1491 ObjCInterfaceDecl *Interface =
1492 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001493 llvm::Constant *Protocols =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001494 EmitProtocolList("\01L_OBJC_CLASS_PROTOCOLS_" + ID->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001495 Interface->protocol_begin(),
1496 Interface->protocol_end());
Chris Lattnerb7b58b12009-04-19 06:02:28 +00001497 const llvm::Type *InterfaceTy;
1498 if (Interface->isForwardDecl())
1499 InterfaceTy = llvm::StructType::get(NULL, NULL);
1500 else
1501 InterfaceTy =
Chris Lattner03d9f342009-04-01 06:23:52 +00001502 CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(Interface));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001503 unsigned Flags = eClassFlags_Factory;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001504 unsigned Size = CGM.getTargetData().getTypePaddedSize(InterfaceTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001505
1506 // FIXME: Set CXX-structors flag.
Daniel Dunbar04d40782009-04-14 06:00:08 +00001507 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001508 Flags |= eClassFlags_Hidden;
1509
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001510 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1511 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
1512 e = ID->instmeth_end(); i != e; ++i) {
1513 // Instance methods should always be defined.
1514 InstanceMethods.push_back(GetMethodConstant(*i));
1515 }
1516 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
1517 e = ID->classmeth_end(); i != e; ++i) {
1518 // Class methods should always be defined.
1519 ClassMethods.push_back(GetMethodConstant(*i));
1520 }
1521
1522 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
1523 e = ID->propimpl_end(); i != e; ++i) {
1524 ObjCPropertyImplDecl *PID = *i;
1525
1526 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1527 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1528
1529 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
1530 if (llvm::Constant *C = GetMethodConstant(MD))
1531 InstanceMethods.push_back(C);
1532 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
1533 if (llvm::Constant *C = GetMethodConstant(MD))
1534 InstanceMethods.push_back(C);
1535 }
1536 }
1537
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001538 std::vector<llvm::Constant*> Values(12);
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001539 Values[ 0] = EmitMetaClass(ID, Protocols, InterfaceTy, ClassMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001540 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001541 // Record a reference to the super class.
1542 LazySymbols.insert(Super->getIdentifier());
1543
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001544 Values[ 1] =
1545 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1546 ObjCTypes.ClassPtrTy);
1547 } else {
1548 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1549 }
1550 Values[ 2] = GetClassName(ID->getIdentifier());
1551 // Version is always 0.
1552 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1553 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1554 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001555 Values[ 6] = EmitIvarList(ID, false);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001556 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001557 EmitMethodList("\01L_OBJC_INSTANCE_METHODS_" + ID->getNameAsString(),
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001558 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001559 InstanceMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001560 // cache is always NULL.
1561 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1562 Values[ 9] = Protocols;
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001563 // FIXME: Set ivar_layout
Fariborz Jahanian667423a2009-03-25 22:36:49 +00001564 // Values[10] = BuildIvarLayout(ID, true);
1565 Values[10] = GetIvarLayoutName(0, ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001566 Values[11] = EmitClassExtension(ID);
1567 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1568 Values);
1569
1570 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001571 CreateMetadataVar(std::string("\01L_OBJC_CLASS_")+ClassName, Init,
1572 "__OBJC,__class,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001573 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001574 DefinedClasses.push_back(GV);
1575}
1576
1577llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
1578 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001579 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001580 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001581 unsigned Flags = eClassFlags_Meta;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001582 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001583
Daniel Dunbar04d40782009-04-14 06:00:08 +00001584 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001585 Flags |= eClassFlags_Hidden;
1586
1587 std::vector<llvm::Constant*> Values(12);
1588 // The isa for the metaclass is the root of the hierarchy.
1589 const ObjCInterfaceDecl *Root = ID->getClassInterface();
1590 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
1591 Root = Super;
1592 Values[ 0] =
1593 llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
1594 ObjCTypes.ClassPtrTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001595 // The super class for the metaclass is emitted as the name of the
1596 // super class. The runtime fixes this up to point to the
1597 // *metaclass* for the super class.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001598 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
1599 Values[ 1] =
1600 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1601 ObjCTypes.ClassPtrTy);
1602 } else {
1603 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1604 }
1605 Values[ 2] = GetClassName(ID->getIdentifier());
1606 // Version is always 0.
1607 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1608 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1609 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001610 Values[ 6] = EmitIvarList(ID, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001611 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001612 EmitMethodList("\01L_OBJC_CLASS_METHODS_" + ID->getNameAsString(),
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001613 "__OBJC,__cls_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001614 Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001615 // cache is always NULL.
1616 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1617 Values[ 9] = Protocols;
1618 // ivar_layout for metaclass is always NULL.
1619 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1620 // The class extension is always unused for metaclasses.
1621 Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1622 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1623 Values);
1624
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001625 std::string Name("\01L_OBJC_METACLASS_");
Chris Lattner8ec03f52008-11-24 03:54:41 +00001626 Name += ID->getNameAsCString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001627
1628 // Check for a forward reference.
1629 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
1630 if (GV) {
1631 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1632 "Forward metaclass reference has incorrect type.");
1633 GV->setLinkage(llvm::GlobalValue::InternalLinkage);
1634 GV->setInitializer(Init);
1635 } else {
1636 GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1637 llvm::GlobalValue::InternalLinkage,
1638 Init, Name,
1639 &CGM.getModule());
1640 }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001641 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001642 GV->setAlignment(4);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001643 UsedGlobals.push_back(GV);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001644
1645 return GV;
1646}
1647
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001648llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001649 std::string Name = "\01L_OBJC_METACLASS_" + ID->getNameAsString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001650
1651 // FIXME: Should we look these up somewhere other than the
1652 // module. Its a bit silly since we only generate these while
1653 // processing an implementation, so exactly one pointer would work
1654 // if know when we entered/exitted an implementation block.
1655
1656 // Check for an existing forward reference.
Fariborz Jahanianb0d27942009-01-07 20:11:22 +00001657 // Previously, metaclass with internal linkage may have been defined.
1658 // pass 'true' as 2nd argument so it is returned.
1659 if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true)) {
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001660 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1661 "Forward metaclass reference has incorrect type.");
1662 return GV;
1663 } else {
1664 // Generate as an external reference to keep a consistent
1665 // module. This will be patched up when we emit the metaclass.
1666 return new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1667 llvm::GlobalValue::ExternalLinkage,
1668 0,
1669 Name,
1670 &CGM.getModule());
1671 }
1672}
1673
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001674/*
1675 struct objc_class_ext {
1676 uint32_t size;
1677 const char *weak_ivar_layout;
1678 struct _objc_property_list *properties;
1679 };
1680*/
1681llvm::Constant *
1682CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
1683 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001684 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassExtensionTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001685
1686 std::vector<llvm::Constant*> Values(3);
1687 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001688 // FIXME: Output weak_ivar_layout string.
Fariborz Jahanian667423a2009-03-25 22:36:49 +00001689 // Values[1] = BuildIvarLayout(ID, false);
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00001690 Values[1] = GetIvarLayoutName(0, ObjCTypes);
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001691 Values[2] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001692 ID, ID->getClassInterface(), ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001693
1694 // Return null if no extension bits are used.
1695 if (Values[1]->isNullValue() && Values[2]->isNullValue())
1696 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1697
1698 llvm::Constant *Init =
1699 llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001700 return CreateMetadataVar("\01L_OBJC_CLASSEXT_" + ID->getNameAsString(),
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001701 Init, "__OBJC,__class_ext,regular,no_dead_strip",
1702 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001703}
1704
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001705/// getInterfaceDeclForIvar - Get the interface declaration node where
1706/// this ivar is declared in.
1707/// FIXME. Ideally, this info should be in the ivar node. But currently
1708/// it is not and prevailing wisdom is that ASTs should not have more
1709/// info than is absolutely needed, even though this info reflects the
1710/// source language.
1711///
1712static const ObjCInterfaceDecl *getInterfaceDeclForIvar(
1713 const ObjCInterfaceDecl *OI,
Douglas Gregor6ab35242009-04-09 21:40:53 +00001714 const ObjCIvarDecl *IVD,
1715 ASTContext &Context) {
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001716 if (!OI)
1717 return 0;
1718 assert(isa<ObjCInterfaceDecl>(OI) && "OI is not an interface");
1719 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1720 E = OI->ivar_end(); I != E; ++I)
1721 if ((*I)->getIdentifier() == IVD->getIdentifier())
1722 return OI;
Fariborz Jahanian5a4b4532009-03-31 17:00:52 +00001723 // look into properties.
Douglas Gregor6ab35242009-04-09 21:40:53 +00001724 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(Context),
1725 E = OI->prop_end(Context); I != E; ++I) {
Fariborz Jahanian5a4b4532009-03-31 17:00:52 +00001726 ObjCPropertyDecl *PDecl = (*I);
1727 if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl())
1728 if (IV->getIdentifier() == IVD->getIdentifier())
1729 return OI;
1730 }
Douglas Gregor6ab35242009-04-09 21:40:53 +00001731 return getInterfaceDeclForIvar(OI->getSuperClass(), IVD, Context);
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001732}
1733
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001734/*
1735 struct objc_ivar {
1736 char *ivar_name;
1737 char *ivar_type;
1738 int ivar_offset;
1739 };
1740
1741 struct objc_ivar_list {
1742 int ivar_count;
1743 struct objc_ivar list[count];
1744 };
1745 */
1746llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001747 bool ForClass) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001748 std::vector<llvm::Constant*> Ivars, Ivar(3);
1749
1750 // When emitting the root class GCC emits ivar entries for the
1751 // actual class structure. It is not clear if we need to follow this
1752 // behavior; for now lets try and get away with not doing it. If so,
1753 // the cleanest solution would be to make up an ObjCInterfaceDecl
1754 // for the class.
1755 if (ForClass)
1756 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001757
1758 ObjCInterfaceDecl *OID =
1759 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00001760 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001761
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00001762 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
1763 GetNamedIvarList(OID, OIvars);
1764
1765 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
1766 ObjCIvarDecl *IVD = OIvars[i];
1767 const FieldDecl *Field = OID->lookupFieldDeclForIvar(CGM.getContext(), IVD);
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00001768 Ivar[0] = GetMethodVarName(Field->getIdentifier());
Devang Patel7794bb82009-03-04 18:21:39 +00001769 Ivar[1] = GetMethodVarType(Field);
Daniel Dunbar6c1aac82009-04-20 20:18:54 +00001770 Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy,
1771 GetIvarBaseOffset(Layout, Field));
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001772 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001773 }
1774
1775 // Return null for empty list.
1776 if (Ivars.empty())
1777 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
1778
1779 std::vector<llvm::Constant*> Values(2);
1780 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
1781 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
1782 Ivars.size());
1783 Values[1] = llvm::ConstantArray::get(AT, Ivars);
1784 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1785
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001786 llvm::GlobalVariable *GV;
1787 if (ForClass)
1788 GV = CreateMetadataVar("\01L_OBJC_CLASS_VARIABLES_" + ID->getNameAsString(),
Daniel Dunbar58a29122009-03-09 22:18:41 +00001789 Init, "__OBJC,__class_vars,regular,no_dead_strip",
1790 4, true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001791 else
1792 GV = CreateMetadataVar("\01L_OBJC_INSTANCE_VARIABLES_"
1793 + ID->getNameAsString(),
1794 Init, "__OBJC,__instance_vars,regular,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001795 4, true);
1796 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.IvarListPtrTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001797}
1798
1799/*
1800 struct objc_method {
1801 SEL method_name;
1802 char *method_types;
1803 void *method;
1804 };
1805
1806 struct objc_method_list {
1807 struct objc_method_list *obsolete;
1808 int count;
1809 struct objc_method methods_list[count];
1810 };
1811*/
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001812
1813/// GetMethodConstant - Return a struct objc_method constant for the
1814/// given method if it has been defined. The result is null if the
1815/// method has not been defined. The return value has type MethodPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001816llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001817 // FIXME: Use DenseMap::lookup
1818 llvm::Function *Fn = MethodDefinitions[MD];
1819 if (!Fn)
1820 return 0;
1821
1822 std::vector<llvm::Constant*> Method(3);
1823 Method[0] =
1824 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1825 ObjCTypes.SelectorPtrTy);
1826 Method[1] = GetMethodVarType(MD);
1827 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
1828 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
1829}
1830
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001831llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name,
1832 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001833 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001834 // Return null for empty list.
1835 if (Methods.empty())
1836 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
1837
1838 std::vector<llvm::Constant*> Values(3);
1839 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1840 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1841 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
1842 Methods.size());
1843 Values[2] = llvm::ConstantArray::get(AT, Methods);
1844 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1845
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001846 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001847 return llvm::ConstantExpr::getBitCast(GV,
1848 ObjCTypes.MethodListPtrTy);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001849}
1850
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001851llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD,
Daniel Dunbarbb36d332009-02-02 21:43:58 +00001852 const ObjCContainerDecl *CD) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001853 std::string Name;
Fariborz Jahanian679a5022009-01-10 21:06:09 +00001854 GetNameForMethod(OMD, CD, Name);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001855
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001856 CodeGenTypes &Types = CGM.getTypes();
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001857 const llvm::FunctionType *MethodTy =
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001858 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001859 llvm::Function *Method =
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001860 llvm::Function::Create(MethodTy,
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001861 llvm::GlobalValue::InternalLinkage,
1862 Name,
1863 &CGM.getModule());
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001864 MethodDefinitions.insert(std::make_pair(OMD, Method));
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001865
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001866 return Method;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001867}
1868
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00001869uint64_t CGObjCCommonMac::GetIvarBaseOffset(const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +00001870 const FieldDecl *Field) {
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00001871 if (!Field->isBitField())
Daniel Dunbar48fa0642009-04-19 02:03:42 +00001872 return Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(Field));
1873
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00001874 // FIXME. Must be a better way of getting a bitfield base offset.
Daniel Dunbar48fa0642009-04-19 02:03:42 +00001875 CodeGenTypes::BitFieldInfo BFI = CGM.getTypes().getBitFieldInfo(Field);
1876 // FIXME: The "field no" for bitfields is something completely
1877 // different; it is the offset in multiples of the base type size!
1878 uint64_t Offset = CGM.getTypes().getLLVMFieldNo(Field);
1879 const llvm::Type *Ty =
1880 CGM.getTypes().ConvertTypeForMemRecursive(Field->getType());
1881 Offset *= CGM.getTypes().getTargetData().getTypePaddedSizeInBits(Ty);
1882 return (Offset + BFI.Begin) / 8;
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00001883}
1884
Daniel Dunbar48fa0642009-04-19 02:03:42 +00001885/// GetFieldBaseOffset - return the field's byte offset.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00001886uint64_t CGObjCCommonMac::GetFieldBaseOffset(const ObjCInterfaceDecl *OI,
1887 const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +00001888 const FieldDecl *Field) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00001889 const ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
Chris Lattnercd0ee142009-03-31 08:33:16 +00001890 const FieldDecl *FD = OI->lookupFieldDeclForIvar(CGM.getContext(), Ivar);
1891 return GetIvarBaseOffset(Layout, FD);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00001892}
1893
Daniel Dunbarfd65d372009-03-09 20:09:19 +00001894llvm::GlobalVariable *
1895CGObjCCommonMac::CreateMetadataVar(const std::string &Name,
1896 llvm::Constant *Init,
1897 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +00001898 unsigned Align,
1899 bool AddToUsed) {
Daniel Dunbarfd65d372009-03-09 20:09:19 +00001900 const llvm::Type *Ty = Init->getType();
1901 llvm::GlobalVariable *GV =
1902 new llvm::GlobalVariable(Ty, false,
1903 llvm::GlobalValue::InternalLinkage,
1904 Init,
1905 Name,
1906 &CGM.getModule());
1907 if (Section)
1908 GV->setSection(Section);
Daniel Dunbar35bd7632009-03-09 20:50:13 +00001909 if (Align)
1910 GV->setAlignment(Align);
1911 if (AddToUsed)
Daniel Dunbarfd65d372009-03-09 20:09:19 +00001912 UsedGlobals.push_back(GV);
1913 return GV;
1914}
1915
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001916llvm::Function *CGObjCMac::ModuleInitFunction() {
Daniel Dunbarf77ac862008-08-11 21:35:06 +00001917 // Abuse this interface function as a place to finalize.
1918 FinishModule();
1919
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001920 return NULL;
1921}
1922
Chris Lattner74391b42009-03-22 21:03:39 +00001923llvm::Constant *CGObjCMac::GetPropertyGetFunction() {
Daniel Dunbar49f66022008-09-24 03:38:44 +00001924 return ObjCTypes.GetPropertyFn;
1925}
1926
Chris Lattner74391b42009-03-22 21:03:39 +00001927llvm::Constant *CGObjCMac::GetPropertySetFunction() {
Daniel Dunbar49f66022008-09-24 03:38:44 +00001928 return ObjCTypes.SetPropertyFn;
1929}
1930
Chris Lattner74391b42009-03-22 21:03:39 +00001931llvm::Constant *CGObjCMac::EnumerationMutationFunction() {
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001932 return ObjCTypes.EnumerationMutationFn;
1933}
1934
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001935/*
1936
1937Objective-C setjmp-longjmp (sjlj) Exception Handling
1938--
1939
1940The basic framework for a @try-catch-finally is as follows:
1941{
1942 objc_exception_data d;
1943 id _rethrow = null;
Anders Carlsson190d00e2009-02-07 21:26:04 +00001944 bool _call_try_exit = true;
1945
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001946 objc_exception_try_enter(&d);
1947 if (!setjmp(d.jmp_buf)) {
1948 ... try body ...
1949 } else {
1950 // exception path
1951 id _caught = objc_exception_extract(&d);
1952
1953 // enter new try scope for handlers
1954 if (!setjmp(d.jmp_buf)) {
1955 ... match exception and execute catch blocks ...
1956
1957 // fell off end, rethrow.
1958 _rethrow = _caught;
Daniel Dunbar898d5082008-09-30 01:06:03 +00001959 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001960 } else {
1961 // exception in catch block
1962 _rethrow = objc_exception_extract(&d);
Anders Carlsson190d00e2009-02-07 21:26:04 +00001963 _call_try_exit = false;
1964 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001965 }
1966 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00001967 ... jump-through-finally to finally_end ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001968
1969finally:
Anders Carlsson190d00e2009-02-07 21:26:04 +00001970 if (_call_try_exit)
1971 objc_exception_try_exit(&d);
1972
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001973 ... finally block ....
Daniel Dunbar898d5082008-09-30 01:06:03 +00001974 ... dispatch to finally destination ...
1975
1976finally_rethrow:
1977 objc_exception_throw(_rethrow);
1978
1979finally_end:
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001980}
1981
1982This framework differs slightly from the one gcc uses, in that gcc
Daniel Dunbar898d5082008-09-30 01:06:03 +00001983uses _rethrow to determine if objc_exception_try_exit should be called
1984and if the object should be rethrown. This breaks in the face of
1985throwing nil and introduces unnecessary branches.
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001986
1987We specialize this framework for a few particular circumstances:
1988
1989 - If there are no catch blocks, then we avoid emitting the second
1990 exception handling context.
1991
1992 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
1993 e)) we avoid emitting the code to rethrow an uncaught exception.
1994
1995 - FIXME: If there is no @finally block we can do a few more
1996 simplifications.
1997
1998Rethrows and Jumps-Through-Finally
1999--
2000
2001Support for implicit rethrows and jumping through the finally block is
2002handled by storing the current exception-handling context in
2003ObjCEHStack.
2004
Daniel Dunbar898d5082008-09-30 01:06:03 +00002005In order to implement proper @finally semantics, we support one basic
2006mechanism for jumping through the finally block to an arbitrary
2007destination. Constructs which generate exits from a @try or @catch
2008block use this mechanism to implement the proper semantics by chaining
2009jumps, as necessary.
2010
2011This mechanism works like the one used for indirect goto: we
2012arbitrarily assign an ID to each destination and store the ID for the
2013destination in a variable prior to entering the finally block. At the
2014end of the finally block we simply create a switch to the proper
2015destination.
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002016
2017Code gen for @synchronized(expr) stmt;
2018Effectively generating code for:
2019objc_sync_enter(expr);
2020@try stmt @finally { objc_sync_exit(expr); }
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002021*/
2022
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002023void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
2024 const Stmt &S) {
2025 bool isTry = isa<ObjCAtTryStmt>(S);
Daniel Dunbar898d5082008-09-30 01:06:03 +00002026 // Create various blocks we refer to for handling @finally.
Daniel Dunbar55e87422008-11-11 02:29:29 +00002027 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002028 llvm::BasicBlock *FinallyExit = CGF.createBasicBlock("finally.exit");
Daniel Dunbar55e87422008-11-11 02:29:29 +00002029 llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
2030 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
2031 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
Daniel Dunbar1c566672009-02-24 01:43:46 +00002032
2033 // For @synchronized, call objc_sync_enter(sync.expr). The
2034 // evaluation of the expression must occur before we enter the
2035 // @synchronized. We can safely avoid a temp here because jumps into
2036 // @synchronized are illegal & this will dominate uses.
2037 llvm::Value *SyncArg = 0;
2038 if (!isTry) {
2039 SyncArg =
2040 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
2041 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00002042 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar1c566672009-02-24 01:43:46 +00002043 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00002044
2045 // Push an EH context entry, used for handling rethrows and jumps
2046 // through finally.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002047 CGF.PushCleanupBlock(FinallyBlock);
2048
Anders Carlsson273558f2009-02-07 21:37:21 +00002049 CGF.ObjCEHValueStack.push_back(0);
2050
Daniel Dunbar898d5082008-09-30 01:06:03 +00002051 // Allocate memory for the exception data and rethrow pointer.
Anders Carlsson80f25672008-09-09 17:59:25 +00002052 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
2053 "exceptiondata.ptr");
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002054 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
2055 "_rethrow");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002056 llvm::Value *CallTryExitPtr = CGF.CreateTempAlloca(llvm::Type::Int1Ty,
2057 "_call_try_exit");
2058 CGF.Builder.CreateStore(llvm::ConstantInt::getTrue(), CallTryExitPtr);
2059
Anders Carlsson80f25672008-09-09 17:59:25 +00002060 // Enter a new try block and call setjmp.
2061 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
2062 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
2063 "jmpbufarray");
2064 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
2065 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
2066 JmpBufPtr, "result");
Daniel Dunbar898d5082008-09-30 01:06:03 +00002067
Daniel Dunbar55e87422008-11-11 02:29:29 +00002068 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
2069 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002070 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002071 TryHandler, TryBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002072
2073 // Emit the @try block.
2074 CGF.EmitBlock(TryBlock);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002075 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
2076 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002077 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002078
2079 // Emit the "exception in @try" block.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002080 CGF.EmitBlock(TryHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002081
2082 // Retrieve the exception object. We may emit multiple blocks but
2083 // nothing can cross this so the value is already in SSA form.
2084 llvm::Value *Caught = CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
2085 ExceptionData,
2086 "caught");
Anders Carlsson273558f2009-02-07 21:37:21 +00002087 CGF.ObjCEHValueStack.back() = Caught;
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002088 if (!isTry)
2089 {
2090 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002091 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002092 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002093 }
2094 else if (const ObjCAtCatchStmt* CatchStmt =
2095 cast<ObjCAtTryStmt>(S).getCatchStmts())
2096 {
Daniel Dunbar55e40722008-09-27 07:03:52 +00002097 // Enter a new exception try block (in case a @catch block throws
2098 // an exception).
Anders Carlsson80f25672008-09-09 17:59:25 +00002099 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002100
Anders Carlsson80f25672008-09-09 17:59:25 +00002101 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
2102 JmpBufPtr, "result");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002103 llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw");
Anders Carlsson80f25672008-09-09 17:59:25 +00002104
Daniel Dunbar55e87422008-11-11 02:29:29 +00002105 llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch");
2106 llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler");
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002107 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002108
2109 CGF.EmitBlock(CatchBlock);
2110
Daniel Dunbar55e40722008-09-27 07:03:52 +00002111 // Handle catch list. As a special case we check if everything is
2112 // matched and avoid generating code for falling off the end if
2113 // so.
2114 bool AllMatched = false;
Anders Carlsson80f25672008-09-09 17:59:25 +00002115 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbar55e87422008-11-11 02:29:29 +00002116 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch");
Anders Carlsson80f25672008-09-09 17:59:25 +00002117
Steve Naroff7ba138a2009-03-03 19:52:17 +00002118 const ParmVarDecl *CatchParam = CatchStmt->getCatchParamDecl();
Daniel Dunbar129271a2008-09-27 07:36:24 +00002119 const PointerType *PT = 0;
2120
Anders Carlsson80f25672008-09-09 17:59:25 +00002121 // catch(...) always matches.
Daniel Dunbar55e40722008-09-27 07:03:52 +00002122 if (!CatchParam) {
2123 AllMatched = true;
2124 } else {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002125 PT = CatchParam->getType()->getAsPointerType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002126
Daniel Dunbar97f61d12008-09-27 22:21:14 +00002127 // catch(id e) always matches.
2128 // FIXME: For the time being we also match id<X>; this should
2129 // be rejected by Sema instead.
Steve Naroff389bf462009-02-12 17:52:19 +00002130 if ((PT && CGF.getContext().isObjCIdStructType(PT->getPointeeType())) ||
Steve Naroff7ba138a2009-03-03 19:52:17 +00002131 CatchParam->getType()->isObjCQualifiedIdType())
Daniel Dunbar55e40722008-09-27 07:03:52 +00002132 AllMatched = true;
Anders Carlsson80f25672008-09-09 17:59:25 +00002133 }
2134
Daniel Dunbar55e40722008-09-27 07:03:52 +00002135 if (AllMatched) {
Anders Carlssondde0a942008-09-11 09:15:33 +00002136 if (CatchParam) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002137 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002138 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002139 CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002140 }
Anders Carlsson1452f552008-09-11 08:21:54 +00002141
Anders Carlssondde0a942008-09-11 09:15:33 +00002142 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002143 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002144 break;
2145 }
2146
Daniel Dunbar129271a2008-09-27 07:36:24 +00002147 assert(PT && "Unexpected non-pointer type in @catch");
2148 QualType T = PT->getPointeeType();
Anders Carlsson4b7ff6e2008-09-11 06:35:14 +00002149 const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002150 assert(ObjCType && "Catch parameter must have Objective-C type!");
2151
2152 // Check if the @catch block matches the exception object.
2153 llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl());
2154
Anders Carlsson80f25672008-09-09 17:59:25 +00002155 llvm::Value *Match = CGF.Builder.CreateCall2(ObjCTypes.ExceptionMatchFn,
2156 Class, Caught, "match");
Anders Carlsson80f25672008-09-09 17:59:25 +00002157
Daniel Dunbar55e87422008-11-11 02:29:29 +00002158 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched");
Anders Carlsson80f25672008-09-09 17:59:25 +00002159
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002160 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002161 MatchedBlock, NextCatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002162
2163 // Emit the @catch block.
2164 CGF.EmitBlock(MatchedBlock);
Steve Naroff7ba138a2009-03-03 19:52:17 +00002165 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002166 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002167
2168 llvm::Value *Tmp =
Steve Naroff7ba138a2009-03-03 19:52:17 +00002169 CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(CatchParam->getType()),
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002170 "tmp");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002171 CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002172
2173 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002174 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002175
2176 CGF.EmitBlock(NextCatchBlock);
2177 }
2178
Daniel Dunbar55e40722008-09-27 07:03:52 +00002179 if (!AllMatched) {
2180 // None of the handlers caught the exception, so store it to be
2181 // rethrown at the end of the @finally block.
2182 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002183 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002184 }
2185
2186 // Emit the exception handler for the @catch blocks.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002187 CGF.EmitBlock(CatchHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002188 CGF.Builder.CreateStore(CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
2189 ExceptionData),
2190 RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002191 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002192 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002193 } else {
Anders Carlsson80f25672008-09-09 17:59:25 +00002194 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002195 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002196 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Anders Carlsson80f25672008-09-09 17:59:25 +00002197 }
2198
Daniel Dunbar898d5082008-09-30 01:06:03 +00002199 // Pop the exception-handling stack entry. It is important to do
2200 // this now, because the code in the @finally block is not in this
2201 // context.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002202 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
2203
Anders Carlsson273558f2009-02-07 21:37:21 +00002204 CGF.ObjCEHValueStack.pop_back();
2205
Anders Carlsson80f25672008-09-09 17:59:25 +00002206 // Emit the @finally block.
2207 CGF.EmitBlock(FinallyBlock);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002208 llvm::Value* CallTryExit = CGF.Builder.CreateLoad(CallTryExitPtr, "tmp");
2209
2210 CGF.Builder.CreateCondBr(CallTryExit, FinallyExit, FinallyNoExit);
2211
2212 CGF.EmitBlock(FinallyExit);
Anders Carlsson80f25672008-09-09 17:59:25 +00002213 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryExitFn, ExceptionData);
Daniel Dunbar129271a2008-09-27 07:36:24 +00002214
2215 CGF.EmitBlock(FinallyNoExit);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002216 if (isTry) {
2217 if (const ObjCAtFinallyStmt* FinallyStmt =
2218 cast<ObjCAtTryStmt>(S).getFinallyStmt())
2219 CGF.EmitStmt(FinallyStmt->getFinallyBody());
Daniel Dunbar1c566672009-02-24 01:43:46 +00002220 } else {
2221 // Emit objc_sync_exit(expr); as finally's sole statement for
2222 // @synchronized.
2223 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, SyncArg);
Fariborz Jahanianf2878e52008-11-21 19:21:53 +00002224 }
Anders Carlsson80f25672008-09-09 17:59:25 +00002225
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002226 // Emit the switch block
2227 if (Info.SwitchBlock)
2228 CGF.EmitBlock(Info.SwitchBlock);
2229 if (Info.EndBlock)
2230 CGF.EmitBlock(Info.EndBlock);
2231
Daniel Dunbar898d5082008-09-30 01:06:03 +00002232 CGF.EmitBlock(FinallyRethrow);
2233 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn,
2234 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002235 CGF.Builder.CreateUnreachable();
Daniel Dunbar898d5082008-09-30 01:06:03 +00002236
2237 CGF.EmitBlock(FinallyEnd);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002238}
2239
2240void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar898d5082008-09-30 01:06:03 +00002241 const ObjCAtThrowStmt &S) {
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002242 llvm::Value *ExceptionAsObject;
2243
2244 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2245 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
2246 ExceptionAsObject =
2247 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
2248 } else {
Anders Carlsson273558f2009-02-07 21:37:21 +00002249 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002250 "Unexpected rethrow outside @catch block.");
Anders Carlsson273558f2009-02-07 21:37:21 +00002251 ExceptionAsObject = CGF.ObjCEHValueStack.back();
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002252 }
2253
2254 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
Anders Carlsson80f25672008-09-09 17:59:25 +00002255 CGF.Builder.CreateUnreachable();
Daniel Dunbara448fb22008-11-11 23:11:34 +00002256
2257 // Clear the insertion point to indicate we are in unreachable code.
2258 CGF.Builder.ClearInsertionPoint();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002259}
2260
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002261/// EmitObjCWeakRead - Code gen for loading value of a __weak
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002262/// object: objc_read_weak (id *src)
2263///
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002264llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002265 llvm::Value *AddrWeakObj)
2266{
Eli Friedman8339b352009-03-07 03:57:15 +00002267 const llvm::Type* DestTy =
2268 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002269 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002270 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002271 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00002272 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002273 return read_weak;
2274}
2275
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002276/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
2277/// objc_assign_weak (id src, id *dst)
2278///
2279void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
2280 llvm::Value *src, llvm::Value *dst)
2281{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002282 const llvm::Type * SrcTy = src->getType();
2283 if (!isa<llvm::PointerType>(SrcTy)) {
2284 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2285 assert(Size <= 8 && "does not support size > 8");
2286 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2287 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002288 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2289 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002290 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2291 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattner96508e12009-04-17 22:12:36 +00002292 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002293 src, dst, "weakassign");
2294 return;
2295}
2296
Fariborz Jahanian58626502008-11-19 00:59:10 +00002297/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
2298/// objc_assign_global (id src, id *dst)
2299///
2300void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
2301 llvm::Value *src, llvm::Value *dst)
2302{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002303 const llvm::Type * SrcTy = src->getType();
2304 if (!isa<llvm::PointerType>(SrcTy)) {
2305 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2306 assert(Size <= 8 && "does not support size > 8");
2307 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2308 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002309 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2310 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002311 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2312 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian58626502008-11-19 00:59:10 +00002313 CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn,
2314 src, dst, "globalassign");
2315 return;
2316}
2317
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002318/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
2319/// objc_assign_ivar (id src, id *dst)
2320///
2321void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
2322 llvm::Value *src, llvm::Value *dst)
2323{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002324 const llvm::Type * SrcTy = src->getType();
2325 if (!isa<llvm::PointerType>(SrcTy)) {
2326 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2327 assert(Size <= 8 && "does not support size > 8");
2328 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2329 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002330 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2331 }
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002332 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2333 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
2334 CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn,
2335 src, dst, "assignivar");
2336 return;
2337}
2338
Fariborz Jahanian58626502008-11-19 00:59:10 +00002339/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
2340/// objc_assign_strongCast (id src, id *dst)
2341///
2342void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
2343 llvm::Value *src, llvm::Value *dst)
2344{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002345 const llvm::Type * SrcTy = src->getType();
2346 if (!isa<llvm::PointerType>(SrcTy)) {
2347 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2348 assert(Size <= 8 && "does not support size > 8");
2349 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2350 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002351 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2352 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002353 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2354 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian58626502008-11-19 00:59:10 +00002355 CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn,
2356 src, dst, "weakassign");
2357 return;
2358}
2359
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002360/// EmitObjCValueForIvar - Code Gen for ivar reference.
2361///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002362LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
2363 QualType ObjectTy,
2364 llvm::Value *BaseValue,
2365 const ObjCIvarDecl *Ivar,
2366 const FieldDecl *Field,
2367 unsigned CVRQualifiers) {
2368 if (Ivar->isBitField())
2369 return CGF.EmitLValueForBitfield(BaseValue, const_cast<FieldDecl *>(Field),
2370 CVRQualifiers);
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002371 // TODO: Add a special case for isa (index 0)
2372 unsigned Index = CGM.getTypes().getLLVMFieldNo(Field);
2373 llvm::Value *V = CGF.Builder.CreateStructGEP(BaseValue, Index, "tmp");
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002374 LValue LV = LValue::MakeAddr(V,
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00002375 Ivar->getType().getCVRQualifiers()|CVRQualifiers,
2376 CGM.getContext().getObjCGCAttrKind(Ivar->getType()));
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002377 LValue::SetObjCIvar(LV, true);
2378 return LV;
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002379}
2380
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002381llvm::Value *CGObjCMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
2382 ObjCInterfaceDecl *Interface,
2383 const ObjCIvarDecl *Ivar) {
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002384 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(Interface);
Daniel Dunbar60952f92009-04-20 00:37:55 +00002385 const FieldDecl *Field =
2386 Interface->lookupFieldDeclForIvar(CGM.getContext(), Ivar);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00002387 uint64_t Offset = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002388 return llvm::ConstantInt::get(
2389 CGM.getTypes().ConvertType(CGM.getContext().LongTy),
2390 Offset);
2391}
2392
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002393/* *** Private Interface *** */
2394
2395/// EmitImageInfo - Emit the image info marker used to encode some module
2396/// level information.
2397///
2398/// See: <rdr://4810609&4810587&4810587>
2399/// struct IMAGE_INFO {
2400/// unsigned version;
2401/// unsigned flags;
2402/// };
2403enum ImageInfoFlags {
Daniel Dunbarc7c6dc02009-04-20 07:11:47 +00002404 eImageInfo_FixAndContinue = (1 << 0), // FIXME: Not sure what
2405 // this implies.
2406 eImageInfo_GarbageCollected = (1 << 1),
2407 eImageInfo_GCOnly = (1 << 2),
2408 eImageInfo_OptimizedByDyld = (1 << 3), // FIXME: When is this set.
2409
2410 // A flag indicating that the module has no instances of an
2411 // @synthesize of a superclass variable. <rdar://problem/6803242>
2412 eImageInfo_CorrectedSynthesize = (1 << 4)
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002413};
2414
2415void CGObjCMac::EmitImageInfo() {
2416 unsigned version = 0; // Version is unused?
2417 unsigned flags = 0;
2418
2419 // FIXME: Fix and continue?
2420 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
2421 flags |= eImageInfo_GarbageCollected;
2422 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
2423 flags |= eImageInfo_GCOnly;
Daniel Dunbarc7c6dc02009-04-20 07:11:47 +00002424
2425 // We never allow @synthesize of a superclass property.
2426 flags |= eImageInfo_CorrectedSynthesize;
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002427
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002428 // Emitted as int[2];
2429 llvm::Constant *values[2] = {
2430 llvm::ConstantInt::get(llvm::Type::Int32Ty, version),
2431 llvm::ConstantInt::get(llvm::Type::Int32Ty, flags)
2432 };
2433 llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002434
2435 const char *Section;
2436 if (ObjCABI == 1)
2437 Section = "__OBJC, __image_info,regular";
2438 else
2439 Section = "__DATA, __objc_imageinfo, regular, no_dead_strip";
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002440 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002441 CreateMetadataVar("\01L_OBJC_IMAGE_INFO",
2442 llvm::ConstantArray::get(AT, values, 2),
2443 Section,
2444 0,
2445 true);
2446 GV->setConstant(true);
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002447}
2448
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002449
2450// struct objc_module {
2451// unsigned long version;
2452// unsigned long size;
2453// const char *name;
2454// Symtab symtab;
2455// };
2456
2457// FIXME: Get from somewhere
2458static const int ModuleVersion = 7;
2459
2460void CGObjCMac::EmitModuleInfo() {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00002461 uint64_t Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ModuleTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002462
2463 std::vector<llvm::Constant*> Values(4);
2464 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
2465 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002466 // This used to be the filename, now it is unused. <rdr://4327263>
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002467 Values[2] = GetClassName(&CGM.getContext().Idents.get(""));
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002468 Values[3] = EmitModuleSymbols();
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002469 CreateMetadataVar("\01L_OBJC_MODULES",
2470 llvm::ConstantStruct::get(ObjCTypes.ModuleTy, Values),
2471 "__OBJC,__module_info,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00002472 4, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002473}
2474
2475llvm::Constant *CGObjCMac::EmitModuleSymbols() {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002476 unsigned NumClasses = DefinedClasses.size();
2477 unsigned NumCategories = DefinedCategories.size();
2478
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002479 // Return null if no symbols were defined.
2480 if (!NumClasses && !NumCategories)
2481 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
2482
2483 std::vector<llvm::Constant*> Values(5);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002484 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2485 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
2486 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
2487 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
2488
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002489 // The runtime expects exactly the list of defined classes followed
2490 // by the list of defined categories, in a single array.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002491 std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002492 for (unsigned i=0; i<NumClasses; i++)
2493 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
2494 ObjCTypes.Int8PtrTy);
2495 for (unsigned i=0; i<NumCategories; i++)
2496 Symbols[NumClasses + i] =
2497 llvm::ConstantExpr::getBitCast(DefinedCategories[i],
2498 ObjCTypes.Int8PtrTy);
2499
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002500 Values[4] =
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002501 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002502 NumClasses + NumCategories),
2503 Symbols);
2504
2505 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2506
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002507 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002508 CreateMetadataVar("\01L_OBJC_SYMBOLS", Init,
2509 "__OBJC,__symbols,regular,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002510 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002511 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
2512}
2513
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002514llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002515 const ObjCInterfaceDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002516 LazySymbols.insert(ID->getIdentifier());
2517
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002518 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
2519
2520 if (!Entry) {
2521 llvm::Constant *Casted =
2522 llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()),
2523 ObjCTypes.ClassPtrTy);
2524 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002525 CreateMetadataVar("\01L_OBJC_CLASS_REFERENCES_", Casted,
2526 "__OBJC,__cls_refs,literal_pointers,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002527 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002528 }
2529
2530 return Builder.CreateLoad(Entry, false, "tmp");
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002531}
2532
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002533llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002534 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
2535
2536 if (!Entry) {
2537 llvm::Constant *Casted =
2538 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
2539 ObjCTypes.SelectorPtrTy);
2540 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002541 CreateMetadataVar("\01L_OBJC_SELECTOR_REFERENCES_", Casted,
2542 "__OBJC,__message_refs,literal_pointers,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002543 4, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002544 }
2545
2546 return Builder.CreateLoad(Entry, false, "tmp");
2547}
2548
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00002549llvm::Constant *CGObjCCommonMac::GetClassName(IdentifierInfo *Ident) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002550 llvm::GlobalVariable *&Entry = ClassNames[Ident];
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002551
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002552 if (!Entry)
2553 Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
2554 llvm::ConstantArray::get(Ident->getName()),
2555 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00002556 1, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002557
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002558 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002559}
2560
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002561/// GetInterfaceDeclStructLayout - Get layout for ivars of given
2562/// interface declaration.
2563const llvm::StructLayout *CGObjCCommonMac::GetInterfaceDeclStructLayout(
2564 const ObjCInterfaceDecl *OID) const {
Daniel Dunbarb02532a2009-04-19 23:41:48 +00002565 // FIXME: When does this happen? It seems pretty bad to do this...
Daniel Dunbar6c1aac82009-04-20 20:18:54 +00002566 if (OID->isForwardDecl())
2567 return CGM.getTargetData().getStructLayout(llvm::StructType::get(NULL,
2568 NULL));
2569
2570 QualType T =
2571 CGM.getContext().getObjCInterfaceType(const_cast<ObjCInterfaceDecl*>(OID));
2572 const llvm::StructType *InterfaceTy =
2573 cast<llvm::StructType>(CGM.getTypes().ConvertType(T));
2574 return CGM.getTargetData().getStructLayout(InterfaceTy);
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002575}
2576
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00002577/// GetIvarLayoutName - Returns a unique constant for the given
2578/// ivar layout bitmap.
2579llvm::Constant *CGObjCCommonMac::GetIvarLayoutName(IdentifierInfo *Ident,
2580 const ObjCCommonTypesHelper &ObjCTypes) {
2581 return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2582}
2583
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002584void CGObjCCommonMac::BuildAggrIvarLayout(const ObjCInterfaceDecl *OI,
2585 const llvm::StructLayout *Layout,
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002586 const RecordDecl *RD,
Chris Lattnerf1690852009-03-31 08:48:01 +00002587 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002588 unsigned int BytePos, bool ForStrongLayout,
2589 int &Index, int &SkIndex, bool &HasUnion) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002590 bool IsUnion = (RD && RD->isUnion());
2591 uint64_t MaxUnionIvarSize = 0;
2592 uint64_t MaxSkippedUnionIvarSize = 0;
2593 FieldDecl *MaxField = 0;
2594 FieldDecl *MaxSkippedField = 0;
Chris Lattnerf1690852009-03-31 08:48:01 +00002595 unsigned base = 0;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002596 if (RecFields.empty())
2597 return;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002598 if (IsUnion)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002599 base = BytePos + GetFieldBaseOffset(OI, Layout, RecFields[0]);
Chris Lattnerf1690852009-03-31 08:48:01 +00002600 unsigned WordSizeInBits = CGM.getContext().Target.getPointerWidth(0);
2601 unsigned ByteSizeInBits = CGM.getContext().Target.getCharWidth();
2602
2603 llvm::SmallVector<FieldDecl*, 16> TmpRecFields;
2604
2605 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002606 FieldDecl *Field = RecFields[i];
2607 // Skip over unnamed or bitfields
2608 if (!Field->getIdentifier() || Field->isBitField())
2609 continue;
2610 QualType FQT = Field->getType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002611 if (FQT->isRecordType() || FQT->isUnionType()) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002612 if (FQT->isUnionType())
2613 HasUnion = true;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002614 else
2615 assert(FQT->isRecordType() &&
2616 "only union/record is supported for ivar layout bitmap");
2617
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002618 const RecordType *RT = FQT->getAsRecordType();
2619 const RecordDecl *RD = RT->getDecl();
Daniel Dunbarb02532a2009-04-19 23:41:48 +00002620 // FIXME - Find a more efficient way of passing records down.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002621 TmpRecFields.append(RD->field_begin(CGM.getContext()),
2622 RD->field_end(CGM.getContext()));
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002623 // FIXME - Is Layout correct?
Chris Lattnerf1690852009-03-31 08:48:01 +00002624 BuildAggrIvarLayout(OI, Layout, RD, TmpRecFields,
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002625 BytePos + GetFieldBaseOffset(OI, Layout, Field),
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002626 ForStrongLayout, Index, SkIndex,
2627 HasUnion);
Chris Lattnerf1690852009-03-31 08:48:01 +00002628 TmpRecFields.clear();
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002629 continue;
2630 }
Chris Lattnerf1690852009-03-31 08:48:01 +00002631
2632 if (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002633 const ConstantArrayType *CArray =
2634 dyn_cast_or_null<ConstantArrayType>(Array);
2635 assert(CArray && "only array with know element size is supported");
2636 FQT = CArray->getElementType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002637 while (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
2638 const ConstantArrayType *CArray =
2639 dyn_cast_or_null<ConstantArrayType>(Array);
2640 FQT = CArray->getElementType();
2641 }
2642
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002643 assert(!FQT->isUnionType() &&
2644 "layout for array of unions not supported");
2645 if (FQT->isRecordType()) {
2646 uint64_t ElCount = CArray->getSize().getZExtValue();
2647 int OldIndex = Index;
2648 int OldSkIndex = SkIndex;
2649
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002650 // FIXME - Use a common routine with the above!
2651 const RecordType *RT = FQT->getAsRecordType();
2652 const RecordDecl *RD = RT->getDecl();
2653 // FIXME - Find a more efficiant way of passing records down.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002654 TmpRecFields.append(RD->field_begin(CGM.getContext()),
2655 RD->field_end(CGM.getContext()));
Chris Lattnerf1690852009-03-31 08:48:01 +00002656
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002657 BuildAggrIvarLayout(OI, Layout, RD,
Chris Lattnerf1690852009-03-31 08:48:01 +00002658 TmpRecFields,
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002659 BytePos + GetFieldBaseOffset(OI, Layout, Field),
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002660 ForStrongLayout, Index, SkIndex,
2661 HasUnion);
Chris Lattnerf1690852009-03-31 08:48:01 +00002662 TmpRecFields.clear();
2663
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002664 // Replicate layout information for each array element. Note that
2665 // one element is already done.
2666 uint64_t ElIx = 1;
2667 for (int FirstIndex = Index, FirstSkIndex = SkIndex;
2668 ElIx < ElCount; ElIx++) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002669 uint64_t Size = CGM.getContext().getTypeSize(RT)/ByteSizeInBits;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002670 for (int i = OldIndex+1; i <= FirstIndex; ++i)
2671 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002672 GC_IVAR gcivar;
2673 gcivar.ivar_bytepos = IvarsInfo[i].ivar_bytepos + Size*ElIx;
2674 gcivar.ivar_size = IvarsInfo[i].ivar_size;
2675 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002676 }
2677
Chris Lattnerf1690852009-03-31 08:48:01 +00002678 for (int i = OldSkIndex+1; i <= FirstSkIndex; ++i) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002679 GC_IVAR skivar;
2680 skivar.ivar_bytepos = SkipIvars[i].ivar_bytepos + Size*ElIx;
2681 skivar.ivar_size = SkipIvars[i].ivar_size;
2682 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002683 }
2684 }
2685 continue;
2686 }
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002687 }
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002688 // At this point, we are done with Record/Union and array there of.
2689 // For other arrays we are down to its element type.
2690 QualType::GCAttrTypes GCAttr = QualType::GCNone;
2691 do {
2692 if (FQT.isObjCGCStrong() || FQT.isObjCGCWeak()) {
2693 GCAttr = FQT.isObjCGCStrong() ? QualType::Strong : QualType::Weak;
2694 break;
2695 }
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002696 else if (CGM.getContext().isObjCObjectPointerType(FQT)) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002697 GCAttr = QualType::Strong;
2698 break;
2699 }
2700 else if (const PointerType *PT = FQT->getAsPointerType()) {
2701 FQT = PT->getPointeeType();
2702 }
2703 else {
2704 break;
2705 }
2706 } while (true);
Chris Lattnerf1690852009-03-31 08:48:01 +00002707
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002708 if ((ForStrongLayout && GCAttr == QualType::Strong)
2709 || (!ForStrongLayout && GCAttr == QualType::Weak)) {
2710 if (IsUnion)
2711 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002712 uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType())
2713 / WordSizeInBits;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002714 if (UnionIvarSize > MaxUnionIvarSize)
2715 {
2716 MaxUnionIvarSize = UnionIvarSize;
2717 MaxField = Field;
2718 }
2719 }
2720 else
2721 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002722 GC_IVAR gcivar;
2723 gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field);
2724 gcivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) /
2725 WordSizeInBits;
2726 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002727 }
2728 }
2729 else if ((ForStrongLayout &&
2730 (GCAttr == QualType::GCNone || GCAttr == QualType::Weak))
2731 || (!ForStrongLayout && GCAttr != QualType::Weak)) {
2732 if (IsUnion)
2733 {
2734 uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType());
2735 if (UnionIvarSize > MaxSkippedUnionIvarSize)
2736 {
2737 MaxSkippedUnionIvarSize = UnionIvarSize;
2738 MaxSkippedField = Field;
2739 }
2740 }
2741 else
2742 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002743 GC_IVAR skivar;
2744 skivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field);
2745 skivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) /
2746 WordSizeInBits;
2747 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002748 }
2749 }
2750 }
Chris Lattnerf1690852009-03-31 08:48:01 +00002751 if (MaxField) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002752 GC_IVAR gcivar;
2753 gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, MaxField);
2754 gcivar.ivar_size = MaxUnionIvarSize;
2755 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002756 }
Chris Lattnerf1690852009-03-31 08:48:01 +00002757
2758 if (MaxSkippedField) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002759 GC_IVAR skivar;
2760 skivar.ivar_bytepos = BytePos +
2761 GetFieldBaseOffset(OI, Layout, MaxSkippedField);
2762 skivar.ivar_size = MaxSkippedUnionIvarSize;
2763 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002764 }
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002765}
2766
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002767static int
Chris Lattnerf1690852009-03-31 08:48:01 +00002768IvarBytePosCompare(const void *a, const void *b)
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002769{
2770 unsigned int sa = ((CGObjCCommonMac::GC_IVAR *)a)->ivar_bytepos;
2771 unsigned int sb = ((CGObjCCommonMac::GC_IVAR *)b)->ivar_bytepos;
2772
2773 if (sa < sb)
2774 return -1;
2775 if (sa > sb)
2776 return 1;
2777 return 0;
2778}
2779
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002780/// BuildIvarLayout - Builds ivar layout bitmap for the class
2781/// implementation for the __strong or __weak case.
2782/// The layout map displays which words in ivar list must be skipped
2783/// and which must be scanned by GC (see below). String is built of bytes.
2784/// Each byte is divided up in two nibbles (4-bit each). Left nibble is count
2785/// of words to skip and right nibble is count of words to scan. So, each
2786/// nibble represents up to 15 workds to skip or scan. Skipping the rest is
2787/// represented by a 0x00 byte which also ends the string.
2788/// 1. when ForStrongLayout is true, following ivars are scanned:
2789/// - id, Class
2790/// - object *
2791/// - __strong anything
2792///
2793/// 2. When ForStrongLayout is false, following ivars are scanned:
2794/// - __weak anything
2795///
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002796llvm::Constant *CGObjCCommonMac::BuildIvarLayout(
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002797 const ObjCImplementationDecl *OMD,
2798 bool ForStrongLayout) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002799 int Index = -1;
2800 int SkIndex = -1;
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002801 bool hasUnion = false;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002802 int SkipScan;
2803 unsigned int WordsToScan, WordsToSkip;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002804 const llvm::Type *PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
2805 if (CGM.getLangOptions().getGCMode() == LangOptions::NonGC)
2806 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002807
Chris Lattnerf1690852009-03-31 08:48:01 +00002808 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002809 const ObjCInterfaceDecl *OI = OMD->getClassInterface();
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002810 CGM.getContext().CollectObjCIvars(OI, RecFields);
2811 if (RecFields.empty())
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002812 return llvm::Constant::getNullValue(PtrTy);
Chris Lattnerf1690852009-03-31 08:48:01 +00002813
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002814 SkipIvars.clear();
2815 IvarsInfo.clear();
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002816
2817 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OI);
Chris Lattnerf1690852009-03-31 08:48:01 +00002818 BuildAggrIvarLayout(OI, Layout, 0, RecFields, 0, ForStrongLayout,
2819 Index, SkIndex, hasUnion);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002820 if (Index == -1)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002821 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002822
2823 // Sort on byte position in case we encounterred a union nested in
2824 // the ivar list.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002825 if (hasUnion && !IvarsInfo.empty())
2826 qsort(&IvarsInfo[0], Index+1, sizeof(GC_IVAR), IvarBytePosCompare);
2827 if (hasUnion && !SkipIvars.empty())
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002828 qsort(&SkipIvars[0], Index+1, sizeof(GC_IVAR), IvarBytePosCompare);
2829
2830 // Build the string of skip/scan nibbles
2831 SkipScan = -1;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002832 SkipScanIvars.clear();
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002833 unsigned int WordSize =
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002834 CGM.getTypes().getTargetData().getTypePaddedSize(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002835 if (IvarsInfo[0].ivar_bytepos == 0) {
2836 WordsToSkip = 0;
2837 WordsToScan = IvarsInfo[0].ivar_size;
2838 }
2839 else {
2840 WordsToSkip = IvarsInfo[0].ivar_bytepos/WordSize;
2841 WordsToScan = IvarsInfo[0].ivar_size;
2842 }
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002843 for (unsigned int i=1, Last=IvarsInfo.size(); i != Last; i++)
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002844 {
2845 unsigned int TailPrevGCObjC =
2846 IvarsInfo[i-1].ivar_bytepos + IvarsInfo[i-1].ivar_size * WordSize;
2847 if (IvarsInfo[i].ivar_bytepos == TailPrevGCObjC)
2848 {
2849 // consecutive 'scanned' object pointers.
2850 WordsToScan += IvarsInfo[i].ivar_size;
2851 }
2852 else
2853 {
2854 // Skip over 'gc'able object pointer which lay over each other.
2855 if (TailPrevGCObjC > IvarsInfo[i].ivar_bytepos)
2856 continue;
2857 // Must skip over 1 or more words. We save current skip/scan values
2858 // and start a new pair.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002859 SKIP_SCAN SkScan;
2860 SkScan.skip = WordsToSkip;
2861 SkScan.scan = WordsToScan;
2862 SkipScanIvars.push_back(SkScan); ++SkipScan;
2863
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002864 // Skip the hole.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002865 SkScan.skip = (IvarsInfo[i].ivar_bytepos - TailPrevGCObjC) / WordSize;
2866 SkScan.scan = 0;
2867 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002868 WordsToSkip = 0;
2869 WordsToScan = IvarsInfo[i].ivar_size;
2870 }
2871 }
2872 if (WordsToScan > 0)
2873 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002874 SKIP_SCAN SkScan;
2875 SkScan.skip = WordsToSkip;
2876 SkScan.scan = WordsToScan;
2877 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002878 }
2879
2880 bool BytesSkipped = false;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002881 if (!SkipIvars.empty())
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002882 {
2883 int LastByteSkipped =
2884 SkipIvars[SkIndex].ivar_bytepos + SkipIvars[SkIndex].ivar_size;
2885 int LastByteScanned =
2886 IvarsInfo[Index].ivar_bytepos + IvarsInfo[Index].ivar_size * WordSize;
2887 BytesSkipped = (LastByteSkipped > LastByteScanned);
2888 // Compute number of bytes to skip at the tail end of the last ivar scanned.
2889 if (BytesSkipped)
2890 {
2891 unsigned int TotalWords = (LastByteSkipped + (WordSize -1)) / WordSize;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002892 SKIP_SCAN SkScan;
2893 SkScan.skip = TotalWords - (LastByteScanned/WordSize);
2894 SkScan.scan = 0;
2895 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002896 }
2897 }
2898 // Mini optimization of nibbles such that an 0xM0 followed by 0x0N is produced
2899 // as 0xMN.
2900 for (int i = 0; i <= SkipScan; i++)
2901 {
2902 if ((i < SkipScan) && SkipScanIvars[i].skip && SkipScanIvars[i].scan == 0
2903 && SkipScanIvars[i+1].skip == 0 && SkipScanIvars[i+1].scan) {
2904 // 0xM0 followed by 0x0N detected.
2905 SkipScanIvars[i].scan = SkipScanIvars[i+1].scan;
2906 for (int j = i+1; j < SkipScan; j++)
2907 SkipScanIvars[j] = SkipScanIvars[j+1];
2908 --SkipScan;
2909 }
2910 }
2911
2912 // Generate the string.
2913 std::string BitMap;
2914 for (int i = 0; i <= SkipScan; i++)
2915 {
2916 unsigned char byte;
2917 unsigned int skip_small = SkipScanIvars[i].skip % 0xf;
2918 unsigned int scan_small = SkipScanIvars[i].scan % 0xf;
2919 unsigned int skip_big = SkipScanIvars[i].skip / 0xf;
2920 unsigned int scan_big = SkipScanIvars[i].scan / 0xf;
2921
2922 if (skip_small > 0 || skip_big > 0)
2923 BytesSkipped = true;
2924 // first skip big.
2925 for (unsigned int ix = 0; ix < skip_big; ix++)
2926 BitMap += (unsigned char)(0xf0);
2927
2928 // next (skip small, scan)
2929 if (skip_small)
2930 {
2931 byte = skip_small << 4;
2932 if (scan_big > 0)
2933 {
2934 byte |= 0xf;
2935 --scan_big;
2936 }
2937 else if (scan_small)
2938 {
2939 byte |= scan_small;
2940 scan_small = 0;
2941 }
2942 BitMap += byte;
2943 }
2944 // next scan big
2945 for (unsigned int ix = 0; ix < scan_big; ix++)
2946 BitMap += (unsigned char)(0x0f);
2947 // last scan small
2948 if (scan_small)
2949 {
2950 byte = scan_small;
2951 BitMap += byte;
2952 }
2953 }
2954 // null terminate string.
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002955 unsigned char zero = 0;
2956 BitMap += zero;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002957 // if ivar_layout bitmap is all 1 bits (nothing skipped) then use NULL as
2958 // final layout.
2959 if (ForStrongLayout && !BytesSkipped)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002960 return llvm::Constant::getNullValue(PtrTy);
2961 llvm::GlobalVariable * Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
2962 llvm::ConstantArray::get(BitMap.c_str()),
2963 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00002964 1, true);
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002965 // FIXME. Need a commomand-line option for this eventually.
2966 if (ForStrongLayout)
2967 printf("\nstrong ivar layout: ");
2968 else
2969 printf("\nweak ivar layout: ");
2970 const unsigned char *s = (unsigned char*)BitMap.c_str();
2971 for (unsigned i = 0; i < BitMap.size(); i++)
Fariborz Jahaniandbf15cb2009-03-26 19:10:36 +00002972 if (!(s[i] & 0xf0))
2973 printf("0x0%x%s", s[i], s[i] != 0 ? ", " : "");
2974 else
2975 printf("0x%x%s", s[i], s[i] != 0 ? ", " : "");
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002976 printf("\n");
2977
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002978 return getConstantGEP(Entry, 0, 0);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002979}
2980
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002981llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002982 llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
2983
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002984 // FIXME: Avoid std::string copying.
2985 if (!Entry)
2986 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_NAME_",
2987 llvm::ConstantArray::get(Sel.getAsString()),
2988 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00002989 1, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002990
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002991 return getConstantGEP(Entry, 0, 0);
2992}
2993
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002994// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002995llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002996 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
2997}
2998
2999// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003000llvm::Constant *CGObjCCommonMac::GetMethodVarName(const std::string &Name) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003001 return GetMethodVarName(&CGM.getContext().Idents.get(Name));
3002}
3003
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00003004llvm::Constant *CGObjCCommonMac::GetMethodVarType(const FieldDecl *Field) {
Devang Patel7794bb82009-03-04 18:21:39 +00003005 std::string TypeStr;
3006 CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
3007
3008 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003009
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003010 if (!Entry)
3011 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3012 llvm::ConstantArray::get(TypeStr),
3013 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003014 1, true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003015
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003016 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003017}
3018
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003019llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003020 std::string TypeStr;
Daniel Dunbarc45ef602008-08-26 21:51:14 +00003021 CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D),
3022 TypeStr);
Devang Patel7794bb82009-03-04 18:21:39 +00003023
3024 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
3025
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003026 if (!Entry)
3027 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3028 llvm::ConstantArray::get(TypeStr),
3029 "__TEXT,__cstring,cstring_literals",
3030 1, true);
Devang Patel7794bb82009-03-04 18:21:39 +00003031
3032 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003033}
3034
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003035// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003036llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003037 llvm::GlobalVariable *&Entry = PropertyNames[Ident];
3038
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003039 if (!Entry)
3040 Entry = CreateMetadataVar("\01L_OBJC_PROP_NAME_ATTR_",
3041 llvm::ConstantArray::get(Ident->getName()),
3042 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003043 1, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003044
3045 return getConstantGEP(Entry, 0, 0);
3046}
3047
3048// FIXME: Merge into a single cstring creation function.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003049// FIXME: This Decl should be more precise.
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003050llvm::Constant *
3051 CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
3052 const Decl *Container) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003053 std::string TypeStr;
3054 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003055 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
3056}
3057
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003058void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D,
3059 const ObjCContainerDecl *CD,
3060 std::string &NameOut) {
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00003061 NameOut = '\01';
3062 NameOut += (D->isInstanceMethod() ? '-' : '+');
Chris Lattner077bf5e2008-11-24 03:33:13 +00003063 NameOut += '[';
Fariborz Jahanian679a5022009-01-10 21:06:09 +00003064 assert (CD && "Missing container decl in GetNameForMethod");
3065 NameOut += CD->getNameAsString();
Fariborz Jahanian1e9aef32009-04-16 18:34:20 +00003066 if (const ObjCCategoryImplDecl *CID =
3067 dyn_cast<ObjCCategoryImplDecl>(D->getDeclContext())) {
3068 NameOut += '(';
3069 NameOut += CID->getNameAsString();
3070 NameOut+= ')';
3071 }
Chris Lattner077bf5e2008-11-24 03:33:13 +00003072 NameOut += ' ';
3073 NameOut += D->getSelector().getAsString();
3074 NameOut += ']';
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00003075}
3076
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003077void CGObjCMac::FinishModule() {
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003078 EmitModuleInfo();
3079
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003080 // Emit the dummy bodies for any protocols which were referenced but
3081 // never defined.
3082 for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
3083 i = Protocols.begin(), e = Protocols.end(); i != e; ++i) {
3084 if (i->second->hasInitializer())
3085 continue;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003086
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003087 std::vector<llvm::Constant*> Values(5);
3088 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
3089 Values[1] = GetClassName(i->first);
3090 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
3091 Values[3] = Values[4] =
3092 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
3093 i->second->setLinkage(llvm::GlobalValue::InternalLinkage);
3094 i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
3095 Values));
3096 }
3097
3098 std::vector<llvm::Constant*> Used;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003099 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003100 e = UsedGlobals.end(); i != e; ++i) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003101 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003102 }
3103
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003104 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003105 llvm::GlobalValue *GV =
3106 new llvm::GlobalVariable(AT, false,
3107 llvm::GlobalValue::AppendingLinkage,
3108 llvm::ConstantArray::get(AT, Used),
3109 "llvm.used",
3110 &CGM.getModule());
3111
3112 GV->setSection("llvm.metadata");
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003113
3114 // Add assembler directives to add lazy undefined symbol references
3115 // for classes which are referenced but not defined. This is
3116 // important for correct linker interaction.
3117
3118 // FIXME: Uh, this isn't particularly portable.
3119 std::stringstream s;
Anders Carlsson565c99f2008-12-10 02:21:04 +00003120
3121 if (!CGM.getModule().getModuleInlineAsm().empty())
3122 s << "\n";
3123
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003124 for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(),
3125 e = LazySymbols.end(); i != e; ++i) {
3126 s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n";
3127 }
3128 for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(),
3129 e = DefinedSymbols.end(); i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003130 s << "\t.objc_class_name_" << (*i)->getName() << "=0\n"
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003131 << "\t.globl .objc_class_name_" << (*i)->getName() << "\n";
3132 }
Anders Carlsson565c99f2008-12-10 02:21:04 +00003133
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003134 CGM.getModule().appendModuleInlineAsm(s.str());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003135}
3136
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003137CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003138 : CGObjCCommonMac(cgm),
3139 ObjCTypes(cgm)
3140{
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003141 ObjCEmptyCacheVar = ObjCEmptyVtableVar = NULL;
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003142 ObjCABI = 2;
3143}
3144
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003145/* *** */
3146
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003147ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm)
3148: CGM(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003149{
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003150 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3151 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003152
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003153 ShortTy = Types.ConvertType(Ctx.ShortTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003154 IntTy = Types.ConvertType(Ctx.IntTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003155 LongTy = Types.ConvertType(Ctx.LongTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00003156 LongLongTy = Types.ConvertType(Ctx.LongLongTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003157 Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3158
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003159 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00003160 PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003161 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003162
3163 // FIXME: It would be nice to unify this with the opaque type, so
3164 // that the IR comes out a bit cleaner.
3165 const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
3166 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003167
3168 // I'm not sure I like this. The implicit coordination is a bit
3169 // gross. We should solve this in a reasonable fashion because this
3170 // is a pretty common task (match some runtime data structure with
3171 // an LLVM data structure).
3172
3173 // FIXME: This is leaked.
3174 // FIXME: Merge with rewriter code?
3175
3176 // struct _objc_super {
3177 // id self;
3178 // Class cls;
3179 // }
3180 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3181 SourceLocation(),
3182 &Ctx.Idents.get("_objc_super"));
Douglas Gregor6ab35242009-04-09 21:40:53 +00003183 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3184 Ctx.getObjCIdType(), 0, false));
3185 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3186 Ctx.getObjCClassType(), 0, false));
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003187 RD->completeDefinition(Ctx);
3188
3189 SuperCTy = Ctx.getTagDeclType(RD);
3190 SuperPtrCTy = Ctx.getPointerType(SuperCTy);
3191
3192 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003193 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
3194
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003195 // struct _prop_t {
3196 // char *name;
3197 // char *attributes;
3198 // }
3199 PropertyTy = llvm::StructType::get(Int8PtrTy,
3200 Int8PtrTy,
3201 NULL);
3202 CGM.getModule().addTypeName("struct._prop_t",
3203 PropertyTy);
3204
3205 // struct _prop_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003206 // uint32_t entsize; // sizeof(struct _prop_t)
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003207 // uint32_t count_of_properties;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003208 // struct _prop_t prop_list[count_of_properties];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003209 // }
3210 PropertyListTy = llvm::StructType::get(IntTy,
3211 IntTy,
3212 llvm::ArrayType::get(PropertyTy, 0),
3213 NULL);
3214 CGM.getModule().addTypeName("struct._prop_list_t",
3215 PropertyListTy);
3216 // struct _prop_list_t *
3217 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
3218
3219 // struct _objc_method {
3220 // SEL _cmd;
3221 // char *method_type;
3222 // char *_imp;
3223 // }
3224 MethodTy = llvm::StructType::get(SelectorPtrTy,
3225 Int8PtrTy,
3226 Int8PtrTy,
3227 NULL);
3228 CGM.getModule().addTypeName("struct._objc_method", MethodTy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003229
3230 // struct _objc_cache *
3231 CacheTy = llvm::OpaqueType::get();
3232 CGM.getModule().addTypeName("struct._objc_cache", CacheTy);
3233 CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003234
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003235 // Property manipulation functions.
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003236
3237 QualType IdType = Ctx.getObjCIdType();
3238 QualType SelType = Ctx.getObjCSelType();
3239 llvm::SmallVector<QualType,16> Params;
3240 const llvm::FunctionType *FTy;
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003241
3242 // id objc_getProperty (id, SEL, ptrdiff_t, bool)
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003243 Params.push_back(IdType);
3244 Params.push_back(SelType);
3245 Params.push_back(Ctx.LongTy);
3246 Params.push_back(Ctx.BoolTy);
3247 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params),
3248 false);
3249 GetPropertyFn = CGM.CreateRuntimeFunction(FTy, "objc_getProperty");
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003250
3251 // void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool)
3252 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003253 Params.push_back(IdType);
3254 Params.push_back(SelType);
3255 Params.push_back(Ctx.LongTy);
3256 Params.push_back(IdType);
3257 Params.push_back(Ctx.BoolTy);
3258 Params.push_back(Ctx.BoolTy);
3259 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
3260 SetPropertyFn = CGM.CreateRuntimeFunction(FTy, "objc_setProperty");
3261
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003262 // Enumeration mutation.
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003263
3264 // void objc_enumerationMutation (id)
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003265 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003266 Params.push_back(IdType);
3267 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
3268 EnumerationMutationFn = CGM.CreateRuntimeFunction(FTy,
3269 "objc_enumerationMutation");
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003270
3271 // gc's API
3272 // id objc_read_weak (id *)
3273 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003274 Params.push_back(Ctx.getPointerType(IdType));
3275 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
3276 GcReadWeakFn = CGM.CreateRuntimeFunction(FTy, "objc_read_weak");
3277
Chris Lattner96508e12009-04-17 22:12:36 +00003278 // id objc_assign_global (id, id *)
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003279 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003280 Params.push_back(IdType);
3281 Params.push_back(Ctx.getPointerType(IdType));
3282
3283 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003284 GcAssignGlobalFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_global");
3285 GcAssignIvarFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_ivar");
3286 GcAssignStrongCastFn =
3287 CGM.CreateRuntimeFunction(FTy, "objc_assign_strongCast");
Anders Carlssonf57c5b22009-02-16 22:59:18 +00003288
3289 // void objc_exception_throw(id)
3290 Params.clear();
3291 Params.push_back(IdType);
3292
3293 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00003294 ExceptionThrowFn =
3295 CGM.CreateRuntimeFunction(FTy, "objc_exception_throw");
Daniel Dunbar1c566672009-02-24 01:43:46 +00003296
3297 // synchronized APIs
Daniel Dunbar1c566672009-02-24 01:43:46 +00003298 // void objc_sync_exit (id)
3299 Params.clear();
3300 Params.push_back(IdType);
3301
3302 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
Daniel Dunbar1c566672009-02-24 01:43:46 +00003303 SyncExitFn = CGM.CreateRuntimeFunction(FTy, "objc_sync_exit");
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003304}
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003305
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003306ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
3307 : ObjCCommonTypesHelper(cgm)
3308{
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003309 // struct _objc_method_description {
3310 // SEL name;
3311 // char *types;
3312 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003313 MethodDescriptionTy =
3314 llvm::StructType::get(SelectorPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003315 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003316 NULL);
3317 CGM.getModule().addTypeName("struct._objc_method_description",
3318 MethodDescriptionTy);
3319
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003320 // struct _objc_method_description_list {
3321 // int count;
3322 // struct _objc_method_description[1];
3323 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003324 MethodDescriptionListTy =
3325 llvm::StructType::get(IntTy,
3326 llvm::ArrayType::get(MethodDescriptionTy, 0),
3327 NULL);
3328 CGM.getModule().addTypeName("struct._objc_method_description_list",
3329 MethodDescriptionListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003330
3331 // struct _objc_method_description_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003332 MethodDescriptionListPtrTy =
3333 llvm::PointerType::getUnqual(MethodDescriptionListTy);
3334
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003335 // Protocol description structures
3336
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003337 // struct _objc_protocol_extension {
3338 // uint32_t size; // sizeof(struct _objc_protocol_extension)
3339 // struct _objc_method_description_list *optional_instance_methods;
3340 // struct _objc_method_description_list *optional_class_methods;
3341 // struct _objc_property_list *instance_properties;
3342 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003343 ProtocolExtensionTy =
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003344 llvm::StructType::get(IntTy,
3345 MethodDescriptionListPtrTy,
3346 MethodDescriptionListPtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003347 PropertyListPtrTy,
3348 NULL);
3349 CGM.getModule().addTypeName("struct._objc_protocol_extension",
3350 ProtocolExtensionTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003351
3352 // struct _objc_protocol_extension *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003353 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
3354
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003355 // Handle recursive construction of Protocol and ProtocolList types
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003356
3357 llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get();
3358 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3359
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003360 const llvm::Type *T =
3361 llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder),
3362 LongTy,
3363 llvm::ArrayType::get(ProtocolTyHolder, 0),
3364 NULL);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003365 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T);
3366
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003367 // struct _objc_protocol {
3368 // struct _objc_protocol_extension *isa;
3369 // char *protocol_name;
3370 // struct _objc_protocol **_objc_protocol_list;
3371 // struct _objc_method_description_list *instance_methods;
3372 // struct _objc_method_description_list *class_methods;
3373 // }
3374 T = llvm::StructType::get(ProtocolExtensionPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003375 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003376 llvm::PointerType::getUnqual(ProtocolListTyHolder),
3377 MethodDescriptionListPtrTy,
3378 MethodDescriptionListPtrTy,
3379 NULL);
3380 cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T);
3381
3382 ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get());
3383 CGM.getModule().addTypeName("struct._objc_protocol_list",
3384 ProtocolListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003385 // struct _objc_protocol_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003386 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
3387
3388 ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get());
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003389 CGM.getModule().addTypeName("struct._objc_protocol", ProtocolTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003390 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003391
3392 // Class description structures
3393
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003394 // struct _objc_ivar {
3395 // char *ivar_name;
3396 // char *ivar_type;
3397 // int ivar_offset;
3398 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003399 IvarTy = llvm::StructType::get(Int8PtrTy,
3400 Int8PtrTy,
3401 IntTy,
3402 NULL);
3403 CGM.getModule().addTypeName("struct._objc_ivar", IvarTy);
3404
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003405 // struct _objc_ivar_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003406 IvarListTy = llvm::OpaqueType::get();
3407 CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy);
3408 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
3409
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003410 // struct _objc_method_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003411 MethodListTy = llvm::OpaqueType::get();
3412 CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy);
3413 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
3414
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003415 // struct _objc_class_extension *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003416 ClassExtensionTy =
3417 llvm::StructType::get(IntTy,
3418 Int8PtrTy,
3419 PropertyListPtrTy,
3420 NULL);
3421 CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy);
3422 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
3423
3424 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3425
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003426 // struct _objc_class {
3427 // Class isa;
3428 // Class super_class;
3429 // char *name;
3430 // long version;
3431 // long info;
3432 // long instance_size;
3433 // struct _objc_ivar_list *ivars;
3434 // struct _objc_method_list *methods;
3435 // struct _objc_cache *cache;
3436 // struct _objc_protocol_list *protocols;
3437 // char *ivar_layout;
3438 // struct _objc_class_ext *ext;
3439 // };
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003440 T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3441 llvm::PointerType::getUnqual(ClassTyHolder),
3442 Int8PtrTy,
3443 LongTy,
3444 LongTy,
3445 LongTy,
3446 IvarListPtrTy,
3447 MethodListPtrTy,
3448 CachePtrTy,
3449 ProtocolListPtrTy,
3450 Int8PtrTy,
3451 ClassExtensionPtrTy,
3452 NULL);
3453 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T);
3454
3455 ClassTy = cast<llvm::StructType>(ClassTyHolder.get());
3456 CGM.getModule().addTypeName("struct._objc_class", ClassTy);
3457 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
3458
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003459 // struct _objc_category {
3460 // char *category_name;
3461 // char *class_name;
3462 // struct _objc_method_list *instance_method;
3463 // struct _objc_method_list *class_method;
3464 // uint32_t size; // sizeof(struct _objc_category)
3465 // struct _objc_property_list *instance_properties;// category's @property
3466 // }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003467 CategoryTy = llvm::StructType::get(Int8PtrTy,
3468 Int8PtrTy,
3469 MethodListPtrTy,
3470 MethodListPtrTy,
3471 ProtocolListPtrTy,
3472 IntTy,
3473 PropertyListPtrTy,
3474 NULL);
3475 CGM.getModule().addTypeName("struct._objc_category", CategoryTy);
3476
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003477 // Global metadata structures
3478
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003479 // struct _objc_symtab {
3480 // long sel_ref_cnt;
3481 // SEL *refs;
3482 // short cls_def_cnt;
3483 // short cat_def_cnt;
3484 // char *defs[cls_def_cnt + cat_def_cnt];
3485 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003486 SymtabTy = llvm::StructType::get(LongTy,
3487 SelectorPtrTy,
3488 ShortTy,
3489 ShortTy,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003490 llvm::ArrayType::get(Int8PtrTy, 0),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003491 NULL);
3492 CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy);
3493 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
3494
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003495 // struct _objc_module {
3496 // long version;
3497 // long size; // sizeof(struct _objc_module)
3498 // char *name;
3499 // struct _objc_symtab* symtab;
3500 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003501 ModuleTy =
3502 llvm::StructType::get(LongTy,
3503 LongTy,
3504 Int8PtrTy,
3505 SymtabPtrTy,
3506 NULL);
3507 CGM.getModule().addTypeName("struct._objc_module", ModuleTy);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003508
Daniel Dunbar49f66022008-09-24 03:38:44 +00003509 // Message send functions.
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003510
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003511 // id objc_msgSend (id, SEL, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003512 std::vector<const llvm::Type*> Params;
3513 Params.push_back(ObjectPtrTy);
3514 Params.push_back(SelectorPtrTy);
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003515 MessageSendFn =
3516 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3517 Params,
3518 true),
3519 "objc_msgSend");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003520
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003521 // id objc_msgSend_stret (id, SEL, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003522 Params.clear();
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003523 Params.push_back(ObjectPtrTy);
3524 Params.push_back(SelectorPtrTy);
3525 MessageSendStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003526 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3527 Params,
3528 true),
3529 "objc_msgSend_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00003530
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003531 //
Daniel Dunbar5669e572008-10-17 03:24:53 +00003532 Params.clear();
3533 Params.push_back(ObjectPtrTy);
3534 Params.push_back(SelectorPtrTy);
3535 // FIXME: This should be long double on x86_64?
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003536 // [double | long double] objc_msgSend_fpret(id self, SEL op, ...)
Daniel Dunbar5669e572008-10-17 03:24:53 +00003537 MessageSendFpretFn =
3538 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::DoubleTy,
3539 Params,
3540 true),
3541 "objc_msgSend_fpret");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003542
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003543 // id objc_msgSendSuper(struct objc_super *super, SEL op, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003544 Params.clear();
3545 Params.push_back(SuperPtrTy);
3546 Params.push_back(SelectorPtrTy);
3547 MessageSendSuperFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003548 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3549 Params,
3550 true),
3551 "objc_msgSendSuper");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003552
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003553 // void objc_msgSendSuper_stret(void * stretAddr, struct objc_super *super,
3554 // SEL op, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003555 Params.clear();
3556 Params.push_back(Int8PtrTy);
3557 Params.push_back(SuperPtrTy);
3558 Params.push_back(SelectorPtrTy);
3559 MessageSendSuperStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003560 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3561 Params,
3562 true),
3563 "objc_msgSendSuper_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00003564
3565 // There is no objc_msgSendSuper_fpret? How can that work?
3566 MessageSendSuperFpretFn = MessageSendSuperFn;
Anders Carlsson2abd89c2008-08-31 04:05:03 +00003567
Anders Carlsson124526b2008-09-09 10:10:21 +00003568 // FIXME: This is the size of the setjmp buffer and should be
3569 // target specific. 18 is what's used on 32-bit X86.
3570 uint64_t SetJmpBufferSize = 18;
3571
3572 // Exceptions
3573 const llvm::Type *StackPtrTy =
Daniel Dunbar10004912008-09-27 06:32:25 +00003574 llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4);
Anders Carlsson124526b2008-09-09 10:10:21 +00003575
3576 ExceptionDataTy =
3577 llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty,
3578 SetJmpBufferSize),
3579 StackPtrTy, NULL);
3580 CGM.getModule().addTypeName("struct._objc_exception_data",
3581 ExceptionDataTy);
3582
3583 Params.clear();
Anders Carlsson124526b2008-09-09 10:10:21 +00003584 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
3585 ExceptionTryEnterFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003586 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3587 Params,
3588 false),
3589 "objc_exception_try_enter");
Anders Carlsson124526b2008-09-09 10:10:21 +00003590 ExceptionTryExitFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003591 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3592 Params,
3593 false),
3594 "objc_exception_try_exit");
Anders Carlsson124526b2008-09-09 10:10:21 +00003595 ExceptionExtractFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003596 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3597 Params,
3598 false),
3599 "objc_exception_extract");
Anders Carlsson124526b2008-09-09 10:10:21 +00003600
3601 Params.clear();
3602 Params.push_back(ClassPtrTy);
3603 Params.push_back(ObjectPtrTy);
3604 ExceptionMatchFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003605 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
3606 Params,
3607 false),
3608 "objc_exception_match");
Chris Lattner10cac6f2008-11-15 21:26:17 +00003609
Anders Carlsson124526b2008-09-09 10:10:21 +00003610 Params.clear();
3611 Params.push_back(llvm::PointerType::getUnqual(llvm::Type::Int32Ty));
3612 SetJmpFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003613 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
3614 Params,
3615 false),
3616 "_setjmp");
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00003617
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003618}
3619
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003620ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003621: ObjCCommonTypesHelper(cgm)
3622{
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003623 // struct _method_list_t {
3624 // uint32_t entsize; // sizeof(struct _objc_method)
3625 // uint32_t method_count;
3626 // struct _objc_method method_list[method_count];
3627 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003628 MethodListnfABITy = llvm::StructType::get(IntTy,
3629 IntTy,
3630 llvm::ArrayType::get(MethodTy, 0),
3631 NULL);
3632 CGM.getModule().addTypeName("struct.__method_list_t",
3633 MethodListnfABITy);
3634 // struct method_list_t *
3635 MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003636
3637 // struct _protocol_t {
3638 // id isa; // NULL
3639 // const char * const protocol_name;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003640 // const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003641 // const struct method_list_t * const instance_methods;
3642 // const struct method_list_t * const class_methods;
3643 // const struct method_list_t *optionalInstanceMethods;
3644 // const struct method_list_t *optionalClassMethods;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003645 // const struct _prop_list_t * properties;
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003646 // const uint32_t size; // sizeof(struct _protocol_t)
3647 // const uint32_t flags; // = 0
3648 // }
3649
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003650 // Holder for struct _protocol_list_t *
3651 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3652
3653 ProtocolnfABITy = llvm::StructType::get(ObjectPtrTy,
3654 Int8PtrTy,
3655 llvm::PointerType::getUnqual(
3656 ProtocolListTyHolder),
3657 MethodListnfABIPtrTy,
3658 MethodListnfABIPtrTy,
3659 MethodListnfABIPtrTy,
3660 MethodListnfABIPtrTy,
3661 PropertyListPtrTy,
3662 IntTy,
3663 IntTy,
3664 NULL);
3665 CGM.getModule().addTypeName("struct._protocol_t",
3666 ProtocolnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003667
3668 // struct _protocol_t*
3669 ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003670
Fariborz Jahanianda320092009-01-29 19:24:30 +00003671 // struct _protocol_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003672 // long protocol_count; // Note, this is 32/64 bit
Daniel Dunbar948e2582009-02-15 07:36:20 +00003673 // struct _protocol_t *[protocol_count];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003674 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003675 ProtocolListnfABITy = llvm::StructType::get(LongTy,
3676 llvm::ArrayType::get(
Daniel Dunbar948e2582009-02-15 07:36:20 +00003677 ProtocolnfABIPtrTy, 0),
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003678 NULL);
3679 CGM.getModule().addTypeName("struct._objc_protocol_list",
3680 ProtocolListnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003681 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(
3682 ProtocolListnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003683
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003684 // struct _objc_protocol_list*
3685 ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003686
3687 // struct _ivar_t {
3688 // unsigned long int *offset; // pointer to ivar offset location
3689 // char *name;
3690 // char *type;
3691 // uint32_t alignment;
3692 // uint32_t size;
3693 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003694 IvarnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(LongTy),
3695 Int8PtrTy,
3696 Int8PtrTy,
3697 IntTy,
3698 IntTy,
3699 NULL);
3700 CGM.getModule().addTypeName("struct._ivar_t", IvarnfABITy);
3701
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003702 // struct _ivar_list_t {
3703 // uint32 entsize; // sizeof(struct _ivar_t)
3704 // uint32 count;
3705 // struct _iver_t list[count];
3706 // }
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003707 IvarListnfABITy = llvm::StructType::get(IntTy,
3708 IntTy,
3709 llvm::ArrayType::get(
3710 IvarnfABITy, 0),
3711 NULL);
3712 CGM.getModule().addTypeName("struct._ivar_list_t", IvarListnfABITy);
3713
3714 IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003715
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003716 // struct _class_ro_t {
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003717 // uint32_t const flags;
3718 // uint32_t const instanceStart;
3719 // uint32_t const instanceSize;
3720 // uint32_t const reserved; // only when building for 64bit targets
3721 // const uint8_t * const ivarLayout;
3722 // const char *const name;
3723 // const struct _method_list_t * const baseMethods;
3724 // const struct _objc_protocol_list *const baseProtocols;
3725 // const struct _ivar_list_t *const ivars;
3726 // const uint8_t * const weakIvarLayout;
3727 // const struct _prop_list_t * const properties;
3728 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003729
3730 // FIXME. Add 'reserved' field in 64bit abi mode!
3731 ClassRonfABITy = llvm::StructType::get(IntTy,
3732 IntTy,
3733 IntTy,
3734 Int8PtrTy,
3735 Int8PtrTy,
3736 MethodListnfABIPtrTy,
3737 ProtocolListnfABIPtrTy,
3738 IvarListnfABIPtrTy,
3739 Int8PtrTy,
3740 PropertyListPtrTy,
3741 NULL);
3742 CGM.getModule().addTypeName("struct._class_ro_t",
3743 ClassRonfABITy);
3744
3745 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
3746 std::vector<const llvm::Type*> Params;
3747 Params.push_back(ObjectPtrTy);
3748 Params.push_back(SelectorPtrTy);
3749 ImpnfABITy = llvm::PointerType::getUnqual(
3750 llvm::FunctionType::get(ObjectPtrTy, Params, false));
3751
3752 // struct _class_t {
3753 // struct _class_t *isa;
3754 // struct _class_t * const superclass;
3755 // void *cache;
3756 // IMP *vtable;
3757 // struct class_ro_t *ro;
3758 // }
3759
3760 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3761 ClassnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3762 llvm::PointerType::getUnqual(ClassTyHolder),
3763 CachePtrTy,
3764 llvm::PointerType::getUnqual(ImpnfABITy),
3765 llvm::PointerType::getUnqual(
3766 ClassRonfABITy),
3767 NULL);
3768 CGM.getModule().addTypeName("struct._class_t", ClassnfABITy);
3769
3770 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(
3771 ClassnfABITy);
3772
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003773 // LLVM for struct _class_t *
3774 ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy);
3775
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003776 // struct _category_t {
3777 // const char * const name;
3778 // struct _class_t *const cls;
3779 // const struct _method_list_t * const instance_methods;
3780 // const struct _method_list_t * const class_methods;
3781 // const struct _protocol_list_t * const protocols;
3782 // const struct _prop_list_t * const properties;
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003783 // }
3784 CategorynfABITy = llvm::StructType::get(Int8PtrTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003785 ClassnfABIPtrTy,
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003786 MethodListnfABIPtrTy,
3787 MethodListnfABIPtrTy,
3788 ProtocolListnfABIPtrTy,
3789 PropertyListPtrTy,
3790 NULL);
3791 CGM.getModule().addTypeName("struct._category_t", CategorynfABITy);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003792
3793 // New types for nonfragile abi messaging.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003794 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3795 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003796
3797 // MessageRefTy - LLVM for:
3798 // struct _message_ref_t {
3799 // IMP messenger;
3800 // SEL name;
3801 // };
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003802
3803 // First the clang type for struct _message_ref_t
3804 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3805 SourceLocation(),
3806 &Ctx.Idents.get("_message_ref_t"));
Douglas Gregor6ab35242009-04-09 21:40:53 +00003807 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3808 Ctx.VoidPtrTy, 0, false));
3809 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3810 Ctx.getObjCSelType(), 0, false));
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003811 RD->completeDefinition(Ctx);
3812
3813 MessageRefCTy = Ctx.getTagDeclType(RD);
3814 MessageRefCPtrTy = Ctx.getPointerType(MessageRefCTy);
3815 MessageRefTy = cast<llvm::StructType>(Types.ConvertType(MessageRefCTy));
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003816
3817 // MessageRefPtrTy - LLVM for struct _message_ref_t*
3818 MessageRefPtrTy = llvm::PointerType::getUnqual(MessageRefTy);
3819
3820 // SuperMessageRefTy - LLVM for:
3821 // struct _super_message_ref_t {
3822 // SUPER_IMP messenger;
3823 // SEL name;
3824 // };
3825 SuperMessageRefTy = llvm::StructType::get(ImpnfABITy,
3826 SelectorPtrTy,
3827 NULL);
3828 CGM.getModule().addTypeName("struct._super_message_ref_t", SuperMessageRefTy);
3829
3830 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
3831 SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy);
3832
3833 // id objc_msgSend_fixup (id, struct message_ref_t*, ...)
3834 Params.clear();
3835 Params.push_back(ObjectPtrTy);
3836 Params.push_back(MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00003837 MessengerTy = llvm::FunctionType::get(ObjectPtrTy,
3838 Params,
3839 true);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003840 MessageSendFixupFn =
Fariborz Jahanianef163782009-02-05 01:13:09 +00003841 CGM.CreateRuntimeFunction(MessengerTy,
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003842 "objc_msgSend_fixup");
3843
3844 // id objc_msgSend_fpret_fixup (id, struct message_ref_t*, ...)
3845 MessageSendFpretFixupFn =
3846 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3847 Params,
3848 true),
3849 "objc_msgSend_fpret_fixup");
3850
3851 // id objc_msgSend_stret_fixup (id, struct message_ref_t*, ...)
3852 MessageSendStretFixupFn =
3853 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3854 Params,
3855 true),
3856 "objc_msgSend_stret_fixup");
3857
3858 // id objc_msgSendId_fixup (id, struct message_ref_t*, ...)
3859 MessageSendIdFixupFn =
3860 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3861 Params,
3862 true),
3863 "objc_msgSendId_fixup");
3864
3865
3866 // id objc_msgSendId_stret_fixup (id, struct message_ref_t*, ...)
3867 MessageSendIdStretFixupFn =
3868 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3869 Params,
3870 true),
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003871 "objc_msgSendId_stret_fixup");
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003872
3873 // id objc_msgSendSuper2_fixup (struct objc_super *,
3874 // struct _super_message_ref_t*, ...)
3875 Params.clear();
3876 Params.push_back(SuperPtrTy);
3877 Params.push_back(SuperMessageRefPtrTy);
3878 MessageSendSuper2FixupFn =
3879 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3880 Params,
3881 true),
3882 "objc_msgSendSuper2_fixup");
3883
3884
3885 // id objc_msgSendSuper2_stret_fixup (struct objc_super *,
3886 // struct _super_message_ref_t*, ...)
3887 MessageSendSuper2StretFixupFn =
3888 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3889 Params,
3890 true),
3891 "objc_msgSendSuper2_stret_fixup");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00003892
3893 Params.clear();
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00003894 Params.push_back(Int8PtrTy);
3895 UnwindResumeOrRethrowFn =
3896 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3897 Params,
3898 false),
3899 "_Unwind_Resume_or_Rethrow");
Daniel Dunbare588b992009-03-01 04:46:24 +00003900 ObjCBeginCatchFn =
3901 CGM.CreateRuntimeFunction(llvm::FunctionType::get(Int8PtrTy,
3902 Params,
3903 false),
3904 "objc_begin_catch");
3905
3906 Params.clear();
3907 ObjCEndCatchFn =
3908 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3909 Params,
3910 false),
3911 "objc_end_catch");
3912
3913 // struct objc_typeinfo {
3914 // const void** vtable; // objc_ehtype_vtable + 2
3915 // const char* name; // c++ typeinfo string
3916 // Class cls;
3917 // };
3918 EHTypeTy = llvm::StructType::get(llvm::PointerType::getUnqual(Int8PtrTy),
3919 Int8PtrTy,
3920 ClassnfABIPtrTy,
3921 NULL);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00003922 CGM.getModule().addTypeName("struct._objc_typeinfo", EHTypeTy);
Daniel Dunbare588b992009-03-01 04:46:24 +00003923 EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy);
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003924}
3925
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003926llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() {
3927 FinishNonFragileABIModule();
3928
3929 return NULL;
3930}
3931
3932void CGObjCNonFragileABIMac::FinishNonFragileABIModule() {
3933 // nonfragile abi has no module definition.
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003934
3935 // Build list of all implemented classe addresses in array
3936 // L_OBJC_LABEL_CLASS_$.
3937 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CLASS_$
3938 // list of 'nonlazy' implementations (defined as those with a +load{}
3939 // method!!).
3940 unsigned NumClasses = DefinedClasses.size();
3941 if (NumClasses) {
3942 std::vector<llvm::Constant*> Symbols(NumClasses);
3943 for (unsigned i=0; i<NumClasses; i++)
3944 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
3945 ObjCTypes.Int8PtrTy);
3946 llvm::Constant* Init =
3947 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
3948 NumClasses),
3949 Symbols);
3950
3951 llvm::GlobalVariable *GV =
3952 new llvm::GlobalVariable(Init->getType(), false,
3953 llvm::GlobalValue::InternalLinkage,
3954 Init,
3955 "\01L_OBJC_LABEL_CLASS_$",
3956 &CGM.getModule());
Daniel Dunbar58a29122009-03-09 22:18:41 +00003957 GV->setAlignment(8);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003958 GV->setSection("__DATA, __objc_classlist, regular, no_dead_strip");
3959 UsedGlobals.push_back(GV);
3960 }
3961
3962 // Build list of all implemented category addresses in array
3963 // L_OBJC_LABEL_CATEGORY_$.
3964 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CATEGORY_$
3965 // list of 'nonlazy' category implementations (defined as those with a +load{}
3966 // method!!).
3967 unsigned NumCategory = DefinedCategories.size();
3968 if (NumCategory) {
3969 std::vector<llvm::Constant*> Symbols(NumCategory);
3970 for (unsigned i=0; i<NumCategory; i++)
3971 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedCategories[i],
3972 ObjCTypes.Int8PtrTy);
3973 llvm::Constant* Init =
3974 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
3975 NumCategory),
3976 Symbols);
3977
3978 llvm::GlobalVariable *GV =
3979 new llvm::GlobalVariable(Init->getType(), false,
3980 llvm::GlobalValue::InternalLinkage,
3981 Init,
3982 "\01L_OBJC_LABEL_CATEGORY_$",
3983 &CGM.getModule());
Daniel Dunbar58a29122009-03-09 22:18:41 +00003984 GV->setAlignment(8);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003985 GV->setSection("__DATA, __objc_catlist, regular, no_dead_strip");
3986 UsedGlobals.push_back(GV);
3987 }
3988
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00003989 // static int L_OBJC_IMAGE_INFO[2] = { 0, flags };
3990 // FIXME. flags can be 0 | 1 | 2 | 6. For now just use 0
3991 std::vector<llvm::Constant*> Values(2);
3992 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, 0);
Fariborz Jahanian067986e2009-02-24 21:08:09 +00003993 unsigned int flags = 0;
Fariborz Jahanian66a5c2c2009-02-24 23:34:44 +00003994 // FIXME: Fix and continue?
3995 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
3996 flags |= eImageInfo_GarbageCollected;
3997 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
3998 flags |= eImageInfo_GCOnly;
Fariborz Jahanian067986e2009-02-24 21:08:09 +00003999 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004000 llvm::Constant* Init = llvm::ConstantArray::get(
4001 llvm::ArrayType::get(ObjCTypes.IntTy, 2),
4002 Values);
4003 llvm::GlobalVariable *IMGV =
4004 new llvm::GlobalVariable(Init->getType(), false,
4005 llvm::GlobalValue::InternalLinkage,
4006 Init,
4007 "\01L_OBJC_IMAGE_INFO",
4008 &CGM.getModule());
4009 IMGV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
4010 UsedGlobals.push_back(IMGV);
4011
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004012 std::vector<llvm::Constant*> Used;
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004013
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004014 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
4015 e = UsedGlobals.end(); i != e; ++i) {
4016 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
4017 }
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004018
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004019 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
4020 llvm::GlobalValue *GV =
4021 new llvm::GlobalVariable(AT, false,
4022 llvm::GlobalValue::AppendingLinkage,
4023 llvm::ConstantArray::get(AT, Used),
4024 "llvm.used",
4025 &CGM.getModule());
4026
4027 GV->setSection("llvm.metadata");
4028
4029}
4030
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004031// Metadata flags
4032enum MetaDataDlags {
4033 CLS = 0x0,
4034 CLS_META = 0x1,
4035 CLS_ROOT = 0x2,
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004036 OBJC2_CLS_HIDDEN = 0x10,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004037 CLS_EXCEPTION = 0x20
4038};
4039/// BuildClassRoTInitializer - generate meta-data for:
4040/// struct _class_ro_t {
4041/// uint32_t const flags;
4042/// uint32_t const instanceStart;
4043/// uint32_t const instanceSize;
4044/// uint32_t const reserved; // only when building for 64bit targets
4045/// const uint8_t * const ivarLayout;
4046/// const char *const name;
4047/// const struct _method_list_t * const baseMethods;
Fariborz Jahanianda320092009-01-29 19:24:30 +00004048/// const struct _protocol_list_t *const baseProtocols;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004049/// const struct _ivar_list_t *const ivars;
4050/// const uint8_t * const weakIvarLayout;
4051/// const struct _prop_list_t * const properties;
4052/// }
4053///
4054llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer(
4055 unsigned flags,
4056 unsigned InstanceStart,
4057 unsigned InstanceSize,
4058 const ObjCImplementationDecl *ID) {
4059 std::string ClassName = ID->getNameAsString();
4060 std::vector<llvm::Constant*> Values(10); // 11 for 64bit targets!
4061 Values[ 0] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
4062 Values[ 1] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceStart);
4063 Values[ 2] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceSize);
4064 // FIXME. For 64bit targets add 0 here.
Fariborz Jahanianda320092009-01-29 19:24:30 +00004065 // FIXME. ivarLayout is currently null!
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00004066 Values[ 3] = GetIvarLayoutName(0, ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004067 Values[ 4] = GetClassName(ID->getIdentifier());
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004068 // const struct _method_list_t * const baseMethods;
4069 std::vector<llvm::Constant*> Methods;
4070 std::string MethodListName("\01l_OBJC_$_");
4071 if (flags & CLS_META) {
4072 MethodListName += "CLASS_METHODS_" + ID->getNameAsString();
4073 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
4074 e = ID->classmeth_end(); i != e; ++i) {
4075 // Class methods should always be defined.
4076 Methods.push_back(GetMethodConstant(*i));
4077 }
4078 } else {
4079 MethodListName += "INSTANCE_METHODS_" + ID->getNameAsString();
4080 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
4081 e = ID->instmeth_end(); i != e; ++i) {
4082 // Instance methods should always be defined.
4083 Methods.push_back(GetMethodConstant(*i));
4084 }
Fariborz Jahanian939abce2009-01-28 22:46:49 +00004085 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
4086 e = ID->propimpl_end(); i != e; ++i) {
4087 ObjCPropertyImplDecl *PID = *i;
4088
4089 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize){
4090 ObjCPropertyDecl *PD = PID->getPropertyDecl();
4091
4092 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
4093 if (llvm::Constant *C = GetMethodConstant(MD))
4094 Methods.push_back(C);
4095 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
4096 if (llvm::Constant *C = GetMethodConstant(MD))
4097 Methods.push_back(C);
4098 }
4099 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004100 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004101 Values[ 5] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004102 "__DATA, __objc_const", Methods);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004103
4104 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4105 assert(OID && "CGObjCNonFragileABIMac::BuildClassRoTInitializer");
4106 Values[ 6] = EmitProtocolList("\01l_OBJC_CLASS_PROTOCOLS_$_"
4107 + OID->getNameAsString(),
4108 OID->protocol_begin(),
4109 OID->protocol_end());
4110
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004111 if (flags & CLS_META)
4112 Values[ 7] = llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4113 else
4114 Values[ 7] = EmitIvarList(ID);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004115 // FIXME. weakIvarLayout is currently null.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00004116 Values[ 8] = GetIvarLayoutName(0, ObjCTypes);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004117 if (flags & CLS_META)
4118 Values[ 9] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4119 else
4120 Values[ 9] =
4121 EmitPropertyList(
4122 "\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
4123 ID, ID->getClassInterface(), ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004124 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassRonfABITy,
4125 Values);
4126 llvm::GlobalVariable *CLASS_RO_GV =
4127 new llvm::GlobalVariable(ObjCTypes.ClassRonfABITy, false,
4128 llvm::GlobalValue::InternalLinkage,
4129 Init,
4130 (flags & CLS_META) ?
4131 std::string("\01l_OBJC_METACLASS_RO_$_")+ClassName :
4132 std::string("\01l_OBJC_CLASS_RO_$_")+ClassName,
4133 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004134 CLASS_RO_GV->setAlignment(
4135 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassRonfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004136 CLASS_RO_GV->setSection("__DATA, __objc_const");
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004137 return CLASS_RO_GV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004138
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004139}
4140
4141/// BuildClassMetaData - This routine defines that to-level meta-data
4142/// for the given ClassName for:
4143/// struct _class_t {
4144/// struct _class_t *isa;
4145/// struct _class_t * const superclass;
4146/// void *cache;
4147/// IMP *vtable;
4148/// struct class_ro_t *ro;
4149/// }
4150///
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004151llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassMetaData(
4152 std::string &ClassName,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004153 llvm::Constant *IsAGV,
4154 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004155 llvm::Constant *ClassRoGV,
4156 bool HiddenVisibility) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004157 std::vector<llvm::Constant*> Values(5);
4158 Values[0] = IsAGV;
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004159 Values[1] = SuperClassGV
4160 ? SuperClassGV
4161 : llvm::Constant::getNullValue(ObjCTypes.ClassnfABIPtrTy);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004162 Values[2] = ObjCEmptyCacheVar; // &ObjCEmptyCacheVar
4163 Values[3] = ObjCEmptyVtableVar; // &ObjCEmptyVtableVar
4164 Values[4] = ClassRoGV; // &CLASS_RO_GV
4165 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassnfABITy,
4166 Values);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004167 llvm::GlobalVariable *GV = GetClassGlobal(ClassName);
4168 GV->setInitializer(Init);
Fariborz Jahaniandd0db2a2009-01-31 01:07:39 +00004169 GV->setSection("__DATA, __objc_data");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004170 GV->setAlignment(
4171 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassnfABITy));
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004172 if (HiddenVisibility)
4173 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004174 return GV;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004175}
4176
Daniel Dunbar6c1aac82009-04-20 20:18:54 +00004177/// countInheritedIvars - count number of ivars in class and its super class(s)
4178///
4179static int countInheritedIvars(const ObjCInterfaceDecl *OI,
4180 ASTContext &Context) {
4181 int count = 0;
4182 if (!OI)
4183 return 0;
4184 const ObjCInterfaceDecl *SuperClass = OI->getSuperClass();
4185 if (SuperClass)
4186 count += countInheritedIvars(SuperClass, Context);
4187 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
4188 E = OI->ivar_end(); I != E; ++I)
4189 ++count;
4190 // look into properties.
4191 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(Context),
4192 E = OI->prop_end(Context); I != E; ++I) {
4193 if ((*I)->getPropertyIvarDecl())
4194 ++count;
4195 }
4196 return count;
4197}
4198
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004199void CGObjCNonFragileABIMac::GetClassSizeInfo(const ObjCInterfaceDecl *OID,
4200 uint32_t &InstanceStart,
4201 uint32_t &InstanceSize) {
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004202 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID);
4203
Daniel Dunbar6ec07162009-04-20 07:18:49 +00004204 int countSuperClassIvars = countInheritedIvars(OID->getSuperClass(),
4205 CGM.getContext());
4206 const RecordDecl *RD = CGM.getContext().addRecordToClass(OID);
4207 RecordDecl::field_iterator firstField = RD->field_begin(CGM.getContext());
4208 RecordDecl::field_iterator lastField = RD->field_end(CGM.getContext());
4209 while (countSuperClassIvars-- > 0) {
4210 lastField = firstField;
4211 ++firstField;
4212 }
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004213
4214 for (RecordDecl::field_iterator e = RD->field_end(CGM.getContext()),
4215 ifield = firstField; ifield != e; ++ifield)
4216 lastField = ifield;
4217
4218 InstanceStart = InstanceSize = 0;
4219 if (lastField != RD->field_end(CGM.getContext())) {
4220 FieldDecl *Field = *lastField;
4221 const llvm::Type *FieldTy =
4222 CGM.getTypes().ConvertTypeForMem(Field->getType());
4223 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
4224 InstanceSize = GetIvarBaseOffset(Layout, Field) + Size;
4225 if (firstField == RD->field_end(CGM.getContext()))
4226 InstanceStart = InstanceSize;
4227 else {
4228 Field = *firstField;
4229 InstanceStart = GetIvarBaseOffset(Layout, Field);
4230 }
4231 }
4232}
4233
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004234void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) {
4235 std::string ClassName = ID->getNameAsString();
4236 if (!ObjCEmptyCacheVar) {
4237 ObjCEmptyCacheVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004238 ObjCTypes.CacheTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004239 false,
4240 llvm::GlobalValue::ExternalLinkage,
4241 0,
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004242 "_objc_empty_cache",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004243 &CGM.getModule());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004244
4245 ObjCEmptyVtableVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004246 ObjCTypes.ImpnfABITy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004247 false,
4248 llvm::GlobalValue::ExternalLinkage,
4249 0,
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004250 "_objc_empty_vtable",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004251 &CGM.getModule());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004252 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004253 assert(ID->getClassInterface() &&
4254 "CGObjCNonFragileABIMac::GenerateClass - class is 0");
Daniel Dunbar6c1aac82009-04-20 20:18:54 +00004255 // FIXME: Is this correct (that meta class size is never computed)?
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004256 uint32_t InstanceStart =
4257 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassnfABITy);
4258 uint32_t InstanceSize = InstanceStart;
4259 uint32_t flags = CLS_META;
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004260 std::string ObjCMetaClassName(getMetaclassSymbolPrefix());
4261 std::string ObjCClassName(getClassSymbolPrefix());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004262
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004263 llvm::GlobalVariable *SuperClassGV, *IsAGV;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004264
Daniel Dunbar04d40782009-04-14 06:00:08 +00004265 bool classIsHidden =
4266 CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004267 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004268 flags |= OBJC2_CLS_HIDDEN;
4269 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004270 // class is root
4271 flags |= CLS_ROOT;
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004272 SuperClassGV = GetClassGlobal(ObjCClassName + ClassName);
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004273 IsAGV = GetClassGlobal(ObjCMetaClassName + ClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004274 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004275 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004276 const ObjCInterfaceDecl *Root = ID->getClassInterface();
4277 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
4278 Root = Super;
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004279 IsAGV = GetClassGlobal(ObjCMetaClassName + Root->getNameAsString());
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004280 // work on super class metadata symbol.
4281 std::string SuperClassName =
4282 ObjCMetaClassName + ID->getClassInterface()->getSuperClass()->getNameAsString();
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004283 SuperClassGV = GetClassGlobal(SuperClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004284 }
4285 llvm::GlobalVariable *CLASS_RO_GV = BuildClassRoTInitializer(flags,
4286 InstanceStart,
4287 InstanceSize,ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004288 std::string TClassName = ObjCMetaClassName + ClassName;
4289 llvm::GlobalVariable *MetaTClass =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004290 BuildClassMetaData(TClassName, IsAGV, SuperClassGV, CLASS_RO_GV,
4291 classIsHidden);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004292
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004293 // Metadata for the class
4294 flags = CLS;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004295 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004296 flags |= OBJC2_CLS_HIDDEN;
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004297
4298 if (hasObjCExceptionAttribute(ID->getClassInterface()))
4299 flags |= CLS_EXCEPTION;
4300
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004301 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004302 flags |= CLS_ROOT;
4303 SuperClassGV = 0;
Chris Lattnerb7b58b12009-04-19 06:02:28 +00004304 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004305 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004306 std::string RootClassName =
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004307 ID->getClassInterface()->getSuperClass()->getNameAsString();
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004308 SuperClassGV = GetClassGlobal(ObjCClassName + RootClassName);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004309 }
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004310 GetClassSizeInfo(ID->getClassInterface(), InstanceStart, InstanceSize);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004311 CLASS_RO_GV = BuildClassRoTInitializer(flags,
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004312 InstanceStart,
4313 InstanceSize,
4314 ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004315
4316 TClassName = ObjCClassName + ClassName;
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004317 llvm::GlobalVariable *ClassMD =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004318 BuildClassMetaData(TClassName, MetaTClass, SuperClassGV, CLASS_RO_GV,
4319 classIsHidden);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004320 DefinedClasses.push_back(ClassMD);
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004321
4322 // Force the definition of the EHType if necessary.
4323 if (flags & CLS_EXCEPTION)
4324 GetInterfaceEHType(ID->getClassInterface(), true);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004325}
4326
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004327/// GenerateProtocolRef - This routine is called to generate code for
4328/// a protocol reference expression; as in:
4329/// @code
4330/// @protocol(Proto1);
4331/// @endcode
4332/// It generates a weak reference to l_OBJC_PROTOCOL_REFERENCE_$_Proto1
4333/// which will hold address of the protocol meta-data.
4334///
4335llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CGBuilderTy &Builder,
4336 const ObjCProtocolDecl *PD) {
4337
Fariborz Jahanian960cd062009-04-10 18:47:34 +00004338 // This routine is called for @protocol only. So, we must build definition
4339 // of protocol's meta-data (not a reference to it!)
4340 //
4341 llvm::Constant *Init = llvm::ConstantExpr::getBitCast(GetOrEmitProtocol(PD),
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004342 ObjCTypes.ExternalProtocolPtrTy);
4343
4344 std::string ProtocolName("\01l_OBJC_PROTOCOL_REFERENCE_$_");
4345 ProtocolName += PD->getNameAsCString();
4346
4347 llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName);
4348 if (PTGV)
4349 return Builder.CreateLoad(PTGV, false, "tmp");
4350 PTGV = new llvm::GlobalVariable(
4351 Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00004352 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004353 Init,
4354 ProtocolName,
4355 &CGM.getModule());
4356 PTGV->setSection("__DATA, __objc_protorefs, coalesced, no_dead_strip");
4357 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4358 UsedGlobals.push_back(PTGV);
4359 return Builder.CreateLoad(PTGV, false, "tmp");
4360}
4361
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004362/// GenerateCategory - Build metadata for a category implementation.
4363/// struct _category_t {
4364/// const char * const name;
4365/// struct _class_t *const cls;
4366/// const struct _method_list_t * const instance_methods;
4367/// const struct _method_list_t * const class_methods;
4368/// const struct _protocol_list_t * const protocols;
4369/// const struct _prop_list_t * const properties;
4370/// }
4371///
4372void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD)
4373{
4374 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004375 const char *Prefix = "\01l_OBJC_$_CATEGORY_";
4376 std::string ExtCatName(Prefix + Interface->getNameAsString()+
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004377 "_$_" + OCD->getNameAsString());
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004378 std::string ExtClassName(getClassSymbolPrefix() +
4379 Interface->getNameAsString());
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004380
4381 std::vector<llvm::Constant*> Values(6);
4382 Values[0] = GetClassName(OCD->getIdentifier());
4383 // meta-class entry symbol
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004384 llvm::GlobalVariable *ClassGV = GetClassGlobal(ExtClassName);
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004385 Values[1] = ClassGV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004386 std::vector<llvm::Constant*> Methods;
4387 std::string MethodListName(Prefix);
4388 MethodListName += "INSTANCE_METHODS_" + Interface->getNameAsString() +
4389 "_$_" + OCD->getNameAsString();
4390
4391 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
4392 e = OCD->instmeth_end(); i != e; ++i) {
4393 // Instance methods should always be defined.
4394 Methods.push_back(GetMethodConstant(*i));
4395 }
4396
4397 Values[2] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004398 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004399 Methods);
4400
4401 MethodListName = Prefix;
4402 MethodListName += "CLASS_METHODS_" + Interface->getNameAsString() + "_$_" +
4403 OCD->getNameAsString();
4404 Methods.clear();
4405 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
4406 e = OCD->classmeth_end(); i != e; ++i) {
4407 // Class methods should always be defined.
4408 Methods.push_back(GetMethodConstant(*i));
4409 }
4410
4411 Values[3] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004412 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004413 Methods);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004414 const ObjCCategoryDecl *Category =
4415 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Fariborz Jahanian943ed6f2009-02-13 17:52:22 +00004416 if (Category) {
4417 std::string ExtName(Interface->getNameAsString() + "_$_" +
4418 OCD->getNameAsString());
4419 Values[4] = EmitProtocolList("\01l_OBJC_CATEGORY_PROTOCOLS_$_"
4420 + Interface->getNameAsString() + "_$_"
4421 + Category->getNameAsString(),
4422 Category->protocol_begin(),
4423 Category->protocol_end());
4424 Values[5] =
4425 EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
4426 OCD, Category, ObjCTypes);
4427 }
4428 else {
4429 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4430 Values[5] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4431 }
4432
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004433 llvm::Constant *Init =
4434 llvm::ConstantStruct::get(ObjCTypes.CategorynfABITy,
4435 Values);
4436 llvm::GlobalVariable *GCATV
4437 = new llvm::GlobalVariable(ObjCTypes.CategorynfABITy,
4438 false,
4439 llvm::GlobalValue::InternalLinkage,
4440 Init,
4441 ExtCatName,
4442 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004443 GCATV->setAlignment(
4444 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.CategorynfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004445 GCATV->setSection("__DATA, __objc_const");
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004446 UsedGlobals.push_back(GCATV);
4447 DefinedCategories.push_back(GCATV);
4448}
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004449
4450/// GetMethodConstant - Return a struct objc_method constant for the
4451/// given method if it has been defined. The result is null if the
4452/// method has not been defined. The return value has type MethodPtrTy.
4453llvm::Constant *CGObjCNonFragileABIMac::GetMethodConstant(
4454 const ObjCMethodDecl *MD) {
4455 // FIXME: Use DenseMap::lookup
4456 llvm::Function *Fn = MethodDefinitions[MD];
4457 if (!Fn)
4458 return 0;
4459
4460 std::vector<llvm::Constant*> Method(3);
4461 Method[0] =
4462 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4463 ObjCTypes.SelectorPtrTy);
4464 Method[1] = GetMethodVarType(MD);
4465 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
4466 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
4467}
4468
4469/// EmitMethodList - Build meta-data for method declarations
4470/// struct _method_list_t {
4471/// uint32_t entsize; // sizeof(struct _objc_method)
4472/// uint32_t method_count;
4473/// struct _objc_method method_list[method_count];
4474/// }
4475///
4476llvm::Constant *CGObjCNonFragileABIMac::EmitMethodList(
4477 const std::string &Name,
4478 const char *Section,
4479 const ConstantVector &Methods) {
4480 // Return null for empty list.
4481 if (Methods.empty())
4482 return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy);
4483
4484 std::vector<llvm::Constant*> Values(3);
4485 // sizeof(struct _objc_method)
4486 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.MethodTy);
4487 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4488 // method_count
4489 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
4490 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
4491 Methods.size());
4492 Values[2] = llvm::ConstantArray::get(AT, Methods);
4493 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4494
4495 llvm::GlobalVariable *GV =
4496 new llvm::GlobalVariable(Init->getType(), false,
4497 llvm::GlobalValue::InternalLinkage,
4498 Init,
4499 Name,
4500 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004501 GV->setAlignment(
4502 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004503 GV->setSection(Section);
4504 UsedGlobals.push_back(GV);
4505 return llvm::ConstantExpr::getBitCast(GV,
4506 ObjCTypes.MethodListnfABIPtrTy);
4507}
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004508
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004509/// ObjCIvarOffsetVariable - Returns the ivar offset variable for
4510/// the given ivar.
4511///
4512llvm::GlobalVariable * CGObjCNonFragileABIMac::ObjCIvarOffsetVariable(
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004513 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004514 const ObjCIvarDecl *Ivar) {
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00004515 std::string Name = "OBJC_IVAR_$_" +
Douglas Gregor6ab35242009-04-09 21:40:53 +00004516 getInterfaceDeclForIvar(ID, Ivar, CGM.getContext())->getNameAsString() +
4517 '.' + Ivar->getNameAsString();
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004518 llvm::GlobalVariable *IvarOffsetGV =
4519 CGM.getModule().getGlobalVariable(Name);
4520 if (!IvarOffsetGV)
4521 IvarOffsetGV =
4522 new llvm::GlobalVariable(ObjCTypes.LongTy,
4523 false,
4524 llvm::GlobalValue::ExternalLinkage,
4525 0,
4526 Name,
4527 &CGM.getModule());
4528 return IvarOffsetGV;
4529}
4530
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004531llvm::Constant * CGObjCNonFragileABIMac::EmitIvarOffsetVar(
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004532 const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004533 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004534 unsigned long int Offset) {
Daniel Dunbar737c5022009-04-19 00:44:02 +00004535 llvm::GlobalVariable *IvarOffsetGV = ObjCIvarOffsetVariable(ID, Ivar);
4536 IvarOffsetGV->setInitializer(llvm::ConstantInt::get(ObjCTypes.LongTy,
4537 Offset));
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004538 IvarOffsetGV->setAlignment(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004539 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.LongTy));
Daniel Dunbar737c5022009-04-19 00:44:02 +00004540
4541 // FIXME: This matches gcc, but shouldn't the visibility be set on
4542 // the use as well (i.e., in ObjCIvarOffsetVariable).
4543 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
4544 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
4545 CGM.getDeclVisibilityMode(ID) == LangOptions::Hidden)
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004546 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar04d40782009-04-14 06:00:08 +00004547 else
Fariborz Jahanian77c9fd22009-04-06 18:30:00 +00004548 IvarOffsetGV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004549 IvarOffsetGV->setSection("__DATA, __objc_const");
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004550 return IvarOffsetGV;
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004551}
4552
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004553/// EmitIvarList - Emit the ivar list for the given
Daniel Dunbar11394522009-04-18 08:51:00 +00004554/// implementation. The return value has type
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004555/// IvarListnfABIPtrTy.
4556/// struct _ivar_t {
4557/// unsigned long int *offset; // pointer to ivar offset location
4558/// char *name;
4559/// char *type;
4560/// uint32_t alignment;
4561/// uint32_t size;
4562/// }
4563/// struct _ivar_list_t {
4564/// uint32 entsize; // sizeof(struct _ivar_t)
4565/// uint32 count;
4566/// struct _iver_t list[count];
4567/// }
4568///
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004569
4570void CGObjCCommonMac::GetNamedIvarList(const ObjCInterfaceDecl *OID,
4571 llvm::SmallVector<ObjCIvarDecl*, 16> &Res) const {
4572 for (ObjCInterfaceDecl::ivar_iterator I = OID->ivar_begin(),
4573 E = OID->ivar_end(); I != E; ++I) {
4574 // Ignore unnamed bit-fields.
4575 if (!(*I)->getDeclName())
4576 continue;
4577
4578 Res.push_back(*I);
4579 }
4580
4581 for (ObjCInterfaceDecl::prop_iterator I = OID->prop_begin(CGM.getContext()),
4582 E = OID->prop_end(CGM.getContext()); I != E; ++I)
4583 if (ObjCIvarDecl *IV = (*I)->getPropertyIvarDecl())
4584 Res.push_back(IV);
4585}
4586
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004587llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList(
4588 const ObjCImplementationDecl *ID) {
4589
4590 std::vector<llvm::Constant*> Ivars, Ivar(5);
4591
4592 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4593 assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface");
4594
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004595 // FIXME. Consolidate this with similar code in GenerateClass.
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00004596 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00004597
Daniel Dunbar91636d62009-04-20 00:33:43 +00004598 // Collect declared and synthesized ivars in a small vector.
Fariborz Jahanian18191882009-03-31 18:11:23 +00004599 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004600 GetNamedIvarList(OID, OIvars);
Fariborz Jahanian99eee362009-04-01 19:37:34 +00004601
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004602 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
4603 ObjCIvarDecl *IVD = OIvars[i];
4604 const FieldDecl *Field = OID->lookupFieldDeclForIvar(CGM.getContext(), IVD);
Daniel Dunbar3eec8aa2009-04-20 05:53:40 +00004605 Ivar[0] = EmitIvarOffsetVar(ID->getClassInterface(), IVD,
Daniel Dunbar48fa0642009-04-19 02:03:42 +00004606 GetIvarBaseOffset(Layout, Field));
Daniel Dunbar3eec8aa2009-04-20 05:53:40 +00004607 Ivar[1] = GetMethodVarName(Field->getIdentifier());
Devang Patel7794bb82009-03-04 18:21:39 +00004608 Ivar[2] = GetMethodVarType(Field);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004609 const llvm::Type *FieldTy =
4610 CGM.getTypes().ConvertTypeForMem(Field->getType());
4611 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
4612 unsigned Align = CGM.getContext().getPreferredTypeAlign(
4613 Field->getType().getTypePtr()) >> 3;
4614 Align = llvm::Log2_32(Align);
4615 Ivar[3] = llvm::ConstantInt::get(ObjCTypes.IntTy, Align);
Daniel Dunbar91636d62009-04-20 00:33:43 +00004616 // NOTE. Size of a bitfield does not match gcc's, because of the
4617 // way bitfields are treated special in each. But I am told that
4618 // 'size' for bitfield ivars is ignored by the runtime so it does
4619 // not matter. If it matters, there is enough info to get the
4620 // bitfield right!
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004621 Ivar[4] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4622 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarnfABITy, Ivar));
4623 }
4624 // Return null for empty list.
4625 if (Ivars.empty())
4626 return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4627 std::vector<llvm::Constant*> Values(3);
4628 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.IvarnfABITy);
4629 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4630 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
4631 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarnfABITy,
4632 Ivars.size());
4633 Values[2] = llvm::ConstantArray::get(AT, Ivars);
4634 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4635 const char *Prefix = "\01l_OBJC_$_INSTANCE_VARIABLES_";
4636 llvm::GlobalVariable *GV =
4637 new llvm::GlobalVariable(Init->getType(), false,
4638 llvm::GlobalValue::InternalLinkage,
4639 Init,
4640 Prefix + OID->getNameAsString(),
4641 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004642 GV->setAlignment(
4643 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004644 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004645
4646 UsedGlobals.push_back(GV);
4647 return llvm::ConstantExpr::getBitCast(GV,
4648 ObjCTypes.IvarListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004649}
4650
4651llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef(
4652 const ObjCProtocolDecl *PD) {
4653 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4654
4655 if (!Entry) {
4656 // We use the initializer as a marker of whether this is a forward
4657 // reference or not. At module finalization we add the empty
4658 // contents for protocols which were referenced but never defined.
4659 Entry =
4660 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
4661 llvm::GlobalValue::ExternalLinkage,
4662 0,
4663 "\01l_OBJC_PROTOCOL_$_" + PD->getNameAsString(),
4664 &CGM.getModule());
4665 Entry->setSection("__DATA,__datacoal_nt,coalesced");
4666 UsedGlobals.push_back(Entry);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004667 }
4668
4669 return Entry;
4670}
4671
4672/// GetOrEmitProtocol - Generate the protocol meta-data:
4673/// @code
4674/// struct _protocol_t {
4675/// id isa; // NULL
4676/// const char * const protocol_name;
4677/// const struct _protocol_list_t * protocol_list; // super protocols
4678/// const struct method_list_t * const instance_methods;
4679/// const struct method_list_t * const class_methods;
4680/// const struct method_list_t *optionalInstanceMethods;
4681/// const struct method_list_t *optionalClassMethods;
4682/// const struct _prop_list_t * properties;
4683/// const uint32_t size; // sizeof(struct _protocol_t)
4684/// const uint32_t flags; // = 0
4685/// }
4686/// @endcode
4687///
4688
4689llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol(
4690 const ObjCProtocolDecl *PD) {
4691 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4692
4693 // Early exit if a defining object has already been generated.
4694 if (Entry && Entry->hasInitializer())
4695 return Entry;
4696
4697 const char *ProtocolName = PD->getNameAsCString();
4698
4699 // Construct method lists.
4700 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
4701 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregor6ab35242009-04-09 21:40:53 +00004702 for (ObjCProtocolDecl::instmeth_iterator
4703 i = PD->instmeth_begin(CGM.getContext()),
4704 e = PD->instmeth_end(CGM.getContext());
4705 i != e; ++i) {
Fariborz Jahanianda320092009-01-29 19:24:30 +00004706 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004707 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004708 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4709 OptInstanceMethods.push_back(C);
4710 } else {
4711 InstanceMethods.push_back(C);
4712 }
4713 }
4714
Douglas Gregor6ab35242009-04-09 21:40:53 +00004715 for (ObjCProtocolDecl::classmeth_iterator
4716 i = PD->classmeth_begin(CGM.getContext()),
4717 e = PD->classmeth_end(CGM.getContext());
4718 i != e; ++i) {
Fariborz Jahanianda320092009-01-29 19:24:30 +00004719 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004720 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004721 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4722 OptClassMethods.push_back(C);
4723 } else {
4724 ClassMethods.push_back(C);
4725 }
4726 }
4727
4728 std::vector<llvm::Constant*> Values(10);
4729 // isa is NULL
4730 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ObjectPtrTy);
4731 Values[1] = GetClassName(PD->getIdentifier());
4732 Values[2] = EmitProtocolList(
4733 "\01l_OBJC_$_PROTOCOL_REFS_" + PD->getNameAsString(),
4734 PD->protocol_begin(),
4735 PD->protocol_end());
4736
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004737 Values[3] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004738 + PD->getNameAsString(),
4739 "__DATA, __objc_const",
4740 InstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004741 Values[4] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004742 + PD->getNameAsString(),
4743 "__DATA, __objc_const",
4744 ClassMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004745 Values[5] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004746 + PD->getNameAsString(),
4747 "__DATA, __objc_const",
4748 OptInstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004749 Values[6] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004750 + PD->getNameAsString(),
4751 "__DATA, __objc_const",
4752 OptClassMethods);
4753 Values[7] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + PD->getNameAsString(),
4754 0, PD, ObjCTypes);
4755 uint32_t Size =
4756 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolnfABITy);
4757 Values[8] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4758 Values[9] = llvm::Constant::getNullValue(ObjCTypes.IntTy);
4759 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolnfABITy,
4760 Values);
4761
4762 if (Entry) {
4763 // Already created, fix the linkage and update the initializer.
Mike Stump286acbd2009-03-07 16:33:28 +00004764 Entry->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004765 Entry->setInitializer(Init);
4766 } else {
4767 Entry =
4768 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004769 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004770 Init,
4771 std::string("\01l_OBJC_PROTOCOL_$_")+ProtocolName,
4772 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004773 Entry->setAlignment(
4774 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABITy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004775 Entry->setSection("__DATA,__datacoal_nt,coalesced");
Fariborz Jahanianda320092009-01-29 19:24:30 +00004776 }
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004777 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
4778
4779 // Use this protocol meta-data to build protocol list table in section
4780 // __DATA, __objc_protolist
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004781 llvm::GlobalVariable *PTGV = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004782 ObjCTypes.ProtocolnfABIPtrTy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004783 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004784 Entry,
4785 std::string("\01l_OBJC_LABEL_PROTOCOL_$_")
4786 +ProtocolName,
4787 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004788 PTGV->setAlignment(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004789 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABIPtrTy));
Daniel Dunbar0bf21992009-04-15 02:56:18 +00004790 PTGV->setSection("__DATA, __objc_protolist, coalesced, no_dead_strip");
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004791 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4792 UsedGlobals.push_back(PTGV);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004793 return Entry;
4794}
4795
4796/// EmitProtocolList - Generate protocol list meta-data:
4797/// @code
4798/// struct _protocol_list_t {
4799/// long protocol_count; // Note, this is 32/64 bit
4800/// struct _protocol_t[protocol_count];
4801/// }
4802/// @endcode
4803///
4804llvm::Constant *
4805CGObjCNonFragileABIMac::EmitProtocolList(const std::string &Name,
4806 ObjCProtocolDecl::protocol_iterator begin,
4807 ObjCProtocolDecl::protocol_iterator end) {
4808 std::vector<llvm::Constant*> ProtocolRefs;
4809
Fariborz Jahanianda320092009-01-29 19:24:30 +00004810 // Just return null for empty protocol lists
Daniel Dunbar948e2582009-02-15 07:36:20 +00004811 if (begin == end)
Fariborz Jahanianda320092009-01-29 19:24:30 +00004812 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4813
Daniel Dunbar948e2582009-02-15 07:36:20 +00004814 // FIXME: We shouldn't need to do this lookup here, should we?
Fariborz Jahanianda320092009-01-29 19:24:30 +00004815 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
4816 if (GV)
Daniel Dunbar948e2582009-02-15 07:36:20 +00004817 return llvm::ConstantExpr::getBitCast(GV,
4818 ObjCTypes.ProtocolListnfABIPtrTy);
4819
4820 for (; begin != end; ++begin)
4821 ProtocolRefs.push_back(GetProtocolRef(*begin)); // Implemented???
4822
Fariborz Jahanianda320092009-01-29 19:24:30 +00004823 // This list is null terminated.
4824 ProtocolRefs.push_back(llvm::Constant::getNullValue(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004825 ObjCTypes.ProtocolnfABIPtrTy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004826
4827 std::vector<llvm::Constant*> Values(2);
4828 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
4829 Values[1] =
Daniel Dunbar948e2582009-02-15 07:36:20 +00004830 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolnfABIPtrTy,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004831 ProtocolRefs.size()),
4832 ProtocolRefs);
4833
4834 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4835 GV = new llvm::GlobalVariable(Init->getType(), false,
4836 llvm::GlobalValue::InternalLinkage,
4837 Init,
4838 Name,
4839 &CGM.getModule());
4840 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004841 GV->setAlignment(
4842 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004843 UsedGlobals.push_back(GV);
Daniel Dunbar948e2582009-02-15 07:36:20 +00004844 return llvm::ConstantExpr::getBitCast(GV,
4845 ObjCTypes.ProtocolListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004846}
4847
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004848/// GetMethodDescriptionConstant - This routine build following meta-data:
4849/// struct _objc_method {
4850/// SEL _cmd;
4851/// char *method_type;
4852/// char *_imp;
4853/// }
4854
4855llvm::Constant *
4856CGObjCNonFragileABIMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
4857 std::vector<llvm::Constant*> Desc(3);
4858 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4859 ObjCTypes.SelectorPtrTy);
4860 Desc[1] = GetMethodVarType(MD);
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004861 // Protocol methods have no implementation. So, this entry is always NULL.
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004862 Desc[2] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
4863 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Desc);
4864}
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004865
4866/// EmitObjCValueForIvar - Code Gen for nonfragile ivar reference.
4867/// This code gen. amounts to generating code for:
4868/// @code
4869/// (type *)((char *)base + _OBJC_IVAR_$_.ivar;
4870/// @encode
4871///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004872LValue CGObjCNonFragileABIMac::EmitObjCValueForIvar(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004873 CodeGen::CodeGenFunction &CGF,
4874 QualType ObjectTy,
4875 llvm::Value *BaseValue,
4876 const ObjCIvarDecl *Ivar,
4877 const FieldDecl *Field,
4878 unsigned CVRQualifiers) {
4879 assert(ObjectTy->isObjCInterfaceType() &&
4880 "CGObjCNonFragileABIMac::EmitObjCValueForIvar");
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004881 ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00004882 llvm::GlobalVariable *IvarOffsetGV = ObjCIvarOffsetVariable(ID, Ivar);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004883
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004884 // (char *) BaseValue
Chris Lattner51123fe2009-04-17 17:46:19 +00004885 llvm::Value *V = CGF.Builder.CreateBitCast(BaseValue, ObjCTypes.Int8PtrTy);
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004886 llvm::Value *Offset = CGF.Builder.CreateLoad(IvarOffsetGV);
4887 // (char*)BaseValue + Offset_symbol
4888 V = CGF.Builder.CreateGEP(V, Offset, "add.ptr");
4889 // (type *)((char*)BaseValue + Offset_symbol)
4890 const llvm::Type *IvarTy =
Chris Lattner51123fe2009-04-17 17:46:19 +00004891 CGM.getTypes().ConvertTypeForMem(Ivar->getType());
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004892 llvm::Type *ptrIvarTy = llvm::PointerType::getUnqual(IvarTy);
4893 V = CGF.Builder.CreateBitCast(V, ptrIvarTy);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004894
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00004895 if (Ivar->isBitField()) {
Chris Lattner51123fe2009-04-17 17:46:19 +00004896 QualType FieldTy = Field->getType();
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00004897 CodeGenTypes::BitFieldInfo bitFieldInfo =
4898 CGM.getTypes().getBitFieldInfo(Field);
4899 return LValue::MakeBitfield(V, bitFieldInfo.Begin, bitFieldInfo.Size,
Chris Lattner51123fe2009-04-17 17:46:19 +00004900 FieldTy->isSignedIntegerType(),
4901 FieldTy.getCVRQualifiers()|CVRQualifiers);
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00004902 }
4903
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004904 LValue LV = LValue::MakeAddr(V,
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004905 Ivar->getType().getCVRQualifiers()|CVRQualifiers,
4906 CGM.getContext().getObjCGCAttrKind(Ivar->getType()));
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004907 LValue::SetObjCIvar(LV, true);
4908 return LV;
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004909}
4910
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004911llvm::Value *CGObjCNonFragileABIMac::EmitIvarOffset(
4912 CodeGen::CodeGenFunction &CGF,
4913 ObjCInterfaceDecl *Interface,
4914 const ObjCIvarDecl *Ivar) {
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00004915 return CGF.Builder.CreateLoad(ObjCIvarOffsetVariable(Interface, Ivar),
4916 false, "ivar");
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004917}
4918
Fariborz Jahanian46551122009-02-04 00:22:57 +00004919CodeGen::RValue CGObjCNonFragileABIMac::EmitMessageSend(
4920 CodeGen::CodeGenFunction &CGF,
4921 QualType ResultType,
4922 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004923 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +00004924 QualType Arg0Ty,
4925 bool IsSuper,
4926 const CallArgList &CallArgs) {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004927 // FIXME. Even though IsSuper is passes. This function doese not
4928 // handle calls to 'super' receivers.
4929 CodeGenTypes &Types = CGM.getTypes();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004930 llvm::Value *Arg0 = Receiver;
4931 if (!IsSuper)
4932 Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy, "tmp");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004933
4934 // Find the message function name.
Fariborz Jahanianef163782009-02-05 01:13:09 +00004935 // FIXME. This is too much work to get the ABI-specific result type
4936 // needed to find the message name.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004937 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType,
4938 llvm::SmallVector<QualType, 16>());
4939 llvm::Constant *Fn;
4940 std::string Name("\01l_");
4941 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004942#if 0
4943 // unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004944 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
4945 Fn = ObjCTypes.MessageSendIdStretFixupFn;
4946 // FIXME. Is there a better way of getting these names.
4947 // They are available in RuntimeFunctions vector pair.
4948 Name += "objc_msgSendId_stret_fixup";
4949 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004950 else
4951#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004952 if (IsSuper) {
4953 Fn = ObjCTypes.MessageSendSuper2StretFixupFn;
4954 Name += "objc_msgSendSuper2_stret_fixup";
4955 }
4956 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004957 {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004958 Fn = ObjCTypes.MessageSendStretFixupFn;
4959 Name += "objc_msgSend_stret_fixup";
4960 }
4961 }
Fariborz Jahanian1a6b3682009-02-05 19:35:43 +00004962 else if (ResultType->isFloatingType() &&
4963 // Selection of frret API only happens in 32bit nonfragile ABI.
4964 CGM.getTargetData().getTypePaddedSize(ObjCTypes.LongTy) == 4) {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004965 Fn = ObjCTypes.MessageSendFpretFixupFn;
4966 Name += "objc_msgSend_fpret_fixup";
4967 }
4968 else {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004969#if 0
4970// unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004971 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
4972 Fn = ObjCTypes.MessageSendIdFixupFn;
4973 Name += "objc_msgSendId_fixup";
4974 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004975 else
4976#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004977 if (IsSuper) {
4978 Fn = ObjCTypes.MessageSendSuper2FixupFn;
4979 Name += "objc_msgSendSuper2_fixup";
4980 }
4981 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004982 {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004983 Fn = ObjCTypes.MessageSendFixupFn;
4984 Name += "objc_msgSend_fixup";
4985 }
4986 }
4987 Name += '_';
4988 std::string SelName(Sel.getAsString());
4989 // Replace all ':' in selector name with '_' ouch!
4990 for(unsigned i = 0; i < SelName.size(); i++)
4991 if (SelName[i] == ':')
4992 SelName[i] = '_';
4993 Name += SelName;
4994 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
4995 if (!GV) {
Daniel Dunbar33af70f2009-04-15 19:03:14 +00004996 // Build message ref table entry.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004997 std::vector<llvm::Constant*> Values(2);
4998 Values[0] = Fn;
4999 Values[1] = GetMethodVarName(Sel);
5000 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
5001 GV = new llvm::GlobalVariable(Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00005002 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005003 Init,
5004 Name,
5005 &CGM.getModule());
5006 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbarf59c1a62009-04-15 19:04:46 +00005007 GV->setAlignment(16);
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005008 GV->setSection("__DATA, __objc_msgrefs, coalesced");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005009 }
5010 llvm::Value *Arg1 = CGF.Builder.CreateBitCast(GV, ObjCTypes.MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00005011
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005012 CallArgList ActualArgs;
5013 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
5014 ActualArgs.push_back(std::make_pair(RValue::get(Arg1),
5015 ObjCTypes.MessageRefCPtrTy));
5016 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Fariborz Jahanianef163782009-02-05 01:13:09 +00005017 const CGFunctionInfo &FnInfo1 = Types.getFunctionInfo(ResultType, ActualArgs);
5018 llvm::Value *Callee = CGF.Builder.CreateStructGEP(Arg1, 0);
5019 Callee = CGF.Builder.CreateLoad(Callee);
Fariborz Jahanian3ab75bd2009-02-14 21:25:36 +00005020 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo1, true);
Fariborz Jahanianef163782009-02-05 01:13:09 +00005021 Callee = CGF.Builder.CreateBitCast(Callee,
5022 llvm::PointerType::getUnqual(FTy));
5023 return CGF.EmitCall(FnInfo1, Callee, ActualArgs);
Fariborz Jahanian46551122009-02-04 00:22:57 +00005024}
5025
5026/// Generate code for a message send expression in the nonfragile abi.
5027CodeGen::RValue CGObjCNonFragileABIMac::GenerateMessageSend(
5028 CodeGen::CodeGenFunction &CGF,
5029 QualType ResultType,
5030 Selector Sel,
5031 llvm::Value *Receiver,
5032 bool IsClassMessage,
5033 const CallArgList &CallArgs) {
Fariborz Jahanian46551122009-02-04 00:22:57 +00005034 return EmitMessageSend(CGF, ResultType, Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005035 Receiver, CGF.getContext().getObjCIdType(),
Fariborz Jahanian46551122009-02-04 00:22:57 +00005036 false, CallArgs);
5037}
5038
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005039llvm::GlobalVariable *
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005040CGObjCNonFragileABIMac::GetClassGlobal(const std::string &Name) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005041 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5042
Daniel Dunbardfff2302009-03-02 05:18:14 +00005043 if (!GV) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005044 GV = new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
5045 llvm::GlobalValue::ExternalLinkage,
5046 0, Name, &CGM.getModule());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005047 }
5048
5049 return GV;
5050}
5051
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005052llvm::Value *CGObjCNonFragileABIMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar11394522009-04-18 08:51:00 +00005053 const ObjCInterfaceDecl *ID) {
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005054 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
5055
5056 if (!Entry) {
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005057 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005058 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005059 Entry =
5060 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5061 llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005062 ClassGV,
Daniel Dunbar11394522009-04-18 08:51:00 +00005063 "\01L_OBJC_CLASSLIST_REFERENCES_$_",
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005064 &CGM.getModule());
5065 Entry->setAlignment(
5066 CGM.getTargetData().getPrefTypeAlignment(
5067 ObjCTypes.ClassnfABIPtrTy));
Daniel Dunbar11394522009-04-18 08:51:00 +00005068 Entry->setSection("__DATA, __objc_classrefs, regular, no_dead_strip");
5069 UsedGlobals.push_back(Entry);
5070 }
5071
5072 return Builder.CreateLoad(Entry, false, "tmp");
5073}
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005074
Daniel Dunbar11394522009-04-18 08:51:00 +00005075llvm::Value *
5076CGObjCNonFragileABIMac::EmitSuperClassRef(CGBuilderTy &Builder,
5077 const ObjCInterfaceDecl *ID) {
5078 llvm::GlobalVariable *&Entry = SuperClassReferences[ID->getIdentifier()];
5079
5080 if (!Entry) {
5081 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
5082 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
5083 Entry =
5084 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5085 llvm::GlobalValue::InternalLinkage,
5086 ClassGV,
5087 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5088 &CGM.getModule());
5089 Entry->setAlignment(
5090 CGM.getTargetData().getPrefTypeAlignment(
5091 ObjCTypes.ClassnfABIPtrTy));
5092 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005093 UsedGlobals.push_back(Entry);
5094 }
5095
5096 return Builder.CreateLoad(Entry, false, "tmp");
5097}
5098
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005099/// EmitMetaClassRef - Return a Value * of the address of _class_t
5100/// meta-data
5101///
5102llvm::Value *CGObjCNonFragileABIMac::EmitMetaClassRef(CGBuilderTy &Builder,
5103 const ObjCInterfaceDecl *ID) {
5104 llvm::GlobalVariable * &Entry = MetaClassReferences[ID->getIdentifier()];
5105 if (Entry)
5106 return Builder.CreateLoad(Entry, false, "tmp");
5107
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005108 std::string MetaClassName(getMetaclassSymbolPrefix() + ID->getNameAsString());
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005109 llvm::GlobalVariable *MetaClassGV = GetClassGlobal(MetaClassName);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005110 Entry =
5111 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5112 llvm::GlobalValue::InternalLinkage,
5113 MetaClassGV,
5114 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5115 &CGM.getModule());
5116 Entry->setAlignment(
5117 CGM.getTargetData().getPrefTypeAlignment(
5118 ObjCTypes.ClassnfABIPtrTy));
5119
Daniel Dunbar33af70f2009-04-15 19:03:14 +00005120 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005121 UsedGlobals.push_back(Entry);
5122
5123 return Builder.CreateLoad(Entry, false, "tmp");
5124}
5125
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005126/// GetClass - Return a reference to the class for the given interface
5127/// decl.
5128llvm::Value *CGObjCNonFragileABIMac::GetClass(CGBuilderTy &Builder,
5129 const ObjCInterfaceDecl *ID) {
5130 return EmitClassRef(Builder, ID);
5131}
5132
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005133/// Generates a message send where the super is the receiver. This is
5134/// a message send to self with special delivery semantics indicating
5135/// which class's method should be called.
5136CodeGen::RValue
5137CGObjCNonFragileABIMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
5138 QualType ResultType,
5139 Selector Sel,
5140 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005141 bool isCategoryImpl,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005142 llvm::Value *Receiver,
5143 bool IsClassMessage,
5144 const CodeGen::CallArgList &CallArgs) {
5145 // ...
5146 // Create and init a super structure; this is a (receiver, class)
5147 // pair we will pass to objc_msgSendSuper.
5148 llvm::Value *ObjCSuper =
5149 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
5150
5151 llvm::Value *ReceiverAsObject =
5152 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
5153 CGF.Builder.CreateStore(ReceiverAsObject,
5154 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
5155
5156 // If this is a class message the metaclass is passed as the target.
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005157 llvm::Value *Target;
5158 if (IsClassMessage) {
5159 if (isCategoryImpl) {
5160 // Message sent to "super' in a class method defined in
5161 // a category implementation.
Daniel Dunbar11394522009-04-18 08:51:00 +00005162 Target = EmitClassRef(CGF.Builder, Class);
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005163 Target = CGF.Builder.CreateStructGEP(Target, 0);
5164 Target = CGF.Builder.CreateLoad(Target);
5165 }
5166 else
5167 Target = EmitMetaClassRef(CGF.Builder, Class);
5168 }
5169 else
Daniel Dunbar11394522009-04-18 08:51:00 +00005170 Target = EmitSuperClassRef(CGF.Builder, Class);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005171
5172 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
5173 // and ObjCTypes types.
5174 const llvm::Type *ClassTy =
5175 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
5176 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
5177 CGF.Builder.CreateStore(Target,
5178 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
5179
5180 return EmitMessageSend(CGF, ResultType, Sel,
5181 ObjCSuper, ObjCTypes.SuperPtrCTy,
5182 true, CallArgs);
5183}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005184
5185llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CGBuilderTy &Builder,
5186 Selector Sel) {
5187 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
5188
5189 if (!Entry) {
5190 llvm::Constant *Casted =
5191 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
5192 ObjCTypes.SelectorPtrTy);
5193 Entry =
5194 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
5195 llvm::GlobalValue::InternalLinkage,
5196 Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
5197 &CGM.getModule());
5198 Entry->setSection("__DATA,__objc_selrefs,literal_pointers,no_dead_strip");
5199 UsedGlobals.push_back(Entry);
5200 }
5201
5202 return Builder.CreateLoad(Entry, false, "tmp");
5203}
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005204/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
5205/// objc_assign_ivar (id src, id *dst)
5206///
5207void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
5208 llvm::Value *src, llvm::Value *dst)
5209{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005210 const llvm::Type * SrcTy = src->getType();
5211 if (!isa<llvm::PointerType>(SrcTy)) {
5212 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5213 assert(Size <= 8 && "does not support size > 8");
5214 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5215 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005216 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5217 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005218 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5219 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5220 CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn,
5221 src, dst, "assignivar");
5222 return;
5223}
5224
5225/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
5226/// objc_assign_strongCast (id src, id *dst)
5227///
5228void CGObjCNonFragileABIMac::EmitObjCStrongCastAssign(
5229 CodeGen::CodeGenFunction &CGF,
5230 llvm::Value *src, llvm::Value *dst)
5231{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005232 const llvm::Type * SrcTy = src->getType();
5233 if (!isa<llvm::PointerType>(SrcTy)) {
5234 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5235 assert(Size <= 8 && "does not support size > 8");
5236 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5237 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005238 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5239 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005240 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5241 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5242 CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn,
5243 src, dst, "weakassign");
5244 return;
5245}
5246
5247/// EmitObjCWeakRead - Code gen for loading value of a __weak
5248/// object: objc_read_weak (id *src)
5249///
5250llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead(
5251 CodeGen::CodeGenFunction &CGF,
5252 llvm::Value *AddrWeakObj)
5253{
Eli Friedman8339b352009-03-07 03:57:15 +00005254 const llvm::Type* DestTy =
5255 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005256 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
5257 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
5258 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00005259 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005260 return read_weak;
5261}
5262
5263/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
5264/// objc_assign_weak (id src, id *dst)
5265///
5266void CGObjCNonFragileABIMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
5267 llvm::Value *src, llvm::Value *dst)
5268{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005269 const llvm::Type * SrcTy = src->getType();
5270 if (!isa<llvm::PointerType>(SrcTy)) {
5271 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5272 assert(Size <= 8 && "does not support size > 8");
5273 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5274 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005275 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5276 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005277 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5278 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattner96508e12009-04-17 22:12:36 +00005279 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005280 src, dst, "weakassign");
5281 return;
5282}
5283
5284/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
5285/// objc_assign_global (id src, id *dst)
5286///
5287void CGObjCNonFragileABIMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
5288 llvm::Value *src, llvm::Value *dst)
5289{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005290 const llvm::Type * SrcTy = src->getType();
5291 if (!isa<llvm::PointerType>(SrcTy)) {
5292 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5293 assert(Size <= 8 && "does not support size > 8");
5294 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5295 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005296 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5297 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005298 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5299 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5300 CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn,
5301 src, dst, "globalassign");
5302 return;
5303}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005304
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005305void
5306CGObjCNonFragileABIMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
5307 const Stmt &S) {
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005308 bool isTry = isa<ObjCAtTryStmt>(S);
5309 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
5310 llvm::BasicBlock *PrevLandingPad = CGF.getInvokeDest();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005311 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005312 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005313 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005314 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
5315
5316 // For @synchronized, call objc_sync_enter(sync.expr). The
5317 // evaluation of the expression must occur before we enter the
5318 // @synchronized. We can safely avoid a temp here because jumps into
5319 // @synchronized are illegal & this will dominate uses.
5320 llvm::Value *SyncArg = 0;
5321 if (!isTry) {
5322 SyncArg =
5323 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
5324 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005325 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005326 }
5327
5328 // Push an EH context entry, used for handling rethrows and jumps
5329 // through finally.
5330 CGF.PushCleanupBlock(FinallyBlock);
5331
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005332 CGF.setInvokeDest(TryHandler);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005333
5334 CGF.EmitBlock(TryBlock);
5335 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
5336 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
5337 CGF.EmitBranchThroughCleanup(FinallyEnd);
5338
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005339 // Emit the exception handler.
5340
5341 CGF.EmitBlock(TryHandler);
5342
5343 llvm::Value *llvm_eh_exception =
5344 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_exception);
5345 llvm::Value *llvm_eh_selector_i64 =
5346 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector_i64);
5347 llvm::Value *llvm_eh_typeid_for_i64 =
5348 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for_i64);
5349 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5350 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(Exc->getType(), "_rethrow");
5351
5352 llvm::SmallVector<llvm::Value*, 8> SelectorArgs;
5353 SelectorArgs.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005354 SelectorArgs.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005355
5356 // Construct the lists of (type, catch body) to handle.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005357 llvm::SmallVector<std::pair<const ParmVarDecl*, const Stmt*>, 8> Handlers;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005358 bool HasCatchAll = false;
5359 if (isTry) {
5360 if (const ObjCAtCatchStmt* CatchStmt =
5361 cast<ObjCAtTryStmt>(S).getCatchStmts()) {
5362 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005363 const ParmVarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
Steve Naroff7ba138a2009-03-03 19:52:17 +00005364 Handlers.push_back(std::make_pair(CatchDecl, CatchStmt->getCatchBody()));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005365
5366 // catch(...) always matches.
Steve Naroff7ba138a2009-03-03 19:52:17 +00005367 if (!CatchDecl) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005368 // Use i8* null here to signal this is a catch all, not a cleanup.
5369 llvm::Value *Null = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
5370 SelectorArgs.push_back(Null);
5371 HasCatchAll = true;
5372 break;
5373 }
5374
Daniel Dunbarede8de92009-03-06 00:01:21 +00005375 if (CGF.getContext().isObjCIdType(CatchDecl->getType()) ||
5376 CatchDecl->getType()->isObjCQualifiedIdType()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005377 llvm::Value *IDEHType =
5378 CGM.getModule().getGlobalVariable("OBJC_EHTYPE_id");
5379 if (!IDEHType)
5380 IDEHType =
5381 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5382 llvm::GlobalValue::ExternalLinkage,
5383 0, "OBJC_EHTYPE_id", &CGM.getModule());
5384 SelectorArgs.push_back(IDEHType);
5385 HasCatchAll = true;
5386 break;
5387 }
5388
5389 // All other types should be Objective-C interface pointer types.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005390 const PointerType *PT = CatchDecl->getType()->getAsPointerType();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005391 assert(PT && "Invalid @catch type.");
5392 const ObjCInterfaceType *IT =
5393 PT->getPointeeType()->getAsObjCInterfaceType();
5394 assert(IT && "Invalid @catch type.");
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005395 llvm::Value *EHType = GetInterfaceEHType(IT->getDecl(), false);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005396 SelectorArgs.push_back(EHType);
5397 }
5398 }
5399 }
5400
5401 // We use a cleanup unless there was already a catch all.
5402 if (!HasCatchAll) {
5403 SelectorArgs.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
Daniel Dunbarede8de92009-03-06 00:01:21 +00005404 Handlers.push_back(std::make_pair((const ParmVarDecl*) 0, (const Stmt*) 0));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005405 }
5406
5407 llvm::Value *Selector =
5408 CGF.Builder.CreateCall(llvm_eh_selector_i64,
5409 SelectorArgs.begin(), SelectorArgs.end(),
5410 "selector");
5411 for (unsigned i = 0, e = Handlers.size(); i != e; ++i) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005412 const ParmVarDecl *CatchParam = Handlers[i].first;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005413 const Stmt *CatchBody = Handlers[i].second;
5414
5415 llvm::BasicBlock *Next = 0;
5416
5417 // The last handler always matches.
5418 if (i + 1 != e) {
5419 assert(CatchParam && "Only last handler can be a catch all.");
5420
5421 llvm::BasicBlock *Match = CGF.createBasicBlock("match");
5422 Next = CGF.createBasicBlock("catch.next");
5423 llvm::Value *Id =
5424 CGF.Builder.CreateCall(llvm_eh_typeid_for_i64,
5425 CGF.Builder.CreateBitCast(SelectorArgs[i+2],
5426 ObjCTypes.Int8PtrTy));
5427 CGF.Builder.CreateCondBr(CGF.Builder.CreateICmpEQ(Selector, Id),
5428 Match, Next);
5429
5430 CGF.EmitBlock(Match);
5431 }
5432
5433 if (CatchBody) {
5434 llvm::BasicBlock *MatchEnd = CGF.createBasicBlock("match.end");
5435 llvm::BasicBlock *MatchHandler = CGF.createBasicBlock("match.handler");
5436
5437 // Cleanups must call objc_end_catch.
5438 //
5439 // FIXME: It seems incorrect for objc_begin_catch to be inside
5440 // this context, but this matches gcc.
5441 CGF.PushCleanupBlock(MatchEnd);
5442 CGF.setInvokeDest(MatchHandler);
5443
5444 llvm::Value *ExcObject =
5445 CGF.Builder.CreateCall(ObjCTypes.ObjCBeginCatchFn, Exc);
5446
5447 // Bind the catch parameter if it exists.
5448 if (CatchParam) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005449 ExcObject =
5450 CGF.Builder.CreateBitCast(ExcObject,
5451 CGF.ConvertType(CatchParam->getType()));
5452 // CatchParam is a ParmVarDecl because of the grammar
5453 // construction used to handle this, but for codegen purposes
5454 // we treat this as a local decl.
5455 CGF.EmitLocalBlockVarDecl(*CatchParam);
5456 CGF.Builder.CreateStore(ExcObject, CGF.GetAddrOfLocalVar(CatchParam));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005457 }
5458
5459 CGF.ObjCEHValueStack.push_back(ExcObject);
5460 CGF.EmitStmt(CatchBody);
5461 CGF.ObjCEHValueStack.pop_back();
5462
5463 CGF.EmitBranchThroughCleanup(FinallyEnd);
5464
5465 CGF.EmitBlock(MatchHandler);
5466
5467 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5468 // We are required to emit this call to satisfy LLVM, even
5469 // though we don't use the result.
5470 llvm::SmallVector<llvm::Value*, 8> Args;
5471 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005472 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005473 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5474 0));
5475 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5476 CGF.Builder.CreateStore(Exc, RethrowPtr);
5477 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5478
5479 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5480
5481 CGF.EmitBlock(MatchEnd);
5482
5483 // Unfortunately, we also have to generate another EH frame here
5484 // in case this throws.
5485 llvm::BasicBlock *MatchEndHandler =
5486 CGF.createBasicBlock("match.end.handler");
5487 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
5488 CGF.Builder.CreateInvoke(ObjCTypes.ObjCEndCatchFn,
5489 Cont, MatchEndHandler,
5490 Args.begin(), Args.begin());
5491
5492 CGF.EmitBlock(Cont);
5493 if (Info.SwitchBlock)
5494 CGF.EmitBlock(Info.SwitchBlock);
5495 if (Info.EndBlock)
5496 CGF.EmitBlock(Info.EndBlock);
5497
5498 CGF.EmitBlock(MatchEndHandler);
5499 Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5500 // We are required to emit this call to satisfy LLVM, even
5501 // though we don't use the result.
5502 Args.clear();
5503 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005504 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005505 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5506 0));
5507 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5508 CGF.Builder.CreateStore(Exc, RethrowPtr);
5509 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5510
5511 if (Next)
5512 CGF.EmitBlock(Next);
5513 } else {
5514 assert(!Next && "catchup should be last handler.");
5515
5516 CGF.Builder.CreateStore(Exc, RethrowPtr);
5517 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5518 }
5519 }
5520
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005521 // Pop the cleanup entry, the @finally is outside this cleanup
5522 // scope.
5523 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5524 CGF.setInvokeDest(PrevLandingPad);
5525
5526 CGF.EmitBlock(FinallyBlock);
5527
5528 if (isTry) {
5529 if (const ObjCAtFinallyStmt* FinallyStmt =
5530 cast<ObjCAtTryStmt>(S).getFinallyStmt())
5531 CGF.EmitStmt(FinallyStmt->getFinallyBody());
5532 } else {
5533 // Emit 'objc_sync_exit(expr)' as finally's sole statement for
5534 // @synchronized.
5535 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, SyncArg);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005536 }
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005537
5538 if (Info.SwitchBlock)
5539 CGF.EmitBlock(Info.SwitchBlock);
5540 if (Info.EndBlock)
5541 CGF.EmitBlock(Info.EndBlock);
5542
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005543 // Branch around the rethrow code.
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005544 CGF.EmitBranch(FinallyEnd);
5545
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005546 CGF.EmitBlock(FinallyRethrow);
5547 CGF.Builder.CreateCall(ObjCTypes.UnwindResumeOrRethrowFn,
5548 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005549 CGF.Builder.CreateUnreachable();
5550
5551 CGF.EmitBlock(FinallyEnd);
5552}
5553
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005554/// EmitThrowStmt - Generate code for a throw statement.
5555void CGObjCNonFragileABIMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
5556 const ObjCAtThrowStmt &S) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005557 llvm::Value *Exception;
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005558 if (const Expr *ThrowExpr = S.getThrowExpr()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005559 Exception = CGF.EmitScalarExpr(ThrowExpr);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005560 } else {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005561 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
5562 "Unexpected rethrow outside @catch block.");
5563 Exception = CGF.ObjCEHValueStack.back();
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005564 }
5565
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005566 llvm::Value *ExceptionAsObject =
5567 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
5568 llvm::BasicBlock *InvokeDest = CGF.getInvokeDest();
5569 if (InvokeDest) {
5570 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
5571 CGF.Builder.CreateInvoke(ObjCTypes.ExceptionThrowFn,
5572 Cont, InvokeDest,
5573 &ExceptionAsObject, &ExceptionAsObject + 1);
5574 CGF.EmitBlock(Cont);
5575 } else
5576 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
5577 CGF.Builder.CreateUnreachable();
5578
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005579 // Clear the insertion point to indicate we are in unreachable code.
5580 CGF.Builder.ClearInsertionPoint();
5581}
Daniel Dunbare588b992009-03-01 04:46:24 +00005582
5583llvm::Value *
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005584CGObjCNonFragileABIMac::GetInterfaceEHType(const ObjCInterfaceDecl *ID,
5585 bool ForDefinition) {
Daniel Dunbare588b992009-03-01 04:46:24 +00005586 llvm::GlobalVariable * &Entry = EHTypeReferences[ID->getIdentifier()];
Daniel Dunbare588b992009-03-01 04:46:24 +00005587
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005588 // If we don't need a definition, return the entry if found or check
5589 // if we use an external reference.
5590 if (!ForDefinition) {
5591 if (Entry)
5592 return Entry;
Daniel Dunbar7e075cb2009-04-07 06:43:45 +00005593
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005594 // If this type (or a super class) has the __objc_exception__
5595 // attribute, emit an external reference.
5596 if (hasObjCExceptionAttribute(ID))
5597 return Entry =
5598 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5599 llvm::GlobalValue::ExternalLinkage,
5600 0,
5601 (std::string("OBJC_EHTYPE_$_") +
5602 ID->getIdentifier()->getName()),
5603 &CGM.getModule());
5604 }
5605
5606 // Otherwise we need to either make a new entry or fill in the
5607 // initializer.
5608 assert((!Entry || !Entry->hasInitializer()) && "Duplicate EHType definition");
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005609 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbare588b992009-03-01 04:46:24 +00005610 std::string VTableName = "objc_ehtype_vtable";
5611 llvm::GlobalVariable *VTableGV =
5612 CGM.getModule().getGlobalVariable(VTableName);
5613 if (!VTableGV)
5614 VTableGV = new llvm::GlobalVariable(ObjCTypes.Int8PtrTy, false,
5615 llvm::GlobalValue::ExternalLinkage,
5616 0, VTableName, &CGM.getModule());
5617
5618 llvm::Value *VTableIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, 2);
5619
5620 std::vector<llvm::Constant*> Values(3);
5621 Values[0] = llvm::ConstantExpr::getGetElementPtr(VTableGV, &VTableIdx, 1);
5622 Values[1] = GetClassName(ID->getIdentifier());
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005623 Values[2] = GetClassGlobal(ClassName);
Daniel Dunbare588b992009-03-01 04:46:24 +00005624 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.EHTypeTy, Values);
5625
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005626 if (Entry) {
5627 Entry->setInitializer(Init);
5628 } else {
5629 Entry = new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5630 llvm::GlobalValue::WeakAnyLinkage,
5631 Init,
5632 (std::string("OBJC_EHTYPE_$_") +
5633 ID->getIdentifier()->getName()),
5634 &CGM.getModule());
5635 }
5636
Daniel Dunbar04d40782009-04-14 06:00:08 +00005637 if (CGM.getLangOptions().getVisibilityMode() == LangOptions::Hidden)
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005638 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005639 Entry->setAlignment(8);
5640
5641 if (ForDefinition) {
5642 Entry->setSection("__DATA,__objc_const");
5643 Entry->setLinkage(llvm::GlobalValue::ExternalLinkage);
5644 } else {
5645 Entry->setSection("__DATA,__datacoal_nt,coalesced");
5646 }
Daniel Dunbare588b992009-03-01 04:46:24 +00005647
5648 return Entry;
5649}
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005650
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00005651/* *** */
5652
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00005653CodeGen::CGObjCRuntime *
5654CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00005655 return new CGObjCMac(CGM);
5656}
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005657
5658CodeGen::CGObjCRuntime *
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00005659CodeGen::CreateMacNonFragileABIObjCRuntime(CodeGen::CodeGenModule &CGM) {
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00005660 return new CGObjCNonFragileABIMac(CGM);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005661}