blob: 269f5d5c362e3d0836e47f00dad0192b5d55a9bf [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 Lattnerbbccd612009-04-22 02:38:11 +0000105 llvm::Constant *getGcAssignGlobalFn() {
106 // id objc_assign_global(id, id *)
107 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
108 Args.push_back(ObjectPtrTy->getPointerTo());
109 llvm::FunctionType *FTy = llvm::FunctionType::get(ObjectPtrTy, Args, false);
110 return CGM.CreateRuntimeFunction(FTy, "objc_assign_global");
111 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000112
113 /// GcAssignIvarFn -- LLVM objc_assign_ivar function.
Chris Lattnerbbccd612009-04-22 02:38:11 +0000114 llvm::Constant *getGcAssignIvarFn() {
115 // id objc_assign_ivar(id, id *)
116 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
117 Args.push_back(ObjectPtrTy->getPointerTo());
118 llvm::FunctionType *FTy = llvm::FunctionType::get(ObjectPtrTy, Args, false);
119 return CGM.CreateRuntimeFunction(FTy, "objc_assign_ivar");
120 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000121
122 /// GcAssignStrongCastFn -- LLVM objc_assign_strongCast function.
Chris Lattnerbbccd612009-04-22 02:38:11 +0000123 llvm::Constant *getGcAssignStrongCastFn() {
124 // id objc_assign_global(id, id *)
125 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
126 Args.push_back(ObjectPtrTy->getPointerTo());
127 llvm::FunctionType *FTy = llvm::FunctionType::get(ObjectPtrTy, Args, false);
128 return CGM.CreateRuntimeFunction(FTy, "objc_assign_strongCast");
129 }
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000130
131 /// ExceptionThrowFn - LLVM objc_exception_throw function.
Chris Lattnerbbccd612009-04-22 02:38:11 +0000132 llvm::Constant *getExceptionThrowFn() {
133 // void objc_exception_throw(id)
134 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
135 llvm::FunctionType *FTy =
136 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
137 return CGM.CreateRuntimeFunction(FTy, "objc_exception_throw");
138 }
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000139
Daniel Dunbar1c566672009-02-24 01:43:46 +0000140 /// SyncEnterFn - LLVM object_sync_enter function.
Chris Lattnerb02e53b2009-04-06 16:53:45 +0000141 llvm::Constant *getSyncEnterFn() {
142 // void objc_sync_enter (id)
143 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
144 llvm::FunctionType *FTy =
145 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
146 return CGM.CreateRuntimeFunction(FTy, "objc_sync_enter");
147 }
Daniel Dunbar1c566672009-02-24 01:43:46 +0000148
149 /// SyncExitFn - LLVM object_sync_exit function.
Chris Lattnerbbccd612009-04-22 02:38:11 +0000150 llvm::Constant *getSyncExitFn() {
151 // void objc_sync_exit (id)
152 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
153 llvm::FunctionType *FTy =
154 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
155 return CGM.CreateRuntimeFunction(FTy, "objc_sync_exit");
156 }
Daniel Dunbar1c566672009-02-24 01:43:46 +0000157
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000158 ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm);
159 ~ObjCCommonTypesHelper(){}
160};
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000161
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000162/// ObjCTypesHelper - Helper class that encapsulates lazy
163/// construction of varies types used during ObjC generation.
164class ObjCTypesHelper : public ObjCCommonTypesHelper {
165private:
166
Chris Lattner4176b0c2009-04-22 02:32:31 +0000167 llvm::Constant *getMessageSendFn() {
168 // id objc_msgSend (id, SEL, ...)
169 std::vector<const llvm::Type*> Params;
170 Params.push_back(ObjectPtrTy);
171 Params.push_back(SelectorPtrTy);
172 return
173 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
174 Params, true),
175 "objc_msgSend");
176 }
177
178 llvm::Constant *getMessageSendStretFn() {
179 // id objc_msgSend_stret (id, SEL, ...)
180 std::vector<const llvm::Type*> Params;
181 Params.push_back(ObjectPtrTy);
182 Params.push_back(SelectorPtrTy);
183 return
184 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
185 Params, true),
186 "objc_msgSend_stret");
187
188 }
189
190 llvm::Constant *getMessageSendFpretFn() {
191 // FIXME: This should be long double on x86_64?
192 // [double | long double] objc_msgSend_fpret(id self, SEL op, ...)
193 std::vector<const llvm::Type*> Params;
194 Params.push_back(ObjectPtrTy);
195 Params.push_back(SelectorPtrTy);
196 return
197 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::DoubleTy,
198 Params,
199 true),
200 "objc_msgSend_fpret");
201
202 }
203
204 llvm::Constant *getMessageSendSuperFn() {
205 // id objc_msgSendSuper(struct objc_super *super, SEL op, ...)
206 std::vector<const llvm::Type*> Params;
207 Params.push_back(SuperPtrTy);
208 Params.push_back(SelectorPtrTy);
209 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
210 Params, true),
211 "objc_msgSendSuper");
212 }
213 llvm::Constant *getMessageSendSuperStretFn() {
214 // void objc_msgSendSuper_stret(void * stretAddr, struct objc_super *super,
215 // SEL op, ...)
216 std::vector<const llvm::Type*> Params;
217 Params.push_back(Int8PtrTy);
218 Params.push_back(SuperPtrTy);
219 Params.push_back(SelectorPtrTy);
220 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
221 Params, true),
222 "objc_msgSendSuper_stret");
223 }
224
225 llvm::Constant *getMessageSendSuperFpretFn() {
226 // There is no objc_msgSendSuper_fpret? How can that work?
227 return getMessageSendSuperFn();
228 }
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000229
230public:
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000231 /// SymtabTy - LLVM type for struct objc_symtab.
232 const llvm::StructType *SymtabTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000233 /// SymtabPtrTy - LLVM type for struct objc_symtab *.
234 const llvm::Type *SymtabPtrTy;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000235 /// ModuleTy - LLVM type for struct objc_module.
236 const llvm::StructType *ModuleTy;
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000237
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000238 /// ProtocolTy - LLVM type for struct objc_protocol.
239 const llvm::StructType *ProtocolTy;
240 /// ProtocolPtrTy - LLVM type for struct objc_protocol *.
241 const llvm::Type *ProtocolPtrTy;
242 /// ProtocolExtensionTy - LLVM type for struct
243 /// objc_protocol_extension.
244 const llvm::StructType *ProtocolExtensionTy;
245 /// ProtocolExtensionTy - LLVM type for struct
246 /// objc_protocol_extension *.
247 const llvm::Type *ProtocolExtensionPtrTy;
248 /// MethodDescriptionTy - LLVM type for struct
249 /// objc_method_description.
250 const llvm::StructType *MethodDescriptionTy;
251 /// MethodDescriptionListTy - LLVM type for struct
252 /// objc_method_description_list.
253 const llvm::StructType *MethodDescriptionListTy;
254 /// MethodDescriptionListPtrTy - LLVM type for struct
255 /// objc_method_description_list *.
256 const llvm::Type *MethodDescriptionListPtrTy;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000257 /// ProtocolListTy - LLVM type for struct objc_property_list.
258 const llvm::Type *ProtocolListTy;
259 /// ProtocolListPtrTy - LLVM type for struct objc_property_list*.
260 const llvm::Type *ProtocolListPtrTy;
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000261 /// CategoryTy - LLVM type for struct objc_category.
262 const llvm::StructType *CategoryTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000263 /// ClassTy - LLVM type for struct objc_class.
264 const llvm::StructType *ClassTy;
265 /// ClassPtrTy - LLVM type for struct objc_class *.
266 const llvm::Type *ClassPtrTy;
267 /// ClassExtensionTy - LLVM type for struct objc_class_ext.
268 const llvm::StructType *ClassExtensionTy;
269 /// ClassExtensionPtrTy - LLVM type for struct objc_class_ext *.
270 const llvm::Type *ClassExtensionPtrTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000271 // IvarTy - LLVM type for struct objc_ivar.
272 const llvm::StructType *IvarTy;
273 /// IvarListTy - LLVM type for struct objc_ivar_list.
274 const llvm::Type *IvarListTy;
275 /// IvarListPtrTy - LLVM type for struct objc_ivar_list *.
276 const llvm::Type *IvarListPtrTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000277 /// MethodListTy - LLVM type for struct objc_method_list.
278 const llvm::Type *MethodListTy;
279 /// MethodListPtrTy - LLVM type for struct objc_method_list *.
280 const llvm::Type *MethodListPtrTy;
Anders Carlsson124526b2008-09-09 10:10:21 +0000281
282 /// ExceptionDataTy - LLVM type for struct _objc_exception_data.
283 const llvm::Type *ExceptionDataTy;
284
Anders Carlsson124526b2008-09-09 10:10:21 +0000285 /// ExceptionTryEnterFn - LLVM objc_exception_try_enter function.
Chris Lattner34b02a12009-04-22 02:26:14 +0000286 llvm::Constant *getExceptionTryEnterFn() {
287 std::vector<const llvm::Type*> Params;
288 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
289 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
290 Params, false),
291 "objc_exception_try_enter");
292 }
Anders Carlsson124526b2008-09-09 10:10:21 +0000293
294 /// ExceptionTryExitFn - LLVM objc_exception_try_exit function.
Chris Lattner34b02a12009-04-22 02:26:14 +0000295 llvm::Constant *getExceptionTryExitFn() {
296 std::vector<const llvm::Type*> Params;
297 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
298 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
299 Params, false),
300 "objc_exception_try_exit");
301 }
Anders Carlsson124526b2008-09-09 10:10:21 +0000302
303 /// ExceptionExtractFn - LLVM objc_exception_extract function.
Chris Lattner34b02a12009-04-22 02:26:14 +0000304 llvm::Constant *getExceptionExtractFn() {
305 std::vector<const llvm::Type*> Params;
306 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
307 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
308 Params, false),
309 "objc_exception_extract");
310
311 }
Anders Carlsson124526b2008-09-09 10:10:21 +0000312
313 /// ExceptionMatchFn - LLVM objc_exception_match function.
Chris Lattner34b02a12009-04-22 02:26:14 +0000314 llvm::Constant *getExceptionMatchFn() {
315 std::vector<const llvm::Type*> Params;
316 Params.push_back(ClassPtrTy);
317 Params.push_back(ObjectPtrTy);
318 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
319 Params, false),
320 "objc_exception_match");
321
322 }
Anders Carlsson124526b2008-09-09 10:10:21 +0000323
324 /// SetJmpFn - LLVM _setjmp function.
Chris Lattner34b02a12009-04-22 02:26:14 +0000325 llvm::Constant *getSetJmpFn() {
326 std::vector<const llvm::Type*> Params;
327 Params.push_back(llvm::PointerType::getUnqual(llvm::Type::Int32Ty));
328 return
329 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
330 Params, false),
331 "_setjmp");
332
333 }
Chris Lattner10cac6f2008-11-15 21:26:17 +0000334
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000335public:
336 ObjCTypesHelper(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000337 ~ObjCTypesHelper() {}
Daniel Dunbar5669e572008-10-17 03:24:53 +0000338
339
Chris Lattner74391b42009-03-22 21:03:39 +0000340 llvm::Constant *getSendFn(bool IsSuper) {
Chris Lattner4176b0c2009-04-22 02:32:31 +0000341 return IsSuper ? getMessageSendSuperFn() : getMessageSendFn();
Daniel Dunbar5669e572008-10-17 03:24:53 +0000342 }
343
Chris Lattner74391b42009-03-22 21:03:39 +0000344 llvm::Constant *getSendStretFn(bool IsSuper) {
Chris Lattner4176b0c2009-04-22 02:32:31 +0000345 return IsSuper ? getMessageSendSuperStretFn() : getMessageSendStretFn();
Daniel Dunbar5669e572008-10-17 03:24:53 +0000346 }
347
Chris Lattner74391b42009-03-22 21:03:39 +0000348 llvm::Constant *getSendFpretFn(bool IsSuper) {
Chris Lattner4176b0c2009-04-22 02:32:31 +0000349 return IsSuper ? getMessageSendSuperFpretFn() : getMessageSendFpretFn();
Daniel Dunbar5669e572008-10-17 03:24:53 +0000350 }
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000351};
352
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000353/// ObjCNonFragileABITypesHelper - will have all types needed by objective-c's
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000354/// modern abi
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000355class ObjCNonFragileABITypesHelper : public ObjCCommonTypesHelper {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000356public:
Chris Lattner74391b42009-03-22 21:03:39 +0000357 llvm::Constant *MessageSendFixupFn, *MessageSendFpretFixupFn,
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000358 *MessageSendStretFixupFn, *MessageSendIdFixupFn,
359 *MessageSendIdStretFixupFn, *MessageSendSuper2FixupFn,
360 *MessageSendSuper2StretFixupFn;
361
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000362 // MethodListnfABITy - LLVM for struct _method_list_t
363 const llvm::StructType *MethodListnfABITy;
364
365 // MethodListnfABIPtrTy - LLVM for struct _method_list_t*
366 const llvm::Type *MethodListnfABIPtrTy;
367
368 // ProtocolnfABITy = LLVM for struct _protocol_t
369 const llvm::StructType *ProtocolnfABITy;
370
Daniel Dunbar948e2582009-02-15 07:36:20 +0000371 // ProtocolnfABIPtrTy = LLVM for struct _protocol_t*
372 const llvm::Type *ProtocolnfABIPtrTy;
373
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000374 // ProtocolListnfABITy - LLVM for struct _objc_protocol_list
375 const llvm::StructType *ProtocolListnfABITy;
376
377 // ProtocolListnfABIPtrTy - LLVM for struct _objc_protocol_list*
378 const llvm::Type *ProtocolListnfABIPtrTy;
379
380 // ClassnfABITy - LLVM for struct _class_t
381 const llvm::StructType *ClassnfABITy;
382
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000383 // ClassnfABIPtrTy - LLVM for struct _class_t*
384 const llvm::Type *ClassnfABIPtrTy;
385
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000386 // IvarnfABITy - LLVM for struct _ivar_t
387 const llvm::StructType *IvarnfABITy;
388
389 // IvarListnfABITy - LLVM for struct _ivar_list_t
390 const llvm::StructType *IvarListnfABITy;
391
392 // IvarListnfABIPtrTy = LLVM for struct _ivar_list_t*
393 const llvm::Type *IvarListnfABIPtrTy;
394
395 // ClassRonfABITy - LLVM for struct _class_ro_t
396 const llvm::StructType *ClassRonfABITy;
397
398 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
399 const llvm::Type *ImpnfABITy;
400
401 // CategorynfABITy - LLVM for struct _category_t
402 const llvm::StructType *CategorynfABITy;
403
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000404 // New types for nonfragile abi messaging.
405
406 // MessageRefTy - LLVM for:
407 // struct _message_ref_t {
408 // IMP messenger;
409 // SEL name;
410 // };
411 const llvm::StructType *MessageRefTy;
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000412 // MessageRefCTy - clang type for struct _message_ref_t
413 QualType MessageRefCTy;
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000414
415 // MessageRefPtrTy - LLVM for struct _message_ref_t*
416 const llvm::Type *MessageRefPtrTy;
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000417 // MessageRefCPtrTy - clang type for struct _message_ref_t*
418 QualType MessageRefCPtrTy;
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000419
Fariborz Jahanianef163782009-02-05 01:13:09 +0000420 // MessengerTy - Type of the messenger (shown as IMP above)
421 const llvm::FunctionType *MessengerTy;
422
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000423 // SuperMessageRefTy - LLVM for:
424 // struct _super_message_ref_t {
425 // SUPER_IMP messenger;
426 // SEL name;
427 // };
428 const llvm::StructType *SuperMessageRefTy;
429
430 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
431 const llvm::Type *SuperMessageRefPtrTy;
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000432
433 /// EHPersonalityPtr - LLVM value for an i8* to the Objective-C
434 /// exception personality function.
Chris Lattnerb02e53b2009-04-06 16:53:45 +0000435 llvm::Value *getEHPersonalityPtr() {
436 llvm::Constant *Personality =
437 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
438 std::vector<const llvm::Type*>(),
439 true),
440 "__objc_personality_v0");
441 return llvm::ConstantExpr::getBitCast(Personality, Int8PtrTy);
442 }
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000443
Chris Lattner8a569112009-04-22 02:15:23 +0000444 llvm::Constant *getUnwindResumeOrRethrowFn() {
445 std::vector<const llvm::Type*> Params;
446 Params.push_back(Int8PtrTy);
447 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
448 Params, false),
449 "_Unwind_Resume_or_Rethrow");
450 }
451
452 llvm::Constant *getObjCEndCatchFn() {
453 std::vector<const llvm::Type*> Params;
454 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
455 Params, false),
456 "objc_end_catch");
457
458 }
459
460 llvm::Constant *getObjCBeginCatchFn() {
461 std::vector<const llvm::Type*> Params;
462 Params.push_back(Int8PtrTy);
463 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(Int8PtrTy,
464 Params, false),
465 "objc_begin_catch");
466 }
Daniel Dunbare588b992009-03-01 04:46:24 +0000467
468 const llvm::StructType *EHTypeTy;
469 const llvm::Type *EHTypePtrTy;
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000470
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000471 ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm);
472 ~ObjCNonFragileABITypesHelper(){}
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000473};
474
475class CGObjCCommonMac : public CodeGen::CGObjCRuntime {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000476public:
477 // FIXME - accessibility
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000478 class GC_IVAR {
Fariborz Jahanian820e0202009-03-11 00:07:04 +0000479 public:
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000480 unsigned int ivar_bytepos;
481 unsigned int ivar_size;
482 GC_IVAR() : ivar_bytepos(0), ivar_size(0) {}
483 };
484
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000485 class SKIP_SCAN {
486 public:
487 unsigned int skip;
488 unsigned int scan;
489 SKIP_SCAN() : skip(0), scan(0) {}
490 };
491
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000492protected:
493 CodeGen::CodeGenModule &CGM;
494 // FIXME! May not be needing this after all.
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000495 unsigned ObjCABI;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000496
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000497 // gc ivar layout bitmap calculation helper caches.
498 llvm::SmallVector<GC_IVAR, 16> SkipIvars;
499 llvm::SmallVector<GC_IVAR, 16> IvarsInfo;
500 llvm::SmallVector<SKIP_SCAN, 32> SkipScanIvars;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000501
Daniel Dunbar242d4dc2008-08-25 06:02:07 +0000502 /// LazySymbols - Symbols to generate a lazy reference for. See
503 /// DefinedSymbols and FinishModule().
504 std::set<IdentifierInfo*> LazySymbols;
505
506 /// DefinedSymbols - External symbols which are defined by this
507 /// module. The symbols in this list and LazySymbols are used to add
508 /// special linker symbols which ensure that Objective-C modules are
509 /// linked properly.
510 std::set<IdentifierInfo*> DefinedSymbols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000511
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000512 /// ClassNames - uniqued class names.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000513 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000514
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000515 /// MethodVarNames - uniqued method variable names.
516 llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000517
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000518 /// MethodVarTypes - uniqued method type signatures. We have to use
519 /// a StringMap here because have no other unique reference.
520 llvm::StringMap<llvm::GlobalVariable*> MethodVarTypes;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000521
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000522 /// MethodDefinitions - map of methods which have been defined in
523 /// this translation unit.
524 llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> MethodDefinitions;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000525
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000526 /// PropertyNames - uniqued method variable names.
527 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000528
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000529 /// ClassReferences - uniqued class references.
530 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000531
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000532 /// SelectorReferences - uniqued selector references.
533 llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000534
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000535 /// Protocols - Protocols for which an objc_protocol structure has
536 /// been emitted. Forward declarations are handled by creating an
537 /// empty structure whose initializer is filled in when/if defined.
538 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> Protocols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000539
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000540 /// DefinedProtocols - Protocols which have actually been
541 /// defined. We should not need this, see FIXME in GenerateProtocol.
542 llvm::DenseSet<IdentifierInfo*> DefinedProtocols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000543
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000544 /// DefinedClasses - List of defined classes.
545 std::vector<llvm::GlobalValue*> DefinedClasses;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000546
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000547 /// DefinedCategories - List of defined categories.
548 std::vector<llvm::GlobalValue*> DefinedCategories;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000549
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000550 /// UsedGlobals - List of globals to pack into the llvm.used metadata
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000551 /// to prevent them from being clobbered.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000552 std::vector<llvm::GlobalVariable*> UsedGlobals;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000553
Fariborz Jahanian56210f72009-01-21 23:34:32 +0000554 /// GetNameForMethod - Return a name for the given method.
555 /// \param[out] NameOut - The return value.
556 void GetNameForMethod(const ObjCMethodDecl *OMD,
557 const ObjCContainerDecl *CD,
558 std::string &NameOut);
559
560 /// GetMethodVarName - Return a unique constant for the given
561 /// selector's name. The return value has type char *.
562 llvm::Constant *GetMethodVarName(Selector Sel);
563 llvm::Constant *GetMethodVarName(IdentifierInfo *Ident);
564 llvm::Constant *GetMethodVarName(const std::string &Name);
565
566 /// GetMethodVarType - Return a unique constant for the given
567 /// selector's name. The return value has type char *.
568
569 // FIXME: This is a horrible name.
570 llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D);
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +0000571 llvm::Constant *GetMethodVarType(const FieldDecl *D);
Fariborz Jahanian56210f72009-01-21 23:34:32 +0000572
573 /// GetPropertyName - Return a unique constant for the given
574 /// name. The return value has type char *.
575 llvm::Constant *GetPropertyName(IdentifierInfo *Ident);
576
577 // FIXME: This can be dropped once string functions are unified.
578 llvm::Constant *GetPropertyTypeString(const ObjCPropertyDecl *PD,
579 const Decl *Container);
580
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000581 /// GetClassName - Return a unique constant for the given selector's
582 /// name. The return value has type char *.
583 llvm::Constant *GetClassName(IdentifierInfo *Ident);
584
Fariborz Jahanian21e6f172009-03-11 21:42:00 +0000585 /// GetInterfaceDeclStructLayout - Get layout for ivars of given
586 /// interface declaration.
587 const llvm::StructLayout *GetInterfaceDeclStructLayout(
588 const ObjCInterfaceDecl *ID) const;
589
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000590 /// BuildIvarLayout - Builds ivar layout bitmap for the class
591 /// implementation for the __strong or __weak case.
592 ///
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000593 llvm::Constant *BuildIvarLayout(const ObjCImplementationDecl *OI,
594 bool ForStrongLayout);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000595
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000596 void BuildAggrIvarLayout(const ObjCInterfaceDecl *OI,
597 const llvm::StructLayout *Layout,
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000598 const RecordDecl *RD,
Chris Lattnerf1690852009-03-31 08:48:01 +0000599 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000600 unsigned int BytePos, bool ForStrongLayout,
601 int &Index, int &SkIndex, bool &HasUnion);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000602
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +0000603 /// GetIvarLayoutName - Returns a unique constant for the given
604 /// ivar layout bitmap.
605 llvm::Constant *GetIvarLayoutName(IdentifierInfo *Ident,
606 const ObjCCommonTypesHelper &ObjCTypes);
607
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +0000608 /// EmitPropertyList - Emit the given property list. The return
609 /// value has type PropertyListPtrTy.
610 llvm::Constant *EmitPropertyList(const std::string &Name,
611 const Decl *Container,
612 const ObjCContainerDecl *OCD,
613 const ObjCCommonTypesHelper &ObjCTypes);
614
Fariborz Jahanianda320092009-01-29 19:24:30 +0000615 /// GetProtocolRef - Return a reference to the internal protocol
616 /// description, creating an empty one if it has not been
617 /// defined. The return value has type ProtocolPtrTy.
618 llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +0000619
620 /// GetIvarBaseOffset - returns ivars byte offset.
621 uint64_t GetIvarBaseOffset(const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +0000622 const FieldDecl *Field);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000623
Chris Lattnercd0ee142009-03-31 08:33:16 +0000624 /// GetFieldBaseOffset - return's field byte offset.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000625 uint64_t GetFieldBaseOffset(const ObjCInterfaceDecl *OI,
626 const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +0000627 const FieldDecl *Field);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000628
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000629 /// CreateMetadataVar - Create a global variable with internal
630 /// linkage for use by the Objective-C runtime.
631 ///
632 /// This is a convenience wrapper which not only creates the
633 /// variable, but also sets the section and alignment and adds the
634 /// global to the UsedGlobals list.
Daniel Dunbar35bd7632009-03-09 20:50:13 +0000635 ///
636 /// \param Name - The variable name.
637 /// \param Init - The variable initializer; this is also used to
638 /// define the type of the variable.
639 /// \param Section - The section the variable should go into, or 0.
640 /// \param Align - The alignment for the variable, or 0.
641 /// \param AddToUsed - Whether the variable should be added to
Daniel Dunbarc1583062009-04-14 17:42:51 +0000642 /// "llvm.used".
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000643 llvm::GlobalVariable *CreateMetadataVar(const std::string &Name,
644 llvm::Constant *Init,
645 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +0000646 unsigned Align,
647 bool AddToUsed);
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000648
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +0000649 /// GetNamedIvarList - Return the list of ivars in the interface
650 /// itself (not including super classes and not including unnamed
651 /// bitfields).
652 ///
653 /// For the non-fragile ABI, this also includes synthesized property
654 /// ivars.
655 void GetNamedIvarList(const ObjCInterfaceDecl *OID,
656 llvm::SmallVector<ObjCIvarDecl*, 16> &Res) const;
657
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000658public:
659 CGObjCCommonMac(CodeGen::CodeGenModule &cgm) : CGM(cgm)
660 { }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000661
Steve Naroff33fdb732009-03-31 16:53:37 +0000662 virtual llvm::Constant *GenerateConstantString(const ObjCStringLiteral *SL);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000663
664 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
665 const ObjCContainerDecl *CD=0);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000666
667 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
668
669 /// GetOrEmitProtocol - Get the protocol object for the given
670 /// declaration, emitting it if necessary. The return value has type
671 /// ProtocolPtrTy.
672 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD)=0;
673
674 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
675 /// object for the given declaration, emitting it if needed. These
676 /// forward references will be filled in with empty bodies if no
677 /// definition is seen. The return value has type ProtocolPtrTy.
678 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD)=0;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000679};
680
681class CGObjCMac : public CGObjCCommonMac {
682private:
683 ObjCTypesHelper ObjCTypes;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000684 /// EmitImageInfo - Emit the image info marker used to encode some module
685 /// level information.
686 void EmitImageInfo();
687
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000688 /// EmitModuleInfo - Another marker encoding module level
689 /// information.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000690 void EmitModuleInfo();
691
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000692 /// EmitModuleSymols - Emit module symbols, the list of defined
693 /// classes and categories. The result has type SymtabPtrTy.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000694 llvm::Constant *EmitModuleSymbols();
695
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000696 /// FinishModule - Write out global data structures at the end of
697 /// processing a translation unit.
698 void FinishModule();
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000699
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000700 /// EmitClassExtension - Generate the class extension structure used
701 /// to store the weak ivar layout and properties. The return value
702 /// has type ClassExtensionPtrTy.
703 llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID);
704
705 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
706 /// for the given class.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000707 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000708 const ObjCInterfaceDecl *ID);
709
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000710 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000711 QualType ResultType,
712 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000713 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000714 QualType Arg0Ty,
715 bool IsSuper,
716 const CallArgList &CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000717
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000718 /// EmitIvarList - Emit the ivar list for the given
719 /// implementation. If ForClass is true the list of class ivars
720 /// (i.e. metaclass ivars) is emitted, otherwise the list of
721 /// interface ivars will be emitted. The return value has type
722 /// IvarListPtrTy.
723 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +0000724 bool ForClass);
725
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000726 /// EmitMetaClass - Emit a forward reference to the class structure
727 /// for the metaclass of the given interface. The return value has
728 /// type ClassPtrTy.
729 llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
730
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000731 /// EmitMetaClass - Emit a class structure for the metaclass of the
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000732 /// given implementation. The return value has type ClassPtrTy.
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000733 llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
734 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000735 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000736 const ConstantVector &Methods);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000737
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000738 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000739
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000740 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000741
742 /// EmitMethodList - Emit the method list for the given
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000743 /// implementation. The return value has type MethodListPtrTy.
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000744 llvm::Constant *EmitMethodList(const std::string &Name,
745 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000746 const ConstantVector &Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000747
748 /// EmitMethodDescList - Emit a method description list for a list of
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000749 /// method declarations.
750 /// - TypeName: The name for the type containing the methods.
751 /// - IsProtocol: True iff these methods are for a protocol.
752 /// - ClassMethds: True iff these are class methods.
753 /// - Required: When true, only "required" methods are
754 /// listed. Similarly, when false only "optional" methods are
755 /// listed. For classes this should always be true.
756 /// - begin, end: The method list to output.
757 ///
758 /// The return value has type MethodDescriptionListPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000759 llvm::Constant *EmitMethodDescList(const std::string &Name,
760 const char *Section,
761 const ConstantVector &Methods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000762
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000763 /// GetOrEmitProtocol - Get the protocol object for the given
764 /// declaration, emitting it if necessary. The return value has type
765 /// ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +0000766 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000767
768 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
769 /// object for the given declaration, emitting it if needed. These
770 /// forward references will be filled in with empty bodies if no
771 /// definition is seen. The return value has type ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +0000772 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000773
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000774 /// EmitProtocolExtension - Generate the protocol extension
775 /// structure used to store optional instance and class methods, and
776 /// protocol properties. The return value has type
777 /// ProtocolExtensionPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000778 llvm::Constant *
779 EmitProtocolExtension(const ObjCProtocolDecl *PD,
780 const ConstantVector &OptInstanceMethods,
781 const ConstantVector &OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000782
783 /// EmitProtocolList - Generate the list of referenced
784 /// protocols. The return value has type ProtocolListPtrTy.
Daniel Dunbardbc933702008-08-21 21:57:41 +0000785 llvm::Constant *EmitProtocolList(const std::string &Name,
786 ObjCProtocolDecl::protocol_iterator begin,
787 ObjCProtocolDecl::protocol_iterator end);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000788
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000789 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
790 /// for the given selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000791 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000792
Fariborz Jahanianda320092009-01-29 19:24:30 +0000793 public:
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000794 CGObjCMac(CodeGen::CodeGenModule &cgm);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000795
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000796 virtual llvm::Function *ModuleInitFunction();
797
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000798 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000799 QualType ResultType,
800 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000801 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000802 bool IsClassMessage,
803 const CallArgList &CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000804
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000805 virtual CodeGen::RValue
806 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000807 QualType ResultType,
808 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000809 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000810 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000811 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000812 bool IsClassMessage,
813 const CallArgList &CallArgs);
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000814
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000815 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000816 const ObjCInterfaceDecl *ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000817
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000818 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000819
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000820 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000821
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000822 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000823
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000824 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000825 const ObjCProtocolDecl *PD);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000826
Chris Lattner74391b42009-03-22 21:03:39 +0000827 virtual llvm::Constant *GetPropertyGetFunction();
828 virtual llvm::Constant *GetPropertySetFunction();
829 virtual llvm::Constant *EnumerationMutationFunction();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000830
Fariborz Jahanianbd71be42008-11-21 00:49:24 +0000831 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
832 const Stmt &S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000833 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
834 const ObjCAtThrowStmt &S);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000835 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +0000836 llvm::Value *AddrWeakObj);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000837 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
838 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000839 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
840 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian7eda8362008-11-20 19:23:36 +0000841 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
842 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000843 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
844 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian0bb20362009-02-02 20:02:29 +0000845
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000846 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
847 QualType ObjectTy,
848 llvm::Value *BaseValue,
849 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000850 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000851 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
852 ObjCInterfaceDecl *Interface,
853 const ObjCIvarDecl *Ivar);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000854};
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000855
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000856class CGObjCNonFragileABIMac : public CGObjCCommonMac {
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000857private:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000858 ObjCNonFragileABITypesHelper ObjCTypes;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000859 llvm::GlobalVariable* ObjCEmptyCacheVar;
860 llvm::GlobalVariable* ObjCEmptyVtableVar;
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000861
Daniel Dunbar11394522009-04-18 08:51:00 +0000862 /// SuperClassReferences - uniqued super class references.
863 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> SuperClassReferences;
864
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000865 /// MetaClassReferences - uniqued meta class references.
866 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> MetaClassReferences;
Daniel Dunbare588b992009-03-01 04:46:24 +0000867
868 /// EHTypeReferences - uniqued class ehtype references.
869 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> EHTypeReferences;
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000870
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000871 /// FinishNonFragileABIModule - Write out global data structures at the end of
872 /// processing a translation unit.
873 void FinishNonFragileABIModule();
Daniel Dunbar8158a2f2009-04-08 04:21:03 +0000874
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000875 llvm::GlobalVariable * BuildClassRoTInitializer(unsigned flags,
876 unsigned InstanceStart,
877 unsigned InstanceSize,
878 const ObjCImplementationDecl *ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +0000879 llvm::GlobalVariable * BuildClassMetaData(std::string &ClassName,
880 llvm::Constant *IsAGV,
881 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +0000882 llvm::Constant *ClassRoGV,
883 bool HiddenVisibility);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000884
885 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
886
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +0000887 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
888
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000889 /// EmitMethodList - Emit the method list for the given
890 /// implementation. The return value has type MethodListnfABITy.
891 llvm::Constant *EmitMethodList(const std::string &Name,
892 const char *Section,
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +0000893 const ConstantVector &Methods);
894 /// EmitIvarList - Emit the ivar list for the given
895 /// implementation. If ForClass is true the list of class ivars
896 /// (i.e. metaclass ivars) is emitted, otherwise the list of
897 /// interface ivars will be emitted. The return value has type
898 /// IvarListnfABIPtrTy.
899 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000900
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000901 llvm::Constant *EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +0000902 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +0000903 unsigned long int offset);
904
Fariborz Jahanianda320092009-01-29 19:24:30 +0000905 /// GetOrEmitProtocol - Get the protocol object for the given
906 /// declaration, emitting it if necessary. The return value has type
907 /// ProtocolPtrTy.
908 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
909
910 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
911 /// object for the given declaration, emitting it if needed. These
912 /// forward references will be filled in with empty bodies if no
913 /// definition is seen. The return value has type ProtocolPtrTy.
914 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
915
916 /// EmitProtocolList - Generate the list of referenced
917 /// protocols. The return value has type ProtocolListPtrTy.
918 llvm::Constant *EmitProtocolList(const std::string &Name,
919 ObjCProtocolDecl::protocol_iterator begin,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000920 ObjCProtocolDecl::protocol_iterator end);
921
922 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
923 QualType ResultType,
924 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000925 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000926 QualType Arg0Ty,
927 bool IsSuper,
928 const CallArgList &CallArgs);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +0000929
930 /// GetClassGlobal - Return the global variable for the Objective-C
931 /// class of the given name.
Fariborz Jahanian0f902942009-04-14 18:41:56 +0000932 llvm::GlobalVariable *GetClassGlobal(const std::string &Name);
933
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000934 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
Daniel Dunbar11394522009-04-18 08:51:00 +0000935 /// for the given class reference.
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000936 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar11394522009-04-18 08:51:00 +0000937 const ObjCInterfaceDecl *ID);
938
939 /// EmitSuperClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
940 /// for the given super class reference.
941 llvm::Value *EmitSuperClassRef(CGBuilderTy &Builder,
942 const ObjCInterfaceDecl *ID);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000943
944 /// EmitMetaClassRef - Return a Value * of the address of _class_t
945 /// meta-data
946 llvm::Value *EmitMetaClassRef(CGBuilderTy &Builder,
947 const ObjCInterfaceDecl *ID);
948
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000949 /// ObjCIvarOffsetVariable - Returns the ivar offset variable for
950 /// the given ivar.
951 ///
Daniel Dunbar5e88bea2009-04-19 00:31:15 +0000952 llvm::GlobalVariable * ObjCIvarOffsetVariable(
Fariborz Jahanian01a0c362009-02-12 18:51:23 +0000953 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000954 const ObjCIvarDecl *Ivar);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000955
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +0000956 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
957 /// for the given selector.
958 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbare588b992009-03-01 04:46:24 +0000959
Daniel Dunbar8158a2f2009-04-08 04:21:03 +0000960 /// GetInterfaceEHType - Get the cached ehtype for the given Objective-C
Daniel Dunbare588b992009-03-01 04:46:24 +0000961 /// interface. The return value has type EHTypePtrTy.
Daniel Dunbar8158a2f2009-04-08 04:21:03 +0000962 llvm::Value *GetInterfaceEHType(const ObjCInterfaceDecl *ID,
963 bool ForDefinition);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +0000964
965 const char *getMetaclassSymbolPrefix() const {
966 return "OBJC_METACLASS_$_";
967 }
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000968
Daniel Dunbar6ab187a2009-04-07 05:48:37 +0000969 const char *getClassSymbolPrefix() const {
970 return "OBJC_CLASS_$_";
971 }
972
Daniel Dunbarb02532a2009-04-19 23:41:48 +0000973 void GetClassSizeInfo(const ObjCInterfaceDecl *OID,
974 uint32_t &InstanceStart,
975 uint32_t &InstanceSize);
976
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000977public:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000978 CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000979 // FIXME. All stubs for now!
980 virtual llvm::Function *ModuleInitFunction();
981
982 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
983 QualType ResultType,
984 Selector Sel,
985 llvm::Value *Receiver,
986 bool IsClassMessage,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000987 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000988
989 virtual CodeGen::RValue
990 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
991 QualType ResultType,
992 Selector Sel,
993 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000994 bool isCategoryImpl,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000995 llvm::Value *Receiver,
996 bool IsClassMessage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000997 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000998
999 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00001000 const ObjCInterfaceDecl *ID);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001001
1002 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel)
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00001003 { return EmitSelector(Builder, Sel); }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001004
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00001005 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001006
1007 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001008 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00001009 const ObjCProtocolDecl *PD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001010
Chris Lattner74391b42009-03-22 21:03:39 +00001011 virtual llvm::Constant *GetPropertyGetFunction() {
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001012 return ObjCTypes.GetPropertyFn;
1013 }
Chris Lattner74391b42009-03-22 21:03:39 +00001014 virtual llvm::Constant *GetPropertySetFunction() {
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001015 return ObjCTypes.SetPropertyFn;
1016 }
Chris Lattner74391b42009-03-22 21:03:39 +00001017 virtual llvm::Constant *EnumerationMutationFunction() {
Daniel Dunbar28ed0842009-02-16 18:48:45 +00001018 return ObjCTypes.EnumerationMutationFn;
1019 }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001020
1021 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00001022 const Stmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001023 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Anders Carlssonf57c5b22009-02-16 22:59:18 +00001024 const ObjCAtThrowStmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001025 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001026 llvm::Value *AddrWeakObj);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001027 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001028 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001029 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001030 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001031 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001032 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001033 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001034 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00001035 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
1036 QualType ObjectTy,
1037 llvm::Value *BaseValue,
1038 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00001039 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001040 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
1041 ObjCInterfaceDecl *Interface,
1042 const ObjCIvarDecl *Ivar);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001043};
1044
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001045} // end anonymous namespace
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001046
1047/* *** Helper Functions *** */
1048
1049/// getConstantGEP() - Help routine to construct simple GEPs.
1050static llvm::Constant *getConstantGEP(llvm::Constant *C,
1051 unsigned idx0,
1052 unsigned idx1) {
1053 llvm::Value *Idxs[] = {
1054 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx0),
1055 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx1)
1056 };
1057 return llvm::ConstantExpr::getGetElementPtr(C, Idxs, 2);
1058}
1059
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001060/// hasObjCExceptionAttribute - Return true if this class or any super
1061/// class has the __objc_exception__ attribute.
1062static bool hasObjCExceptionAttribute(const ObjCInterfaceDecl *OID) {
Daniel Dunbarb11fa0d2009-04-13 21:08:27 +00001063 if (OID->hasAttr<ObjCExceptionAttr>())
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001064 return true;
1065 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
1066 return hasObjCExceptionAttribute(Super);
1067 return false;
1068}
1069
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001070/* *** CGObjCMac Public Interface *** */
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001071
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001072CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm),
1073 ObjCTypes(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001074{
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001075 ObjCABI = 1;
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001076 EmitImageInfo();
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001077}
1078
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +00001079/// GetClass - Return a reference to the class for the given interface
1080/// decl.
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001081llvm::Value *CGObjCMac::GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001082 const ObjCInterfaceDecl *ID) {
1083 return EmitClassRef(Builder, ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001084}
1085
1086/// GetSelector - Return the pointer to the unique'd string for this selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001087llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00001088 return EmitSelector(Builder, Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001089}
1090
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001091/// Generate a constant CFString object.
1092/*
1093 struct __builtin_CFString {
1094 const int *isa; // point to __CFConstantStringClassReference
1095 int flags;
1096 const char *str;
1097 long length;
1098 };
1099*/
1100
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001101llvm::Constant *CGObjCCommonMac::GenerateConstantString(
Steve Naroff33fdb732009-03-31 16:53:37 +00001102 const ObjCStringLiteral *SL) {
Steve Naroff8d4141f2009-04-01 13:55:36 +00001103 return CGM.GetAddrOfConstantCFString(SL->getString());
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001104}
1105
1106/// Generates a message send where the super is the receiver. This is
1107/// a message send to self with special delivery semantics indicating
1108/// which class's method should be called.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +00001109CodeGen::RValue
1110CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001111 QualType ResultType,
1112 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001113 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00001114 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001115 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001116 bool IsClassMessage,
Daniel Dunbar46f45b92008-09-09 01:06:48 +00001117 const CodeGen::CallArgList &CallArgs) {
Daniel Dunbare8b470d2008-08-23 04:28:29 +00001118 // Create and init a super structure; this is a (receiver, class)
1119 // pair we will pass to objc_msgSendSuper.
1120 llvm::Value *ObjCSuper =
1121 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
1122 llvm::Value *ReceiverAsObject =
1123 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
1124 CGF.Builder.CreateStore(ReceiverAsObject,
1125 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
Daniel Dunbare8b470d2008-08-23 04:28:29 +00001126
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001127 // If this is a class message the metaclass is passed as the target.
1128 llvm::Value *Target;
1129 if (IsClassMessage) {
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00001130 if (isCategoryImpl) {
1131 // Message sent to 'super' in a class method defined in a category
1132 // implementation requires an odd treatment.
1133 // If we are in a class method, we must retrieve the
1134 // _metaclass_ for the current class, pointed at by
1135 // the class's "isa" pointer. The following assumes that
1136 // isa" is the first ivar in a class (which it must be).
1137 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
1138 Target = CGF.Builder.CreateStructGEP(Target, 0);
1139 Target = CGF.Builder.CreateLoad(Target);
1140 }
1141 else {
1142 llvm::Value *MetaClassPtr = EmitMetaClassRef(Class);
1143 llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1);
1144 llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr);
1145 Target = Super;
1146 }
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001147 } else {
1148 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
1149 }
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001150 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
1151 // and ObjCTypes types.
1152 const llvm::Type *ClassTy =
1153 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001154 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001155 CGF.Builder.CreateStore(Target,
1156 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
1157
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001158 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001159 ObjCSuper, ObjCTypes.SuperPtrCTy,
1160 true, CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001161}
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001162
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001163/// Generate code for a message send expression.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +00001164CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001165 QualType ResultType,
1166 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001167 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001168 bool IsClassMessage,
1169 const CallArgList &CallArgs) {
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001170 llvm::Value *Arg0 =
1171 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy, "tmp");
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001172 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001173 Arg0, CGF.getContext().getObjCIdType(),
1174 false, CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001175}
1176
1177CodeGen::RValue CGObjCMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001178 QualType ResultType,
1179 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001180 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001181 QualType Arg0Ty,
1182 bool IsSuper,
1183 const CallArgList &CallArgs) {
1184 CallArgList ActualArgs;
Daniel Dunbar46f45b92008-09-09 01:06:48 +00001185 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
1186 ActualArgs.push_back(std::make_pair(RValue::get(EmitSelector(CGF.Builder,
1187 Sel)),
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001188 CGF.getContext().getObjCSelType()));
1189 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001190
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001191 CodeGenTypes &Types = CGM.getTypes();
1192 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs);
1193 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo, false);
Daniel Dunbar5669e572008-10-17 03:24:53 +00001194
1195 llvm::Constant *Fn;
Daniel Dunbar88b53962009-02-02 22:03:45 +00001196 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Daniel Dunbar5669e572008-10-17 03:24:53 +00001197 Fn = ObjCTypes.getSendStretFn(IsSuper);
1198 } else if (ResultType->isFloatingType()) {
1199 // FIXME: Sadly, this is wrong. This actually depends on the
1200 // architecture. This happens to be right for x86-32 though.
1201 Fn = ObjCTypes.getSendFpretFn(IsSuper);
1202 } else {
1203 Fn = ObjCTypes.getSendFn(IsSuper);
1204 }
Daniel Dunbar62d5c1b2008-09-10 07:00:50 +00001205 Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy));
Daniel Dunbar88b53962009-02-02 22:03:45 +00001206 return CGF.EmitCall(FnInfo, Fn, ActualArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001207}
1208
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001209llvm::Value *CGObjCMac::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001210 const ObjCProtocolDecl *PD) {
Daniel Dunbarc67876d2008-09-04 04:33:15 +00001211 // FIXME: I don't understand why gcc generates this, or where it is
1212 // resolved. Investigate. Its also wasteful to look this up over and
1213 // over.
1214 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1215
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001216 return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
1217 ObjCTypes.ExternalProtocolPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001218}
1219
Fariborz Jahanianda320092009-01-29 19:24:30 +00001220void CGObjCCommonMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001221 // FIXME: We shouldn't need this, the protocol decl should contain
1222 // enough information to tell us whether this was a declaration or a
1223 // definition.
1224 DefinedProtocols.insert(PD->getIdentifier());
1225
1226 // If we have generated a forward reference to this protocol, emit
1227 // it now. Otherwise do nothing, the protocol objects are lazily
1228 // emitted.
1229 if (Protocols.count(PD->getIdentifier()))
1230 GetOrEmitProtocol(PD);
1231}
1232
Fariborz Jahanianda320092009-01-29 19:24:30 +00001233llvm::Constant *CGObjCCommonMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001234 if (DefinedProtocols.count(PD->getIdentifier()))
1235 return GetOrEmitProtocol(PD);
1236 return GetOrEmitProtocolRef(PD);
1237}
1238
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001239/*
1240 // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions
1241 struct _objc_protocol {
1242 struct _objc_protocol_extension *isa;
1243 char *protocol_name;
1244 struct _objc_protocol_list *protocol_list;
1245 struct _objc__method_prototype_list *instance_methods;
1246 struct _objc__method_prototype_list *class_methods
1247 };
1248
1249 See EmitProtocolExtension().
1250*/
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001251llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
1252 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1253
1254 // Early exit if a defining object has already been generated.
1255 if (Entry && Entry->hasInitializer())
1256 return Entry;
1257
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001258 // FIXME: I don't understand why gcc generates this, or where it is
1259 // resolved. Investigate. Its also wasteful to look this up over and
1260 // over.
1261 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1262
Chris Lattner8ec03f52008-11-24 03:54:41 +00001263 const char *ProtocolName = PD->getNameAsCString();
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001264
1265 // Construct method lists.
1266 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1267 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregor6ab35242009-04-09 21:40:53 +00001268 for (ObjCProtocolDecl::instmeth_iterator
1269 i = PD->instmeth_begin(CGM.getContext()),
1270 e = PD->instmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001271 ObjCMethodDecl *MD = *i;
1272 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1273 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1274 OptInstanceMethods.push_back(C);
1275 } else {
1276 InstanceMethods.push_back(C);
1277 }
1278 }
1279
Douglas Gregor6ab35242009-04-09 21:40:53 +00001280 for (ObjCProtocolDecl::classmeth_iterator
1281 i = PD->classmeth_begin(CGM.getContext()),
1282 e = PD->classmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001283 ObjCMethodDecl *MD = *i;
1284 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1285 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1286 OptClassMethods.push_back(C);
1287 } else {
1288 ClassMethods.push_back(C);
1289 }
1290 }
1291
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001292 std::vector<llvm::Constant*> Values(5);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001293 Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001294 Values[1] = GetClassName(PD->getIdentifier());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001295 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001296 EmitProtocolList("\01L_OBJC_PROTOCOL_REFS_" + PD->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001297 PD->protocol_begin(),
1298 PD->protocol_end());
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001299 Values[3] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001300 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_"
1301 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001302 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1303 InstanceMethods);
1304 Values[4] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001305 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_"
1306 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001307 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1308 ClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001309 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
1310 Values);
1311
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001312 if (Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001313 // Already created, fix the linkage and update the initializer.
1314 Entry->setLinkage(llvm::GlobalValue::InternalLinkage);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001315 Entry->setInitializer(Init);
1316 } else {
1317 Entry =
1318 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
1319 llvm::GlobalValue::InternalLinkage,
1320 Init,
1321 std::string("\01L_OBJC_PROTOCOL_")+ProtocolName,
1322 &CGM.getModule());
1323 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001324 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001325 UsedGlobals.push_back(Entry);
1326 // FIXME: Is this necessary? Why only for protocol?
1327 Entry->setAlignment(4);
1328 }
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001329
1330 return Entry;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001331}
1332
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001333llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001334 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1335
1336 if (!Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001337 // We use the initializer as a marker of whether this is a forward
1338 // reference or not. At module finalization we add the empty
1339 // contents for protocols which were referenced but never defined.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001340 Entry =
1341 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001342 llvm::GlobalValue::ExternalLinkage,
1343 0,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001344 "\01L_OBJC_PROTOCOL_" + PD->getNameAsString(),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001345 &CGM.getModule());
1346 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001347 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001348 UsedGlobals.push_back(Entry);
1349 // FIXME: Is this necessary? Why only for protocol?
1350 Entry->setAlignment(4);
1351 }
1352
1353 return Entry;
1354}
1355
1356/*
1357 struct _objc_protocol_extension {
1358 uint32_t size;
1359 struct objc_method_description_list *optional_instance_methods;
1360 struct objc_method_description_list *optional_class_methods;
1361 struct objc_property_list *instance_properties;
1362 };
1363*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001364llvm::Constant *
1365CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
1366 const ConstantVector &OptInstanceMethods,
1367 const ConstantVector &OptClassMethods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001368 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001369 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolExtensionTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001370 std::vector<llvm::Constant*> Values(4);
1371 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001372 Values[1] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001373 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_"
1374 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001375 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1376 OptInstanceMethods);
1377 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001378 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_"
1379 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001380 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1381 OptClassMethods);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001382 Values[3] = EmitPropertyList("\01L_OBJC_$_PROP_PROTO_LIST_" +
1383 PD->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001384 0, PD, ObjCTypes);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001385
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001386 // Return null if no extension bits are used.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001387 if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
1388 Values[3]->isNullValue())
1389 return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
1390
1391 llvm::Constant *Init =
1392 llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001393
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001394 // No special section, but goes in llvm.used
1395 return CreateMetadataVar("\01L_OBJC_PROTOCOLEXT_" + PD->getNameAsString(),
1396 Init,
1397 0, 0, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001398}
1399
1400/*
1401 struct objc_protocol_list {
1402 struct objc_protocol_list *next;
1403 long count;
1404 Protocol *list[];
1405 };
1406*/
Daniel Dunbardbc933702008-08-21 21:57:41 +00001407llvm::Constant *
1408CGObjCMac::EmitProtocolList(const std::string &Name,
1409 ObjCProtocolDecl::protocol_iterator begin,
1410 ObjCProtocolDecl::protocol_iterator end) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001411 std::vector<llvm::Constant*> ProtocolRefs;
1412
Daniel Dunbardbc933702008-08-21 21:57:41 +00001413 for (; begin != end; ++begin)
1414 ProtocolRefs.push_back(GetProtocolRef(*begin));
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001415
1416 // Just return null for empty protocol lists
1417 if (ProtocolRefs.empty())
1418 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1419
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001420 // This list is null terminated.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001421 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
1422
1423 std::vector<llvm::Constant*> Values(3);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001424 // This field is only used by the runtime.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001425 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1426 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
1427 Values[2] =
1428 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
1429 ProtocolRefs.size()),
1430 ProtocolRefs);
1431
1432 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1433 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001434 CreateMetadataVar(Name, Init, "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001435 4, false);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001436 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
1437}
1438
1439/*
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001440 struct _objc_property {
1441 const char * const name;
1442 const char * const attributes;
1443 };
1444
1445 struct _objc_property_list {
1446 uint32_t entsize; // sizeof (struct _objc_property)
1447 uint32_t prop_count;
1448 struct _objc_property[prop_count];
1449 };
1450*/
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001451llvm::Constant *CGObjCCommonMac::EmitPropertyList(const std::string &Name,
1452 const Decl *Container,
1453 const ObjCContainerDecl *OCD,
1454 const ObjCCommonTypesHelper &ObjCTypes) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001455 std::vector<llvm::Constant*> Properties, Prop(2);
Douglas Gregor6ab35242009-04-09 21:40:53 +00001456 for (ObjCContainerDecl::prop_iterator I = OCD->prop_begin(CGM.getContext()),
1457 E = OCD->prop_end(CGM.getContext()); I != E; ++I) {
Steve Naroff93983f82009-01-11 12:47:58 +00001458 const ObjCPropertyDecl *PD = *I;
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001459 Prop[0] = GetPropertyName(PD->getIdentifier());
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00001460 Prop[1] = GetPropertyTypeString(PD, Container);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001461 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
1462 Prop));
1463 }
1464
1465 // Return null for empty list.
1466 if (Properties.empty())
1467 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1468
1469 unsigned PropertySize =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001470 CGM.getTargetData().getTypePaddedSize(ObjCTypes.PropertyTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001471 std::vector<llvm::Constant*> Values(3);
1472 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
1473 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
1474 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
1475 Properties.size());
1476 Values[2] = llvm::ConstantArray::get(AT, Properties);
1477 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1478
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001479 llvm::GlobalVariable *GV =
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001480 CreateMetadataVar(Name, Init,
1481 (ObjCABI == 2) ? "__DATA, __objc_const" :
1482 "__OBJC,__property,regular,no_dead_strip",
1483 (ObjCABI == 2) ? 8 : 4,
1484 true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001485 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.PropertyListPtrTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001486}
1487
1488/*
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001489 struct objc_method_description_list {
1490 int count;
1491 struct objc_method_description list[];
1492 };
1493*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001494llvm::Constant *
1495CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
1496 std::vector<llvm::Constant*> Desc(2);
1497 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1498 ObjCTypes.SelectorPtrTy);
1499 Desc[1] = GetMethodVarType(MD);
1500 return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
1501 Desc);
1502}
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001503
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001504llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name,
1505 const char *Section,
1506 const ConstantVector &Methods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001507 // Return null for empty list.
1508 if (Methods.empty())
1509 return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
1510
1511 std::vector<llvm::Constant*> Values(2);
1512 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1513 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
1514 Methods.size());
1515 Values[1] = llvm::ConstantArray::get(AT, Methods);
1516 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1517
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001518 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001519 return llvm::ConstantExpr::getBitCast(GV,
1520 ObjCTypes.MethodDescriptionListPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001521}
1522
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001523/*
1524 struct _objc_category {
1525 char *category_name;
1526 char *class_name;
1527 struct _objc_method_list *instance_methods;
1528 struct _objc_method_list *class_methods;
1529 struct _objc_protocol_list *protocols;
1530 uint32_t size; // <rdar://4585769>
1531 struct _objc_property_list *instance_properties;
1532 };
1533 */
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001534void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001535 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.CategoryTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001536
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001537 // FIXME: This is poor design, the OCD should have a pointer to the
1538 // category decl. Additionally, note that Category can be null for
1539 // the @implementation w/o an @interface case. Sema should just
1540 // create one for us as it does for @implementation so everyone else
1541 // can live life under a clear blue sky.
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001542 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001543 const ObjCCategoryDecl *Category =
1544 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001545 std::string ExtName(Interface->getNameAsString() + "_" +
1546 OCD->getNameAsString());
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001547
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001548 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1549 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
1550 e = OCD->instmeth_end(); i != e; ++i) {
1551 // Instance methods should always be defined.
1552 InstanceMethods.push_back(GetMethodConstant(*i));
1553 }
1554 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
1555 e = OCD->classmeth_end(); i != e; ++i) {
1556 // Class methods should always be defined.
1557 ClassMethods.push_back(GetMethodConstant(*i));
1558 }
1559
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001560 std::vector<llvm::Constant*> Values(7);
1561 Values[0] = GetClassName(OCD->getIdentifier());
1562 Values[1] = GetClassName(Interface->getIdentifier());
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001563 Values[2] =
1564 EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") +
1565 ExtName,
1566 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001567 InstanceMethods);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001568 Values[3] =
1569 EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName,
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001570 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001571 ClassMethods);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001572 if (Category) {
1573 Values[4] =
1574 EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName,
1575 Category->protocol_begin(),
1576 Category->protocol_end());
1577 } else {
1578 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1579 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001580 Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001581
1582 // If there is no category @interface then there can be no properties.
1583 if (Category) {
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001584 Values[6] = EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001585 OCD, Category, ObjCTypes);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001586 } else {
1587 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1588 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001589
1590 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
1591 Values);
1592
1593 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001594 CreateMetadataVar(std::string("\01L_OBJC_CATEGORY_")+ExtName, Init,
1595 "__OBJC,__category,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001596 4, true);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001597 DefinedCategories.push_back(GV);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001598}
1599
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001600// FIXME: Get from somewhere?
1601enum ClassFlags {
1602 eClassFlags_Factory = 0x00001,
1603 eClassFlags_Meta = 0x00002,
1604 // <rdr://5142207>
1605 eClassFlags_HasCXXStructors = 0x02000,
1606 eClassFlags_Hidden = 0x20000,
1607 eClassFlags_ABI2_Hidden = 0x00010,
1608 eClassFlags_ABI2_HasCXXStructors = 0x00004 // <rdr://4923634>
1609};
1610
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001611/*
1612 struct _objc_class {
1613 Class isa;
1614 Class super_class;
1615 const char *name;
1616 long version;
1617 long info;
1618 long instance_size;
1619 struct _objc_ivar_list *ivars;
1620 struct _objc_method_list *methods;
1621 struct _objc_cache *cache;
1622 struct _objc_protocol_list *protocols;
1623 // Objective-C 1.0 extensions (<rdr://4585769>)
1624 const char *ivar_layout;
1625 struct _objc_class_ext *ext;
1626 };
1627
1628 See EmitClassExtension();
1629 */
1630void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001631 DefinedSymbols.insert(ID->getIdentifier());
1632
Chris Lattner8ec03f52008-11-24 03:54:41 +00001633 std::string ClassName = ID->getNameAsString();
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001634 // FIXME: Gross
1635 ObjCInterfaceDecl *Interface =
1636 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001637 llvm::Constant *Protocols =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001638 EmitProtocolList("\01L_OBJC_CLASS_PROTOCOLS_" + ID->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001639 Interface->protocol_begin(),
1640 Interface->protocol_end());
Chris Lattnerb7b58b12009-04-19 06:02:28 +00001641 const llvm::Type *InterfaceTy;
1642 if (Interface->isForwardDecl())
1643 InterfaceTy = llvm::StructType::get(NULL, NULL);
1644 else
1645 InterfaceTy =
Chris Lattner03d9f342009-04-01 06:23:52 +00001646 CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(Interface));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001647 unsigned Flags = eClassFlags_Factory;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001648 unsigned Size = CGM.getTargetData().getTypePaddedSize(InterfaceTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001649
1650 // FIXME: Set CXX-structors flag.
Daniel Dunbar04d40782009-04-14 06:00:08 +00001651 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001652 Flags |= eClassFlags_Hidden;
1653
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001654 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1655 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
1656 e = ID->instmeth_end(); i != e; ++i) {
1657 // Instance methods should always be defined.
1658 InstanceMethods.push_back(GetMethodConstant(*i));
1659 }
1660 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
1661 e = ID->classmeth_end(); i != e; ++i) {
1662 // Class methods should always be defined.
1663 ClassMethods.push_back(GetMethodConstant(*i));
1664 }
1665
1666 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
1667 e = ID->propimpl_end(); i != e; ++i) {
1668 ObjCPropertyImplDecl *PID = *i;
1669
1670 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1671 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1672
1673 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
1674 if (llvm::Constant *C = GetMethodConstant(MD))
1675 InstanceMethods.push_back(C);
1676 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
1677 if (llvm::Constant *C = GetMethodConstant(MD))
1678 InstanceMethods.push_back(C);
1679 }
1680 }
1681
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001682 std::vector<llvm::Constant*> Values(12);
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001683 Values[ 0] = EmitMetaClass(ID, Protocols, InterfaceTy, ClassMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001684 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001685 // Record a reference to the super class.
1686 LazySymbols.insert(Super->getIdentifier());
1687
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001688 Values[ 1] =
1689 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1690 ObjCTypes.ClassPtrTy);
1691 } else {
1692 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1693 }
1694 Values[ 2] = GetClassName(ID->getIdentifier());
1695 // Version is always 0.
1696 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1697 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1698 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001699 Values[ 6] = EmitIvarList(ID, false);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001700 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001701 EmitMethodList("\01L_OBJC_INSTANCE_METHODS_" + ID->getNameAsString(),
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001702 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001703 InstanceMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001704 // cache is always NULL.
1705 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1706 Values[ 9] = Protocols;
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001707 // FIXME: Set ivar_layout
Fariborz Jahanian667423a2009-03-25 22:36:49 +00001708 // Values[10] = BuildIvarLayout(ID, true);
1709 Values[10] = GetIvarLayoutName(0, ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001710 Values[11] = EmitClassExtension(ID);
1711 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1712 Values);
1713
1714 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001715 CreateMetadataVar(std::string("\01L_OBJC_CLASS_")+ClassName, Init,
1716 "__OBJC,__class,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001717 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001718 DefinedClasses.push_back(GV);
1719}
1720
1721llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
1722 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001723 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001724 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001725 unsigned Flags = eClassFlags_Meta;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001726 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001727
Daniel Dunbar04d40782009-04-14 06:00:08 +00001728 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001729 Flags |= eClassFlags_Hidden;
1730
1731 std::vector<llvm::Constant*> Values(12);
1732 // The isa for the metaclass is the root of the hierarchy.
1733 const ObjCInterfaceDecl *Root = ID->getClassInterface();
1734 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
1735 Root = Super;
1736 Values[ 0] =
1737 llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
1738 ObjCTypes.ClassPtrTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001739 // The super class for the metaclass is emitted as the name of the
1740 // super class. The runtime fixes this up to point to the
1741 // *metaclass* for the super class.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001742 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
1743 Values[ 1] =
1744 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1745 ObjCTypes.ClassPtrTy);
1746 } else {
1747 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1748 }
1749 Values[ 2] = GetClassName(ID->getIdentifier());
1750 // Version is always 0.
1751 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1752 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1753 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001754 Values[ 6] = EmitIvarList(ID, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001755 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001756 EmitMethodList("\01L_OBJC_CLASS_METHODS_" + ID->getNameAsString(),
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001757 "__OBJC,__cls_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001758 Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001759 // cache is always NULL.
1760 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1761 Values[ 9] = Protocols;
1762 // ivar_layout for metaclass is always NULL.
1763 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1764 // The class extension is always unused for metaclasses.
1765 Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1766 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1767 Values);
1768
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001769 std::string Name("\01L_OBJC_METACLASS_");
Chris Lattner8ec03f52008-11-24 03:54:41 +00001770 Name += ID->getNameAsCString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001771
1772 // Check for a forward reference.
1773 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
1774 if (GV) {
1775 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1776 "Forward metaclass reference has incorrect type.");
1777 GV->setLinkage(llvm::GlobalValue::InternalLinkage);
1778 GV->setInitializer(Init);
1779 } else {
1780 GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1781 llvm::GlobalValue::InternalLinkage,
1782 Init, Name,
1783 &CGM.getModule());
1784 }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001785 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001786 GV->setAlignment(4);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001787 UsedGlobals.push_back(GV);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001788
1789 return GV;
1790}
1791
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001792llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001793 std::string Name = "\01L_OBJC_METACLASS_" + ID->getNameAsString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001794
1795 // FIXME: Should we look these up somewhere other than the
1796 // module. Its a bit silly since we only generate these while
1797 // processing an implementation, so exactly one pointer would work
1798 // if know when we entered/exitted an implementation block.
1799
1800 // Check for an existing forward reference.
Fariborz Jahanianb0d27942009-01-07 20:11:22 +00001801 // Previously, metaclass with internal linkage may have been defined.
1802 // pass 'true' as 2nd argument so it is returned.
1803 if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true)) {
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001804 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1805 "Forward metaclass reference has incorrect type.");
1806 return GV;
1807 } else {
1808 // Generate as an external reference to keep a consistent
1809 // module. This will be patched up when we emit the metaclass.
1810 return new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1811 llvm::GlobalValue::ExternalLinkage,
1812 0,
1813 Name,
1814 &CGM.getModule());
1815 }
1816}
1817
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001818/*
1819 struct objc_class_ext {
1820 uint32_t size;
1821 const char *weak_ivar_layout;
1822 struct _objc_property_list *properties;
1823 };
1824*/
1825llvm::Constant *
1826CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
1827 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001828 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassExtensionTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001829
1830 std::vector<llvm::Constant*> Values(3);
1831 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001832 // FIXME: Output weak_ivar_layout string.
Fariborz Jahanian667423a2009-03-25 22:36:49 +00001833 // Values[1] = BuildIvarLayout(ID, false);
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00001834 Values[1] = GetIvarLayoutName(0, ObjCTypes);
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001835 Values[2] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001836 ID, ID->getClassInterface(), ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001837
1838 // Return null if no extension bits are used.
1839 if (Values[1]->isNullValue() && Values[2]->isNullValue())
1840 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1841
1842 llvm::Constant *Init =
1843 llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001844 return CreateMetadataVar("\01L_OBJC_CLASSEXT_" + ID->getNameAsString(),
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001845 Init, "__OBJC,__class_ext,regular,no_dead_strip",
1846 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001847}
1848
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001849/// getInterfaceDeclForIvar - Get the interface declaration node where
1850/// this ivar is declared in.
1851/// FIXME. Ideally, this info should be in the ivar node. But currently
1852/// it is not and prevailing wisdom is that ASTs should not have more
1853/// info than is absolutely needed, even though this info reflects the
1854/// source language.
1855///
1856static const ObjCInterfaceDecl *getInterfaceDeclForIvar(
1857 const ObjCInterfaceDecl *OI,
Douglas Gregor6ab35242009-04-09 21:40:53 +00001858 const ObjCIvarDecl *IVD,
1859 ASTContext &Context) {
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001860 if (!OI)
1861 return 0;
1862 assert(isa<ObjCInterfaceDecl>(OI) && "OI is not an interface");
1863 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1864 E = OI->ivar_end(); I != E; ++I)
1865 if ((*I)->getIdentifier() == IVD->getIdentifier())
1866 return OI;
Fariborz Jahanian5a4b4532009-03-31 17:00:52 +00001867 // look into properties.
Douglas Gregor6ab35242009-04-09 21:40:53 +00001868 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(Context),
1869 E = OI->prop_end(Context); I != E; ++I) {
Fariborz Jahanian5a4b4532009-03-31 17:00:52 +00001870 ObjCPropertyDecl *PDecl = (*I);
1871 if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl())
1872 if (IV->getIdentifier() == IVD->getIdentifier())
1873 return OI;
1874 }
Douglas Gregor6ab35242009-04-09 21:40:53 +00001875 return getInterfaceDeclForIvar(OI->getSuperClass(), IVD, Context);
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001876}
1877
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001878/*
1879 struct objc_ivar {
1880 char *ivar_name;
1881 char *ivar_type;
1882 int ivar_offset;
1883 };
1884
1885 struct objc_ivar_list {
1886 int ivar_count;
1887 struct objc_ivar list[count];
1888 };
1889 */
1890llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001891 bool ForClass) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001892 std::vector<llvm::Constant*> Ivars, Ivar(3);
1893
1894 // When emitting the root class GCC emits ivar entries for the
1895 // actual class structure. It is not clear if we need to follow this
1896 // behavior; for now lets try and get away with not doing it. If so,
1897 // the cleanest solution would be to make up an ObjCInterfaceDecl
1898 // for the class.
1899 if (ForClass)
1900 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001901
1902 ObjCInterfaceDecl *OID =
1903 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00001904 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001905
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00001906 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
1907 GetNamedIvarList(OID, OIvars);
1908
1909 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
1910 ObjCIvarDecl *IVD = OIvars[i];
1911 const FieldDecl *Field = OID->lookupFieldDeclForIvar(CGM.getContext(), IVD);
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00001912 Ivar[0] = GetMethodVarName(Field->getIdentifier());
Devang Patel7794bb82009-03-04 18:21:39 +00001913 Ivar[1] = GetMethodVarType(Field);
Daniel Dunbar6c1aac82009-04-20 20:18:54 +00001914 Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy,
1915 GetIvarBaseOffset(Layout, Field));
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001916 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001917 }
1918
1919 // Return null for empty list.
1920 if (Ivars.empty())
1921 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
1922
1923 std::vector<llvm::Constant*> Values(2);
1924 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
1925 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
1926 Ivars.size());
1927 Values[1] = llvm::ConstantArray::get(AT, Ivars);
1928 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1929
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001930 llvm::GlobalVariable *GV;
1931 if (ForClass)
1932 GV = CreateMetadataVar("\01L_OBJC_CLASS_VARIABLES_" + ID->getNameAsString(),
Daniel Dunbar58a29122009-03-09 22:18:41 +00001933 Init, "__OBJC,__class_vars,regular,no_dead_strip",
1934 4, true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001935 else
1936 GV = CreateMetadataVar("\01L_OBJC_INSTANCE_VARIABLES_"
1937 + ID->getNameAsString(),
1938 Init, "__OBJC,__instance_vars,regular,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001939 4, true);
1940 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.IvarListPtrTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001941}
1942
1943/*
1944 struct objc_method {
1945 SEL method_name;
1946 char *method_types;
1947 void *method;
1948 };
1949
1950 struct objc_method_list {
1951 struct objc_method_list *obsolete;
1952 int count;
1953 struct objc_method methods_list[count];
1954 };
1955*/
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001956
1957/// GetMethodConstant - Return a struct objc_method constant for the
1958/// given method if it has been defined. The result is null if the
1959/// method has not been defined. The return value has type MethodPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001960llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001961 // FIXME: Use DenseMap::lookup
1962 llvm::Function *Fn = MethodDefinitions[MD];
1963 if (!Fn)
1964 return 0;
1965
1966 std::vector<llvm::Constant*> Method(3);
1967 Method[0] =
1968 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1969 ObjCTypes.SelectorPtrTy);
1970 Method[1] = GetMethodVarType(MD);
1971 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
1972 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
1973}
1974
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001975llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name,
1976 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001977 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001978 // Return null for empty list.
1979 if (Methods.empty())
1980 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
1981
1982 std::vector<llvm::Constant*> Values(3);
1983 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1984 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1985 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
1986 Methods.size());
1987 Values[2] = llvm::ConstantArray::get(AT, Methods);
1988 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1989
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001990 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001991 return llvm::ConstantExpr::getBitCast(GV,
1992 ObjCTypes.MethodListPtrTy);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001993}
1994
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001995llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD,
Daniel Dunbarbb36d332009-02-02 21:43:58 +00001996 const ObjCContainerDecl *CD) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001997 std::string Name;
Fariborz Jahanian679a5022009-01-10 21:06:09 +00001998 GetNameForMethod(OMD, CD, Name);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001999
Daniel Dunbar541b63b2009-02-02 23:23:47 +00002000 CodeGenTypes &Types = CGM.getTypes();
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00002001 const llvm::FunctionType *MethodTy =
Daniel Dunbar541b63b2009-02-02 23:23:47 +00002002 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002003 llvm::Function *Method =
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00002004 llvm::Function::Create(MethodTy,
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002005 llvm::GlobalValue::InternalLinkage,
2006 Name,
2007 &CGM.getModule());
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002008 MethodDefinitions.insert(std::make_pair(OMD, Method));
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002009
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002010 return Method;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00002011}
2012
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00002013uint64_t CGObjCCommonMac::GetIvarBaseOffset(const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +00002014 const FieldDecl *Field) {
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00002015 if (!Field->isBitField())
Daniel Dunbar48fa0642009-04-19 02:03:42 +00002016 return Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(Field));
2017
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00002018 // FIXME. Must be a better way of getting a bitfield base offset.
Daniel Dunbar48fa0642009-04-19 02:03:42 +00002019 CodeGenTypes::BitFieldInfo BFI = CGM.getTypes().getBitFieldInfo(Field);
2020 // FIXME: The "field no" for bitfields is something completely
2021 // different; it is the offset in multiples of the base type size!
2022 uint64_t Offset = CGM.getTypes().getLLVMFieldNo(Field);
2023 const llvm::Type *Ty =
2024 CGM.getTypes().ConvertTypeForMemRecursive(Field->getType());
2025 Offset *= CGM.getTypes().getTargetData().getTypePaddedSizeInBits(Ty);
2026 return (Offset + BFI.Begin) / 8;
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00002027}
2028
Daniel Dunbar48fa0642009-04-19 02:03:42 +00002029/// GetFieldBaseOffset - return the field's byte offset.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002030uint64_t CGObjCCommonMac::GetFieldBaseOffset(const ObjCInterfaceDecl *OI,
2031 const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +00002032 const FieldDecl *Field) {
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00002033 // Is this a c struct?
2034 if (!OI)
2035 return Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(Field));
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002036 const ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
Chris Lattnercd0ee142009-03-31 08:33:16 +00002037 const FieldDecl *FD = OI->lookupFieldDeclForIvar(CGM.getContext(), Ivar);
2038 return GetIvarBaseOffset(Layout, FD);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002039}
2040
Daniel Dunbarfd65d372009-03-09 20:09:19 +00002041llvm::GlobalVariable *
2042CGObjCCommonMac::CreateMetadataVar(const std::string &Name,
2043 llvm::Constant *Init,
2044 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +00002045 unsigned Align,
2046 bool AddToUsed) {
Daniel Dunbarfd65d372009-03-09 20:09:19 +00002047 const llvm::Type *Ty = Init->getType();
2048 llvm::GlobalVariable *GV =
2049 new llvm::GlobalVariable(Ty, false,
2050 llvm::GlobalValue::InternalLinkage,
2051 Init,
2052 Name,
2053 &CGM.getModule());
2054 if (Section)
2055 GV->setSection(Section);
Daniel Dunbar35bd7632009-03-09 20:50:13 +00002056 if (Align)
2057 GV->setAlignment(Align);
2058 if (AddToUsed)
Daniel Dunbarfd65d372009-03-09 20:09:19 +00002059 UsedGlobals.push_back(GV);
2060 return GV;
2061}
2062
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00002063llvm::Function *CGObjCMac::ModuleInitFunction() {
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002064 // Abuse this interface function as a place to finalize.
2065 FinishModule();
2066
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00002067 return NULL;
2068}
2069
Chris Lattner74391b42009-03-22 21:03:39 +00002070llvm::Constant *CGObjCMac::GetPropertyGetFunction() {
Daniel Dunbar49f66022008-09-24 03:38:44 +00002071 return ObjCTypes.GetPropertyFn;
2072}
2073
Chris Lattner74391b42009-03-22 21:03:39 +00002074llvm::Constant *CGObjCMac::GetPropertySetFunction() {
Daniel Dunbar49f66022008-09-24 03:38:44 +00002075 return ObjCTypes.SetPropertyFn;
2076}
2077
Chris Lattner74391b42009-03-22 21:03:39 +00002078llvm::Constant *CGObjCMac::EnumerationMutationFunction() {
Anders Carlsson2abd89c2008-08-31 04:05:03 +00002079 return ObjCTypes.EnumerationMutationFn;
2080}
2081
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002082/*
2083
2084Objective-C setjmp-longjmp (sjlj) Exception Handling
2085--
2086
2087The basic framework for a @try-catch-finally is as follows:
2088{
2089 objc_exception_data d;
2090 id _rethrow = null;
Anders Carlsson190d00e2009-02-07 21:26:04 +00002091 bool _call_try_exit = true;
2092
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002093 objc_exception_try_enter(&d);
2094 if (!setjmp(d.jmp_buf)) {
2095 ... try body ...
2096 } else {
2097 // exception path
2098 id _caught = objc_exception_extract(&d);
2099
2100 // enter new try scope for handlers
2101 if (!setjmp(d.jmp_buf)) {
2102 ... match exception and execute catch blocks ...
2103
2104 // fell off end, rethrow.
2105 _rethrow = _caught;
Daniel Dunbar898d5082008-09-30 01:06:03 +00002106 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002107 } else {
2108 // exception in catch block
2109 _rethrow = objc_exception_extract(&d);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002110 _call_try_exit = false;
2111 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002112 }
2113 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00002114 ... jump-through-finally to finally_end ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002115
2116finally:
Anders Carlsson190d00e2009-02-07 21:26:04 +00002117 if (_call_try_exit)
2118 objc_exception_try_exit(&d);
2119
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002120 ... finally block ....
Daniel Dunbar898d5082008-09-30 01:06:03 +00002121 ... dispatch to finally destination ...
2122
2123finally_rethrow:
2124 objc_exception_throw(_rethrow);
2125
2126finally_end:
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002127}
2128
2129This framework differs slightly from the one gcc uses, in that gcc
Daniel Dunbar898d5082008-09-30 01:06:03 +00002130uses _rethrow to determine if objc_exception_try_exit should be called
2131and if the object should be rethrown. This breaks in the face of
2132throwing nil and introduces unnecessary branches.
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002133
2134We specialize this framework for a few particular circumstances:
2135
2136 - If there are no catch blocks, then we avoid emitting the second
2137 exception handling context.
2138
2139 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
2140 e)) we avoid emitting the code to rethrow an uncaught exception.
2141
2142 - FIXME: If there is no @finally block we can do a few more
2143 simplifications.
2144
2145Rethrows and Jumps-Through-Finally
2146--
2147
2148Support for implicit rethrows and jumping through the finally block is
2149handled by storing the current exception-handling context in
2150ObjCEHStack.
2151
Daniel Dunbar898d5082008-09-30 01:06:03 +00002152In order to implement proper @finally semantics, we support one basic
2153mechanism for jumping through the finally block to an arbitrary
2154destination. Constructs which generate exits from a @try or @catch
2155block use this mechanism to implement the proper semantics by chaining
2156jumps, as necessary.
2157
2158This mechanism works like the one used for indirect goto: we
2159arbitrarily assign an ID to each destination and store the ID for the
2160destination in a variable prior to entering the finally block. At the
2161end of the finally block we simply create a switch to the proper
2162destination.
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002163
2164Code gen for @synchronized(expr) stmt;
2165Effectively generating code for:
2166objc_sync_enter(expr);
2167@try stmt @finally { objc_sync_exit(expr); }
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002168*/
2169
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002170void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
2171 const Stmt &S) {
2172 bool isTry = isa<ObjCAtTryStmt>(S);
Daniel Dunbar898d5082008-09-30 01:06:03 +00002173 // Create various blocks we refer to for handling @finally.
Daniel Dunbar55e87422008-11-11 02:29:29 +00002174 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002175 llvm::BasicBlock *FinallyExit = CGF.createBasicBlock("finally.exit");
Daniel Dunbar55e87422008-11-11 02:29:29 +00002176 llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
2177 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
2178 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
Daniel Dunbar1c566672009-02-24 01:43:46 +00002179
2180 // For @synchronized, call objc_sync_enter(sync.expr). The
2181 // evaluation of the expression must occur before we enter the
2182 // @synchronized. We can safely avoid a temp here because jumps into
2183 // @synchronized are illegal & this will dominate uses.
2184 llvm::Value *SyncArg = 0;
2185 if (!isTry) {
2186 SyncArg =
2187 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
2188 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00002189 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar1c566672009-02-24 01:43:46 +00002190 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00002191
2192 // Push an EH context entry, used for handling rethrows and jumps
2193 // through finally.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002194 CGF.PushCleanupBlock(FinallyBlock);
2195
Anders Carlsson273558f2009-02-07 21:37:21 +00002196 CGF.ObjCEHValueStack.push_back(0);
2197
Daniel Dunbar898d5082008-09-30 01:06:03 +00002198 // Allocate memory for the exception data and rethrow pointer.
Anders Carlsson80f25672008-09-09 17:59:25 +00002199 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
2200 "exceptiondata.ptr");
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002201 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
2202 "_rethrow");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002203 llvm::Value *CallTryExitPtr = CGF.CreateTempAlloca(llvm::Type::Int1Ty,
2204 "_call_try_exit");
2205 CGF.Builder.CreateStore(llvm::ConstantInt::getTrue(), CallTryExitPtr);
2206
Anders Carlsson80f25672008-09-09 17:59:25 +00002207 // Enter a new try block and call setjmp.
Chris Lattner34b02a12009-04-22 02:26:14 +00002208 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryEnterFn(), ExceptionData);
Anders Carlsson80f25672008-09-09 17:59:25 +00002209 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
2210 "jmpbufarray");
2211 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
Chris Lattner34b02a12009-04-22 02:26:14 +00002212 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.getSetJmpFn(),
Anders Carlsson80f25672008-09-09 17:59:25 +00002213 JmpBufPtr, "result");
Daniel Dunbar898d5082008-09-30 01:06:03 +00002214
Daniel Dunbar55e87422008-11-11 02:29:29 +00002215 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
2216 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002217 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002218 TryHandler, TryBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002219
2220 // Emit the @try block.
2221 CGF.EmitBlock(TryBlock);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002222 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
2223 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002224 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002225
2226 // Emit the "exception in @try" block.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002227 CGF.EmitBlock(TryHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002228
2229 // Retrieve the exception object. We may emit multiple blocks but
2230 // nothing can cross this so the value is already in SSA form.
Chris Lattner34b02a12009-04-22 02:26:14 +00002231 llvm::Value *Caught =
2232 CGF.Builder.CreateCall(ObjCTypes.getExceptionExtractFn(),
2233 ExceptionData, "caught");
Anders Carlsson273558f2009-02-07 21:37:21 +00002234 CGF.ObjCEHValueStack.back() = Caught;
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002235 if (!isTry)
2236 {
2237 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002238 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002239 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002240 }
2241 else if (const ObjCAtCatchStmt* CatchStmt =
2242 cast<ObjCAtTryStmt>(S).getCatchStmts())
2243 {
Daniel Dunbar55e40722008-09-27 07:03:52 +00002244 // Enter a new exception try block (in case a @catch block throws
2245 // an exception).
Chris Lattner34b02a12009-04-22 02:26:14 +00002246 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryEnterFn(), ExceptionData);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002247
Chris Lattner34b02a12009-04-22 02:26:14 +00002248 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.getSetJmpFn(),
Anders Carlsson80f25672008-09-09 17:59:25 +00002249 JmpBufPtr, "result");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002250 llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw");
Anders Carlsson80f25672008-09-09 17:59:25 +00002251
Daniel Dunbar55e87422008-11-11 02:29:29 +00002252 llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch");
2253 llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler");
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002254 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002255
2256 CGF.EmitBlock(CatchBlock);
2257
Daniel Dunbar55e40722008-09-27 07:03:52 +00002258 // Handle catch list. As a special case we check if everything is
2259 // matched and avoid generating code for falling off the end if
2260 // so.
2261 bool AllMatched = false;
Anders Carlsson80f25672008-09-09 17:59:25 +00002262 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbar55e87422008-11-11 02:29:29 +00002263 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch");
Anders Carlsson80f25672008-09-09 17:59:25 +00002264
Steve Naroff7ba138a2009-03-03 19:52:17 +00002265 const ParmVarDecl *CatchParam = CatchStmt->getCatchParamDecl();
Daniel Dunbar129271a2008-09-27 07:36:24 +00002266 const PointerType *PT = 0;
2267
Anders Carlsson80f25672008-09-09 17:59:25 +00002268 // catch(...) always matches.
Daniel Dunbar55e40722008-09-27 07:03:52 +00002269 if (!CatchParam) {
2270 AllMatched = true;
2271 } else {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002272 PT = CatchParam->getType()->getAsPointerType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002273
Daniel Dunbar97f61d12008-09-27 22:21:14 +00002274 // catch(id e) always matches.
2275 // FIXME: For the time being we also match id<X>; this should
2276 // be rejected by Sema instead.
Steve Naroff389bf462009-02-12 17:52:19 +00002277 if ((PT && CGF.getContext().isObjCIdStructType(PT->getPointeeType())) ||
Steve Naroff7ba138a2009-03-03 19:52:17 +00002278 CatchParam->getType()->isObjCQualifiedIdType())
Daniel Dunbar55e40722008-09-27 07:03:52 +00002279 AllMatched = true;
Anders Carlsson80f25672008-09-09 17:59:25 +00002280 }
2281
Daniel Dunbar55e40722008-09-27 07:03:52 +00002282 if (AllMatched) {
Anders Carlssondde0a942008-09-11 09:15:33 +00002283 if (CatchParam) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002284 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002285 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002286 CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002287 }
Anders Carlsson1452f552008-09-11 08:21:54 +00002288
Anders Carlssondde0a942008-09-11 09:15:33 +00002289 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002290 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002291 break;
2292 }
2293
Daniel Dunbar129271a2008-09-27 07:36:24 +00002294 assert(PT && "Unexpected non-pointer type in @catch");
2295 QualType T = PT->getPointeeType();
Anders Carlsson4b7ff6e2008-09-11 06:35:14 +00002296 const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002297 assert(ObjCType && "Catch parameter must have Objective-C type!");
2298
2299 // Check if the @catch block matches the exception object.
2300 llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl());
2301
Chris Lattner34b02a12009-04-22 02:26:14 +00002302 llvm::Value *Match =
2303 CGF.Builder.CreateCall2(ObjCTypes.getExceptionMatchFn(),
2304 Class, Caught, "match");
Anders Carlsson80f25672008-09-09 17:59:25 +00002305
Daniel Dunbar55e87422008-11-11 02:29:29 +00002306 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched");
Anders Carlsson80f25672008-09-09 17:59:25 +00002307
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002308 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002309 MatchedBlock, NextCatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002310
2311 // Emit the @catch block.
2312 CGF.EmitBlock(MatchedBlock);
Steve Naroff7ba138a2009-03-03 19:52:17 +00002313 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002314 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002315
2316 llvm::Value *Tmp =
Steve Naroff7ba138a2009-03-03 19:52:17 +00002317 CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(CatchParam->getType()),
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002318 "tmp");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002319 CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002320
2321 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002322 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002323
2324 CGF.EmitBlock(NextCatchBlock);
2325 }
2326
Daniel Dunbar55e40722008-09-27 07:03:52 +00002327 if (!AllMatched) {
2328 // None of the handlers caught the exception, so store it to be
2329 // rethrown at the end of the @finally block.
2330 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002331 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002332 }
2333
2334 // Emit the exception handler for the @catch blocks.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002335 CGF.EmitBlock(CatchHandler);
Chris Lattner34b02a12009-04-22 02:26:14 +00002336 CGF.Builder.CreateStore(
2337 CGF.Builder.CreateCall(ObjCTypes.getExceptionExtractFn(),
2338 ExceptionData),
Daniel Dunbar55e40722008-09-27 07:03:52 +00002339 RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002340 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002341 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002342 } else {
Anders Carlsson80f25672008-09-09 17:59:25 +00002343 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002344 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002345 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Anders Carlsson80f25672008-09-09 17:59:25 +00002346 }
2347
Daniel Dunbar898d5082008-09-30 01:06:03 +00002348 // Pop the exception-handling stack entry. It is important to do
2349 // this now, because the code in the @finally block is not in this
2350 // context.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002351 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
2352
Anders Carlsson273558f2009-02-07 21:37:21 +00002353 CGF.ObjCEHValueStack.pop_back();
2354
Anders Carlsson80f25672008-09-09 17:59:25 +00002355 // Emit the @finally block.
2356 CGF.EmitBlock(FinallyBlock);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002357 llvm::Value* CallTryExit = CGF.Builder.CreateLoad(CallTryExitPtr, "tmp");
2358
2359 CGF.Builder.CreateCondBr(CallTryExit, FinallyExit, FinallyNoExit);
2360
2361 CGF.EmitBlock(FinallyExit);
Chris Lattner34b02a12009-04-22 02:26:14 +00002362 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryExitFn(), ExceptionData);
Daniel Dunbar129271a2008-09-27 07:36:24 +00002363
2364 CGF.EmitBlock(FinallyNoExit);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002365 if (isTry) {
2366 if (const ObjCAtFinallyStmt* FinallyStmt =
2367 cast<ObjCAtTryStmt>(S).getFinallyStmt())
2368 CGF.EmitStmt(FinallyStmt->getFinallyBody());
Daniel Dunbar1c566672009-02-24 01:43:46 +00002369 } else {
2370 // Emit objc_sync_exit(expr); as finally's sole statement for
2371 // @synchronized.
Chris Lattnerbbccd612009-04-22 02:38:11 +00002372 CGF.Builder.CreateCall(ObjCTypes.getSyncExitFn(), SyncArg);
Fariborz Jahanianf2878e52008-11-21 19:21:53 +00002373 }
Anders Carlsson80f25672008-09-09 17:59:25 +00002374
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002375 // Emit the switch block
2376 if (Info.SwitchBlock)
2377 CGF.EmitBlock(Info.SwitchBlock);
2378 if (Info.EndBlock)
2379 CGF.EmitBlock(Info.EndBlock);
2380
Daniel Dunbar898d5082008-09-30 01:06:03 +00002381 CGF.EmitBlock(FinallyRethrow);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002382 CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(),
Daniel Dunbar898d5082008-09-30 01:06:03 +00002383 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002384 CGF.Builder.CreateUnreachable();
Daniel Dunbar898d5082008-09-30 01:06:03 +00002385
2386 CGF.EmitBlock(FinallyEnd);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002387}
2388
2389void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar898d5082008-09-30 01:06:03 +00002390 const ObjCAtThrowStmt &S) {
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002391 llvm::Value *ExceptionAsObject;
2392
2393 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2394 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
2395 ExceptionAsObject =
2396 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
2397 } else {
Anders Carlsson273558f2009-02-07 21:37:21 +00002398 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002399 "Unexpected rethrow outside @catch block.");
Anders Carlsson273558f2009-02-07 21:37:21 +00002400 ExceptionAsObject = CGF.ObjCEHValueStack.back();
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002401 }
2402
Chris Lattnerbbccd612009-04-22 02:38:11 +00002403 CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(), ExceptionAsObject);
Anders Carlsson80f25672008-09-09 17:59:25 +00002404 CGF.Builder.CreateUnreachable();
Daniel Dunbara448fb22008-11-11 23:11:34 +00002405
2406 // Clear the insertion point to indicate we are in unreachable code.
2407 CGF.Builder.ClearInsertionPoint();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002408}
2409
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002410/// EmitObjCWeakRead - Code gen for loading value of a __weak
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002411/// object: objc_read_weak (id *src)
2412///
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002413llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002414 llvm::Value *AddrWeakObj)
2415{
Eli Friedman8339b352009-03-07 03:57:15 +00002416 const llvm::Type* DestTy =
2417 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002418 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002419 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002420 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00002421 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002422 return read_weak;
2423}
2424
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002425/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
2426/// objc_assign_weak (id src, id *dst)
2427///
2428void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
2429 llvm::Value *src, llvm::Value *dst)
2430{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002431 const llvm::Type * SrcTy = src->getType();
2432 if (!isa<llvm::PointerType>(SrcTy)) {
2433 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2434 assert(Size <= 8 && "does not support size > 8");
2435 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2436 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002437 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2438 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002439 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2440 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattner96508e12009-04-17 22:12:36 +00002441 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002442 src, dst, "weakassign");
2443 return;
2444}
2445
Fariborz Jahanian58626502008-11-19 00:59:10 +00002446/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
2447/// objc_assign_global (id src, id *dst)
2448///
2449void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
2450 llvm::Value *src, llvm::Value *dst)
2451{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002452 const llvm::Type * SrcTy = src->getType();
2453 if (!isa<llvm::PointerType>(SrcTy)) {
2454 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2455 assert(Size <= 8 && "does not support size > 8");
2456 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2457 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002458 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2459 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002460 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2461 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002462 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignGlobalFn(),
Fariborz Jahanian58626502008-11-19 00:59:10 +00002463 src, dst, "globalassign");
2464 return;
2465}
2466
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002467/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
2468/// objc_assign_ivar (id src, id *dst)
2469///
2470void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
2471 llvm::Value *src, llvm::Value *dst)
2472{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002473 const llvm::Type * SrcTy = src->getType();
2474 if (!isa<llvm::PointerType>(SrcTy)) {
2475 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2476 assert(Size <= 8 && "does not support size > 8");
2477 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2478 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002479 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2480 }
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002481 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2482 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002483 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignIvarFn(),
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002484 src, dst, "assignivar");
2485 return;
2486}
2487
Fariborz Jahanian58626502008-11-19 00:59:10 +00002488/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
2489/// objc_assign_strongCast (id src, id *dst)
2490///
2491void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
2492 llvm::Value *src, llvm::Value *dst)
2493{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002494 const llvm::Type * SrcTy = src->getType();
2495 if (!isa<llvm::PointerType>(SrcTy)) {
2496 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2497 assert(Size <= 8 && "does not support size > 8");
2498 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2499 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002500 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2501 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002502 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2503 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002504 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignStrongCastFn(),
Fariborz Jahanian58626502008-11-19 00:59:10 +00002505 src, dst, "weakassign");
2506 return;
2507}
2508
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002509/// EmitObjCValueForIvar - Code Gen for ivar reference.
2510///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002511LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
2512 QualType ObjectTy,
2513 llvm::Value *BaseValue,
2514 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002515 unsigned CVRQualifiers) {
Daniel Dunbar525c9b72009-04-21 01:19:28 +00002516 const ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
2517 const FieldDecl *Field = ID->lookupFieldDeclForIvar(CGM.getContext(), Ivar);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002518 if (Ivar->isBitField())
2519 return CGF.EmitLValueForBitfield(BaseValue, const_cast<FieldDecl *>(Field),
2520 CVRQualifiers);
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002521 // TODO: Add a special case for isa (index 0)
2522 unsigned Index = CGM.getTypes().getLLVMFieldNo(Field);
2523 llvm::Value *V = CGF.Builder.CreateStructGEP(BaseValue, Index, "tmp");
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002524 LValue LV = LValue::MakeAddr(V,
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00002525 Ivar->getType().getCVRQualifiers()|CVRQualifiers,
2526 CGM.getContext().getObjCGCAttrKind(Ivar->getType()));
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002527 LValue::SetObjCIvar(LV, true);
2528 return LV;
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002529}
2530
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002531llvm::Value *CGObjCMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
2532 ObjCInterfaceDecl *Interface,
2533 const ObjCIvarDecl *Ivar) {
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002534 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(Interface);
Daniel Dunbar60952f92009-04-20 00:37:55 +00002535 const FieldDecl *Field =
2536 Interface->lookupFieldDeclForIvar(CGM.getContext(), Ivar);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00002537 uint64_t Offset = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002538 return llvm::ConstantInt::get(
2539 CGM.getTypes().ConvertType(CGM.getContext().LongTy),
2540 Offset);
2541}
2542
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002543/* *** Private Interface *** */
2544
2545/// EmitImageInfo - Emit the image info marker used to encode some module
2546/// level information.
2547///
2548/// See: <rdr://4810609&4810587&4810587>
2549/// struct IMAGE_INFO {
2550/// unsigned version;
2551/// unsigned flags;
2552/// };
2553enum ImageInfoFlags {
Daniel Dunbarc7c6dc02009-04-20 07:11:47 +00002554 eImageInfo_FixAndContinue = (1 << 0), // FIXME: Not sure what
2555 // this implies.
2556 eImageInfo_GarbageCollected = (1 << 1),
2557 eImageInfo_GCOnly = (1 << 2),
2558 eImageInfo_OptimizedByDyld = (1 << 3), // FIXME: When is this set.
2559
2560 // A flag indicating that the module has no instances of an
2561 // @synthesize of a superclass variable. <rdar://problem/6803242>
2562 eImageInfo_CorrectedSynthesize = (1 << 4)
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002563};
2564
2565void CGObjCMac::EmitImageInfo() {
2566 unsigned version = 0; // Version is unused?
2567 unsigned flags = 0;
2568
2569 // FIXME: Fix and continue?
2570 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
2571 flags |= eImageInfo_GarbageCollected;
2572 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
2573 flags |= eImageInfo_GCOnly;
Daniel Dunbarc7c6dc02009-04-20 07:11:47 +00002574
2575 // We never allow @synthesize of a superclass property.
2576 flags |= eImageInfo_CorrectedSynthesize;
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002577
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002578 // Emitted as int[2];
2579 llvm::Constant *values[2] = {
2580 llvm::ConstantInt::get(llvm::Type::Int32Ty, version),
2581 llvm::ConstantInt::get(llvm::Type::Int32Ty, flags)
2582 };
2583 llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002584
2585 const char *Section;
2586 if (ObjCABI == 1)
2587 Section = "__OBJC, __image_info,regular";
2588 else
2589 Section = "__DATA, __objc_imageinfo, regular, no_dead_strip";
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002590 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002591 CreateMetadataVar("\01L_OBJC_IMAGE_INFO",
2592 llvm::ConstantArray::get(AT, values, 2),
2593 Section,
2594 0,
2595 true);
2596 GV->setConstant(true);
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002597}
2598
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002599
2600// struct objc_module {
2601// unsigned long version;
2602// unsigned long size;
2603// const char *name;
2604// Symtab symtab;
2605// };
2606
2607// FIXME: Get from somewhere
2608static const int ModuleVersion = 7;
2609
2610void CGObjCMac::EmitModuleInfo() {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00002611 uint64_t Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ModuleTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002612
2613 std::vector<llvm::Constant*> Values(4);
2614 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
2615 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002616 // This used to be the filename, now it is unused. <rdr://4327263>
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002617 Values[2] = GetClassName(&CGM.getContext().Idents.get(""));
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002618 Values[3] = EmitModuleSymbols();
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002619 CreateMetadataVar("\01L_OBJC_MODULES",
2620 llvm::ConstantStruct::get(ObjCTypes.ModuleTy, Values),
2621 "__OBJC,__module_info,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00002622 4, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002623}
2624
2625llvm::Constant *CGObjCMac::EmitModuleSymbols() {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002626 unsigned NumClasses = DefinedClasses.size();
2627 unsigned NumCategories = DefinedCategories.size();
2628
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002629 // Return null if no symbols were defined.
2630 if (!NumClasses && !NumCategories)
2631 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
2632
2633 std::vector<llvm::Constant*> Values(5);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002634 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2635 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
2636 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
2637 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
2638
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002639 // The runtime expects exactly the list of defined classes followed
2640 // by the list of defined categories, in a single array.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002641 std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002642 for (unsigned i=0; i<NumClasses; i++)
2643 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
2644 ObjCTypes.Int8PtrTy);
2645 for (unsigned i=0; i<NumCategories; i++)
2646 Symbols[NumClasses + i] =
2647 llvm::ConstantExpr::getBitCast(DefinedCategories[i],
2648 ObjCTypes.Int8PtrTy);
2649
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002650 Values[4] =
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002651 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002652 NumClasses + NumCategories),
2653 Symbols);
2654
2655 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2656
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002657 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002658 CreateMetadataVar("\01L_OBJC_SYMBOLS", Init,
2659 "__OBJC,__symbols,regular,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002660 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002661 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
2662}
2663
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002664llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002665 const ObjCInterfaceDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002666 LazySymbols.insert(ID->getIdentifier());
2667
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002668 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
2669
2670 if (!Entry) {
2671 llvm::Constant *Casted =
2672 llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()),
2673 ObjCTypes.ClassPtrTy);
2674 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002675 CreateMetadataVar("\01L_OBJC_CLASS_REFERENCES_", Casted,
2676 "__OBJC,__cls_refs,literal_pointers,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002677 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002678 }
2679
2680 return Builder.CreateLoad(Entry, false, "tmp");
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002681}
2682
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002683llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002684 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
2685
2686 if (!Entry) {
2687 llvm::Constant *Casted =
2688 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
2689 ObjCTypes.SelectorPtrTy);
2690 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002691 CreateMetadataVar("\01L_OBJC_SELECTOR_REFERENCES_", Casted,
2692 "__OBJC,__message_refs,literal_pointers,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002693 4, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002694 }
2695
2696 return Builder.CreateLoad(Entry, false, "tmp");
2697}
2698
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00002699llvm::Constant *CGObjCCommonMac::GetClassName(IdentifierInfo *Ident) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002700 llvm::GlobalVariable *&Entry = ClassNames[Ident];
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002701
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002702 if (!Entry)
2703 Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
2704 llvm::ConstantArray::get(Ident->getName()),
2705 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00002706 1, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002707
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002708 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002709}
2710
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002711/// GetInterfaceDeclStructLayout - Get layout for ivars of given
2712/// interface declaration.
2713const llvm::StructLayout *CGObjCCommonMac::GetInterfaceDeclStructLayout(
2714 const ObjCInterfaceDecl *OID) const {
Daniel Dunbar24c89912009-04-21 21:41:56 +00002715 assert(!OID->isForwardDecl() && "Invalid interface decl!");
Daniel Dunbar6c1aac82009-04-20 20:18:54 +00002716 QualType T =
2717 CGM.getContext().getObjCInterfaceType(const_cast<ObjCInterfaceDecl*>(OID));
2718 const llvm::StructType *InterfaceTy =
2719 cast<llvm::StructType>(CGM.getTypes().ConvertType(T));
2720 return CGM.getTargetData().getStructLayout(InterfaceTy);
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002721}
2722
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00002723/// GetIvarLayoutName - Returns a unique constant for the given
2724/// ivar layout bitmap.
2725llvm::Constant *CGObjCCommonMac::GetIvarLayoutName(IdentifierInfo *Ident,
2726 const ObjCCommonTypesHelper &ObjCTypes) {
2727 return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2728}
2729
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002730void CGObjCCommonMac::BuildAggrIvarLayout(const ObjCInterfaceDecl *OI,
2731 const llvm::StructLayout *Layout,
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002732 const RecordDecl *RD,
Chris Lattnerf1690852009-03-31 08:48:01 +00002733 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002734 unsigned int BytePos, bool ForStrongLayout,
2735 int &Index, int &SkIndex, bool &HasUnion) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002736 bool IsUnion = (RD && RD->isUnion());
2737 uint64_t MaxUnionIvarSize = 0;
2738 uint64_t MaxSkippedUnionIvarSize = 0;
2739 FieldDecl *MaxField = 0;
2740 FieldDecl *MaxSkippedField = 0;
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002741 FieldDecl *LastFieldBitfield = 0;
2742
Chris Lattnerf1690852009-03-31 08:48:01 +00002743 unsigned base = 0;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002744 if (RecFields.empty())
2745 return;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002746 if (IsUnion)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002747 base = BytePos + GetFieldBaseOffset(OI, Layout, RecFields[0]);
Chris Lattnerf1690852009-03-31 08:48:01 +00002748 unsigned WordSizeInBits = CGM.getContext().Target.getPointerWidth(0);
2749 unsigned ByteSizeInBits = CGM.getContext().Target.getCharWidth();
2750
2751 llvm::SmallVector<FieldDecl*, 16> TmpRecFields;
2752
2753 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002754 FieldDecl *Field = RecFields[i];
2755 // Skip over unnamed or bitfields
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002756 if (!Field->getIdentifier() || Field->isBitField()) {
2757 LastFieldBitfield = Field;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002758 continue;
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002759 }
2760 LastFieldBitfield = 0;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002761 QualType FQT = Field->getType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002762 if (FQT->isRecordType() || FQT->isUnionType()) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002763 if (FQT->isUnionType())
2764 HasUnion = true;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002765 else
2766 assert(FQT->isRecordType() &&
2767 "only union/record is supported for ivar layout bitmap");
2768
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002769 const RecordType *RT = FQT->getAsRecordType();
2770 const RecordDecl *RD = RT->getDecl();
Daniel Dunbarb02532a2009-04-19 23:41:48 +00002771 // FIXME - Find a more efficient way of passing records down.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002772 TmpRecFields.append(RD->field_begin(CGM.getContext()),
2773 RD->field_end(CGM.getContext()));
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00002774 const llvm::Type *Ty = CGM.getTypes().ConvertType(FQT);
2775 const llvm::StructLayout *RecLayout =
2776 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(Ty));
2777
2778 BuildAggrIvarLayout(0, RecLayout, RD, TmpRecFields,
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002779 BytePos + GetFieldBaseOffset(OI, Layout, Field),
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002780 ForStrongLayout, Index, SkIndex,
2781 HasUnion);
Chris Lattnerf1690852009-03-31 08:48:01 +00002782 TmpRecFields.clear();
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002783 continue;
2784 }
Chris Lattnerf1690852009-03-31 08:48:01 +00002785
2786 if (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002787 const ConstantArrayType *CArray =
2788 dyn_cast_or_null<ConstantArrayType>(Array);
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002789 uint64_t ElCount = CArray->getSize().getZExtValue();
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002790 assert(CArray && "only array with know element size is supported");
2791 FQT = CArray->getElementType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002792 while (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
2793 const ConstantArrayType *CArray =
2794 dyn_cast_or_null<ConstantArrayType>(Array);
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002795 ElCount *= CArray->getSize().getZExtValue();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002796 FQT = CArray->getElementType();
2797 }
2798
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002799 assert(!FQT->isUnionType() &&
2800 "layout for array of unions not supported");
2801 if (FQT->isRecordType()) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002802 int OldIndex = Index;
2803 int OldSkIndex = SkIndex;
2804
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002805 // FIXME - Use a common routine with the above!
2806 const RecordType *RT = FQT->getAsRecordType();
2807 const RecordDecl *RD = RT->getDecl();
2808 // FIXME - Find a more efficiant way of passing records down.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002809 TmpRecFields.append(RD->field_begin(CGM.getContext()),
2810 RD->field_end(CGM.getContext()));
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00002811 const llvm::Type *Ty = CGM.getTypes().ConvertType(FQT);
2812 const llvm::StructLayout *RecLayout =
2813 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(Ty));
Chris Lattnerf1690852009-03-31 08:48:01 +00002814
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00002815 BuildAggrIvarLayout(0, RecLayout, RD,
Chris Lattnerf1690852009-03-31 08:48:01 +00002816 TmpRecFields,
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002817 BytePos + GetFieldBaseOffset(OI, Layout, Field),
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002818 ForStrongLayout, Index, SkIndex,
2819 HasUnion);
Chris Lattnerf1690852009-03-31 08:48:01 +00002820 TmpRecFields.clear();
2821
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002822 // Replicate layout information for each array element. Note that
2823 // one element is already done.
2824 uint64_t ElIx = 1;
2825 for (int FirstIndex = Index, FirstSkIndex = SkIndex;
2826 ElIx < ElCount; ElIx++) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002827 uint64_t Size = CGM.getContext().getTypeSize(RT)/ByteSizeInBits;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002828 for (int i = OldIndex+1; i <= FirstIndex; ++i)
2829 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002830 GC_IVAR gcivar;
2831 gcivar.ivar_bytepos = IvarsInfo[i].ivar_bytepos + Size*ElIx;
2832 gcivar.ivar_size = IvarsInfo[i].ivar_size;
2833 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002834 }
2835
Chris Lattnerf1690852009-03-31 08:48:01 +00002836 for (int i = OldSkIndex+1; i <= FirstSkIndex; ++i) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002837 GC_IVAR skivar;
2838 skivar.ivar_bytepos = SkipIvars[i].ivar_bytepos + Size*ElIx;
2839 skivar.ivar_size = SkipIvars[i].ivar_size;
2840 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002841 }
2842 }
2843 continue;
2844 }
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002845 }
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002846 // At this point, we are done with Record/Union and array there of.
2847 // For other arrays we are down to its element type.
2848 QualType::GCAttrTypes GCAttr = QualType::GCNone;
2849 do {
2850 if (FQT.isObjCGCStrong() || FQT.isObjCGCWeak()) {
2851 GCAttr = FQT.isObjCGCStrong() ? QualType::Strong : QualType::Weak;
2852 break;
2853 }
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002854 else if (CGM.getContext().isObjCObjectPointerType(FQT)) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002855 GCAttr = QualType::Strong;
2856 break;
2857 }
2858 else if (const PointerType *PT = FQT->getAsPointerType()) {
2859 FQT = PT->getPointeeType();
2860 }
2861 else {
2862 break;
2863 }
2864 } while (true);
Chris Lattnerf1690852009-03-31 08:48:01 +00002865
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002866 if ((ForStrongLayout && GCAttr == QualType::Strong)
2867 || (!ForStrongLayout && GCAttr == QualType::Weak)) {
2868 if (IsUnion)
2869 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002870 uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType())
2871 / WordSizeInBits;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002872 if (UnionIvarSize > MaxUnionIvarSize)
2873 {
2874 MaxUnionIvarSize = UnionIvarSize;
2875 MaxField = Field;
2876 }
2877 }
2878 else
2879 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002880 GC_IVAR gcivar;
2881 gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field);
2882 gcivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) /
2883 WordSizeInBits;
2884 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002885 }
2886 }
2887 else if ((ForStrongLayout &&
2888 (GCAttr == QualType::GCNone || GCAttr == QualType::Weak))
2889 || (!ForStrongLayout && GCAttr != QualType::Weak)) {
2890 if (IsUnion)
2891 {
2892 uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType());
2893 if (UnionIvarSize > MaxSkippedUnionIvarSize)
2894 {
2895 MaxSkippedUnionIvarSize = UnionIvarSize;
2896 MaxSkippedField = Field;
2897 }
2898 }
2899 else
2900 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002901 GC_IVAR skivar;
2902 skivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field);
2903 skivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) /
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002904 ByteSizeInBits;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002905 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002906 }
2907 }
2908 }
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002909 if (LastFieldBitfield) {
2910 // Last field was a bitfield. Must update skip info.
2911 GC_IVAR skivar;
2912 skivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout,
2913 LastFieldBitfield);
2914 Expr *BitWidth = LastFieldBitfield->getBitWidth();
2915 uint64_t BitFieldSize =
2916 BitWidth->getIntegerConstantExprValue(CGM.getContext()).getZExtValue();
2917 skivar.ivar_size = (BitFieldSize / ByteSizeInBits)
2918 + ((BitFieldSize % ByteSizeInBits) != 0);
2919 SkipIvars.push_back(skivar); ++SkIndex;
2920 }
2921
Chris Lattnerf1690852009-03-31 08:48:01 +00002922 if (MaxField) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002923 GC_IVAR gcivar;
2924 gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, MaxField);
2925 gcivar.ivar_size = MaxUnionIvarSize;
2926 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002927 }
Chris Lattnerf1690852009-03-31 08:48:01 +00002928
2929 if (MaxSkippedField) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002930 GC_IVAR skivar;
2931 skivar.ivar_bytepos = BytePos +
2932 GetFieldBaseOffset(OI, Layout, MaxSkippedField);
2933 skivar.ivar_size = MaxSkippedUnionIvarSize;
2934 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002935 }
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002936}
2937
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002938static int
Chris Lattnerf1690852009-03-31 08:48:01 +00002939IvarBytePosCompare(const void *a, const void *b)
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002940{
2941 unsigned int sa = ((CGObjCCommonMac::GC_IVAR *)a)->ivar_bytepos;
2942 unsigned int sb = ((CGObjCCommonMac::GC_IVAR *)b)->ivar_bytepos;
2943
2944 if (sa < sb)
2945 return -1;
2946 if (sa > sb)
2947 return 1;
2948 return 0;
2949}
2950
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002951/// BuildIvarLayout - Builds ivar layout bitmap for the class
2952/// implementation for the __strong or __weak case.
2953/// The layout map displays which words in ivar list must be skipped
2954/// and which must be scanned by GC (see below). String is built of bytes.
2955/// Each byte is divided up in two nibbles (4-bit each). Left nibble is count
2956/// of words to skip and right nibble is count of words to scan. So, each
2957/// nibble represents up to 15 workds to skip or scan. Skipping the rest is
2958/// represented by a 0x00 byte which also ends the string.
2959/// 1. when ForStrongLayout is true, following ivars are scanned:
2960/// - id, Class
2961/// - object *
2962/// - __strong anything
2963///
2964/// 2. When ForStrongLayout is false, following ivars are scanned:
2965/// - __weak anything
2966///
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002967llvm::Constant *CGObjCCommonMac::BuildIvarLayout(
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002968 const ObjCImplementationDecl *OMD,
2969 bool ForStrongLayout) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002970 int Index = -1;
2971 int SkIndex = -1;
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002972 bool hasUnion = false;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002973 int SkipScan;
2974 unsigned int WordsToScan, WordsToSkip;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002975 const llvm::Type *PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
2976 if (CGM.getLangOptions().getGCMode() == LangOptions::NonGC)
2977 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002978
Chris Lattnerf1690852009-03-31 08:48:01 +00002979 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002980 const ObjCInterfaceDecl *OI = OMD->getClassInterface();
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002981 CGM.getContext().CollectObjCIvars(OI, RecFields);
2982 if (RecFields.empty())
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002983 return llvm::Constant::getNullValue(PtrTy);
Chris Lattnerf1690852009-03-31 08:48:01 +00002984
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002985 SkipIvars.clear();
2986 IvarsInfo.clear();
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002987
2988 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OI);
Chris Lattnerf1690852009-03-31 08:48:01 +00002989 BuildAggrIvarLayout(OI, Layout, 0, RecFields, 0, ForStrongLayout,
2990 Index, SkIndex, hasUnion);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002991 if (Index == -1)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002992 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002993
2994 // Sort on byte position in case we encounterred a union nested in
2995 // the ivar list.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002996 if (hasUnion && !IvarsInfo.empty())
2997 qsort(&IvarsInfo[0], Index+1, sizeof(GC_IVAR), IvarBytePosCompare);
2998 if (hasUnion && !SkipIvars.empty())
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002999 qsort(&SkipIvars[0], Index+1, sizeof(GC_IVAR), IvarBytePosCompare);
3000
3001 // Build the string of skip/scan nibbles
3002 SkipScan = -1;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003003 SkipScanIvars.clear();
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003004 unsigned int WordSize =
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003005 CGM.getTypes().getTargetData().getTypePaddedSize(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003006 if (IvarsInfo[0].ivar_bytepos == 0) {
3007 WordsToSkip = 0;
3008 WordsToScan = IvarsInfo[0].ivar_size;
3009 }
3010 else {
3011 WordsToSkip = IvarsInfo[0].ivar_bytepos/WordSize;
3012 WordsToScan = IvarsInfo[0].ivar_size;
3013 }
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003014 for (unsigned int i=1, Last=IvarsInfo.size(); i != Last; i++)
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003015 {
3016 unsigned int TailPrevGCObjC =
3017 IvarsInfo[i-1].ivar_bytepos + IvarsInfo[i-1].ivar_size * WordSize;
3018 if (IvarsInfo[i].ivar_bytepos == TailPrevGCObjC)
3019 {
3020 // consecutive 'scanned' object pointers.
3021 WordsToScan += IvarsInfo[i].ivar_size;
3022 }
3023 else
3024 {
3025 // Skip over 'gc'able object pointer which lay over each other.
3026 if (TailPrevGCObjC > IvarsInfo[i].ivar_bytepos)
3027 continue;
3028 // Must skip over 1 or more words. We save current skip/scan values
3029 // and start a new pair.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003030 SKIP_SCAN SkScan;
3031 SkScan.skip = WordsToSkip;
3032 SkScan.scan = WordsToScan;
3033 SkipScanIvars.push_back(SkScan); ++SkipScan;
3034
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003035 // Skip the hole.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003036 SkScan.skip = (IvarsInfo[i].ivar_bytepos - TailPrevGCObjC) / WordSize;
3037 SkScan.scan = 0;
3038 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003039 WordsToSkip = 0;
3040 WordsToScan = IvarsInfo[i].ivar_size;
3041 }
3042 }
3043 if (WordsToScan > 0)
3044 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003045 SKIP_SCAN SkScan;
3046 SkScan.skip = WordsToSkip;
3047 SkScan.scan = WordsToScan;
3048 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003049 }
3050
3051 bool BytesSkipped = false;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003052 if (!SkipIvars.empty())
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003053 {
3054 int LastByteSkipped =
3055 SkipIvars[SkIndex].ivar_bytepos + SkipIvars[SkIndex].ivar_size;
3056 int LastByteScanned =
3057 IvarsInfo[Index].ivar_bytepos + IvarsInfo[Index].ivar_size * WordSize;
3058 BytesSkipped = (LastByteSkipped > LastByteScanned);
3059 // Compute number of bytes to skip at the tail end of the last ivar scanned.
3060 if (BytesSkipped)
3061 {
3062 unsigned int TotalWords = (LastByteSkipped + (WordSize -1)) / WordSize;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003063 SKIP_SCAN SkScan;
3064 SkScan.skip = TotalWords - (LastByteScanned/WordSize);
3065 SkScan.scan = 0;
3066 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003067 }
3068 }
3069 // Mini optimization of nibbles such that an 0xM0 followed by 0x0N is produced
3070 // as 0xMN.
3071 for (int i = 0; i <= SkipScan; i++)
3072 {
3073 if ((i < SkipScan) && SkipScanIvars[i].skip && SkipScanIvars[i].scan == 0
3074 && SkipScanIvars[i+1].skip == 0 && SkipScanIvars[i+1].scan) {
3075 // 0xM0 followed by 0x0N detected.
3076 SkipScanIvars[i].scan = SkipScanIvars[i+1].scan;
3077 for (int j = i+1; j < SkipScan; j++)
3078 SkipScanIvars[j] = SkipScanIvars[j+1];
3079 --SkipScan;
3080 }
3081 }
3082
3083 // Generate the string.
3084 std::string BitMap;
3085 for (int i = 0; i <= SkipScan; i++)
3086 {
3087 unsigned char byte;
3088 unsigned int skip_small = SkipScanIvars[i].skip % 0xf;
3089 unsigned int scan_small = SkipScanIvars[i].scan % 0xf;
3090 unsigned int skip_big = SkipScanIvars[i].skip / 0xf;
3091 unsigned int scan_big = SkipScanIvars[i].scan / 0xf;
3092
3093 if (skip_small > 0 || skip_big > 0)
3094 BytesSkipped = true;
3095 // first skip big.
3096 for (unsigned int ix = 0; ix < skip_big; ix++)
3097 BitMap += (unsigned char)(0xf0);
3098
3099 // next (skip small, scan)
3100 if (skip_small)
3101 {
3102 byte = skip_small << 4;
3103 if (scan_big > 0)
3104 {
3105 byte |= 0xf;
3106 --scan_big;
3107 }
3108 else if (scan_small)
3109 {
3110 byte |= scan_small;
3111 scan_small = 0;
3112 }
3113 BitMap += byte;
3114 }
3115 // next scan big
3116 for (unsigned int ix = 0; ix < scan_big; ix++)
3117 BitMap += (unsigned char)(0x0f);
3118 // last scan small
3119 if (scan_small)
3120 {
3121 byte = scan_small;
3122 BitMap += byte;
3123 }
3124 }
3125 // null terminate string.
Fariborz Jahanian667423a2009-03-25 22:36:49 +00003126 unsigned char zero = 0;
3127 BitMap += zero;
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00003128
3129 if (CGM.getLangOptions().ObjCGCBitmapPrint) {
3130 printf("\n%s ivar layout for class '%s': ",
3131 ForStrongLayout ? "strong" : "weak",
3132 OMD->getClassInterface()->getNameAsCString());
3133 const unsigned char *s = (unsigned char*)BitMap.c_str();
3134 for (unsigned i = 0; i < BitMap.size(); i++)
3135 if (!(s[i] & 0xf0))
3136 printf("0x0%x%s", s[i], s[i] != 0 ? ", " : "");
3137 else
3138 printf("0x%x%s", s[i], s[i] != 0 ? ", " : "");
3139 printf("\n");
3140 }
3141
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003142 // if ivar_layout bitmap is all 1 bits (nothing skipped) then use NULL as
3143 // final layout.
3144 if (ForStrongLayout && !BytesSkipped)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003145 return llvm::Constant::getNullValue(PtrTy);
3146 llvm::GlobalVariable * Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
3147 llvm::ConstantArray::get(BitMap.c_str()),
3148 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003149 1, true);
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00003150 return getConstantGEP(Entry, 0, 0);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003151}
3152
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003153llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003154 llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
3155
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003156 // FIXME: Avoid std::string copying.
3157 if (!Entry)
3158 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_NAME_",
3159 llvm::ConstantArray::get(Sel.getAsString()),
3160 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003161 1, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003162
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003163 return getConstantGEP(Entry, 0, 0);
3164}
3165
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003166// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003167llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003168 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
3169}
3170
3171// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003172llvm::Constant *CGObjCCommonMac::GetMethodVarName(const std::string &Name) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003173 return GetMethodVarName(&CGM.getContext().Idents.get(Name));
3174}
3175
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00003176llvm::Constant *CGObjCCommonMac::GetMethodVarType(const FieldDecl *Field) {
Devang Patel7794bb82009-03-04 18:21:39 +00003177 std::string TypeStr;
3178 CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
3179
3180 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003181
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003182 if (!Entry)
3183 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3184 llvm::ConstantArray::get(TypeStr),
3185 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003186 1, true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003187
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003188 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003189}
3190
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003191llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003192 std::string TypeStr;
Daniel Dunbarc45ef602008-08-26 21:51:14 +00003193 CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D),
3194 TypeStr);
Devang Patel7794bb82009-03-04 18:21:39 +00003195
3196 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
3197
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003198 if (!Entry)
3199 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3200 llvm::ConstantArray::get(TypeStr),
3201 "__TEXT,__cstring,cstring_literals",
3202 1, true);
Devang Patel7794bb82009-03-04 18:21:39 +00003203
3204 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003205}
3206
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003207// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003208llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003209 llvm::GlobalVariable *&Entry = PropertyNames[Ident];
3210
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003211 if (!Entry)
3212 Entry = CreateMetadataVar("\01L_OBJC_PROP_NAME_ATTR_",
3213 llvm::ConstantArray::get(Ident->getName()),
3214 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003215 1, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003216
3217 return getConstantGEP(Entry, 0, 0);
3218}
3219
3220// FIXME: Merge into a single cstring creation function.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003221// FIXME: This Decl should be more precise.
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003222llvm::Constant *
3223 CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
3224 const Decl *Container) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003225 std::string TypeStr;
3226 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003227 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
3228}
3229
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003230void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D,
3231 const ObjCContainerDecl *CD,
3232 std::string &NameOut) {
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00003233 NameOut = '\01';
3234 NameOut += (D->isInstanceMethod() ? '-' : '+');
Chris Lattner077bf5e2008-11-24 03:33:13 +00003235 NameOut += '[';
Fariborz Jahanian679a5022009-01-10 21:06:09 +00003236 assert (CD && "Missing container decl in GetNameForMethod");
3237 NameOut += CD->getNameAsString();
Fariborz Jahanian1e9aef32009-04-16 18:34:20 +00003238 if (const ObjCCategoryImplDecl *CID =
3239 dyn_cast<ObjCCategoryImplDecl>(D->getDeclContext())) {
3240 NameOut += '(';
3241 NameOut += CID->getNameAsString();
3242 NameOut+= ')';
3243 }
Chris Lattner077bf5e2008-11-24 03:33:13 +00003244 NameOut += ' ';
3245 NameOut += D->getSelector().getAsString();
3246 NameOut += ']';
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00003247}
3248
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003249void CGObjCMac::FinishModule() {
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003250 EmitModuleInfo();
3251
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003252 // Emit the dummy bodies for any protocols which were referenced but
3253 // never defined.
3254 for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
3255 i = Protocols.begin(), e = Protocols.end(); i != e; ++i) {
3256 if (i->second->hasInitializer())
3257 continue;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003258
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003259 std::vector<llvm::Constant*> Values(5);
3260 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
3261 Values[1] = GetClassName(i->first);
3262 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
3263 Values[3] = Values[4] =
3264 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
3265 i->second->setLinkage(llvm::GlobalValue::InternalLinkage);
3266 i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
3267 Values));
3268 }
3269
3270 std::vector<llvm::Constant*> Used;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003271 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003272 e = UsedGlobals.end(); i != e; ++i) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003273 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003274 }
3275
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003276 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003277 llvm::GlobalValue *GV =
3278 new llvm::GlobalVariable(AT, false,
3279 llvm::GlobalValue::AppendingLinkage,
3280 llvm::ConstantArray::get(AT, Used),
3281 "llvm.used",
3282 &CGM.getModule());
3283
3284 GV->setSection("llvm.metadata");
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003285
3286 // Add assembler directives to add lazy undefined symbol references
3287 // for classes which are referenced but not defined. This is
3288 // important for correct linker interaction.
3289
3290 // FIXME: Uh, this isn't particularly portable.
3291 std::stringstream s;
Anders Carlsson565c99f2008-12-10 02:21:04 +00003292
3293 if (!CGM.getModule().getModuleInlineAsm().empty())
3294 s << "\n";
3295
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003296 for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(),
3297 e = LazySymbols.end(); i != e; ++i) {
3298 s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n";
3299 }
3300 for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(),
3301 e = DefinedSymbols.end(); i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003302 s << "\t.objc_class_name_" << (*i)->getName() << "=0\n"
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003303 << "\t.globl .objc_class_name_" << (*i)->getName() << "\n";
3304 }
Anders Carlsson565c99f2008-12-10 02:21:04 +00003305
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003306 CGM.getModule().appendModuleInlineAsm(s.str());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003307}
3308
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003309CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003310 : CGObjCCommonMac(cgm),
3311 ObjCTypes(cgm)
3312{
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003313 ObjCEmptyCacheVar = ObjCEmptyVtableVar = NULL;
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003314 ObjCABI = 2;
3315}
3316
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003317/* *** */
3318
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003319ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm)
3320: CGM(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003321{
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003322 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3323 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003324
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003325 ShortTy = Types.ConvertType(Ctx.ShortTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003326 IntTy = Types.ConvertType(Ctx.IntTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003327 LongTy = Types.ConvertType(Ctx.LongTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00003328 LongLongTy = Types.ConvertType(Ctx.LongLongTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003329 Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3330
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003331 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00003332 PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003333 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003334
3335 // FIXME: It would be nice to unify this with the opaque type, so
3336 // that the IR comes out a bit cleaner.
3337 const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
3338 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003339
3340 // I'm not sure I like this. The implicit coordination is a bit
3341 // gross. We should solve this in a reasonable fashion because this
3342 // is a pretty common task (match some runtime data structure with
3343 // an LLVM data structure).
3344
3345 // FIXME: This is leaked.
3346 // FIXME: Merge with rewriter code?
3347
3348 // struct _objc_super {
3349 // id self;
3350 // Class cls;
3351 // }
3352 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3353 SourceLocation(),
3354 &Ctx.Idents.get("_objc_super"));
Douglas Gregor6ab35242009-04-09 21:40:53 +00003355 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3356 Ctx.getObjCIdType(), 0, false));
3357 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3358 Ctx.getObjCClassType(), 0, false));
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003359 RD->completeDefinition(Ctx);
3360
3361 SuperCTy = Ctx.getTagDeclType(RD);
3362 SuperPtrCTy = Ctx.getPointerType(SuperCTy);
3363
3364 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003365 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
3366
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003367 // struct _prop_t {
3368 // char *name;
3369 // char *attributes;
3370 // }
3371 PropertyTy = llvm::StructType::get(Int8PtrTy,
3372 Int8PtrTy,
3373 NULL);
3374 CGM.getModule().addTypeName("struct._prop_t",
3375 PropertyTy);
3376
3377 // struct _prop_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003378 // uint32_t entsize; // sizeof(struct _prop_t)
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003379 // uint32_t count_of_properties;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003380 // struct _prop_t prop_list[count_of_properties];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003381 // }
3382 PropertyListTy = llvm::StructType::get(IntTy,
3383 IntTy,
3384 llvm::ArrayType::get(PropertyTy, 0),
3385 NULL);
3386 CGM.getModule().addTypeName("struct._prop_list_t",
3387 PropertyListTy);
3388 // struct _prop_list_t *
3389 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
3390
3391 // struct _objc_method {
3392 // SEL _cmd;
3393 // char *method_type;
3394 // char *_imp;
3395 // }
3396 MethodTy = llvm::StructType::get(SelectorPtrTy,
3397 Int8PtrTy,
3398 Int8PtrTy,
3399 NULL);
3400 CGM.getModule().addTypeName("struct._objc_method", MethodTy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003401
3402 // struct _objc_cache *
3403 CacheTy = llvm::OpaqueType::get();
3404 CGM.getModule().addTypeName("struct._objc_cache", CacheTy);
3405 CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003406
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003407 // Property manipulation functions.
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003408
3409 QualType IdType = Ctx.getObjCIdType();
3410 QualType SelType = Ctx.getObjCSelType();
3411 llvm::SmallVector<QualType,16> Params;
3412 const llvm::FunctionType *FTy;
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003413
3414 // id objc_getProperty (id, SEL, ptrdiff_t, bool)
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003415 Params.push_back(IdType);
3416 Params.push_back(SelType);
3417 Params.push_back(Ctx.LongTy);
3418 Params.push_back(Ctx.BoolTy);
3419 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params),
3420 false);
3421 GetPropertyFn = CGM.CreateRuntimeFunction(FTy, "objc_getProperty");
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003422
3423 // void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool)
3424 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003425 Params.push_back(IdType);
3426 Params.push_back(SelType);
3427 Params.push_back(Ctx.LongTy);
3428 Params.push_back(IdType);
3429 Params.push_back(Ctx.BoolTy);
3430 Params.push_back(Ctx.BoolTy);
3431 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
3432 SetPropertyFn = CGM.CreateRuntimeFunction(FTy, "objc_setProperty");
3433
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003434 // Enumeration mutation.
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003435
3436 // void objc_enumerationMutation (id)
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003437 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003438 Params.push_back(IdType);
3439 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
3440 EnumerationMutationFn = CGM.CreateRuntimeFunction(FTy,
3441 "objc_enumerationMutation");
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003442
3443 // gc's API
3444 // id objc_read_weak (id *)
3445 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003446 Params.push_back(Ctx.getPointerType(IdType));
3447 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
3448 GcReadWeakFn = CGM.CreateRuntimeFunction(FTy, "objc_read_weak");
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003449}
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003450
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003451ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
3452 : ObjCCommonTypesHelper(cgm)
3453{
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003454 // struct _objc_method_description {
3455 // SEL name;
3456 // char *types;
3457 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003458 MethodDescriptionTy =
3459 llvm::StructType::get(SelectorPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003460 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003461 NULL);
3462 CGM.getModule().addTypeName("struct._objc_method_description",
3463 MethodDescriptionTy);
3464
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003465 // struct _objc_method_description_list {
3466 // int count;
3467 // struct _objc_method_description[1];
3468 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003469 MethodDescriptionListTy =
3470 llvm::StructType::get(IntTy,
3471 llvm::ArrayType::get(MethodDescriptionTy, 0),
3472 NULL);
3473 CGM.getModule().addTypeName("struct._objc_method_description_list",
3474 MethodDescriptionListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003475
3476 // struct _objc_method_description_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003477 MethodDescriptionListPtrTy =
3478 llvm::PointerType::getUnqual(MethodDescriptionListTy);
3479
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003480 // Protocol description structures
3481
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003482 // struct _objc_protocol_extension {
3483 // uint32_t size; // sizeof(struct _objc_protocol_extension)
3484 // struct _objc_method_description_list *optional_instance_methods;
3485 // struct _objc_method_description_list *optional_class_methods;
3486 // struct _objc_property_list *instance_properties;
3487 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003488 ProtocolExtensionTy =
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003489 llvm::StructType::get(IntTy,
3490 MethodDescriptionListPtrTy,
3491 MethodDescriptionListPtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003492 PropertyListPtrTy,
3493 NULL);
3494 CGM.getModule().addTypeName("struct._objc_protocol_extension",
3495 ProtocolExtensionTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003496
3497 // struct _objc_protocol_extension *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003498 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
3499
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003500 // Handle recursive construction of Protocol and ProtocolList types
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003501
3502 llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get();
3503 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3504
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003505 const llvm::Type *T =
3506 llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder),
3507 LongTy,
3508 llvm::ArrayType::get(ProtocolTyHolder, 0),
3509 NULL);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003510 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T);
3511
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003512 // struct _objc_protocol {
3513 // struct _objc_protocol_extension *isa;
3514 // char *protocol_name;
3515 // struct _objc_protocol **_objc_protocol_list;
3516 // struct _objc_method_description_list *instance_methods;
3517 // struct _objc_method_description_list *class_methods;
3518 // }
3519 T = llvm::StructType::get(ProtocolExtensionPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003520 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003521 llvm::PointerType::getUnqual(ProtocolListTyHolder),
3522 MethodDescriptionListPtrTy,
3523 MethodDescriptionListPtrTy,
3524 NULL);
3525 cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T);
3526
3527 ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get());
3528 CGM.getModule().addTypeName("struct._objc_protocol_list",
3529 ProtocolListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003530 // struct _objc_protocol_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003531 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
3532
3533 ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get());
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003534 CGM.getModule().addTypeName("struct._objc_protocol", ProtocolTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003535 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003536
3537 // Class description structures
3538
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003539 // struct _objc_ivar {
3540 // char *ivar_name;
3541 // char *ivar_type;
3542 // int ivar_offset;
3543 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003544 IvarTy = llvm::StructType::get(Int8PtrTy,
3545 Int8PtrTy,
3546 IntTy,
3547 NULL);
3548 CGM.getModule().addTypeName("struct._objc_ivar", IvarTy);
3549
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003550 // struct _objc_ivar_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003551 IvarListTy = llvm::OpaqueType::get();
3552 CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy);
3553 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
3554
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003555 // struct _objc_method_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003556 MethodListTy = llvm::OpaqueType::get();
3557 CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy);
3558 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
3559
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003560 // struct _objc_class_extension *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003561 ClassExtensionTy =
3562 llvm::StructType::get(IntTy,
3563 Int8PtrTy,
3564 PropertyListPtrTy,
3565 NULL);
3566 CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy);
3567 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
3568
3569 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3570
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003571 // struct _objc_class {
3572 // Class isa;
3573 // Class super_class;
3574 // char *name;
3575 // long version;
3576 // long info;
3577 // long instance_size;
3578 // struct _objc_ivar_list *ivars;
3579 // struct _objc_method_list *methods;
3580 // struct _objc_cache *cache;
3581 // struct _objc_protocol_list *protocols;
3582 // char *ivar_layout;
3583 // struct _objc_class_ext *ext;
3584 // };
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003585 T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3586 llvm::PointerType::getUnqual(ClassTyHolder),
3587 Int8PtrTy,
3588 LongTy,
3589 LongTy,
3590 LongTy,
3591 IvarListPtrTy,
3592 MethodListPtrTy,
3593 CachePtrTy,
3594 ProtocolListPtrTy,
3595 Int8PtrTy,
3596 ClassExtensionPtrTy,
3597 NULL);
3598 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T);
3599
3600 ClassTy = cast<llvm::StructType>(ClassTyHolder.get());
3601 CGM.getModule().addTypeName("struct._objc_class", ClassTy);
3602 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
3603
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003604 // struct _objc_category {
3605 // char *category_name;
3606 // char *class_name;
3607 // struct _objc_method_list *instance_method;
3608 // struct _objc_method_list *class_method;
3609 // uint32_t size; // sizeof(struct _objc_category)
3610 // struct _objc_property_list *instance_properties;// category's @property
3611 // }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003612 CategoryTy = llvm::StructType::get(Int8PtrTy,
3613 Int8PtrTy,
3614 MethodListPtrTy,
3615 MethodListPtrTy,
3616 ProtocolListPtrTy,
3617 IntTy,
3618 PropertyListPtrTy,
3619 NULL);
3620 CGM.getModule().addTypeName("struct._objc_category", CategoryTy);
3621
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003622 // Global metadata structures
3623
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003624 // struct _objc_symtab {
3625 // long sel_ref_cnt;
3626 // SEL *refs;
3627 // short cls_def_cnt;
3628 // short cat_def_cnt;
3629 // char *defs[cls_def_cnt + cat_def_cnt];
3630 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003631 SymtabTy = llvm::StructType::get(LongTy,
3632 SelectorPtrTy,
3633 ShortTy,
3634 ShortTy,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003635 llvm::ArrayType::get(Int8PtrTy, 0),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003636 NULL);
3637 CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy);
3638 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
3639
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003640 // struct _objc_module {
3641 // long version;
3642 // long size; // sizeof(struct _objc_module)
3643 // char *name;
3644 // struct _objc_symtab* symtab;
3645 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003646 ModuleTy =
3647 llvm::StructType::get(LongTy,
3648 LongTy,
3649 Int8PtrTy,
3650 SymtabPtrTy,
3651 NULL);
3652 CGM.getModule().addTypeName("struct._objc_module", ModuleTy);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003653
Anders Carlsson2abd89c2008-08-31 04:05:03 +00003654
Anders Carlsson124526b2008-09-09 10:10:21 +00003655 // FIXME: This is the size of the setjmp buffer and should be
3656 // target specific. 18 is what's used on 32-bit X86.
3657 uint64_t SetJmpBufferSize = 18;
3658
3659 // Exceptions
3660 const llvm::Type *StackPtrTy =
Daniel Dunbar10004912008-09-27 06:32:25 +00003661 llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4);
Anders Carlsson124526b2008-09-09 10:10:21 +00003662
3663 ExceptionDataTy =
3664 llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty,
3665 SetJmpBufferSize),
3666 StackPtrTy, NULL);
3667 CGM.getModule().addTypeName("struct._objc_exception_data",
3668 ExceptionDataTy);
3669
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003670}
3671
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003672ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003673: ObjCCommonTypesHelper(cgm)
3674{
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003675 // struct _method_list_t {
3676 // uint32_t entsize; // sizeof(struct _objc_method)
3677 // uint32_t method_count;
3678 // struct _objc_method method_list[method_count];
3679 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003680 MethodListnfABITy = llvm::StructType::get(IntTy,
3681 IntTy,
3682 llvm::ArrayType::get(MethodTy, 0),
3683 NULL);
3684 CGM.getModule().addTypeName("struct.__method_list_t",
3685 MethodListnfABITy);
3686 // struct method_list_t *
3687 MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003688
3689 // struct _protocol_t {
3690 // id isa; // NULL
3691 // const char * const protocol_name;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003692 // const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003693 // const struct method_list_t * const instance_methods;
3694 // const struct method_list_t * const class_methods;
3695 // const struct method_list_t *optionalInstanceMethods;
3696 // const struct method_list_t *optionalClassMethods;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003697 // const struct _prop_list_t * properties;
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003698 // const uint32_t size; // sizeof(struct _protocol_t)
3699 // const uint32_t flags; // = 0
3700 // }
3701
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003702 // Holder for struct _protocol_list_t *
3703 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3704
3705 ProtocolnfABITy = llvm::StructType::get(ObjectPtrTy,
3706 Int8PtrTy,
3707 llvm::PointerType::getUnqual(
3708 ProtocolListTyHolder),
3709 MethodListnfABIPtrTy,
3710 MethodListnfABIPtrTy,
3711 MethodListnfABIPtrTy,
3712 MethodListnfABIPtrTy,
3713 PropertyListPtrTy,
3714 IntTy,
3715 IntTy,
3716 NULL);
3717 CGM.getModule().addTypeName("struct._protocol_t",
3718 ProtocolnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003719
3720 // struct _protocol_t*
3721 ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003722
Fariborz Jahanianda320092009-01-29 19:24:30 +00003723 // struct _protocol_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003724 // long protocol_count; // Note, this is 32/64 bit
Daniel Dunbar948e2582009-02-15 07:36:20 +00003725 // struct _protocol_t *[protocol_count];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003726 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003727 ProtocolListnfABITy = llvm::StructType::get(LongTy,
3728 llvm::ArrayType::get(
Daniel Dunbar948e2582009-02-15 07:36:20 +00003729 ProtocolnfABIPtrTy, 0),
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003730 NULL);
3731 CGM.getModule().addTypeName("struct._objc_protocol_list",
3732 ProtocolListnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003733 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(
3734 ProtocolListnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003735
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003736 // struct _objc_protocol_list*
3737 ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003738
3739 // struct _ivar_t {
3740 // unsigned long int *offset; // pointer to ivar offset location
3741 // char *name;
3742 // char *type;
3743 // uint32_t alignment;
3744 // uint32_t size;
3745 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003746 IvarnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(LongTy),
3747 Int8PtrTy,
3748 Int8PtrTy,
3749 IntTy,
3750 IntTy,
3751 NULL);
3752 CGM.getModule().addTypeName("struct._ivar_t", IvarnfABITy);
3753
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003754 // struct _ivar_list_t {
3755 // uint32 entsize; // sizeof(struct _ivar_t)
3756 // uint32 count;
3757 // struct _iver_t list[count];
3758 // }
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003759 IvarListnfABITy = llvm::StructType::get(IntTy,
3760 IntTy,
3761 llvm::ArrayType::get(
3762 IvarnfABITy, 0),
3763 NULL);
3764 CGM.getModule().addTypeName("struct._ivar_list_t", IvarListnfABITy);
3765
3766 IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003767
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003768 // struct _class_ro_t {
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003769 // uint32_t const flags;
3770 // uint32_t const instanceStart;
3771 // uint32_t const instanceSize;
3772 // uint32_t const reserved; // only when building for 64bit targets
3773 // const uint8_t * const ivarLayout;
3774 // const char *const name;
3775 // const struct _method_list_t * const baseMethods;
3776 // const struct _objc_protocol_list *const baseProtocols;
3777 // const struct _ivar_list_t *const ivars;
3778 // const uint8_t * const weakIvarLayout;
3779 // const struct _prop_list_t * const properties;
3780 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003781
3782 // FIXME. Add 'reserved' field in 64bit abi mode!
3783 ClassRonfABITy = llvm::StructType::get(IntTy,
3784 IntTy,
3785 IntTy,
3786 Int8PtrTy,
3787 Int8PtrTy,
3788 MethodListnfABIPtrTy,
3789 ProtocolListnfABIPtrTy,
3790 IvarListnfABIPtrTy,
3791 Int8PtrTy,
3792 PropertyListPtrTy,
3793 NULL);
3794 CGM.getModule().addTypeName("struct._class_ro_t",
3795 ClassRonfABITy);
3796
3797 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
3798 std::vector<const llvm::Type*> Params;
3799 Params.push_back(ObjectPtrTy);
3800 Params.push_back(SelectorPtrTy);
3801 ImpnfABITy = llvm::PointerType::getUnqual(
3802 llvm::FunctionType::get(ObjectPtrTy, Params, false));
3803
3804 // struct _class_t {
3805 // struct _class_t *isa;
3806 // struct _class_t * const superclass;
3807 // void *cache;
3808 // IMP *vtable;
3809 // struct class_ro_t *ro;
3810 // }
3811
3812 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3813 ClassnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3814 llvm::PointerType::getUnqual(ClassTyHolder),
3815 CachePtrTy,
3816 llvm::PointerType::getUnqual(ImpnfABITy),
3817 llvm::PointerType::getUnqual(
3818 ClassRonfABITy),
3819 NULL);
3820 CGM.getModule().addTypeName("struct._class_t", ClassnfABITy);
3821
3822 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(
3823 ClassnfABITy);
3824
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003825 // LLVM for struct _class_t *
3826 ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy);
3827
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003828 // struct _category_t {
3829 // const char * const name;
3830 // struct _class_t *const cls;
3831 // const struct _method_list_t * const instance_methods;
3832 // const struct _method_list_t * const class_methods;
3833 // const struct _protocol_list_t * const protocols;
3834 // const struct _prop_list_t * const properties;
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003835 // }
3836 CategorynfABITy = llvm::StructType::get(Int8PtrTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003837 ClassnfABIPtrTy,
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003838 MethodListnfABIPtrTy,
3839 MethodListnfABIPtrTy,
3840 ProtocolListnfABIPtrTy,
3841 PropertyListPtrTy,
3842 NULL);
3843 CGM.getModule().addTypeName("struct._category_t", CategorynfABITy);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003844
3845 // New types for nonfragile abi messaging.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003846 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3847 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003848
3849 // MessageRefTy - LLVM for:
3850 // struct _message_ref_t {
3851 // IMP messenger;
3852 // SEL name;
3853 // };
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003854
3855 // First the clang type for struct _message_ref_t
3856 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3857 SourceLocation(),
3858 &Ctx.Idents.get("_message_ref_t"));
Douglas Gregor6ab35242009-04-09 21:40:53 +00003859 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3860 Ctx.VoidPtrTy, 0, false));
3861 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3862 Ctx.getObjCSelType(), 0, false));
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003863 RD->completeDefinition(Ctx);
3864
3865 MessageRefCTy = Ctx.getTagDeclType(RD);
3866 MessageRefCPtrTy = Ctx.getPointerType(MessageRefCTy);
3867 MessageRefTy = cast<llvm::StructType>(Types.ConvertType(MessageRefCTy));
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003868
3869 // MessageRefPtrTy - LLVM for struct _message_ref_t*
3870 MessageRefPtrTy = llvm::PointerType::getUnqual(MessageRefTy);
3871
3872 // SuperMessageRefTy - LLVM for:
3873 // struct _super_message_ref_t {
3874 // SUPER_IMP messenger;
3875 // SEL name;
3876 // };
3877 SuperMessageRefTy = llvm::StructType::get(ImpnfABITy,
3878 SelectorPtrTy,
3879 NULL);
3880 CGM.getModule().addTypeName("struct._super_message_ref_t", SuperMessageRefTy);
3881
3882 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
3883 SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy);
3884
3885 // id objc_msgSend_fixup (id, struct message_ref_t*, ...)
3886 Params.clear();
3887 Params.push_back(ObjectPtrTy);
3888 Params.push_back(MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00003889 MessengerTy = llvm::FunctionType::get(ObjectPtrTy,
3890 Params,
3891 true);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003892 MessageSendFixupFn =
Fariborz Jahanianef163782009-02-05 01:13:09 +00003893 CGM.CreateRuntimeFunction(MessengerTy,
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003894 "objc_msgSend_fixup");
3895
3896 // id objc_msgSend_fpret_fixup (id, struct message_ref_t*, ...)
3897 MessageSendFpretFixupFn =
3898 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3899 Params,
3900 true),
3901 "objc_msgSend_fpret_fixup");
3902
3903 // id objc_msgSend_stret_fixup (id, struct message_ref_t*, ...)
3904 MessageSendStretFixupFn =
3905 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3906 Params,
3907 true),
3908 "objc_msgSend_stret_fixup");
3909
3910 // id objc_msgSendId_fixup (id, struct message_ref_t*, ...)
3911 MessageSendIdFixupFn =
3912 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3913 Params,
3914 true),
3915 "objc_msgSendId_fixup");
3916
3917
3918 // id objc_msgSendId_stret_fixup (id, struct message_ref_t*, ...)
3919 MessageSendIdStretFixupFn =
3920 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3921 Params,
3922 true),
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003923 "objc_msgSendId_stret_fixup");
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003924
3925 // id objc_msgSendSuper2_fixup (struct objc_super *,
3926 // struct _super_message_ref_t*, ...)
3927 Params.clear();
3928 Params.push_back(SuperPtrTy);
3929 Params.push_back(SuperMessageRefPtrTy);
3930 MessageSendSuper2FixupFn =
3931 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3932 Params,
3933 true),
3934 "objc_msgSendSuper2_fixup");
3935
3936
3937 // id objc_msgSendSuper2_stret_fixup (struct objc_super *,
3938 // struct _super_message_ref_t*, ...)
3939 MessageSendSuper2StretFixupFn =
3940 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3941 Params,
3942 true),
3943 "objc_msgSendSuper2_stret_fixup");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00003944
3945 Params.clear();
Daniel Dunbare588b992009-03-01 04:46:24 +00003946
3947 // struct objc_typeinfo {
3948 // const void** vtable; // objc_ehtype_vtable + 2
3949 // const char* name; // c++ typeinfo string
3950 // Class cls;
3951 // };
3952 EHTypeTy = llvm::StructType::get(llvm::PointerType::getUnqual(Int8PtrTy),
3953 Int8PtrTy,
3954 ClassnfABIPtrTy,
3955 NULL);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00003956 CGM.getModule().addTypeName("struct._objc_typeinfo", EHTypeTy);
Daniel Dunbare588b992009-03-01 04:46:24 +00003957 EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy);
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003958}
3959
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003960llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() {
3961 FinishNonFragileABIModule();
3962
3963 return NULL;
3964}
3965
3966void CGObjCNonFragileABIMac::FinishNonFragileABIModule() {
3967 // nonfragile abi has no module definition.
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003968
3969 // Build list of all implemented classe addresses in array
3970 // L_OBJC_LABEL_CLASS_$.
3971 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CLASS_$
3972 // list of 'nonlazy' implementations (defined as those with a +load{}
3973 // method!!).
3974 unsigned NumClasses = DefinedClasses.size();
3975 if (NumClasses) {
3976 std::vector<llvm::Constant*> Symbols(NumClasses);
3977 for (unsigned i=0; i<NumClasses; i++)
3978 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
3979 ObjCTypes.Int8PtrTy);
3980 llvm::Constant* Init =
3981 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
3982 NumClasses),
3983 Symbols);
3984
3985 llvm::GlobalVariable *GV =
3986 new llvm::GlobalVariable(Init->getType(), false,
3987 llvm::GlobalValue::InternalLinkage,
3988 Init,
3989 "\01L_OBJC_LABEL_CLASS_$",
3990 &CGM.getModule());
Daniel Dunbar58a29122009-03-09 22:18:41 +00003991 GV->setAlignment(8);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003992 GV->setSection("__DATA, __objc_classlist, regular, no_dead_strip");
3993 UsedGlobals.push_back(GV);
3994 }
3995
3996 // Build list of all implemented category addresses in array
3997 // L_OBJC_LABEL_CATEGORY_$.
3998 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CATEGORY_$
3999 // list of 'nonlazy' category implementations (defined as those with a +load{}
4000 // method!!).
4001 unsigned NumCategory = DefinedCategories.size();
4002 if (NumCategory) {
4003 std::vector<llvm::Constant*> Symbols(NumCategory);
4004 for (unsigned i=0; i<NumCategory; i++)
4005 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedCategories[i],
4006 ObjCTypes.Int8PtrTy);
4007 llvm::Constant* Init =
4008 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
4009 NumCategory),
4010 Symbols);
4011
4012 llvm::GlobalVariable *GV =
4013 new llvm::GlobalVariable(Init->getType(), false,
4014 llvm::GlobalValue::InternalLinkage,
4015 Init,
4016 "\01L_OBJC_LABEL_CATEGORY_$",
4017 &CGM.getModule());
Daniel Dunbar58a29122009-03-09 22:18:41 +00004018 GV->setAlignment(8);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004019 GV->setSection("__DATA, __objc_catlist, regular, no_dead_strip");
4020 UsedGlobals.push_back(GV);
4021 }
4022
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004023 // static int L_OBJC_IMAGE_INFO[2] = { 0, flags };
4024 // FIXME. flags can be 0 | 1 | 2 | 6. For now just use 0
4025 std::vector<llvm::Constant*> Values(2);
4026 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, 0);
Fariborz Jahanian067986e2009-02-24 21:08:09 +00004027 unsigned int flags = 0;
Fariborz Jahanian66a5c2c2009-02-24 23:34:44 +00004028 // FIXME: Fix and continue?
4029 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
4030 flags |= eImageInfo_GarbageCollected;
4031 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
4032 flags |= eImageInfo_GCOnly;
Fariborz Jahanian067986e2009-02-24 21:08:09 +00004033 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004034 llvm::Constant* Init = llvm::ConstantArray::get(
4035 llvm::ArrayType::get(ObjCTypes.IntTy, 2),
4036 Values);
4037 llvm::GlobalVariable *IMGV =
4038 new llvm::GlobalVariable(Init->getType(), false,
4039 llvm::GlobalValue::InternalLinkage,
4040 Init,
4041 "\01L_OBJC_IMAGE_INFO",
4042 &CGM.getModule());
4043 IMGV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
4044 UsedGlobals.push_back(IMGV);
4045
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004046 std::vector<llvm::Constant*> Used;
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004047
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004048 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
4049 e = UsedGlobals.end(); i != e; ++i) {
4050 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
4051 }
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004052
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004053 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
4054 llvm::GlobalValue *GV =
4055 new llvm::GlobalVariable(AT, false,
4056 llvm::GlobalValue::AppendingLinkage,
4057 llvm::ConstantArray::get(AT, Used),
4058 "llvm.used",
4059 &CGM.getModule());
4060
4061 GV->setSection("llvm.metadata");
4062
4063}
4064
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004065// Metadata flags
4066enum MetaDataDlags {
4067 CLS = 0x0,
4068 CLS_META = 0x1,
4069 CLS_ROOT = 0x2,
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004070 OBJC2_CLS_HIDDEN = 0x10,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004071 CLS_EXCEPTION = 0x20
4072};
4073/// BuildClassRoTInitializer - generate meta-data for:
4074/// struct _class_ro_t {
4075/// uint32_t const flags;
4076/// uint32_t const instanceStart;
4077/// uint32_t const instanceSize;
4078/// uint32_t const reserved; // only when building for 64bit targets
4079/// const uint8_t * const ivarLayout;
4080/// const char *const name;
4081/// const struct _method_list_t * const baseMethods;
Fariborz Jahanianda320092009-01-29 19:24:30 +00004082/// const struct _protocol_list_t *const baseProtocols;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004083/// const struct _ivar_list_t *const ivars;
4084/// const uint8_t * const weakIvarLayout;
4085/// const struct _prop_list_t * const properties;
4086/// }
4087///
4088llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer(
4089 unsigned flags,
4090 unsigned InstanceStart,
4091 unsigned InstanceSize,
4092 const ObjCImplementationDecl *ID) {
4093 std::string ClassName = ID->getNameAsString();
4094 std::vector<llvm::Constant*> Values(10); // 11 for 64bit targets!
4095 Values[ 0] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
4096 Values[ 1] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceStart);
4097 Values[ 2] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceSize);
4098 // FIXME. For 64bit targets add 0 here.
Fariborz Jahanianda320092009-01-29 19:24:30 +00004099 // FIXME. ivarLayout is currently null!
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00004100 // Values[ 3] = (flags & CLS_META) ? GetIvarLayoutName(0, ObjCTypes)
4101 // : BuildIvarLayout(ID, true);
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00004102 Values[ 3] = GetIvarLayoutName(0, ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004103 Values[ 4] = GetClassName(ID->getIdentifier());
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004104 // const struct _method_list_t * const baseMethods;
4105 std::vector<llvm::Constant*> Methods;
4106 std::string MethodListName("\01l_OBJC_$_");
4107 if (flags & CLS_META) {
4108 MethodListName += "CLASS_METHODS_" + ID->getNameAsString();
4109 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
4110 e = ID->classmeth_end(); i != e; ++i) {
4111 // Class methods should always be defined.
4112 Methods.push_back(GetMethodConstant(*i));
4113 }
4114 } else {
4115 MethodListName += "INSTANCE_METHODS_" + ID->getNameAsString();
4116 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
4117 e = ID->instmeth_end(); i != e; ++i) {
4118 // Instance methods should always be defined.
4119 Methods.push_back(GetMethodConstant(*i));
4120 }
Fariborz Jahanian939abce2009-01-28 22:46:49 +00004121 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
4122 e = ID->propimpl_end(); i != e; ++i) {
4123 ObjCPropertyImplDecl *PID = *i;
4124
4125 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize){
4126 ObjCPropertyDecl *PD = PID->getPropertyDecl();
4127
4128 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
4129 if (llvm::Constant *C = GetMethodConstant(MD))
4130 Methods.push_back(C);
4131 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
4132 if (llvm::Constant *C = GetMethodConstant(MD))
4133 Methods.push_back(C);
4134 }
4135 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004136 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004137 Values[ 5] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004138 "__DATA, __objc_const", Methods);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004139
4140 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4141 assert(OID && "CGObjCNonFragileABIMac::BuildClassRoTInitializer");
4142 Values[ 6] = EmitProtocolList("\01l_OBJC_CLASS_PROTOCOLS_$_"
4143 + OID->getNameAsString(),
4144 OID->protocol_begin(),
4145 OID->protocol_end());
4146
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004147 if (flags & CLS_META)
4148 Values[ 7] = llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4149 else
4150 Values[ 7] = EmitIvarList(ID);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004151 // FIXME. weakIvarLayout is currently null.
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00004152 // Values[ 8] = (flags & CLS_META) ? GetIvarLayoutName(0, ObjCTypes)
4153 // : BuildIvarLayout(ID, false);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00004154 Values[ 8] = GetIvarLayoutName(0, ObjCTypes);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004155 if (flags & CLS_META)
4156 Values[ 9] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4157 else
4158 Values[ 9] =
4159 EmitPropertyList(
4160 "\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
4161 ID, ID->getClassInterface(), ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004162 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassRonfABITy,
4163 Values);
4164 llvm::GlobalVariable *CLASS_RO_GV =
4165 new llvm::GlobalVariable(ObjCTypes.ClassRonfABITy, false,
4166 llvm::GlobalValue::InternalLinkage,
4167 Init,
4168 (flags & CLS_META) ?
4169 std::string("\01l_OBJC_METACLASS_RO_$_")+ClassName :
4170 std::string("\01l_OBJC_CLASS_RO_$_")+ClassName,
4171 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004172 CLASS_RO_GV->setAlignment(
4173 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassRonfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004174 CLASS_RO_GV->setSection("__DATA, __objc_const");
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004175 return CLASS_RO_GV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004176
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004177}
4178
4179/// BuildClassMetaData - This routine defines that to-level meta-data
4180/// for the given ClassName for:
4181/// struct _class_t {
4182/// struct _class_t *isa;
4183/// struct _class_t * const superclass;
4184/// void *cache;
4185/// IMP *vtable;
4186/// struct class_ro_t *ro;
4187/// }
4188///
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004189llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassMetaData(
4190 std::string &ClassName,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004191 llvm::Constant *IsAGV,
4192 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004193 llvm::Constant *ClassRoGV,
4194 bool HiddenVisibility) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004195 std::vector<llvm::Constant*> Values(5);
4196 Values[0] = IsAGV;
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004197 Values[1] = SuperClassGV
4198 ? SuperClassGV
4199 : llvm::Constant::getNullValue(ObjCTypes.ClassnfABIPtrTy);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004200 Values[2] = ObjCEmptyCacheVar; // &ObjCEmptyCacheVar
4201 Values[3] = ObjCEmptyVtableVar; // &ObjCEmptyVtableVar
4202 Values[4] = ClassRoGV; // &CLASS_RO_GV
4203 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassnfABITy,
4204 Values);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004205 llvm::GlobalVariable *GV = GetClassGlobal(ClassName);
4206 GV->setInitializer(Init);
Fariborz Jahaniandd0db2a2009-01-31 01:07:39 +00004207 GV->setSection("__DATA, __objc_data");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004208 GV->setAlignment(
4209 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassnfABITy));
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004210 if (HiddenVisibility)
4211 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004212 return GV;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004213}
4214
Daniel Dunbar6c1aac82009-04-20 20:18:54 +00004215/// countInheritedIvars - count number of ivars in class and its super class(s)
4216///
4217static int countInheritedIvars(const ObjCInterfaceDecl *OI,
4218 ASTContext &Context) {
4219 int count = 0;
4220 if (!OI)
4221 return 0;
4222 const ObjCInterfaceDecl *SuperClass = OI->getSuperClass();
4223 if (SuperClass)
4224 count += countInheritedIvars(SuperClass, Context);
4225 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
4226 E = OI->ivar_end(); I != E; ++I)
4227 ++count;
4228 // look into properties.
4229 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(Context),
4230 E = OI->prop_end(Context); I != E; ++I) {
4231 if ((*I)->getPropertyIvarDecl())
4232 ++count;
4233 }
4234 return count;
4235}
4236
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004237void CGObjCNonFragileABIMac::GetClassSizeInfo(const ObjCInterfaceDecl *OID,
4238 uint32_t &InstanceStart,
4239 uint32_t &InstanceSize) {
Daniel Dunbar24c89912009-04-21 21:41:56 +00004240 assert(!OID->isForwardDecl() && "Invalid interface decl!");
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004241 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID);
4242
Daniel Dunbar6ec07162009-04-20 07:18:49 +00004243 int countSuperClassIvars = countInheritedIvars(OID->getSuperClass(),
4244 CGM.getContext());
4245 const RecordDecl *RD = CGM.getContext().addRecordToClass(OID);
4246 RecordDecl::field_iterator firstField = RD->field_begin(CGM.getContext());
4247 RecordDecl::field_iterator lastField = RD->field_end(CGM.getContext());
4248 while (countSuperClassIvars-- > 0) {
4249 lastField = firstField;
4250 ++firstField;
4251 }
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004252
4253 for (RecordDecl::field_iterator e = RD->field_end(CGM.getContext()),
4254 ifield = firstField; ifield != e; ++ifield)
4255 lastField = ifield;
4256
4257 InstanceStart = InstanceSize = 0;
4258 if (lastField != RD->field_end(CGM.getContext())) {
4259 FieldDecl *Field = *lastField;
4260 const llvm::Type *FieldTy =
4261 CGM.getTypes().ConvertTypeForMem(Field->getType());
4262 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
4263 InstanceSize = GetIvarBaseOffset(Layout, Field) + Size;
4264 if (firstField == RD->field_end(CGM.getContext()))
4265 InstanceStart = InstanceSize;
4266 else {
4267 Field = *firstField;
4268 InstanceStart = GetIvarBaseOffset(Layout, Field);
4269 }
4270 }
4271}
4272
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004273void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) {
4274 std::string ClassName = ID->getNameAsString();
4275 if (!ObjCEmptyCacheVar) {
4276 ObjCEmptyCacheVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004277 ObjCTypes.CacheTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004278 false,
4279 llvm::GlobalValue::ExternalLinkage,
4280 0,
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004281 "_objc_empty_cache",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004282 &CGM.getModule());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004283
4284 ObjCEmptyVtableVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004285 ObjCTypes.ImpnfABITy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004286 false,
4287 llvm::GlobalValue::ExternalLinkage,
4288 0,
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004289 "_objc_empty_vtable",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004290 &CGM.getModule());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004291 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004292 assert(ID->getClassInterface() &&
4293 "CGObjCNonFragileABIMac::GenerateClass - class is 0");
Daniel Dunbar6c1aac82009-04-20 20:18:54 +00004294 // FIXME: Is this correct (that meta class size is never computed)?
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004295 uint32_t InstanceStart =
4296 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassnfABITy);
4297 uint32_t InstanceSize = InstanceStart;
4298 uint32_t flags = CLS_META;
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004299 std::string ObjCMetaClassName(getMetaclassSymbolPrefix());
4300 std::string ObjCClassName(getClassSymbolPrefix());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004301
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004302 llvm::GlobalVariable *SuperClassGV, *IsAGV;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004303
Daniel Dunbar04d40782009-04-14 06:00:08 +00004304 bool classIsHidden =
4305 CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004306 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004307 flags |= OBJC2_CLS_HIDDEN;
4308 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004309 // class is root
4310 flags |= CLS_ROOT;
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004311 SuperClassGV = GetClassGlobal(ObjCClassName + ClassName);
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004312 IsAGV = GetClassGlobal(ObjCMetaClassName + ClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004313 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004314 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004315 const ObjCInterfaceDecl *Root = ID->getClassInterface();
4316 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
4317 Root = Super;
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004318 IsAGV = GetClassGlobal(ObjCMetaClassName + Root->getNameAsString());
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004319 // work on super class metadata symbol.
4320 std::string SuperClassName =
4321 ObjCMetaClassName + ID->getClassInterface()->getSuperClass()->getNameAsString();
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004322 SuperClassGV = GetClassGlobal(SuperClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004323 }
4324 llvm::GlobalVariable *CLASS_RO_GV = BuildClassRoTInitializer(flags,
4325 InstanceStart,
4326 InstanceSize,ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004327 std::string TClassName = ObjCMetaClassName + ClassName;
4328 llvm::GlobalVariable *MetaTClass =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004329 BuildClassMetaData(TClassName, IsAGV, SuperClassGV, CLASS_RO_GV,
4330 classIsHidden);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004331
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004332 // Metadata for the class
4333 flags = CLS;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004334 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004335 flags |= OBJC2_CLS_HIDDEN;
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004336
4337 if (hasObjCExceptionAttribute(ID->getClassInterface()))
4338 flags |= CLS_EXCEPTION;
4339
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004340 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004341 flags |= CLS_ROOT;
4342 SuperClassGV = 0;
Chris Lattnerb7b58b12009-04-19 06:02:28 +00004343 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004344 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004345 std::string RootClassName =
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004346 ID->getClassInterface()->getSuperClass()->getNameAsString();
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004347 SuperClassGV = GetClassGlobal(ObjCClassName + RootClassName);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004348 }
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004349 GetClassSizeInfo(ID->getClassInterface(), InstanceStart, InstanceSize);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004350 CLASS_RO_GV = BuildClassRoTInitializer(flags,
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004351 InstanceStart,
4352 InstanceSize,
4353 ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004354
4355 TClassName = ObjCClassName + ClassName;
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004356 llvm::GlobalVariable *ClassMD =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004357 BuildClassMetaData(TClassName, MetaTClass, SuperClassGV, CLASS_RO_GV,
4358 classIsHidden);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004359 DefinedClasses.push_back(ClassMD);
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004360
4361 // Force the definition of the EHType if necessary.
4362 if (flags & CLS_EXCEPTION)
4363 GetInterfaceEHType(ID->getClassInterface(), true);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004364}
4365
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004366/// GenerateProtocolRef - This routine is called to generate code for
4367/// a protocol reference expression; as in:
4368/// @code
4369/// @protocol(Proto1);
4370/// @endcode
4371/// It generates a weak reference to l_OBJC_PROTOCOL_REFERENCE_$_Proto1
4372/// which will hold address of the protocol meta-data.
4373///
4374llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CGBuilderTy &Builder,
4375 const ObjCProtocolDecl *PD) {
4376
Fariborz Jahanian960cd062009-04-10 18:47:34 +00004377 // This routine is called for @protocol only. So, we must build definition
4378 // of protocol's meta-data (not a reference to it!)
4379 //
4380 llvm::Constant *Init = llvm::ConstantExpr::getBitCast(GetOrEmitProtocol(PD),
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004381 ObjCTypes.ExternalProtocolPtrTy);
4382
4383 std::string ProtocolName("\01l_OBJC_PROTOCOL_REFERENCE_$_");
4384 ProtocolName += PD->getNameAsCString();
4385
4386 llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName);
4387 if (PTGV)
4388 return Builder.CreateLoad(PTGV, false, "tmp");
4389 PTGV = new llvm::GlobalVariable(
4390 Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00004391 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004392 Init,
4393 ProtocolName,
4394 &CGM.getModule());
4395 PTGV->setSection("__DATA, __objc_protorefs, coalesced, no_dead_strip");
4396 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4397 UsedGlobals.push_back(PTGV);
4398 return Builder.CreateLoad(PTGV, false, "tmp");
4399}
4400
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004401/// GenerateCategory - Build metadata for a category implementation.
4402/// struct _category_t {
4403/// const char * const name;
4404/// struct _class_t *const cls;
4405/// const struct _method_list_t * const instance_methods;
4406/// const struct _method_list_t * const class_methods;
4407/// const struct _protocol_list_t * const protocols;
4408/// const struct _prop_list_t * const properties;
4409/// }
4410///
4411void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD)
4412{
4413 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004414 const char *Prefix = "\01l_OBJC_$_CATEGORY_";
4415 std::string ExtCatName(Prefix + Interface->getNameAsString()+
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004416 "_$_" + OCD->getNameAsString());
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004417 std::string ExtClassName(getClassSymbolPrefix() +
4418 Interface->getNameAsString());
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004419
4420 std::vector<llvm::Constant*> Values(6);
4421 Values[0] = GetClassName(OCD->getIdentifier());
4422 // meta-class entry symbol
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004423 llvm::GlobalVariable *ClassGV = GetClassGlobal(ExtClassName);
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004424 Values[1] = ClassGV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004425 std::vector<llvm::Constant*> Methods;
4426 std::string MethodListName(Prefix);
4427 MethodListName += "INSTANCE_METHODS_" + Interface->getNameAsString() +
4428 "_$_" + OCD->getNameAsString();
4429
4430 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
4431 e = OCD->instmeth_end(); i != e; ++i) {
4432 // Instance methods should always be defined.
4433 Methods.push_back(GetMethodConstant(*i));
4434 }
4435
4436 Values[2] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004437 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004438 Methods);
4439
4440 MethodListName = Prefix;
4441 MethodListName += "CLASS_METHODS_" + Interface->getNameAsString() + "_$_" +
4442 OCD->getNameAsString();
4443 Methods.clear();
4444 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
4445 e = OCD->classmeth_end(); i != e; ++i) {
4446 // Class methods should always be defined.
4447 Methods.push_back(GetMethodConstant(*i));
4448 }
4449
4450 Values[3] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004451 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004452 Methods);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004453 const ObjCCategoryDecl *Category =
4454 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Fariborz Jahanian943ed6f2009-02-13 17:52:22 +00004455 if (Category) {
4456 std::string ExtName(Interface->getNameAsString() + "_$_" +
4457 OCD->getNameAsString());
4458 Values[4] = EmitProtocolList("\01l_OBJC_CATEGORY_PROTOCOLS_$_"
4459 + Interface->getNameAsString() + "_$_"
4460 + Category->getNameAsString(),
4461 Category->protocol_begin(),
4462 Category->protocol_end());
4463 Values[5] =
4464 EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
4465 OCD, Category, ObjCTypes);
4466 }
4467 else {
4468 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4469 Values[5] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4470 }
4471
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004472 llvm::Constant *Init =
4473 llvm::ConstantStruct::get(ObjCTypes.CategorynfABITy,
4474 Values);
4475 llvm::GlobalVariable *GCATV
4476 = new llvm::GlobalVariable(ObjCTypes.CategorynfABITy,
4477 false,
4478 llvm::GlobalValue::InternalLinkage,
4479 Init,
4480 ExtCatName,
4481 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004482 GCATV->setAlignment(
4483 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.CategorynfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004484 GCATV->setSection("__DATA, __objc_const");
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004485 UsedGlobals.push_back(GCATV);
4486 DefinedCategories.push_back(GCATV);
4487}
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004488
4489/// GetMethodConstant - Return a struct objc_method constant for the
4490/// given method if it has been defined. The result is null if the
4491/// method has not been defined. The return value has type MethodPtrTy.
4492llvm::Constant *CGObjCNonFragileABIMac::GetMethodConstant(
4493 const ObjCMethodDecl *MD) {
4494 // FIXME: Use DenseMap::lookup
4495 llvm::Function *Fn = MethodDefinitions[MD];
4496 if (!Fn)
4497 return 0;
4498
4499 std::vector<llvm::Constant*> Method(3);
4500 Method[0] =
4501 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4502 ObjCTypes.SelectorPtrTy);
4503 Method[1] = GetMethodVarType(MD);
4504 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
4505 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
4506}
4507
4508/// EmitMethodList - Build meta-data for method declarations
4509/// struct _method_list_t {
4510/// uint32_t entsize; // sizeof(struct _objc_method)
4511/// uint32_t method_count;
4512/// struct _objc_method method_list[method_count];
4513/// }
4514///
4515llvm::Constant *CGObjCNonFragileABIMac::EmitMethodList(
4516 const std::string &Name,
4517 const char *Section,
4518 const ConstantVector &Methods) {
4519 // Return null for empty list.
4520 if (Methods.empty())
4521 return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy);
4522
4523 std::vector<llvm::Constant*> Values(3);
4524 // sizeof(struct _objc_method)
4525 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.MethodTy);
4526 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4527 // method_count
4528 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
4529 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
4530 Methods.size());
4531 Values[2] = llvm::ConstantArray::get(AT, Methods);
4532 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4533
4534 llvm::GlobalVariable *GV =
4535 new llvm::GlobalVariable(Init->getType(), false,
4536 llvm::GlobalValue::InternalLinkage,
4537 Init,
4538 Name,
4539 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004540 GV->setAlignment(
4541 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004542 GV->setSection(Section);
4543 UsedGlobals.push_back(GV);
4544 return llvm::ConstantExpr::getBitCast(GV,
4545 ObjCTypes.MethodListnfABIPtrTy);
4546}
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004547
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004548/// ObjCIvarOffsetVariable - Returns the ivar offset variable for
4549/// the given ivar.
4550///
4551llvm::GlobalVariable * CGObjCNonFragileABIMac::ObjCIvarOffsetVariable(
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004552 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004553 const ObjCIvarDecl *Ivar) {
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00004554 std::string Name = "OBJC_IVAR_$_" +
Douglas Gregor6ab35242009-04-09 21:40:53 +00004555 getInterfaceDeclForIvar(ID, Ivar, CGM.getContext())->getNameAsString() +
4556 '.' + Ivar->getNameAsString();
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004557 llvm::GlobalVariable *IvarOffsetGV =
4558 CGM.getModule().getGlobalVariable(Name);
4559 if (!IvarOffsetGV)
4560 IvarOffsetGV =
4561 new llvm::GlobalVariable(ObjCTypes.LongTy,
4562 false,
4563 llvm::GlobalValue::ExternalLinkage,
4564 0,
4565 Name,
4566 &CGM.getModule());
4567 return IvarOffsetGV;
4568}
4569
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004570llvm::Constant * CGObjCNonFragileABIMac::EmitIvarOffsetVar(
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004571 const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004572 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004573 unsigned long int Offset) {
Daniel Dunbar737c5022009-04-19 00:44:02 +00004574 llvm::GlobalVariable *IvarOffsetGV = ObjCIvarOffsetVariable(ID, Ivar);
4575 IvarOffsetGV->setInitializer(llvm::ConstantInt::get(ObjCTypes.LongTy,
4576 Offset));
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004577 IvarOffsetGV->setAlignment(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004578 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.LongTy));
Daniel Dunbar737c5022009-04-19 00:44:02 +00004579
4580 // FIXME: This matches gcc, but shouldn't the visibility be set on
4581 // the use as well (i.e., in ObjCIvarOffsetVariable).
4582 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
4583 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
4584 CGM.getDeclVisibilityMode(ID) == LangOptions::Hidden)
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004585 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar04d40782009-04-14 06:00:08 +00004586 else
Fariborz Jahanian77c9fd22009-04-06 18:30:00 +00004587 IvarOffsetGV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004588 IvarOffsetGV->setSection("__DATA, __objc_const");
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004589 return IvarOffsetGV;
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004590}
4591
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004592/// EmitIvarList - Emit the ivar list for the given
Daniel Dunbar11394522009-04-18 08:51:00 +00004593/// implementation. The return value has type
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004594/// IvarListnfABIPtrTy.
4595/// struct _ivar_t {
4596/// unsigned long int *offset; // pointer to ivar offset location
4597/// char *name;
4598/// char *type;
4599/// uint32_t alignment;
4600/// uint32_t size;
4601/// }
4602/// struct _ivar_list_t {
4603/// uint32 entsize; // sizeof(struct _ivar_t)
4604/// uint32 count;
4605/// struct _iver_t list[count];
4606/// }
4607///
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004608
4609void CGObjCCommonMac::GetNamedIvarList(const ObjCInterfaceDecl *OID,
4610 llvm::SmallVector<ObjCIvarDecl*, 16> &Res) const {
4611 for (ObjCInterfaceDecl::ivar_iterator I = OID->ivar_begin(),
4612 E = OID->ivar_end(); I != E; ++I) {
4613 // Ignore unnamed bit-fields.
4614 if (!(*I)->getDeclName())
4615 continue;
4616
4617 Res.push_back(*I);
4618 }
4619
4620 for (ObjCInterfaceDecl::prop_iterator I = OID->prop_begin(CGM.getContext()),
4621 E = OID->prop_end(CGM.getContext()); I != E; ++I)
4622 if (ObjCIvarDecl *IV = (*I)->getPropertyIvarDecl())
4623 Res.push_back(IV);
4624}
4625
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004626llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList(
4627 const ObjCImplementationDecl *ID) {
4628
4629 std::vector<llvm::Constant*> Ivars, Ivar(5);
4630
4631 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4632 assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface");
4633
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004634 // FIXME. Consolidate this with similar code in GenerateClass.
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00004635 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00004636
Daniel Dunbar91636d62009-04-20 00:33:43 +00004637 // Collect declared and synthesized ivars in a small vector.
Fariborz Jahanian18191882009-03-31 18:11:23 +00004638 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004639 GetNamedIvarList(OID, OIvars);
Fariborz Jahanian99eee362009-04-01 19:37:34 +00004640
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004641 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
4642 ObjCIvarDecl *IVD = OIvars[i];
4643 const FieldDecl *Field = OID->lookupFieldDeclForIvar(CGM.getContext(), IVD);
Daniel Dunbar3eec8aa2009-04-20 05:53:40 +00004644 Ivar[0] = EmitIvarOffsetVar(ID->getClassInterface(), IVD,
Daniel Dunbar48fa0642009-04-19 02:03:42 +00004645 GetIvarBaseOffset(Layout, Field));
Daniel Dunbar3eec8aa2009-04-20 05:53:40 +00004646 Ivar[1] = GetMethodVarName(Field->getIdentifier());
Devang Patel7794bb82009-03-04 18:21:39 +00004647 Ivar[2] = GetMethodVarType(Field);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004648 const llvm::Type *FieldTy =
4649 CGM.getTypes().ConvertTypeForMem(Field->getType());
4650 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
4651 unsigned Align = CGM.getContext().getPreferredTypeAlign(
4652 Field->getType().getTypePtr()) >> 3;
4653 Align = llvm::Log2_32(Align);
4654 Ivar[3] = llvm::ConstantInt::get(ObjCTypes.IntTy, Align);
Daniel Dunbar91636d62009-04-20 00:33:43 +00004655 // NOTE. Size of a bitfield does not match gcc's, because of the
4656 // way bitfields are treated special in each. But I am told that
4657 // 'size' for bitfield ivars is ignored by the runtime so it does
4658 // not matter. If it matters, there is enough info to get the
4659 // bitfield right!
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004660 Ivar[4] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4661 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarnfABITy, Ivar));
4662 }
4663 // Return null for empty list.
4664 if (Ivars.empty())
4665 return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4666 std::vector<llvm::Constant*> Values(3);
4667 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.IvarnfABITy);
4668 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4669 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
4670 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarnfABITy,
4671 Ivars.size());
4672 Values[2] = llvm::ConstantArray::get(AT, Ivars);
4673 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4674 const char *Prefix = "\01l_OBJC_$_INSTANCE_VARIABLES_";
4675 llvm::GlobalVariable *GV =
4676 new llvm::GlobalVariable(Init->getType(), false,
4677 llvm::GlobalValue::InternalLinkage,
4678 Init,
4679 Prefix + OID->getNameAsString(),
4680 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004681 GV->setAlignment(
4682 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004683 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004684
4685 UsedGlobals.push_back(GV);
4686 return llvm::ConstantExpr::getBitCast(GV,
4687 ObjCTypes.IvarListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004688}
4689
4690llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef(
4691 const ObjCProtocolDecl *PD) {
4692 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4693
4694 if (!Entry) {
4695 // We use the initializer as a marker of whether this is a forward
4696 // reference or not. At module finalization we add the empty
4697 // contents for protocols which were referenced but never defined.
4698 Entry =
4699 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
4700 llvm::GlobalValue::ExternalLinkage,
4701 0,
4702 "\01l_OBJC_PROTOCOL_$_" + PD->getNameAsString(),
4703 &CGM.getModule());
4704 Entry->setSection("__DATA,__datacoal_nt,coalesced");
4705 UsedGlobals.push_back(Entry);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004706 }
4707
4708 return Entry;
4709}
4710
4711/// GetOrEmitProtocol - Generate the protocol meta-data:
4712/// @code
4713/// struct _protocol_t {
4714/// id isa; // NULL
4715/// const char * const protocol_name;
4716/// const struct _protocol_list_t * protocol_list; // super protocols
4717/// const struct method_list_t * const instance_methods;
4718/// const struct method_list_t * const class_methods;
4719/// const struct method_list_t *optionalInstanceMethods;
4720/// const struct method_list_t *optionalClassMethods;
4721/// const struct _prop_list_t * properties;
4722/// const uint32_t size; // sizeof(struct _protocol_t)
4723/// const uint32_t flags; // = 0
4724/// }
4725/// @endcode
4726///
4727
4728llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol(
4729 const ObjCProtocolDecl *PD) {
4730 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4731
4732 // Early exit if a defining object has already been generated.
4733 if (Entry && Entry->hasInitializer())
4734 return Entry;
4735
4736 const char *ProtocolName = PD->getNameAsCString();
4737
4738 // Construct method lists.
4739 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
4740 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregor6ab35242009-04-09 21:40:53 +00004741 for (ObjCProtocolDecl::instmeth_iterator
4742 i = PD->instmeth_begin(CGM.getContext()),
4743 e = PD->instmeth_end(CGM.getContext());
4744 i != e; ++i) {
Fariborz Jahanianda320092009-01-29 19:24:30 +00004745 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004746 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004747 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4748 OptInstanceMethods.push_back(C);
4749 } else {
4750 InstanceMethods.push_back(C);
4751 }
4752 }
4753
Douglas Gregor6ab35242009-04-09 21:40:53 +00004754 for (ObjCProtocolDecl::classmeth_iterator
4755 i = PD->classmeth_begin(CGM.getContext()),
4756 e = PD->classmeth_end(CGM.getContext());
4757 i != e; ++i) {
Fariborz Jahanianda320092009-01-29 19:24:30 +00004758 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004759 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004760 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4761 OptClassMethods.push_back(C);
4762 } else {
4763 ClassMethods.push_back(C);
4764 }
4765 }
4766
4767 std::vector<llvm::Constant*> Values(10);
4768 // isa is NULL
4769 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ObjectPtrTy);
4770 Values[1] = GetClassName(PD->getIdentifier());
4771 Values[2] = EmitProtocolList(
4772 "\01l_OBJC_$_PROTOCOL_REFS_" + PD->getNameAsString(),
4773 PD->protocol_begin(),
4774 PD->protocol_end());
4775
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004776 Values[3] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004777 + PD->getNameAsString(),
4778 "__DATA, __objc_const",
4779 InstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004780 Values[4] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004781 + PD->getNameAsString(),
4782 "__DATA, __objc_const",
4783 ClassMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004784 Values[5] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004785 + PD->getNameAsString(),
4786 "__DATA, __objc_const",
4787 OptInstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004788 Values[6] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004789 + PD->getNameAsString(),
4790 "__DATA, __objc_const",
4791 OptClassMethods);
4792 Values[7] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + PD->getNameAsString(),
4793 0, PD, ObjCTypes);
4794 uint32_t Size =
4795 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolnfABITy);
4796 Values[8] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4797 Values[9] = llvm::Constant::getNullValue(ObjCTypes.IntTy);
4798 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolnfABITy,
4799 Values);
4800
4801 if (Entry) {
4802 // Already created, fix the linkage and update the initializer.
Mike Stump286acbd2009-03-07 16:33:28 +00004803 Entry->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004804 Entry->setInitializer(Init);
4805 } else {
4806 Entry =
4807 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004808 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004809 Init,
4810 std::string("\01l_OBJC_PROTOCOL_$_")+ProtocolName,
4811 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004812 Entry->setAlignment(
4813 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABITy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004814 Entry->setSection("__DATA,__datacoal_nt,coalesced");
Fariborz Jahanianda320092009-01-29 19:24:30 +00004815 }
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004816 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
4817
4818 // Use this protocol meta-data to build protocol list table in section
4819 // __DATA, __objc_protolist
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004820 llvm::GlobalVariable *PTGV = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004821 ObjCTypes.ProtocolnfABIPtrTy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004822 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004823 Entry,
4824 std::string("\01l_OBJC_LABEL_PROTOCOL_$_")
4825 +ProtocolName,
4826 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004827 PTGV->setAlignment(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004828 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABIPtrTy));
Daniel Dunbar0bf21992009-04-15 02:56:18 +00004829 PTGV->setSection("__DATA, __objc_protolist, coalesced, no_dead_strip");
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004830 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4831 UsedGlobals.push_back(PTGV);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004832 return Entry;
4833}
4834
4835/// EmitProtocolList - Generate protocol list meta-data:
4836/// @code
4837/// struct _protocol_list_t {
4838/// long protocol_count; // Note, this is 32/64 bit
4839/// struct _protocol_t[protocol_count];
4840/// }
4841/// @endcode
4842///
4843llvm::Constant *
4844CGObjCNonFragileABIMac::EmitProtocolList(const std::string &Name,
4845 ObjCProtocolDecl::protocol_iterator begin,
4846 ObjCProtocolDecl::protocol_iterator end) {
4847 std::vector<llvm::Constant*> ProtocolRefs;
4848
Fariborz Jahanianda320092009-01-29 19:24:30 +00004849 // Just return null for empty protocol lists
Daniel Dunbar948e2582009-02-15 07:36:20 +00004850 if (begin == end)
Fariborz Jahanianda320092009-01-29 19:24:30 +00004851 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4852
Daniel Dunbar948e2582009-02-15 07:36:20 +00004853 // FIXME: We shouldn't need to do this lookup here, should we?
Fariborz Jahanianda320092009-01-29 19:24:30 +00004854 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
4855 if (GV)
Daniel Dunbar948e2582009-02-15 07:36:20 +00004856 return llvm::ConstantExpr::getBitCast(GV,
4857 ObjCTypes.ProtocolListnfABIPtrTy);
4858
4859 for (; begin != end; ++begin)
4860 ProtocolRefs.push_back(GetProtocolRef(*begin)); // Implemented???
4861
Fariborz Jahanianda320092009-01-29 19:24:30 +00004862 // This list is null terminated.
4863 ProtocolRefs.push_back(llvm::Constant::getNullValue(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004864 ObjCTypes.ProtocolnfABIPtrTy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004865
4866 std::vector<llvm::Constant*> Values(2);
4867 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
4868 Values[1] =
Daniel Dunbar948e2582009-02-15 07:36:20 +00004869 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolnfABIPtrTy,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004870 ProtocolRefs.size()),
4871 ProtocolRefs);
4872
4873 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4874 GV = new llvm::GlobalVariable(Init->getType(), false,
4875 llvm::GlobalValue::InternalLinkage,
4876 Init,
4877 Name,
4878 &CGM.getModule());
4879 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004880 GV->setAlignment(
4881 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004882 UsedGlobals.push_back(GV);
Daniel Dunbar948e2582009-02-15 07:36:20 +00004883 return llvm::ConstantExpr::getBitCast(GV,
4884 ObjCTypes.ProtocolListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004885}
4886
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004887/// GetMethodDescriptionConstant - This routine build following meta-data:
4888/// struct _objc_method {
4889/// SEL _cmd;
4890/// char *method_type;
4891/// char *_imp;
4892/// }
4893
4894llvm::Constant *
4895CGObjCNonFragileABIMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
4896 std::vector<llvm::Constant*> Desc(3);
4897 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4898 ObjCTypes.SelectorPtrTy);
4899 Desc[1] = GetMethodVarType(MD);
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004900 // Protocol methods have no implementation. So, this entry is always NULL.
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004901 Desc[2] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
4902 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Desc);
4903}
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004904
4905/// EmitObjCValueForIvar - Code Gen for nonfragile ivar reference.
4906/// This code gen. amounts to generating code for:
4907/// @code
4908/// (type *)((char *)base + _OBJC_IVAR_$_.ivar;
4909/// @encode
4910///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004911LValue CGObjCNonFragileABIMac::EmitObjCValueForIvar(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004912 CodeGen::CodeGenFunction &CGF,
4913 QualType ObjectTy,
4914 llvm::Value *BaseValue,
4915 const ObjCIvarDecl *Ivar,
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004916 unsigned CVRQualifiers) {
Daniel Dunbar525c9b72009-04-21 01:19:28 +00004917 const ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
4918 const FieldDecl *Field = ID->lookupFieldDeclForIvar(CGM.getContext(), Ivar);
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00004919 llvm::GlobalVariable *IvarOffsetGV = ObjCIvarOffsetVariable(ID, Ivar);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004920
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004921 // (char *) BaseValue
Chris Lattner51123fe2009-04-17 17:46:19 +00004922 llvm::Value *V = CGF.Builder.CreateBitCast(BaseValue, ObjCTypes.Int8PtrTy);
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004923 llvm::Value *Offset = CGF.Builder.CreateLoad(IvarOffsetGV);
4924 // (char*)BaseValue + Offset_symbol
4925 V = CGF.Builder.CreateGEP(V, Offset, "add.ptr");
4926 // (type *)((char*)BaseValue + Offset_symbol)
4927 const llvm::Type *IvarTy =
Chris Lattner51123fe2009-04-17 17:46:19 +00004928 CGM.getTypes().ConvertTypeForMem(Ivar->getType());
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004929 llvm::Type *ptrIvarTy = llvm::PointerType::getUnqual(IvarTy);
4930 V = CGF.Builder.CreateBitCast(V, ptrIvarTy);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004931
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00004932 if (Ivar->isBitField()) {
Chris Lattner51123fe2009-04-17 17:46:19 +00004933 QualType FieldTy = Field->getType();
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00004934 CodeGenTypes::BitFieldInfo bitFieldInfo =
4935 CGM.getTypes().getBitFieldInfo(Field);
4936 return LValue::MakeBitfield(V, bitFieldInfo.Begin, bitFieldInfo.Size,
Chris Lattner51123fe2009-04-17 17:46:19 +00004937 FieldTy->isSignedIntegerType(),
4938 FieldTy.getCVRQualifiers()|CVRQualifiers);
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00004939 }
4940
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004941 LValue LV = LValue::MakeAddr(V,
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004942 Ivar->getType().getCVRQualifiers()|CVRQualifiers,
4943 CGM.getContext().getObjCGCAttrKind(Ivar->getType()));
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004944 LValue::SetObjCIvar(LV, true);
4945 return LV;
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004946}
4947
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004948llvm::Value *CGObjCNonFragileABIMac::EmitIvarOffset(
4949 CodeGen::CodeGenFunction &CGF,
4950 ObjCInterfaceDecl *Interface,
4951 const ObjCIvarDecl *Ivar) {
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00004952 return CGF.Builder.CreateLoad(ObjCIvarOffsetVariable(Interface, Ivar),
4953 false, "ivar");
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004954}
4955
Fariborz Jahanian46551122009-02-04 00:22:57 +00004956CodeGen::RValue CGObjCNonFragileABIMac::EmitMessageSend(
4957 CodeGen::CodeGenFunction &CGF,
4958 QualType ResultType,
4959 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004960 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +00004961 QualType Arg0Ty,
4962 bool IsSuper,
4963 const CallArgList &CallArgs) {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004964 // FIXME. Even though IsSuper is passes. This function doese not
4965 // handle calls to 'super' receivers.
4966 CodeGenTypes &Types = CGM.getTypes();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004967 llvm::Value *Arg0 = Receiver;
4968 if (!IsSuper)
4969 Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy, "tmp");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004970
4971 // Find the message function name.
Fariborz Jahanianef163782009-02-05 01:13:09 +00004972 // FIXME. This is too much work to get the ABI-specific result type
4973 // needed to find the message name.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004974 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType,
4975 llvm::SmallVector<QualType, 16>());
4976 llvm::Constant *Fn;
4977 std::string Name("\01l_");
4978 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004979#if 0
4980 // unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004981 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
4982 Fn = ObjCTypes.MessageSendIdStretFixupFn;
4983 // FIXME. Is there a better way of getting these names.
4984 // They are available in RuntimeFunctions vector pair.
4985 Name += "objc_msgSendId_stret_fixup";
4986 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004987 else
4988#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004989 if (IsSuper) {
4990 Fn = ObjCTypes.MessageSendSuper2StretFixupFn;
4991 Name += "objc_msgSendSuper2_stret_fixup";
4992 }
4993 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004994 {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004995 Fn = ObjCTypes.MessageSendStretFixupFn;
4996 Name += "objc_msgSend_stret_fixup";
4997 }
4998 }
Fariborz Jahanian1a6b3682009-02-05 19:35:43 +00004999 else if (ResultType->isFloatingType() &&
5000 // Selection of frret API only happens in 32bit nonfragile ABI.
5001 CGM.getTargetData().getTypePaddedSize(ObjCTypes.LongTy) == 4) {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005002 Fn = ObjCTypes.MessageSendFpretFixupFn;
5003 Name += "objc_msgSend_fpret_fixup";
5004 }
5005 else {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005006#if 0
5007// unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005008 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
5009 Fn = ObjCTypes.MessageSendIdFixupFn;
5010 Name += "objc_msgSendId_fixup";
5011 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005012 else
5013#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005014 if (IsSuper) {
5015 Fn = ObjCTypes.MessageSendSuper2FixupFn;
5016 Name += "objc_msgSendSuper2_fixup";
5017 }
5018 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005019 {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005020 Fn = ObjCTypes.MessageSendFixupFn;
5021 Name += "objc_msgSend_fixup";
5022 }
5023 }
5024 Name += '_';
5025 std::string SelName(Sel.getAsString());
5026 // Replace all ':' in selector name with '_' ouch!
5027 for(unsigned i = 0; i < SelName.size(); i++)
5028 if (SelName[i] == ':')
5029 SelName[i] = '_';
5030 Name += SelName;
5031 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5032 if (!GV) {
Daniel Dunbar33af70f2009-04-15 19:03:14 +00005033 // Build message ref table entry.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005034 std::vector<llvm::Constant*> Values(2);
5035 Values[0] = Fn;
5036 Values[1] = GetMethodVarName(Sel);
5037 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
5038 GV = new llvm::GlobalVariable(Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00005039 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005040 Init,
5041 Name,
5042 &CGM.getModule());
5043 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbarf59c1a62009-04-15 19:04:46 +00005044 GV->setAlignment(16);
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005045 GV->setSection("__DATA, __objc_msgrefs, coalesced");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005046 }
5047 llvm::Value *Arg1 = CGF.Builder.CreateBitCast(GV, ObjCTypes.MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00005048
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005049 CallArgList ActualArgs;
5050 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
5051 ActualArgs.push_back(std::make_pair(RValue::get(Arg1),
5052 ObjCTypes.MessageRefCPtrTy));
5053 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Fariborz Jahanianef163782009-02-05 01:13:09 +00005054 const CGFunctionInfo &FnInfo1 = Types.getFunctionInfo(ResultType, ActualArgs);
5055 llvm::Value *Callee = CGF.Builder.CreateStructGEP(Arg1, 0);
5056 Callee = CGF.Builder.CreateLoad(Callee);
Fariborz Jahanian3ab75bd2009-02-14 21:25:36 +00005057 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo1, true);
Fariborz Jahanianef163782009-02-05 01:13:09 +00005058 Callee = CGF.Builder.CreateBitCast(Callee,
5059 llvm::PointerType::getUnqual(FTy));
5060 return CGF.EmitCall(FnInfo1, Callee, ActualArgs);
Fariborz Jahanian46551122009-02-04 00:22:57 +00005061}
5062
5063/// Generate code for a message send expression in the nonfragile abi.
5064CodeGen::RValue CGObjCNonFragileABIMac::GenerateMessageSend(
5065 CodeGen::CodeGenFunction &CGF,
5066 QualType ResultType,
5067 Selector Sel,
5068 llvm::Value *Receiver,
5069 bool IsClassMessage,
5070 const CallArgList &CallArgs) {
Fariborz Jahanian46551122009-02-04 00:22:57 +00005071 return EmitMessageSend(CGF, ResultType, Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005072 Receiver, CGF.getContext().getObjCIdType(),
Fariborz Jahanian46551122009-02-04 00:22:57 +00005073 false, CallArgs);
5074}
5075
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005076llvm::GlobalVariable *
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005077CGObjCNonFragileABIMac::GetClassGlobal(const std::string &Name) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005078 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5079
Daniel Dunbardfff2302009-03-02 05:18:14 +00005080 if (!GV) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005081 GV = new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
5082 llvm::GlobalValue::ExternalLinkage,
5083 0, Name, &CGM.getModule());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005084 }
5085
5086 return GV;
5087}
5088
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005089llvm::Value *CGObjCNonFragileABIMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar11394522009-04-18 08:51:00 +00005090 const ObjCInterfaceDecl *ID) {
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005091 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
5092
5093 if (!Entry) {
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005094 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005095 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005096 Entry =
5097 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5098 llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005099 ClassGV,
Daniel Dunbar11394522009-04-18 08:51:00 +00005100 "\01L_OBJC_CLASSLIST_REFERENCES_$_",
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005101 &CGM.getModule());
5102 Entry->setAlignment(
5103 CGM.getTargetData().getPrefTypeAlignment(
5104 ObjCTypes.ClassnfABIPtrTy));
Daniel Dunbar11394522009-04-18 08:51:00 +00005105 Entry->setSection("__DATA, __objc_classrefs, regular, no_dead_strip");
5106 UsedGlobals.push_back(Entry);
5107 }
5108
5109 return Builder.CreateLoad(Entry, false, "tmp");
5110}
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005111
Daniel Dunbar11394522009-04-18 08:51:00 +00005112llvm::Value *
5113CGObjCNonFragileABIMac::EmitSuperClassRef(CGBuilderTy &Builder,
5114 const ObjCInterfaceDecl *ID) {
5115 llvm::GlobalVariable *&Entry = SuperClassReferences[ID->getIdentifier()];
5116
5117 if (!Entry) {
5118 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
5119 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
5120 Entry =
5121 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5122 llvm::GlobalValue::InternalLinkage,
5123 ClassGV,
5124 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5125 &CGM.getModule());
5126 Entry->setAlignment(
5127 CGM.getTargetData().getPrefTypeAlignment(
5128 ObjCTypes.ClassnfABIPtrTy));
5129 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005130 UsedGlobals.push_back(Entry);
5131 }
5132
5133 return Builder.CreateLoad(Entry, false, "tmp");
5134}
5135
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005136/// EmitMetaClassRef - Return a Value * of the address of _class_t
5137/// meta-data
5138///
5139llvm::Value *CGObjCNonFragileABIMac::EmitMetaClassRef(CGBuilderTy &Builder,
5140 const ObjCInterfaceDecl *ID) {
5141 llvm::GlobalVariable * &Entry = MetaClassReferences[ID->getIdentifier()];
5142 if (Entry)
5143 return Builder.CreateLoad(Entry, false, "tmp");
5144
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005145 std::string MetaClassName(getMetaclassSymbolPrefix() + ID->getNameAsString());
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005146 llvm::GlobalVariable *MetaClassGV = GetClassGlobal(MetaClassName);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005147 Entry =
5148 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5149 llvm::GlobalValue::InternalLinkage,
5150 MetaClassGV,
5151 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5152 &CGM.getModule());
5153 Entry->setAlignment(
5154 CGM.getTargetData().getPrefTypeAlignment(
5155 ObjCTypes.ClassnfABIPtrTy));
5156
Daniel Dunbar33af70f2009-04-15 19:03:14 +00005157 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005158 UsedGlobals.push_back(Entry);
5159
5160 return Builder.CreateLoad(Entry, false, "tmp");
5161}
5162
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005163/// GetClass - Return a reference to the class for the given interface
5164/// decl.
5165llvm::Value *CGObjCNonFragileABIMac::GetClass(CGBuilderTy &Builder,
5166 const ObjCInterfaceDecl *ID) {
5167 return EmitClassRef(Builder, ID);
5168}
5169
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005170/// Generates a message send where the super is the receiver. This is
5171/// a message send to self with special delivery semantics indicating
5172/// which class's method should be called.
5173CodeGen::RValue
5174CGObjCNonFragileABIMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
5175 QualType ResultType,
5176 Selector Sel,
5177 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005178 bool isCategoryImpl,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005179 llvm::Value *Receiver,
5180 bool IsClassMessage,
5181 const CodeGen::CallArgList &CallArgs) {
5182 // ...
5183 // Create and init a super structure; this is a (receiver, class)
5184 // pair we will pass to objc_msgSendSuper.
5185 llvm::Value *ObjCSuper =
5186 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
5187
5188 llvm::Value *ReceiverAsObject =
5189 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
5190 CGF.Builder.CreateStore(ReceiverAsObject,
5191 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
5192
5193 // If this is a class message the metaclass is passed as the target.
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005194 llvm::Value *Target;
5195 if (IsClassMessage) {
5196 if (isCategoryImpl) {
5197 // Message sent to "super' in a class method defined in
5198 // a category implementation.
Daniel Dunbar11394522009-04-18 08:51:00 +00005199 Target = EmitClassRef(CGF.Builder, Class);
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005200 Target = CGF.Builder.CreateStructGEP(Target, 0);
5201 Target = CGF.Builder.CreateLoad(Target);
5202 }
5203 else
5204 Target = EmitMetaClassRef(CGF.Builder, Class);
5205 }
5206 else
Daniel Dunbar11394522009-04-18 08:51:00 +00005207 Target = EmitSuperClassRef(CGF.Builder, Class);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005208
5209 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
5210 // and ObjCTypes types.
5211 const llvm::Type *ClassTy =
5212 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
5213 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
5214 CGF.Builder.CreateStore(Target,
5215 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
5216
5217 return EmitMessageSend(CGF, ResultType, Sel,
5218 ObjCSuper, ObjCTypes.SuperPtrCTy,
5219 true, CallArgs);
5220}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005221
5222llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CGBuilderTy &Builder,
5223 Selector Sel) {
5224 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
5225
5226 if (!Entry) {
5227 llvm::Constant *Casted =
5228 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
5229 ObjCTypes.SelectorPtrTy);
5230 Entry =
5231 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
5232 llvm::GlobalValue::InternalLinkage,
5233 Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
5234 &CGM.getModule());
5235 Entry->setSection("__DATA,__objc_selrefs,literal_pointers,no_dead_strip");
5236 UsedGlobals.push_back(Entry);
5237 }
5238
5239 return Builder.CreateLoad(Entry, false, "tmp");
5240}
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005241/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
5242/// objc_assign_ivar (id src, id *dst)
5243///
5244void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
5245 llvm::Value *src, llvm::Value *dst)
5246{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005247 const llvm::Type * SrcTy = src->getType();
5248 if (!isa<llvm::PointerType>(SrcTy)) {
5249 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5250 assert(Size <= 8 && "does not support size > 8");
5251 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5252 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005253 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5254 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005255 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5256 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00005257 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignIvarFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005258 src, dst, "assignivar");
5259 return;
5260}
5261
5262/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
5263/// objc_assign_strongCast (id src, id *dst)
5264///
5265void CGObjCNonFragileABIMac::EmitObjCStrongCastAssign(
5266 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 Lattnerbbccd612009-04-22 02:38:11 +00005279 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignStrongCastFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005280 src, dst, "weakassign");
5281 return;
5282}
5283
5284/// EmitObjCWeakRead - Code gen for loading value of a __weak
5285/// object: objc_read_weak (id *src)
5286///
5287llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead(
5288 CodeGen::CodeGenFunction &CGF,
5289 llvm::Value *AddrWeakObj)
5290{
Eli Friedman8339b352009-03-07 03:57:15 +00005291 const llvm::Type* DestTy =
5292 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005293 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
5294 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
5295 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00005296 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005297 return read_weak;
5298}
5299
5300/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
5301/// objc_assign_weak (id src, id *dst)
5302///
5303void CGObjCNonFragileABIMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
5304 llvm::Value *src, llvm::Value *dst)
5305{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005306 const llvm::Type * SrcTy = src->getType();
5307 if (!isa<llvm::PointerType>(SrcTy)) {
5308 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5309 assert(Size <= 8 && "does not support size > 8");
5310 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5311 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005312 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5313 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005314 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5315 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattner96508e12009-04-17 22:12:36 +00005316 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005317 src, dst, "weakassign");
5318 return;
5319}
5320
5321/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
5322/// objc_assign_global (id src, id *dst)
5323///
5324void CGObjCNonFragileABIMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
5325 llvm::Value *src, llvm::Value *dst)
5326{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005327 const llvm::Type * SrcTy = src->getType();
5328 if (!isa<llvm::PointerType>(SrcTy)) {
5329 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5330 assert(Size <= 8 && "does not support size > 8");
5331 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5332 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005333 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5334 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005335 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5336 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00005337 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignGlobalFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005338 src, dst, "globalassign");
5339 return;
5340}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005341
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005342void
5343CGObjCNonFragileABIMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
5344 const Stmt &S) {
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005345 bool isTry = isa<ObjCAtTryStmt>(S);
5346 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
5347 llvm::BasicBlock *PrevLandingPad = CGF.getInvokeDest();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005348 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005349 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005350 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005351 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
5352
5353 // For @synchronized, call objc_sync_enter(sync.expr). The
5354 // evaluation of the expression must occur before we enter the
5355 // @synchronized. We can safely avoid a temp here because jumps into
5356 // @synchronized are illegal & this will dominate uses.
5357 llvm::Value *SyncArg = 0;
5358 if (!isTry) {
5359 SyncArg =
5360 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
5361 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005362 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005363 }
5364
5365 // Push an EH context entry, used for handling rethrows and jumps
5366 // through finally.
5367 CGF.PushCleanupBlock(FinallyBlock);
5368
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005369 CGF.setInvokeDest(TryHandler);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005370
5371 CGF.EmitBlock(TryBlock);
5372 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
5373 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
5374 CGF.EmitBranchThroughCleanup(FinallyEnd);
5375
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005376 // Emit the exception handler.
5377
5378 CGF.EmitBlock(TryHandler);
5379
5380 llvm::Value *llvm_eh_exception =
5381 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_exception);
5382 llvm::Value *llvm_eh_selector_i64 =
5383 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector_i64);
5384 llvm::Value *llvm_eh_typeid_for_i64 =
5385 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for_i64);
5386 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5387 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(Exc->getType(), "_rethrow");
5388
5389 llvm::SmallVector<llvm::Value*, 8> SelectorArgs;
5390 SelectorArgs.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005391 SelectorArgs.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005392
5393 // Construct the lists of (type, catch body) to handle.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005394 llvm::SmallVector<std::pair<const ParmVarDecl*, const Stmt*>, 8> Handlers;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005395 bool HasCatchAll = false;
5396 if (isTry) {
5397 if (const ObjCAtCatchStmt* CatchStmt =
5398 cast<ObjCAtTryStmt>(S).getCatchStmts()) {
5399 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005400 const ParmVarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
Steve Naroff7ba138a2009-03-03 19:52:17 +00005401 Handlers.push_back(std::make_pair(CatchDecl, CatchStmt->getCatchBody()));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005402
5403 // catch(...) always matches.
Steve Naroff7ba138a2009-03-03 19:52:17 +00005404 if (!CatchDecl) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005405 // Use i8* null here to signal this is a catch all, not a cleanup.
5406 llvm::Value *Null = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
5407 SelectorArgs.push_back(Null);
5408 HasCatchAll = true;
5409 break;
5410 }
5411
Daniel Dunbarede8de92009-03-06 00:01:21 +00005412 if (CGF.getContext().isObjCIdType(CatchDecl->getType()) ||
5413 CatchDecl->getType()->isObjCQualifiedIdType()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005414 llvm::Value *IDEHType =
5415 CGM.getModule().getGlobalVariable("OBJC_EHTYPE_id");
5416 if (!IDEHType)
5417 IDEHType =
5418 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5419 llvm::GlobalValue::ExternalLinkage,
5420 0, "OBJC_EHTYPE_id", &CGM.getModule());
5421 SelectorArgs.push_back(IDEHType);
5422 HasCatchAll = true;
5423 break;
5424 }
5425
5426 // All other types should be Objective-C interface pointer types.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005427 const PointerType *PT = CatchDecl->getType()->getAsPointerType();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005428 assert(PT && "Invalid @catch type.");
5429 const ObjCInterfaceType *IT =
5430 PT->getPointeeType()->getAsObjCInterfaceType();
5431 assert(IT && "Invalid @catch type.");
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005432 llvm::Value *EHType = GetInterfaceEHType(IT->getDecl(), false);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005433 SelectorArgs.push_back(EHType);
5434 }
5435 }
5436 }
5437
5438 // We use a cleanup unless there was already a catch all.
5439 if (!HasCatchAll) {
5440 SelectorArgs.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
Daniel Dunbarede8de92009-03-06 00:01:21 +00005441 Handlers.push_back(std::make_pair((const ParmVarDecl*) 0, (const Stmt*) 0));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005442 }
5443
5444 llvm::Value *Selector =
5445 CGF.Builder.CreateCall(llvm_eh_selector_i64,
5446 SelectorArgs.begin(), SelectorArgs.end(),
5447 "selector");
5448 for (unsigned i = 0, e = Handlers.size(); i != e; ++i) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005449 const ParmVarDecl *CatchParam = Handlers[i].first;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005450 const Stmt *CatchBody = Handlers[i].second;
5451
5452 llvm::BasicBlock *Next = 0;
5453
5454 // The last handler always matches.
5455 if (i + 1 != e) {
5456 assert(CatchParam && "Only last handler can be a catch all.");
5457
5458 llvm::BasicBlock *Match = CGF.createBasicBlock("match");
5459 Next = CGF.createBasicBlock("catch.next");
5460 llvm::Value *Id =
5461 CGF.Builder.CreateCall(llvm_eh_typeid_for_i64,
5462 CGF.Builder.CreateBitCast(SelectorArgs[i+2],
5463 ObjCTypes.Int8PtrTy));
5464 CGF.Builder.CreateCondBr(CGF.Builder.CreateICmpEQ(Selector, Id),
5465 Match, Next);
5466
5467 CGF.EmitBlock(Match);
5468 }
5469
5470 if (CatchBody) {
5471 llvm::BasicBlock *MatchEnd = CGF.createBasicBlock("match.end");
5472 llvm::BasicBlock *MatchHandler = CGF.createBasicBlock("match.handler");
5473
5474 // Cleanups must call objc_end_catch.
5475 //
5476 // FIXME: It seems incorrect for objc_begin_catch to be inside
5477 // this context, but this matches gcc.
5478 CGF.PushCleanupBlock(MatchEnd);
5479 CGF.setInvokeDest(MatchHandler);
5480
5481 llvm::Value *ExcObject =
Chris Lattner8a569112009-04-22 02:15:23 +00005482 CGF.Builder.CreateCall(ObjCTypes.getObjCBeginCatchFn(), Exc);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005483
5484 // Bind the catch parameter if it exists.
5485 if (CatchParam) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005486 ExcObject =
5487 CGF.Builder.CreateBitCast(ExcObject,
5488 CGF.ConvertType(CatchParam->getType()));
5489 // CatchParam is a ParmVarDecl because of the grammar
5490 // construction used to handle this, but for codegen purposes
5491 // we treat this as a local decl.
5492 CGF.EmitLocalBlockVarDecl(*CatchParam);
5493 CGF.Builder.CreateStore(ExcObject, CGF.GetAddrOfLocalVar(CatchParam));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005494 }
5495
5496 CGF.ObjCEHValueStack.push_back(ExcObject);
5497 CGF.EmitStmt(CatchBody);
5498 CGF.ObjCEHValueStack.pop_back();
5499
5500 CGF.EmitBranchThroughCleanup(FinallyEnd);
5501
5502 CGF.EmitBlock(MatchHandler);
5503
5504 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5505 // We are required to emit this call to satisfy LLVM, even
5506 // though we don't use the result.
5507 llvm::SmallVector<llvm::Value*, 8> Args;
5508 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005509 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005510 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5511 0));
5512 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5513 CGF.Builder.CreateStore(Exc, RethrowPtr);
5514 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5515
5516 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5517
5518 CGF.EmitBlock(MatchEnd);
5519
5520 // Unfortunately, we also have to generate another EH frame here
5521 // in case this throws.
5522 llvm::BasicBlock *MatchEndHandler =
5523 CGF.createBasicBlock("match.end.handler");
5524 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
Chris Lattner8a569112009-04-22 02:15:23 +00005525 CGF.Builder.CreateInvoke(ObjCTypes.getObjCEndCatchFn(),
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005526 Cont, MatchEndHandler,
5527 Args.begin(), Args.begin());
5528
5529 CGF.EmitBlock(Cont);
5530 if (Info.SwitchBlock)
5531 CGF.EmitBlock(Info.SwitchBlock);
5532 if (Info.EndBlock)
5533 CGF.EmitBlock(Info.EndBlock);
5534
5535 CGF.EmitBlock(MatchEndHandler);
5536 Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5537 // We are required to emit this call to satisfy LLVM, even
5538 // though we don't use the result.
5539 Args.clear();
5540 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005541 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005542 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5543 0));
5544 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5545 CGF.Builder.CreateStore(Exc, RethrowPtr);
5546 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5547
5548 if (Next)
5549 CGF.EmitBlock(Next);
5550 } else {
5551 assert(!Next && "catchup should be last handler.");
5552
5553 CGF.Builder.CreateStore(Exc, RethrowPtr);
5554 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5555 }
5556 }
5557
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005558 // Pop the cleanup entry, the @finally is outside this cleanup
5559 // scope.
5560 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5561 CGF.setInvokeDest(PrevLandingPad);
5562
5563 CGF.EmitBlock(FinallyBlock);
5564
5565 if (isTry) {
5566 if (const ObjCAtFinallyStmt* FinallyStmt =
5567 cast<ObjCAtTryStmt>(S).getFinallyStmt())
5568 CGF.EmitStmt(FinallyStmt->getFinallyBody());
5569 } else {
5570 // Emit 'objc_sync_exit(expr)' as finally's sole statement for
5571 // @synchronized.
Chris Lattnerbbccd612009-04-22 02:38:11 +00005572 CGF.Builder.CreateCall(ObjCTypes.getSyncExitFn(), SyncArg);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005573 }
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005574
5575 if (Info.SwitchBlock)
5576 CGF.EmitBlock(Info.SwitchBlock);
5577 if (Info.EndBlock)
5578 CGF.EmitBlock(Info.EndBlock);
5579
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005580 // Branch around the rethrow code.
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005581 CGF.EmitBranch(FinallyEnd);
5582
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005583 CGF.EmitBlock(FinallyRethrow);
Chris Lattner8a569112009-04-22 02:15:23 +00005584 CGF.Builder.CreateCall(ObjCTypes.getUnwindResumeOrRethrowFn(),
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005585 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005586 CGF.Builder.CreateUnreachable();
5587
5588 CGF.EmitBlock(FinallyEnd);
5589}
5590
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005591/// EmitThrowStmt - Generate code for a throw statement.
5592void CGObjCNonFragileABIMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
5593 const ObjCAtThrowStmt &S) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005594 llvm::Value *Exception;
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005595 if (const Expr *ThrowExpr = S.getThrowExpr()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005596 Exception = CGF.EmitScalarExpr(ThrowExpr);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005597 } else {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005598 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
5599 "Unexpected rethrow outside @catch block.");
5600 Exception = CGF.ObjCEHValueStack.back();
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005601 }
5602
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005603 llvm::Value *ExceptionAsObject =
5604 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
5605 llvm::BasicBlock *InvokeDest = CGF.getInvokeDest();
5606 if (InvokeDest) {
5607 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
Chris Lattnerbbccd612009-04-22 02:38:11 +00005608 CGF.Builder.CreateInvoke(ObjCTypes.getExceptionThrowFn(),
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005609 Cont, InvokeDest,
5610 &ExceptionAsObject, &ExceptionAsObject + 1);
5611 CGF.EmitBlock(Cont);
5612 } else
Chris Lattnerbbccd612009-04-22 02:38:11 +00005613 CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(), ExceptionAsObject);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005614 CGF.Builder.CreateUnreachable();
5615
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005616 // Clear the insertion point to indicate we are in unreachable code.
5617 CGF.Builder.ClearInsertionPoint();
5618}
Daniel Dunbare588b992009-03-01 04:46:24 +00005619
5620llvm::Value *
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005621CGObjCNonFragileABIMac::GetInterfaceEHType(const ObjCInterfaceDecl *ID,
5622 bool ForDefinition) {
Daniel Dunbare588b992009-03-01 04:46:24 +00005623 llvm::GlobalVariable * &Entry = EHTypeReferences[ID->getIdentifier()];
Daniel Dunbare588b992009-03-01 04:46:24 +00005624
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005625 // If we don't need a definition, return the entry if found or check
5626 // if we use an external reference.
5627 if (!ForDefinition) {
5628 if (Entry)
5629 return Entry;
Daniel Dunbar7e075cb2009-04-07 06:43:45 +00005630
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005631 // If this type (or a super class) has the __objc_exception__
5632 // attribute, emit an external reference.
5633 if (hasObjCExceptionAttribute(ID))
5634 return Entry =
5635 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5636 llvm::GlobalValue::ExternalLinkage,
5637 0,
5638 (std::string("OBJC_EHTYPE_$_") +
5639 ID->getIdentifier()->getName()),
5640 &CGM.getModule());
5641 }
5642
5643 // Otherwise we need to either make a new entry or fill in the
5644 // initializer.
5645 assert((!Entry || !Entry->hasInitializer()) && "Duplicate EHType definition");
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005646 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbare588b992009-03-01 04:46:24 +00005647 std::string VTableName = "objc_ehtype_vtable";
5648 llvm::GlobalVariable *VTableGV =
5649 CGM.getModule().getGlobalVariable(VTableName);
5650 if (!VTableGV)
5651 VTableGV = new llvm::GlobalVariable(ObjCTypes.Int8PtrTy, false,
5652 llvm::GlobalValue::ExternalLinkage,
5653 0, VTableName, &CGM.getModule());
5654
5655 llvm::Value *VTableIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, 2);
5656
5657 std::vector<llvm::Constant*> Values(3);
5658 Values[0] = llvm::ConstantExpr::getGetElementPtr(VTableGV, &VTableIdx, 1);
5659 Values[1] = GetClassName(ID->getIdentifier());
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005660 Values[2] = GetClassGlobal(ClassName);
Daniel Dunbare588b992009-03-01 04:46:24 +00005661 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.EHTypeTy, Values);
5662
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005663 if (Entry) {
5664 Entry->setInitializer(Init);
5665 } else {
5666 Entry = new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5667 llvm::GlobalValue::WeakAnyLinkage,
5668 Init,
5669 (std::string("OBJC_EHTYPE_$_") +
5670 ID->getIdentifier()->getName()),
5671 &CGM.getModule());
5672 }
5673
Daniel Dunbar04d40782009-04-14 06:00:08 +00005674 if (CGM.getLangOptions().getVisibilityMode() == LangOptions::Hidden)
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005675 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005676 Entry->setAlignment(8);
5677
5678 if (ForDefinition) {
5679 Entry->setSection("__DATA,__objc_const");
5680 Entry->setLinkage(llvm::GlobalValue::ExternalLinkage);
5681 } else {
5682 Entry->setSection("__DATA,__datacoal_nt,coalesced");
5683 }
Daniel Dunbare588b992009-03-01 04:46:24 +00005684
5685 return Entry;
5686}
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005687
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00005688/* *** */
5689
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00005690CodeGen::CGObjCRuntime *
5691CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00005692 return new CGObjCMac(CGM);
5693}
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005694
5695CodeGen::CGObjCRuntime *
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00005696CodeGen::CreateMacNonFragileABIObjCRuntime(CodeGen::CodeGenModule &CGM) {
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00005697 return new CGObjCNonFragileABIMac(CGM);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005698}