blob: e0f44925131ce44145ddc7efd619d99c72306d63 [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 Lattner72db6c32009-04-22 02:44:54 +000087 llvm::Constant *getGetPropertyFn() {
88 CodeGen::CodeGenTypes &Types = CGM.getTypes();
89 ASTContext &Ctx = CGM.getContext();
90 // id objc_getProperty (id, SEL, ptrdiff_t, bool)
91 llvm::SmallVector<QualType,16> Params;
92 QualType IdType = Ctx.getObjCIdType();
93 QualType SelType = Ctx.getObjCSelType();
94 Params.push_back(IdType);
95 Params.push_back(SelType);
96 Params.push_back(Ctx.LongTy);
97 Params.push_back(Ctx.BoolTy);
98 const llvm::FunctionType *FTy =
99 Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
100 return CGM.CreateRuntimeFunction(FTy, "objc_getProperty");
101 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000102
Chris Lattner72db6c32009-04-22 02:44:54 +0000103 llvm::Constant *getSetPropertyFn() {
104 CodeGen::CodeGenTypes &Types = CGM.getTypes();
105 ASTContext &Ctx = CGM.getContext();
106 // void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool)
107 llvm::SmallVector<QualType,16> Params;
108 QualType IdType = Ctx.getObjCIdType();
109 QualType SelType = Ctx.getObjCSelType();
110 Params.push_back(IdType);
111 Params.push_back(SelType);
112 Params.push_back(Ctx.LongTy);
113 Params.push_back(IdType);
114 Params.push_back(Ctx.BoolTy);
115 Params.push_back(Ctx.BoolTy);
116 const llvm::FunctionType *FTy =
117 Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
118 return CGM.CreateRuntimeFunction(FTy, "objc_setProperty");
119 }
120
121 llvm::Constant *getEnumerationMutationFn() {
122 // void objc_enumerationMutation (id)
123 std::vector<const llvm::Type*> Args;
124 Args.push_back(ObjectPtrTy);
125 llvm::FunctionType *FTy =
126 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
127 return CGM.CreateRuntimeFunction(FTy, "objc_enumerationMutation");
128 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000129
130 /// GcReadWeakFn -- LLVM objc_read_weak (id *src) function.
Chris Lattner72db6c32009-04-22 02:44:54 +0000131 llvm::Constant *getGcReadWeakFn() {
132 // id objc_read_weak (id *)
133 std::vector<const llvm::Type*> Args;
134 Args.push_back(ObjectPtrTy->getPointerTo());
135 llvm::FunctionType *FTy = llvm::FunctionType::get(ObjectPtrTy, Args, false);
136 return CGM.CreateRuntimeFunction(FTy, "objc_read_weak");
137 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000138
139 /// GcAssignWeakFn -- LLVM objc_assign_weak function.
Chris Lattner96508e12009-04-17 22:12:36 +0000140 llvm::Constant *getGcAssignWeakFn() {
141 // id objc_assign_weak (id, id *)
142 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
143 Args.push_back(ObjectPtrTy->getPointerTo());
144 llvm::FunctionType *FTy =
145 llvm::FunctionType::get(ObjectPtrTy, Args, false);
146 return CGM.CreateRuntimeFunction(FTy, "objc_assign_weak");
147 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000148
149 /// GcAssignGlobalFn -- LLVM objc_assign_global function.
Chris Lattnerbbccd612009-04-22 02:38:11 +0000150 llvm::Constant *getGcAssignGlobalFn() {
151 // id objc_assign_global(id, id *)
152 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
153 Args.push_back(ObjectPtrTy->getPointerTo());
154 llvm::FunctionType *FTy = llvm::FunctionType::get(ObjectPtrTy, Args, false);
155 return CGM.CreateRuntimeFunction(FTy, "objc_assign_global");
156 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000157
158 /// GcAssignIvarFn -- LLVM objc_assign_ivar function.
Chris Lattnerbbccd612009-04-22 02:38:11 +0000159 llvm::Constant *getGcAssignIvarFn() {
160 // id objc_assign_ivar(id, id *)
161 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
162 Args.push_back(ObjectPtrTy->getPointerTo());
163 llvm::FunctionType *FTy = llvm::FunctionType::get(ObjectPtrTy, Args, false);
164 return CGM.CreateRuntimeFunction(FTy, "objc_assign_ivar");
165 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000166
167 /// GcAssignStrongCastFn -- LLVM objc_assign_strongCast function.
Chris Lattnerbbccd612009-04-22 02:38:11 +0000168 llvm::Constant *getGcAssignStrongCastFn() {
169 // id objc_assign_global(id, id *)
170 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
171 Args.push_back(ObjectPtrTy->getPointerTo());
172 llvm::FunctionType *FTy = llvm::FunctionType::get(ObjectPtrTy, Args, false);
173 return CGM.CreateRuntimeFunction(FTy, "objc_assign_strongCast");
174 }
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000175
176 /// ExceptionThrowFn - LLVM objc_exception_throw function.
Chris Lattnerbbccd612009-04-22 02:38:11 +0000177 llvm::Constant *getExceptionThrowFn() {
178 // void objc_exception_throw(id)
179 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
180 llvm::FunctionType *FTy =
181 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
182 return CGM.CreateRuntimeFunction(FTy, "objc_exception_throw");
183 }
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000184
Daniel Dunbar1c566672009-02-24 01:43:46 +0000185 /// SyncEnterFn - LLVM object_sync_enter function.
Chris Lattnerb02e53b2009-04-06 16:53:45 +0000186 llvm::Constant *getSyncEnterFn() {
187 // void objc_sync_enter (id)
188 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
189 llvm::FunctionType *FTy =
190 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
191 return CGM.CreateRuntimeFunction(FTy, "objc_sync_enter");
192 }
Daniel Dunbar1c566672009-02-24 01:43:46 +0000193
194 /// SyncExitFn - LLVM object_sync_exit function.
Chris Lattnerbbccd612009-04-22 02:38:11 +0000195 llvm::Constant *getSyncExitFn() {
196 // void objc_sync_exit (id)
197 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
198 llvm::FunctionType *FTy =
199 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
200 return CGM.CreateRuntimeFunction(FTy, "objc_sync_exit");
201 }
Daniel Dunbar1c566672009-02-24 01:43:46 +0000202
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000203 ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm);
204 ~ObjCCommonTypesHelper(){}
205};
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000206
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000207/// ObjCTypesHelper - Helper class that encapsulates lazy
208/// construction of varies types used during ObjC generation.
209class ObjCTypesHelper : public ObjCCommonTypesHelper {
210private:
211
Chris Lattner4176b0c2009-04-22 02:32:31 +0000212 llvm::Constant *getMessageSendFn() {
213 // id objc_msgSend (id, SEL, ...)
214 std::vector<const llvm::Type*> Params;
215 Params.push_back(ObjectPtrTy);
216 Params.push_back(SelectorPtrTy);
217 return
218 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
219 Params, true),
220 "objc_msgSend");
221 }
222
223 llvm::Constant *getMessageSendStretFn() {
224 // id objc_msgSend_stret (id, SEL, ...)
225 std::vector<const llvm::Type*> Params;
226 Params.push_back(ObjectPtrTy);
227 Params.push_back(SelectorPtrTy);
228 return
229 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
230 Params, true),
231 "objc_msgSend_stret");
232
233 }
234
235 llvm::Constant *getMessageSendFpretFn() {
236 // FIXME: This should be long double on x86_64?
237 // [double | long double] objc_msgSend_fpret(id self, SEL op, ...)
238 std::vector<const llvm::Type*> Params;
239 Params.push_back(ObjectPtrTy);
240 Params.push_back(SelectorPtrTy);
241 return
242 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::DoubleTy,
243 Params,
244 true),
245 "objc_msgSend_fpret");
246
247 }
248
249 llvm::Constant *getMessageSendSuperFn() {
250 // id objc_msgSendSuper(struct objc_super *super, SEL op, ...)
251 std::vector<const llvm::Type*> Params;
252 Params.push_back(SuperPtrTy);
253 Params.push_back(SelectorPtrTy);
254 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
255 Params, true),
256 "objc_msgSendSuper");
257 }
258 llvm::Constant *getMessageSendSuperStretFn() {
259 // void objc_msgSendSuper_stret(void * stretAddr, struct objc_super *super,
260 // SEL op, ...)
261 std::vector<const llvm::Type*> Params;
262 Params.push_back(Int8PtrTy);
263 Params.push_back(SuperPtrTy);
264 Params.push_back(SelectorPtrTy);
265 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
266 Params, true),
267 "objc_msgSendSuper_stret");
268 }
269
270 llvm::Constant *getMessageSendSuperFpretFn() {
271 // There is no objc_msgSendSuper_fpret? How can that work?
272 return getMessageSendSuperFn();
273 }
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000274
275public:
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000276 /// SymtabTy - LLVM type for struct objc_symtab.
277 const llvm::StructType *SymtabTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000278 /// SymtabPtrTy - LLVM type for struct objc_symtab *.
279 const llvm::Type *SymtabPtrTy;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000280 /// ModuleTy - LLVM type for struct objc_module.
281 const llvm::StructType *ModuleTy;
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000282
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000283 /// ProtocolTy - LLVM type for struct objc_protocol.
284 const llvm::StructType *ProtocolTy;
285 /// ProtocolPtrTy - LLVM type for struct objc_protocol *.
286 const llvm::Type *ProtocolPtrTy;
287 /// ProtocolExtensionTy - LLVM type for struct
288 /// objc_protocol_extension.
289 const llvm::StructType *ProtocolExtensionTy;
290 /// ProtocolExtensionTy - LLVM type for struct
291 /// objc_protocol_extension *.
292 const llvm::Type *ProtocolExtensionPtrTy;
293 /// MethodDescriptionTy - LLVM type for struct
294 /// objc_method_description.
295 const llvm::StructType *MethodDescriptionTy;
296 /// MethodDescriptionListTy - LLVM type for struct
297 /// objc_method_description_list.
298 const llvm::StructType *MethodDescriptionListTy;
299 /// MethodDescriptionListPtrTy - LLVM type for struct
300 /// objc_method_description_list *.
301 const llvm::Type *MethodDescriptionListPtrTy;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000302 /// ProtocolListTy - LLVM type for struct objc_property_list.
303 const llvm::Type *ProtocolListTy;
304 /// ProtocolListPtrTy - LLVM type for struct objc_property_list*.
305 const llvm::Type *ProtocolListPtrTy;
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000306 /// CategoryTy - LLVM type for struct objc_category.
307 const llvm::StructType *CategoryTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000308 /// ClassTy - LLVM type for struct objc_class.
309 const llvm::StructType *ClassTy;
310 /// ClassPtrTy - LLVM type for struct objc_class *.
311 const llvm::Type *ClassPtrTy;
312 /// ClassExtensionTy - LLVM type for struct objc_class_ext.
313 const llvm::StructType *ClassExtensionTy;
314 /// ClassExtensionPtrTy - LLVM type for struct objc_class_ext *.
315 const llvm::Type *ClassExtensionPtrTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000316 // IvarTy - LLVM type for struct objc_ivar.
317 const llvm::StructType *IvarTy;
318 /// IvarListTy - LLVM type for struct objc_ivar_list.
319 const llvm::Type *IvarListTy;
320 /// IvarListPtrTy - LLVM type for struct objc_ivar_list *.
321 const llvm::Type *IvarListPtrTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000322 /// MethodListTy - LLVM type for struct objc_method_list.
323 const llvm::Type *MethodListTy;
324 /// MethodListPtrTy - LLVM type for struct objc_method_list *.
325 const llvm::Type *MethodListPtrTy;
Anders Carlsson124526b2008-09-09 10:10:21 +0000326
327 /// ExceptionDataTy - LLVM type for struct _objc_exception_data.
328 const llvm::Type *ExceptionDataTy;
329
Anders Carlsson124526b2008-09-09 10:10:21 +0000330 /// ExceptionTryEnterFn - LLVM objc_exception_try_enter function.
Chris Lattner34b02a12009-04-22 02:26:14 +0000331 llvm::Constant *getExceptionTryEnterFn() {
332 std::vector<const llvm::Type*> Params;
333 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
334 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
335 Params, false),
336 "objc_exception_try_enter");
337 }
Anders Carlsson124526b2008-09-09 10:10:21 +0000338
339 /// ExceptionTryExitFn - LLVM objc_exception_try_exit function.
Chris Lattner34b02a12009-04-22 02:26:14 +0000340 llvm::Constant *getExceptionTryExitFn() {
341 std::vector<const llvm::Type*> Params;
342 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
343 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
344 Params, false),
345 "objc_exception_try_exit");
346 }
Anders Carlsson124526b2008-09-09 10:10:21 +0000347
348 /// ExceptionExtractFn - LLVM objc_exception_extract function.
Chris Lattner34b02a12009-04-22 02:26:14 +0000349 llvm::Constant *getExceptionExtractFn() {
350 std::vector<const llvm::Type*> Params;
351 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
352 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
353 Params, false),
354 "objc_exception_extract");
355
356 }
Anders Carlsson124526b2008-09-09 10:10:21 +0000357
358 /// ExceptionMatchFn - LLVM objc_exception_match function.
Chris Lattner34b02a12009-04-22 02:26:14 +0000359 llvm::Constant *getExceptionMatchFn() {
360 std::vector<const llvm::Type*> Params;
361 Params.push_back(ClassPtrTy);
362 Params.push_back(ObjectPtrTy);
363 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
364 Params, false),
365 "objc_exception_match");
366
367 }
Anders Carlsson124526b2008-09-09 10:10:21 +0000368
369 /// SetJmpFn - LLVM _setjmp function.
Chris Lattner34b02a12009-04-22 02:26:14 +0000370 llvm::Constant *getSetJmpFn() {
371 std::vector<const llvm::Type*> Params;
372 Params.push_back(llvm::PointerType::getUnqual(llvm::Type::Int32Ty));
373 return
374 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
375 Params, false),
376 "_setjmp");
377
378 }
Chris Lattner10cac6f2008-11-15 21:26:17 +0000379
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000380public:
381 ObjCTypesHelper(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000382 ~ObjCTypesHelper() {}
Daniel Dunbar5669e572008-10-17 03:24:53 +0000383
384
Chris Lattner74391b42009-03-22 21:03:39 +0000385 llvm::Constant *getSendFn(bool IsSuper) {
Chris Lattner4176b0c2009-04-22 02:32:31 +0000386 return IsSuper ? getMessageSendSuperFn() : getMessageSendFn();
Daniel Dunbar5669e572008-10-17 03:24:53 +0000387 }
388
Chris Lattner74391b42009-03-22 21:03:39 +0000389 llvm::Constant *getSendStretFn(bool IsSuper) {
Chris Lattner4176b0c2009-04-22 02:32:31 +0000390 return IsSuper ? getMessageSendSuperStretFn() : getMessageSendStretFn();
Daniel Dunbar5669e572008-10-17 03:24:53 +0000391 }
392
Chris Lattner74391b42009-03-22 21:03:39 +0000393 llvm::Constant *getSendFpretFn(bool IsSuper) {
Chris Lattner4176b0c2009-04-22 02:32:31 +0000394 return IsSuper ? getMessageSendSuperFpretFn() : getMessageSendFpretFn();
Daniel Dunbar5669e572008-10-17 03:24:53 +0000395 }
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000396};
397
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000398/// ObjCNonFragileABITypesHelper - will have all types needed by objective-c's
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000399/// modern abi
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000400class ObjCNonFragileABITypesHelper : public ObjCCommonTypesHelper {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000401public:
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000402
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000403 // MethodListnfABITy - LLVM for struct _method_list_t
404 const llvm::StructType *MethodListnfABITy;
405
406 // MethodListnfABIPtrTy - LLVM for struct _method_list_t*
407 const llvm::Type *MethodListnfABIPtrTy;
408
409 // ProtocolnfABITy = LLVM for struct _protocol_t
410 const llvm::StructType *ProtocolnfABITy;
411
Daniel Dunbar948e2582009-02-15 07:36:20 +0000412 // ProtocolnfABIPtrTy = LLVM for struct _protocol_t*
413 const llvm::Type *ProtocolnfABIPtrTy;
414
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000415 // ProtocolListnfABITy - LLVM for struct _objc_protocol_list
416 const llvm::StructType *ProtocolListnfABITy;
417
418 // ProtocolListnfABIPtrTy - LLVM for struct _objc_protocol_list*
419 const llvm::Type *ProtocolListnfABIPtrTy;
420
421 // ClassnfABITy - LLVM for struct _class_t
422 const llvm::StructType *ClassnfABITy;
423
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000424 // ClassnfABIPtrTy - LLVM for struct _class_t*
425 const llvm::Type *ClassnfABIPtrTy;
426
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000427 // IvarnfABITy - LLVM for struct _ivar_t
428 const llvm::StructType *IvarnfABITy;
429
430 // IvarListnfABITy - LLVM for struct _ivar_list_t
431 const llvm::StructType *IvarListnfABITy;
432
433 // IvarListnfABIPtrTy = LLVM for struct _ivar_list_t*
434 const llvm::Type *IvarListnfABIPtrTy;
435
436 // ClassRonfABITy - LLVM for struct _class_ro_t
437 const llvm::StructType *ClassRonfABITy;
438
439 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
440 const llvm::Type *ImpnfABITy;
441
442 // CategorynfABITy - LLVM for struct _category_t
443 const llvm::StructType *CategorynfABITy;
444
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000445 // New types for nonfragile abi messaging.
446
447 // MessageRefTy - LLVM for:
448 // struct _message_ref_t {
449 // IMP messenger;
450 // SEL name;
451 // };
452 const llvm::StructType *MessageRefTy;
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000453 // MessageRefCTy - clang type for struct _message_ref_t
454 QualType MessageRefCTy;
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000455
456 // MessageRefPtrTy - LLVM for struct _message_ref_t*
457 const llvm::Type *MessageRefPtrTy;
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000458 // MessageRefCPtrTy - clang type for struct _message_ref_t*
459 QualType MessageRefCPtrTy;
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000460
Fariborz Jahanianef163782009-02-05 01:13:09 +0000461 // MessengerTy - Type of the messenger (shown as IMP above)
462 const llvm::FunctionType *MessengerTy;
463
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000464 // SuperMessageRefTy - LLVM for:
465 // struct _super_message_ref_t {
466 // SUPER_IMP messenger;
467 // SEL name;
468 // };
469 const llvm::StructType *SuperMessageRefTy;
470
471 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
472 const llvm::Type *SuperMessageRefPtrTy;
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000473
Chris Lattner1c02f862009-04-22 02:53:24 +0000474 llvm::Constant *getMessageSendFixupFn() {
475 // id objc_msgSend_fixup(id, struct message_ref_t*, ...)
476 std::vector<const llvm::Type*> Params;
477 Params.push_back(ObjectPtrTy);
478 Params.push_back(MessageRefPtrTy);
479 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
480 Params, true),
481 "objc_msgSend_fixup");
482 }
483
484 llvm::Constant *getMessageSendFpretFixupFn() {
485 // id objc_msgSend_fpret_fixup(id, struct message_ref_t*, ...)
486 std::vector<const llvm::Type*> Params;
487 Params.push_back(ObjectPtrTy);
488 Params.push_back(MessageRefPtrTy);
489 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
490 Params, true),
491 "objc_msgSend_fpret_fixup");
492 }
493
494 llvm::Constant *getMessageSendStretFixupFn() {
495 // id objc_msgSend_stret_fixup(id, struct message_ref_t*, ...)
496 std::vector<const llvm::Type*> Params;
497 Params.push_back(ObjectPtrTy);
498 Params.push_back(MessageRefPtrTy);
499 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
500 Params, true),
501 "objc_msgSend_stret_fixup");
502 }
503
504 llvm::Constant *getMessageSendIdFixupFn() {
505 // id objc_msgSendId_fixup(id, struct message_ref_t*, ...)
506 std::vector<const llvm::Type*> Params;
507 Params.push_back(ObjectPtrTy);
508 Params.push_back(MessageRefPtrTy);
509 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
510 Params, true),
511 "objc_msgSendId_fixup");
512 }
513
514 llvm::Constant *getMessageSendIdStretFixupFn() {
515 // id objc_msgSendId_stret_fixup(id, struct message_ref_t*, ...)
516 std::vector<const llvm::Type*> Params;
517 Params.push_back(ObjectPtrTy);
518 Params.push_back(MessageRefPtrTy);
519 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
520 Params, true),
521 "objc_msgSendId_stret_fixup");
522 }
523 llvm::Constant *getMessageSendSuper2FixupFn() {
524 // id objc_msgSendSuper2_fixup (struct objc_super *,
525 // struct _super_message_ref_t*, ...)
526 std::vector<const llvm::Type*> Params;
527 Params.push_back(SuperPtrTy);
528 Params.push_back(SuperMessageRefPtrTy);
529 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
530 Params, true),
531 "objc_msgSendSuper2_fixup");
532 }
533
534 llvm::Constant *getMessageSendSuper2StretFixupFn() {
535 // id objc_msgSendSuper2_stret_fixup(struct objc_super *,
536 // struct _super_message_ref_t*, ...)
537 std::vector<const llvm::Type*> Params;
538 Params.push_back(SuperPtrTy);
539 Params.push_back(SuperMessageRefPtrTy);
540 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
541 Params, true),
542 "objc_msgSendSuper2_stret_fixup");
543 }
544
545
546
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000547 /// EHPersonalityPtr - LLVM value for an i8* to the Objective-C
548 /// exception personality function.
Chris Lattnerb02e53b2009-04-06 16:53:45 +0000549 llvm::Value *getEHPersonalityPtr() {
550 llvm::Constant *Personality =
551 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
552 std::vector<const llvm::Type*>(),
553 true),
554 "__objc_personality_v0");
555 return llvm::ConstantExpr::getBitCast(Personality, Int8PtrTy);
556 }
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000557
Chris Lattner8a569112009-04-22 02:15:23 +0000558 llvm::Constant *getUnwindResumeOrRethrowFn() {
559 std::vector<const llvm::Type*> Params;
560 Params.push_back(Int8PtrTy);
561 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
562 Params, false),
563 "_Unwind_Resume_or_Rethrow");
564 }
565
566 llvm::Constant *getObjCEndCatchFn() {
567 std::vector<const llvm::Type*> Params;
568 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
569 Params, false),
570 "objc_end_catch");
571
572 }
573
574 llvm::Constant *getObjCBeginCatchFn() {
575 std::vector<const llvm::Type*> Params;
576 Params.push_back(Int8PtrTy);
577 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(Int8PtrTy,
578 Params, false),
579 "objc_begin_catch");
580 }
Daniel Dunbare588b992009-03-01 04:46:24 +0000581
582 const llvm::StructType *EHTypeTy;
583 const llvm::Type *EHTypePtrTy;
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000584
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000585 ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm);
586 ~ObjCNonFragileABITypesHelper(){}
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000587};
588
589class CGObjCCommonMac : public CodeGen::CGObjCRuntime {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000590public:
591 // FIXME - accessibility
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000592 class GC_IVAR {
Fariborz Jahanian820e0202009-03-11 00:07:04 +0000593 public:
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000594 unsigned int ivar_bytepos;
595 unsigned int ivar_size;
596 GC_IVAR() : ivar_bytepos(0), ivar_size(0) {}
597 };
598
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000599 class SKIP_SCAN {
600 public:
601 unsigned int skip;
602 unsigned int scan;
603 SKIP_SCAN() : skip(0), scan(0) {}
604 };
605
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000606protected:
607 CodeGen::CodeGenModule &CGM;
608 // FIXME! May not be needing this after all.
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000609 unsigned ObjCABI;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000610
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000611 // gc ivar layout bitmap calculation helper caches.
612 llvm::SmallVector<GC_IVAR, 16> SkipIvars;
613 llvm::SmallVector<GC_IVAR, 16> IvarsInfo;
614 llvm::SmallVector<SKIP_SCAN, 32> SkipScanIvars;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000615
Daniel Dunbar242d4dc2008-08-25 06:02:07 +0000616 /// LazySymbols - Symbols to generate a lazy reference for. See
617 /// DefinedSymbols and FinishModule().
618 std::set<IdentifierInfo*> LazySymbols;
619
620 /// DefinedSymbols - External symbols which are defined by this
621 /// module. The symbols in this list and LazySymbols are used to add
622 /// special linker symbols which ensure that Objective-C modules are
623 /// linked properly.
624 std::set<IdentifierInfo*> DefinedSymbols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000625
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000626 /// ClassNames - uniqued class names.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000627 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000628
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000629 /// MethodVarNames - uniqued method variable names.
630 llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000631
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000632 /// MethodVarTypes - uniqued method type signatures. We have to use
633 /// a StringMap here because have no other unique reference.
634 llvm::StringMap<llvm::GlobalVariable*> MethodVarTypes;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000635
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000636 /// MethodDefinitions - map of methods which have been defined in
637 /// this translation unit.
638 llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> MethodDefinitions;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000639
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000640 /// PropertyNames - uniqued method variable names.
641 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000642
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000643 /// ClassReferences - uniqued class references.
644 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000645
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000646 /// SelectorReferences - uniqued selector references.
647 llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000648
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000649 /// Protocols - Protocols for which an objc_protocol structure has
650 /// been emitted. Forward declarations are handled by creating an
651 /// empty structure whose initializer is filled in when/if defined.
652 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> Protocols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000653
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000654 /// DefinedProtocols - Protocols which have actually been
655 /// defined. We should not need this, see FIXME in GenerateProtocol.
656 llvm::DenseSet<IdentifierInfo*> DefinedProtocols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000657
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000658 /// DefinedClasses - List of defined classes.
659 std::vector<llvm::GlobalValue*> DefinedClasses;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000660
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000661 /// DefinedCategories - List of defined categories.
662 std::vector<llvm::GlobalValue*> DefinedCategories;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000663
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000664 /// UsedGlobals - List of globals to pack into the llvm.used metadata
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000665 /// to prevent them from being clobbered.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000666 std::vector<llvm::GlobalVariable*> UsedGlobals;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000667
Fariborz Jahanian56210f72009-01-21 23:34:32 +0000668 /// GetNameForMethod - Return a name for the given method.
669 /// \param[out] NameOut - The return value.
670 void GetNameForMethod(const ObjCMethodDecl *OMD,
671 const ObjCContainerDecl *CD,
672 std::string &NameOut);
673
674 /// GetMethodVarName - Return a unique constant for the given
675 /// selector's name. The return value has type char *.
676 llvm::Constant *GetMethodVarName(Selector Sel);
677 llvm::Constant *GetMethodVarName(IdentifierInfo *Ident);
678 llvm::Constant *GetMethodVarName(const std::string &Name);
679
680 /// GetMethodVarType - Return a unique constant for the given
681 /// selector's name. The return value has type char *.
682
683 // FIXME: This is a horrible name.
684 llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D);
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +0000685 llvm::Constant *GetMethodVarType(const FieldDecl *D);
Fariborz Jahanian56210f72009-01-21 23:34:32 +0000686
687 /// GetPropertyName - Return a unique constant for the given
688 /// name. The return value has type char *.
689 llvm::Constant *GetPropertyName(IdentifierInfo *Ident);
690
691 // FIXME: This can be dropped once string functions are unified.
692 llvm::Constant *GetPropertyTypeString(const ObjCPropertyDecl *PD,
693 const Decl *Container);
694
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000695 /// GetClassName - Return a unique constant for the given selector's
696 /// name. The return value has type char *.
697 llvm::Constant *GetClassName(IdentifierInfo *Ident);
698
Fariborz Jahanian21e6f172009-03-11 21:42:00 +0000699 /// GetInterfaceDeclStructLayout - Get layout for ivars of given
700 /// interface declaration.
701 const llvm::StructLayout *GetInterfaceDeclStructLayout(
702 const ObjCInterfaceDecl *ID) const;
703
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000704 /// BuildIvarLayout - Builds ivar layout bitmap for the class
705 /// implementation for the __strong or __weak case.
706 ///
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000707 llvm::Constant *BuildIvarLayout(const ObjCImplementationDecl *OI,
708 bool ForStrongLayout);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000709
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000710 void BuildAggrIvarLayout(const ObjCInterfaceDecl *OI,
711 const llvm::StructLayout *Layout,
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000712 const RecordDecl *RD,
Chris Lattnerf1690852009-03-31 08:48:01 +0000713 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000714 unsigned int BytePos, bool ForStrongLayout,
715 int &Index, int &SkIndex, bool &HasUnion);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000716
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +0000717 /// GetIvarLayoutName - Returns a unique constant for the given
718 /// ivar layout bitmap.
719 llvm::Constant *GetIvarLayoutName(IdentifierInfo *Ident,
720 const ObjCCommonTypesHelper &ObjCTypes);
721
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +0000722 /// EmitPropertyList - Emit the given property list. The return
723 /// value has type PropertyListPtrTy.
724 llvm::Constant *EmitPropertyList(const std::string &Name,
725 const Decl *Container,
726 const ObjCContainerDecl *OCD,
727 const ObjCCommonTypesHelper &ObjCTypes);
728
Fariborz Jahanianda320092009-01-29 19:24:30 +0000729 /// GetProtocolRef - Return a reference to the internal protocol
730 /// description, creating an empty one if it has not been
731 /// defined. The return value has type ProtocolPtrTy.
732 llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +0000733
734 /// GetIvarBaseOffset - returns ivars byte offset.
735 uint64_t GetIvarBaseOffset(const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +0000736 const FieldDecl *Field);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000737
Chris Lattnercd0ee142009-03-31 08:33:16 +0000738 /// GetFieldBaseOffset - return's field byte offset.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000739 uint64_t GetFieldBaseOffset(const ObjCInterfaceDecl *OI,
740 const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +0000741 const FieldDecl *Field);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000742
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000743 /// CreateMetadataVar - Create a global variable with internal
744 /// linkage for use by the Objective-C runtime.
745 ///
746 /// This is a convenience wrapper which not only creates the
747 /// variable, but also sets the section and alignment and adds the
748 /// global to the UsedGlobals list.
Daniel Dunbar35bd7632009-03-09 20:50:13 +0000749 ///
750 /// \param Name - The variable name.
751 /// \param Init - The variable initializer; this is also used to
752 /// define the type of the variable.
753 /// \param Section - The section the variable should go into, or 0.
754 /// \param Align - The alignment for the variable, or 0.
755 /// \param AddToUsed - Whether the variable should be added to
Daniel Dunbarc1583062009-04-14 17:42:51 +0000756 /// "llvm.used".
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000757 llvm::GlobalVariable *CreateMetadataVar(const std::string &Name,
758 llvm::Constant *Init,
759 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +0000760 unsigned Align,
761 bool AddToUsed);
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000762
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +0000763 /// GetNamedIvarList - Return the list of ivars in the interface
764 /// itself (not including super classes and not including unnamed
765 /// bitfields).
766 ///
767 /// For the non-fragile ABI, this also includes synthesized property
768 /// ivars.
769 void GetNamedIvarList(const ObjCInterfaceDecl *OID,
770 llvm::SmallVector<ObjCIvarDecl*, 16> &Res) const;
771
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000772public:
773 CGObjCCommonMac(CodeGen::CodeGenModule &cgm) : CGM(cgm)
774 { }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000775
Steve Naroff33fdb732009-03-31 16:53:37 +0000776 virtual llvm::Constant *GenerateConstantString(const ObjCStringLiteral *SL);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000777
778 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
779 const ObjCContainerDecl *CD=0);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000780
781 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
782
783 /// GetOrEmitProtocol - Get the protocol object for the given
784 /// declaration, emitting it if necessary. The return value has type
785 /// ProtocolPtrTy.
786 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD)=0;
787
788 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
789 /// object for the given declaration, emitting it if needed. These
790 /// forward references will be filled in with empty bodies if no
791 /// definition is seen. The return value has type ProtocolPtrTy.
792 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD)=0;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000793};
794
795class CGObjCMac : public CGObjCCommonMac {
796private:
797 ObjCTypesHelper ObjCTypes;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000798 /// EmitImageInfo - Emit the image info marker used to encode some module
799 /// level information.
800 void EmitImageInfo();
801
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000802 /// EmitModuleInfo - Another marker encoding module level
803 /// information.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000804 void EmitModuleInfo();
805
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000806 /// EmitModuleSymols - Emit module symbols, the list of defined
807 /// classes and categories. The result has type SymtabPtrTy.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000808 llvm::Constant *EmitModuleSymbols();
809
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000810 /// FinishModule - Write out global data structures at the end of
811 /// processing a translation unit.
812 void FinishModule();
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000813
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000814 /// EmitClassExtension - Generate the class extension structure used
815 /// to store the weak ivar layout and properties. The return value
816 /// has type ClassExtensionPtrTy.
817 llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID);
818
819 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
820 /// for the given class.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000821 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000822 const ObjCInterfaceDecl *ID);
823
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000824 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000825 QualType ResultType,
826 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000827 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000828 QualType Arg0Ty,
829 bool IsSuper,
830 const CallArgList &CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000831
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000832 /// EmitIvarList - Emit the ivar list for the given
833 /// implementation. If ForClass is true the list of class ivars
834 /// (i.e. metaclass ivars) is emitted, otherwise the list of
835 /// interface ivars will be emitted. The return value has type
836 /// IvarListPtrTy.
837 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +0000838 bool ForClass);
839
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000840 /// EmitMetaClass - Emit a forward reference to the class structure
841 /// for the metaclass of the given interface. The return value has
842 /// type ClassPtrTy.
843 llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
844
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000845 /// EmitMetaClass - Emit a class structure for the metaclass of the
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000846 /// given implementation. The return value has type ClassPtrTy.
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000847 llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
848 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000849 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000850 const ConstantVector &Methods);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000851
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000852 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000853
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000854 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000855
856 /// EmitMethodList - Emit the method list for the given
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000857 /// implementation. The return value has type MethodListPtrTy.
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000858 llvm::Constant *EmitMethodList(const std::string &Name,
859 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000860 const ConstantVector &Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000861
862 /// EmitMethodDescList - Emit a method description list for a list of
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000863 /// method declarations.
864 /// - TypeName: The name for the type containing the methods.
865 /// - IsProtocol: True iff these methods are for a protocol.
866 /// - ClassMethds: True iff these are class methods.
867 /// - Required: When true, only "required" methods are
868 /// listed. Similarly, when false only "optional" methods are
869 /// listed. For classes this should always be true.
870 /// - begin, end: The method list to output.
871 ///
872 /// The return value has type MethodDescriptionListPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000873 llvm::Constant *EmitMethodDescList(const std::string &Name,
874 const char *Section,
875 const ConstantVector &Methods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000876
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000877 /// GetOrEmitProtocol - Get the protocol object for the given
878 /// declaration, emitting it if necessary. The return value has type
879 /// ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +0000880 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000881
882 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
883 /// object for the given declaration, emitting it if needed. These
884 /// forward references will be filled in with empty bodies if no
885 /// definition is seen. The return value has type ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +0000886 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000887
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000888 /// EmitProtocolExtension - Generate the protocol extension
889 /// structure used to store optional instance and class methods, and
890 /// protocol properties. The return value has type
891 /// ProtocolExtensionPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000892 llvm::Constant *
893 EmitProtocolExtension(const ObjCProtocolDecl *PD,
894 const ConstantVector &OptInstanceMethods,
895 const ConstantVector &OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000896
897 /// EmitProtocolList - Generate the list of referenced
898 /// protocols. The return value has type ProtocolListPtrTy.
Daniel Dunbardbc933702008-08-21 21:57:41 +0000899 llvm::Constant *EmitProtocolList(const std::string &Name,
900 ObjCProtocolDecl::protocol_iterator begin,
901 ObjCProtocolDecl::protocol_iterator end);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000902
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000903 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
904 /// for the given selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000905 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000906
Fariborz Jahanianda320092009-01-29 19:24:30 +0000907 public:
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000908 CGObjCMac(CodeGen::CodeGenModule &cgm);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000909
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000910 virtual llvm::Function *ModuleInitFunction();
911
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000912 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000913 QualType ResultType,
914 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000915 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000916 bool IsClassMessage,
917 const CallArgList &CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000918
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000919 virtual CodeGen::RValue
920 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000921 QualType ResultType,
922 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000923 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000924 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000925 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000926 bool IsClassMessage,
927 const CallArgList &CallArgs);
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000928
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000929 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000930 const ObjCInterfaceDecl *ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000931
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000932 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000933
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000934 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000935
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000936 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000937
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000938 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000939 const ObjCProtocolDecl *PD);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000940
Chris Lattner74391b42009-03-22 21:03:39 +0000941 virtual llvm::Constant *GetPropertyGetFunction();
942 virtual llvm::Constant *GetPropertySetFunction();
943 virtual llvm::Constant *EnumerationMutationFunction();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000944
Fariborz Jahanianbd71be42008-11-21 00:49:24 +0000945 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
946 const Stmt &S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000947 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
948 const ObjCAtThrowStmt &S);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000949 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +0000950 llvm::Value *AddrWeakObj);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000951 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
952 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000953 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
954 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian7eda8362008-11-20 19:23:36 +0000955 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
956 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000957 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
958 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian0bb20362009-02-02 20:02:29 +0000959
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000960 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
961 QualType ObjectTy,
962 llvm::Value *BaseValue,
963 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000964 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000965 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
966 ObjCInterfaceDecl *Interface,
967 const ObjCIvarDecl *Ivar);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000968};
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000969
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000970class CGObjCNonFragileABIMac : public CGObjCCommonMac {
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000971private:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000972 ObjCNonFragileABITypesHelper ObjCTypes;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000973 llvm::GlobalVariable* ObjCEmptyCacheVar;
974 llvm::GlobalVariable* ObjCEmptyVtableVar;
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000975
Daniel Dunbar11394522009-04-18 08:51:00 +0000976 /// SuperClassReferences - uniqued super class references.
977 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> SuperClassReferences;
978
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000979 /// MetaClassReferences - uniqued meta class references.
980 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> MetaClassReferences;
Daniel Dunbare588b992009-03-01 04:46:24 +0000981
982 /// EHTypeReferences - uniqued class ehtype references.
983 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> EHTypeReferences;
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000984
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000985 /// FinishNonFragileABIModule - Write out global data structures at the end of
986 /// processing a translation unit.
987 void FinishNonFragileABIModule();
Daniel Dunbar8158a2f2009-04-08 04:21:03 +0000988
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000989 llvm::GlobalVariable * BuildClassRoTInitializer(unsigned flags,
990 unsigned InstanceStart,
991 unsigned InstanceSize,
992 const ObjCImplementationDecl *ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +0000993 llvm::GlobalVariable * BuildClassMetaData(std::string &ClassName,
994 llvm::Constant *IsAGV,
995 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +0000996 llvm::Constant *ClassRoGV,
997 bool HiddenVisibility);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000998
999 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
1000
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00001001 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
1002
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001003 /// EmitMethodList - Emit the method list for the given
1004 /// implementation. The return value has type MethodListnfABITy.
1005 llvm::Constant *EmitMethodList(const std::string &Name,
1006 const char *Section,
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00001007 const ConstantVector &Methods);
1008 /// EmitIvarList - Emit the ivar list for the given
1009 /// implementation. If ForClass is true the list of class ivars
1010 /// (i.e. metaclass ivars) is emitted, otherwise the list of
1011 /// interface ivars will be emitted. The return value has type
1012 /// IvarListnfABIPtrTy.
1013 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00001014
Fariborz Jahanianed157d32009-02-10 20:21:06 +00001015 llvm::Constant *EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00001016 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00001017 unsigned long int offset);
1018
Fariborz Jahanianda320092009-01-29 19:24:30 +00001019 /// GetOrEmitProtocol - Get the protocol object for the given
1020 /// declaration, emitting it if necessary. The return value has type
1021 /// ProtocolPtrTy.
1022 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
1023
1024 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
1025 /// object for the given declaration, emitting it if needed. These
1026 /// forward references will be filled in with empty bodies if no
1027 /// definition is seen. The return value has type ProtocolPtrTy.
1028 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
1029
1030 /// EmitProtocolList - Generate the list of referenced
1031 /// protocols. The return value has type ProtocolListPtrTy.
1032 llvm::Constant *EmitProtocolList(const std::string &Name,
1033 ObjCProtocolDecl::protocol_iterator begin,
Fariborz Jahanian46551122009-02-04 00:22:57 +00001034 ObjCProtocolDecl::protocol_iterator end);
1035
1036 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
1037 QualType ResultType,
1038 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00001039 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +00001040 QualType Arg0Ty,
1041 bool IsSuper,
1042 const CallArgList &CallArgs);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00001043
1044 /// GetClassGlobal - Return the global variable for the Objective-C
1045 /// class of the given name.
Fariborz Jahanian0f902942009-04-14 18:41:56 +00001046 llvm::GlobalVariable *GetClassGlobal(const std::string &Name);
1047
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00001048 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
Daniel Dunbar11394522009-04-18 08:51:00 +00001049 /// for the given class reference.
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00001050 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar11394522009-04-18 08:51:00 +00001051 const ObjCInterfaceDecl *ID);
1052
1053 /// EmitSuperClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
1054 /// for the given super class reference.
1055 llvm::Value *EmitSuperClassRef(CGBuilderTy &Builder,
1056 const ObjCInterfaceDecl *ID);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00001057
1058 /// EmitMetaClassRef - Return a Value * of the address of _class_t
1059 /// meta-data
1060 llvm::Value *EmitMetaClassRef(CGBuilderTy &Builder,
1061 const ObjCInterfaceDecl *ID);
1062
Fariborz Jahanianed157d32009-02-10 20:21:06 +00001063 /// ObjCIvarOffsetVariable - Returns the ivar offset variable for
1064 /// the given ivar.
1065 ///
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00001066 llvm::GlobalVariable * ObjCIvarOffsetVariable(
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001067 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +00001068 const ObjCIvarDecl *Ivar);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00001069
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00001070 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
1071 /// for the given selector.
1072 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbare588b992009-03-01 04:46:24 +00001073
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001074 /// GetInterfaceEHType - Get the cached ehtype for the given Objective-C
Daniel Dunbare588b992009-03-01 04:46:24 +00001075 /// interface. The return value has type EHTypePtrTy.
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001076 llvm::Value *GetInterfaceEHType(const ObjCInterfaceDecl *ID,
1077 bool ForDefinition);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00001078
1079 const char *getMetaclassSymbolPrefix() const {
1080 return "OBJC_METACLASS_$_";
1081 }
Daniel Dunbar4ff36842009-03-02 06:08:11 +00001082
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00001083 const char *getClassSymbolPrefix() const {
1084 return "OBJC_CLASS_$_";
1085 }
1086
Daniel Dunbarb02532a2009-04-19 23:41:48 +00001087 void GetClassSizeInfo(const ObjCInterfaceDecl *OID,
1088 uint32_t &InstanceStart,
1089 uint32_t &InstanceSize);
1090
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001091public:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00001092 CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001093 // FIXME. All stubs for now!
1094 virtual llvm::Function *ModuleInitFunction();
1095
1096 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
1097 QualType ResultType,
1098 Selector Sel,
1099 llvm::Value *Receiver,
1100 bool IsClassMessage,
Fariborz Jahanian46551122009-02-04 00:22:57 +00001101 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001102
1103 virtual CodeGen::RValue
1104 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
1105 QualType ResultType,
1106 Selector Sel,
1107 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00001108 bool isCategoryImpl,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001109 llvm::Value *Receiver,
1110 bool IsClassMessage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00001111 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001112
1113 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00001114 const ObjCInterfaceDecl *ID);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001115
1116 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel)
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00001117 { return EmitSelector(Builder, Sel); }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001118
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00001119 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001120
1121 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001122 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00001123 const ObjCProtocolDecl *PD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001124
Chris Lattner74391b42009-03-22 21:03:39 +00001125 virtual llvm::Constant *GetPropertyGetFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00001126 return ObjCTypes.getGetPropertyFn();
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001127 }
Chris Lattner74391b42009-03-22 21:03:39 +00001128 virtual llvm::Constant *GetPropertySetFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00001129 return ObjCTypes.getSetPropertyFn();
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001130 }
Chris Lattner74391b42009-03-22 21:03:39 +00001131 virtual llvm::Constant *EnumerationMutationFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00001132 return ObjCTypes.getEnumerationMutationFn();
Daniel Dunbar28ed0842009-02-16 18:48:45 +00001133 }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001134
1135 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00001136 const Stmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001137 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Anders Carlssonf57c5b22009-02-16 22:59:18 +00001138 const ObjCAtThrowStmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001139 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001140 llvm::Value *AddrWeakObj);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001141 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001142 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001143 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001144 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001145 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001146 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001147 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001148 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00001149 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
1150 QualType ObjectTy,
1151 llvm::Value *BaseValue,
1152 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00001153 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001154 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
1155 ObjCInterfaceDecl *Interface,
1156 const ObjCIvarDecl *Ivar);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001157};
1158
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001159} // end anonymous namespace
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001160
1161/* *** Helper Functions *** */
1162
1163/// getConstantGEP() - Help routine to construct simple GEPs.
1164static llvm::Constant *getConstantGEP(llvm::Constant *C,
1165 unsigned idx0,
1166 unsigned idx1) {
1167 llvm::Value *Idxs[] = {
1168 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx0),
1169 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx1)
1170 };
1171 return llvm::ConstantExpr::getGetElementPtr(C, Idxs, 2);
1172}
1173
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001174/// hasObjCExceptionAttribute - Return true if this class or any super
1175/// class has the __objc_exception__ attribute.
1176static bool hasObjCExceptionAttribute(const ObjCInterfaceDecl *OID) {
Daniel Dunbarb11fa0d2009-04-13 21:08:27 +00001177 if (OID->hasAttr<ObjCExceptionAttr>())
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001178 return true;
1179 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
1180 return hasObjCExceptionAttribute(Super);
1181 return false;
1182}
1183
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001184/* *** CGObjCMac Public Interface *** */
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001185
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001186CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm),
1187 ObjCTypes(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001188{
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001189 ObjCABI = 1;
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001190 EmitImageInfo();
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001191}
1192
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +00001193/// GetClass - Return a reference to the class for the given interface
1194/// decl.
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001195llvm::Value *CGObjCMac::GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001196 const ObjCInterfaceDecl *ID) {
1197 return EmitClassRef(Builder, ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001198}
1199
1200/// GetSelector - Return the pointer to the unique'd string for this selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001201llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00001202 return EmitSelector(Builder, Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001203}
1204
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001205/// Generate a constant CFString object.
1206/*
1207 struct __builtin_CFString {
1208 const int *isa; // point to __CFConstantStringClassReference
1209 int flags;
1210 const char *str;
1211 long length;
1212 };
1213*/
1214
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001215llvm::Constant *CGObjCCommonMac::GenerateConstantString(
Steve Naroff33fdb732009-03-31 16:53:37 +00001216 const ObjCStringLiteral *SL) {
Steve Naroff8d4141f2009-04-01 13:55:36 +00001217 return CGM.GetAddrOfConstantCFString(SL->getString());
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001218}
1219
1220/// Generates a message send where the super is the receiver. This is
1221/// a message send to self with special delivery semantics indicating
1222/// which class's method should be called.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +00001223CodeGen::RValue
1224CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001225 QualType ResultType,
1226 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001227 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00001228 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001229 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001230 bool IsClassMessage,
Daniel Dunbar46f45b92008-09-09 01:06:48 +00001231 const CodeGen::CallArgList &CallArgs) {
Daniel Dunbare8b470d2008-08-23 04:28:29 +00001232 // Create and init a super structure; this is a (receiver, class)
1233 // pair we will pass to objc_msgSendSuper.
1234 llvm::Value *ObjCSuper =
1235 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
1236 llvm::Value *ReceiverAsObject =
1237 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
1238 CGF.Builder.CreateStore(ReceiverAsObject,
1239 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
Daniel Dunbare8b470d2008-08-23 04:28:29 +00001240
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001241 // If this is a class message the metaclass is passed as the target.
1242 llvm::Value *Target;
1243 if (IsClassMessage) {
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00001244 if (isCategoryImpl) {
1245 // Message sent to 'super' in a class method defined in a category
1246 // implementation requires an odd treatment.
1247 // If we are in a class method, we must retrieve the
1248 // _metaclass_ for the current class, pointed at by
1249 // the class's "isa" pointer. The following assumes that
1250 // isa" is the first ivar in a class (which it must be).
1251 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
1252 Target = CGF.Builder.CreateStructGEP(Target, 0);
1253 Target = CGF.Builder.CreateLoad(Target);
1254 }
1255 else {
1256 llvm::Value *MetaClassPtr = EmitMetaClassRef(Class);
1257 llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1);
1258 llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr);
1259 Target = Super;
1260 }
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001261 } else {
1262 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
1263 }
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001264 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
1265 // and ObjCTypes types.
1266 const llvm::Type *ClassTy =
1267 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001268 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001269 CGF.Builder.CreateStore(Target,
1270 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
1271
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001272 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001273 ObjCSuper, ObjCTypes.SuperPtrCTy,
1274 true, CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001275}
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001276
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001277/// Generate code for a message send expression.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +00001278CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001279 QualType ResultType,
1280 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001281 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001282 bool IsClassMessage,
1283 const CallArgList &CallArgs) {
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001284 llvm::Value *Arg0 =
1285 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy, "tmp");
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001286 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001287 Arg0, CGF.getContext().getObjCIdType(),
1288 false, CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001289}
1290
1291CodeGen::RValue CGObjCMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001292 QualType ResultType,
1293 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001294 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001295 QualType Arg0Ty,
1296 bool IsSuper,
1297 const CallArgList &CallArgs) {
1298 CallArgList ActualArgs;
Daniel Dunbar46f45b92008-09-09 01:06:48 +00001299 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
1300 ActualArgs.push_back(std::make_pair(RValue::get(EmitSelector(CGF.Builder,
1301 Sel)),
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001302 CGF.getContext().getObjCSelType()));
1303 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001304
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001305 CodeGenTypes &Types = CGM.getTypes();
1306 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs);
1307 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo, false);
Daniel Dunbar5669e572008-10-17 03:24:53 +00001308
1309 llvm::Constant *Fn;
Daniel Dunbar88b53962009-02-02 22:03:45 +00001310 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Daniel Dunbar5669e572008-10-17 03:24:53 +00001311 Fn = ObjCTypes.getSendStretFn(IsSuper);
1312 } else if (ResultType->isFloatingType()) {
1313 // FIXME: Sadly, this is wrong. This actually depends on the
1314 // architecture. This happens to be right for x86-32 though.
1315 Fn = ObjCTypes.getSendFpretFn(IsSuper);
1316 } else {
1317 Fn = ObjCTypes.getSendFn(IsSuper);
1318 }
Daniel Dunbar62d5c1b2008-09-10 07:00:50 +00001319 Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy));
Daniel Dunbar88b53962009-02-02 22:03:45 +00001320 return CGF.EmitCall(FnInfo, Fn, ActualArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001321}
1322
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001323llvm::Value *CGObjCMac::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001324 const ObjCProtocolDecl *PD) {
Daniel Dunbarc67876d2008-09-04 04:33:15 +00001325 // FIXME: I don't understand why gcc generates this, or where it is
1326 // resolved. Investigate. Its also wasteful to look this up over and
1327 // over.
1328 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1329
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001330 return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
1331 ObjCTypes.ExternalProtocolPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001332}
1333
Fariborz Jahanianda320092009-01-29 19:24:30 +00001334void CGObjCCommonMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001335 // FIXME: We shouldn't need this, the protocol decl should contain
1336 // enough information to tell us whether this was a declaration or a
1337 // definition.
1338 DefinedProtocols.insert(PD->getIdentifier());
1339
1340 // If we have generated a forward reference to this protocol, emit
1341 // it now. Otherwise do nothing, the protocol objects are lazily
1342 // emitted.
1343 if (Protocols.count(PD->getIdentifier()))
1344 GetOrEmitProtocol(PD);
1345}
1346
Fariborz Jahanianda320092009-01-29 19:24:30 +00001347llvm::Constant *CGObjCCommonMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001348 if (DefinedProtocols.count(PD->getIdentifier()))
1349 return GetOrEmitProtocol(PD);
1350 return GetOrEmitProtocolRef(PD);
1351}
1352
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001353/*
1354 // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions
1355 struct _objc_protocol {
1356 struct _objc_protocol_extension *isa;
1357 char *protocol_name;
1358 struct _objc_protocol_list *protocol_list;
1359 struct _objc__method_prototype_list *instance_methods;
1360 struct _objc__method_prototype_list *class_methods
1361 };
1362
1363 See EmitProtocolExtension().
1364*/
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001365llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
1366 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1367
1368 // Early exit if a defining object has already been generated.
1369 if (Entry && Entry->hasInitializer())
1370 return Entry;
1371
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001372 // FIXME: I don't understand why gcc generates this, or where it is
1373 // resolved. Investigate. Its also wasteful to look this up over and
1374 // over.
1375 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1376
Chris Lattner8ec03f52008-11-24 03:54:41 +00001377 const char *ProtocolName = PD->getNameAsCString();
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001378
1379 // Construct method lists.
1380 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1381 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregor6ab35242009-04-09 21:40:53 +00001382 for (ObjCProtocolDecl::instmeth_iterator
1383 i = PD->instmeth_begin(CGM.getContext()),
1384 e = PD->instmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001385 ObjCMethodDecl *MD = *i;
1386 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1387 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1388 OptInstanceMethods.push_back(C);
1389 } else {
1390 InstanceMethods.push_back(C);
1391 }
1392 }
1393
Douglas Gregor6ab35242009-04-09 21:40:53 +00001394 for (ObjCProtocolDecl::classmeth_iterator
1395 i = PD->classmeth_begin(CGM.getContext()),
1396 e = PD->classmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001397 ObjCMethodDecl *MD = *i;
1398 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1399 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1400 OptClassMethods.push_back(C);
1401 } else {
1402 ClassMethods.push_back(C);
1403 }
1404 }
1405
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001406 std::vector<llvm::Constant*> Values(5);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001407 Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001408 Values[1] = GetClassName(PD->getIdentifier());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001409 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001410 EmitProtocolList("\01L_OBJC_PROTOCOL_REFS_" + PD->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001411 PD->protocol_begin(),
1412 PD->protocol_end());
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001413 Values[3] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001414 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_"
1415 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001416 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1417 InstanceMethods);
1418 Values[4] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001419 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_"
1420 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001421 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1422 ClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001423 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
1424 Values);
1425
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001426 if (Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001427 // Already created, fix the linkage and update the initializer.
1428 Entry->setLinkage(llvm::GlobalValue::InternalLinkage);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001429 Entry->setInitializer(Init);
1430 } else {
1431 Entry =
1432 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
1433 llvm::GlobalValue::InternalLinkage,
1434 Init,
1435 std::string("\01L_OBJC_PROTOCOL_")+ProtocolName,
1436 &CGM.getModule());
1437 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001438 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001439 UsedGlobals.push_back(Entry);
1440 // FIXME: Is this necessary? Why only for protocol?
1441 Entry->setAlignment(4);
1442 }
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001443
1444 return Entry;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001445}
1446
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001447llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001448 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1449
1450 if (!Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001451 // We use the initializer as a marker of whether this is a forward
1452 // reference or not. At module finalization we add the empty
1453 // contents for protocols which were referenced but never defined.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001454 Entry =
1455 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001456 llvm::GlobalValue::ExternalLinkage,
1457 0,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001458 "\01L_OBJC_PROTOCOL_" + PD->getNameAsString(),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001459 &CGM.getModule());
1460 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001461 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001462 UsedGlobals.push_back(Entry);
1463 // FIXME: Is this necessary? Why only for protocol?
1464 Entry->setAlignment(4);
1465 }
1466
1467 return Entry;
1468}
1469
1470/*
1471 struct _objc_protocol_extension {
1472 uint32_t size;
1473 struct objc_method_description_list *optional_instance_methods;
1474 struct objc_method_description_list *optional_class_methods;
1475 struct objc_property_list *instance_properties;
1476 };
1477*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001478llvm::Constant *
1479CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
1480 const ConstantVector &OptInstanceMethods,
1481 const ConstantVector &OptClassMethods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001482 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001483 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolExtensionTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001484 std::vector<llvm::Constant*> Values(4);
1485 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001486 Values[1] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001487 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_"
1488 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001489 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1490 OptInstanceMethods);
1491 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001492 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_"
1493 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001494 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1495 OptClassMethods);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001496 Values[3] = EmitPropertyList("\01L_OBJC_$_PROP_PROTO_LIST_" +
1497 PD->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001498 0, PD, ObjCTypes);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001499
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001500 // Return null if no extension bits are used.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001501 if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
1502 Values[3]->isNullValue())
1503 return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
1504
1505 llvm::Constant *Init =
1506 llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001507
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001508 // No special section, but goes in llvm.used
1509 return CreateMetadataVar("\01L_OBJC_PROTOCOLEXT_" + PD->getNameAsString(),
1510 Init,
1511 0, 0, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001512}
1513
1514/*
1515 struct objc_protocol_list {
1516 struct objc_protocol_list *next;
1517 long count;
1518 Protocol *list[];
1519 };
1520*/
Daniel Dunbardbc933702008-08-21 21:57:41 +00001521llvm::Constant *
1522CGObjCMac::EmitProtocolList(const std::string &Name,
1523 ObjCProtocolDecl::protocol_iterator begin,
1524 ObjCProtocolDecl::protocol_iterator end) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001525 std::vector<llvm::Constant*> ProtocolRefs;
1526
Daniel Dunbardbc933702008-08-21 21:57:41 +00001527 for (; begin != end; ++begin)
1528 ProtocolRefs.push_back(GetProtocolRef(*begin));
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001529
1530 // Just return null for empty protocol lists
1531 if (ProtocolRefs.empty())
1532 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1533
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001534 // This list is null terminated.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001535 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
1536
1537 std::vector<llvm::Constant*> Values(3);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001538 // This field is only used by the runtime.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001539 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1540 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
1541 Values[2] =
1542 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
1543 ProtocolRefs.size()),
1544 ProtocolRefs);
1545
1546 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1547 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001548 CreateMetadataVar(Name, Init, "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001549 4, false);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001550 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
1551}
1552
1553/*
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001554 struct _objc_property {
1555 const char * const name;
1556 const char * const attributes;
1557 };
1558
1559 struct _objc_property_list {
1560 uint32_t entsize; // sizeof (struct _objc_property)
1561 uint32_t prop_count;
1562 struct _objc_property[prop_count];
1563 };
1564*/
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001565llvm::Constant *CGObjCCommonMac::EmitPropertyList(const std::string &Name,
1566 const Decl *Container,
1567 const ObjCContainerDecl *OCD,
1568 const ObjCCommonTypesHelper &ObjCTypes) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001569 std::vector<llvm::Constant*> Properties, Prop(2);
Douglas Gregor6ab35242009-04-09 21:40:53 +00001570 for (ObjCContainerDecl::prop_iterator I = OCD->prop_begin(CGM.getContext()),
1571 E = OCD->prop_end(CGM.getContext()); I != E; ++I) {
Steve Naroff93983f82009-01-11 12:47:58 +00001572 const ObjCPropertyDecl *PD = *I;
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001573 Prop[0] = GetPropertyName(PD->getIdentifier());
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00001574 Prop[1] = GetPropertyTypeString(PD, Container);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001575 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
1576 Prop));
1577 }
1578
1579 // Return null for empty list.
1580 if (Properties.empty())
1581 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1582
1583 unsigned PropertySize =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001584 CGM.getTargetData().getTypePaddedSize(ObjCTypes.PropertyTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001585 std::vector<llvm::Constant*> Values(3);
1586 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
1587 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
1588 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
1589 Properties.size());
1590 Values[2] = llvm::ConstantArray::get(AT, Properties);
1591 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1592
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001593 llvm::GlobalVariable *GV =
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001594 CreateMetadataVar(Name, Init,
1595 (ObjCABI == 2) ? "__DATA, __objc_const" :
1596 "__OBJC,__property,regular,no_dead_strip",
1597 (ObjCABI == 2) ? 8 : 4,
1598 true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001599 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.PropertyListPtrTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001600}
1601
1602/*
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001603 struct objc_method_description_list {
1604 int count;
1605 struct objc_method_description list[];
1606 };
1607*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001608llvm::Constant *
1609CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
1610 std::vector<llvm::Constant*> Desc(2);
1611 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1612 ObjCTypes.SelectorPtrTy);
1613 Desc[1] = GetMethodVarType(MD);
1614 return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
1615 Desc);
1616}
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001617
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001618llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name,
1619 const char *Section,
1620 const ConstantVector &Methods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001621 // Return null for empty list.
1622 if (Methods.empty())
1623 return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
1624
1625 std::vector<llvm::Constant*> Values(2);
1626 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1627 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
1628 Methods.size());
1629 Values[1] = llvm::ConstantArray::get(AT, Methods);
1630 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1631
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001632 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001633 return llvm::ConstantExpr::getBitCast(GV,
1634 ObjCTypes.MethodDescriptionListPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001635}
1636
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001637/*
1638 struct _objc_category {
1639 char *category_name;
1640 char *class_name;
1641 struct _objc_method_list *instance_methods;
1642 struct _objc_method_list *class_methods;
1643 struct _objc_protocol_list *protocols;
1644 uint32_t size; // <rdar://4585769>
1645 struct _objc_property_list *instance_properties;
1646 };
1647 */
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001648void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001649 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.CategoryTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001650
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001651 // FIXME: This is poor design, the OCD should have a pointer to the
1652 // category decl. Additionally, note that Category can be null for
1653 // the @implementation w/o an @interface case. Sema should just
1654 // create one for us as it does for @implementation so everyone else
1655 // can live life under a clear blue sky.
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001656 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001657 const ObjCCategoryDecl *Category =
1658 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001659 std::string ExtName(Interface->getNameAsString() + "_" +
1660 OCD->getNameAsString());
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001661
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001662 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1663 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
1664 e = OCD->instmeth_end(); i != e; ++i) {
1665 // Instance methods should always be defined.
1666 InstanceMethods.push_back(GetMethodConstant(*i));
1667 }
1668 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
1669 e = OCD->classmeth_end(); i != e; ++i) {
1670 // Class methods should always be defined.
1671 ClassMethods.push_back(GetMethodConstant(*i));
1672 }
1673
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001674 std::vector<llvm::Constant*> Values(7);
1675 Values[0] = GetClassName(OCD->getIdentifier());
1676 Values[1] = GetClassName(Interface->getIdentifier());
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001677 Values[2] =
1678 EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") +
1679 ExtName,
1680 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001681 InstanceMethods);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001682 Values[3] =
1683 EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName,
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001684 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001685 ClassMethods);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001686 if (Category) {
1687 Values[4] =
1688 EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName,
1689 Category->protocol_begin(),
1690 Category->protocol_end());
1691 } else {
1692 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1693 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001694 Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001695
1696 // If there is no category @interface then there can be no properties.
1697 if (Category) {
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001698 Values[6] = EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001699 OCD, Category, ObjCTypes);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001700 } else {
1701 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1702 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001703
1704 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
1705 Values);
1706
1707 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001708 CreateMetadataVar(std::string("\01L_OBJC_CATEGORY_")+ExtName, Init,
1709 "__OBJC,__category,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001710 4, true);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001711 DefinedCategories.push_back(GV);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001712}
1713
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001714// FIXME: Get from somewhere?
1715enum ClassFlags {
1716 eClassFlags_Factory = 0x00001,
1717 eClassFlags_Meta = 0x00002,
1718 // <rdr://5142207>
1719 eClassFlags_HasCXXStructors = 0x02000,
1720 eClassFlags_Hidden = 0x20000,
1721 eClassFlags_ABI2_Hidden = 0x00010,
1722 eClassFlags_ABI2_HasCXXStructors = 0x00004 // <rdr://4923634>
1723};
1724
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001725/*
1726 struct _objc_class {
1727 Class isa;
1728 Class super_class;
1729 const char *name;
1730 long version;
1731 long info;
1732 long instance_size;
1733 struct _objc_ivar_list *ivars;
1734 struct _objc_method_list *methods;
1735 struct _objc_cache *cache;
1736 struct _objc_protocol_list *protocols;
1737 // Objective-C 1.0 extensions (<rdr://4585769>)
1738 const char *ivar_layout;
1739 struct _objc_class_ext *ext;
1740 };
1741
1742 See EmitClassExtension();
1743 */
1744void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001745 DefinedSymbols.insert(ID->getIdentifier());
1746
Chris Lattner8ec03f52008-11-24 03:54:41 +00001747 std::string ClassName = ID->getNameAsString();
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001748 // FIXME: Gross
1749 ObjCInterfaceDecl *Interface =
1750 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001751 llvm::Constant *Protocols =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001752 EmitProtocolList("\01L_OBJC_CLASS_PROTOCOLS_" + ID->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001753 Interface->protocol_begin(),
1754 Interface->protocol_end());
Chris Lattnerb7b58b12009-04-19 06:02:28 +00001755 const llvm::Type *InterfaceTy;
1756 if (Interface->isForwardDecl())
1757 InterfaceTy = llvm::StructType::get(NULL, NULL);
1758 else
1759 InterfaceTy =
Chris Lattner03d9f342009-04-01 06:23:52 +00001760 CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(Interface));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001761 unsigned Flags = eClassFlags_Factory;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001762 unsigned Size = CGM.getTargetData().getTypePaddedSize(InterfaceTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001763
1764 // FIXME: Set CXX-structors flag.
Daniel Dunbar04d40782009-04-14 06:00:08 +00001765 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001766 Flags |= eClassFlags_Hidden;
1767
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001768 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1769 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
1770 e = ID->instmeth_end(); i != e; ++i) {
1771 // Instance methods should always be defined.
1772 InstanceMethods.push_back(GetMethodConstant(*i));
1773 }
1774 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
1775 e = ID->classmeth_end(); i != e; ++i) {
1776 // Class methods should always be defined.
1777 ClassMethods.push_back(GetMethodConstant(*i));
1778 }
1779
1780 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
1781 e = ID->propimpl_end(); i != e; ++i) {
1782 ObjCPropertyImplDecl *PID = *i;
1783
1784 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1785 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1786
1787 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
1788 if (llvm::Constant *C = GetMethodConstant(MD))
1789 InstanceMethods.push_back(C);
1790 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
1791 if (llvm::Constant *C = GetMethodConstant(MD))
1792 InstanceMethods.push_back(C);
1793 }
1794 }
1795
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001796 std::vector<llvm::Constant*> Values(12);
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001797 Values[ 0] = EmitMetaClass(ID, Protocols, InterfaceTy, ClassMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001798 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001799 // Record a reference to the super class.
1800 LazySymbols.insert(Super->getIdentifier());
1801
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001802 Values[ 1] =
1803 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1804 ObjCTypes.ClassPtrTy);
1805 } else {
1806 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1807 }
1808 Values[ 2] = GetClassName(ID->getIdentifier());
1809 // Version is always 0.
1810 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1811 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1812 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001813 Values[ 6] = EmitIvarList(ID, false);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001814 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001815 EmitMethodList("\01L_OBJC_INSTANCE_METHODS_" + ID->getNameAsString(),
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001816 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001817 InstanceMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001818 // cache is always NULL.
1819 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1820 Values[ 9] = Protocols;
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001821 // FIXME: Set ivar_layout
Fariborz Jahanian667423a2009-03-25 22:36:49 +00001822 // Values[10] = BuildIvarLayout(ID, true);
1823 Values[10] = GetIvarLayoutName(0, ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001824 Values[11] = EmitClassExtension(ID);
1825 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1826 Values);
1827
1828 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001829 CreateMetadataVar(std::string("\01L_OBJC_CLASS_")+ClassName, Init,
1830 "__OBJC,__class,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001831 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001832 DefinedClasses.push_back(GV);
1833}
1834
1835llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
1836 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001837 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001838 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001839 unsigned Flags = eClassFlags_Meta;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001840 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001841
Daniel Dunbar04d40782009-04-14 06:00:08 +00001842 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001843 Flags |= eClassFlags_Hidden;
1844
1845 std::vector<llvm::Constant*> Values(12);
1846 // The isa for the metaclass is the root of the hierarchy.
1847 const ObjCInterfaceDecl *Root = ID->getClassInterface();
1848 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
1849 Root = Super;
1850 Values[ 0] =
1851 llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
1852 ObjCTypes.ClassPtrTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001853 // The super class for the metaclass is emitted as the name of the
1854 // super class. The runtime fixes this up to point to the
1855 // *metaclass* for the super class.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001856 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
1857 Values[ 1] =
1858 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1859 ObjCTypes.ClassPtrTy);
1860 } else {
1861 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1862 }
1863 Values[ 2] = GetClassName(ID->getIdentifier());
1864 // Version is always 0.
1865 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1866 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1867 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001868 Values[ 6] = EmitIvarList(ID, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001869 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001870 EmitMethodList("\01L_OBJC_CLASS_METHODS_" + ID->getNameAsString(),
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001871 "__OBJC,__cls_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001872 Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001873 // cache is always NULL.
1874 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1875 Values[ 9] = Protocols;
1876 // ivar_layout for metaclass is always NULL.
1877 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1878 // The class extension is always unused for metaclasses.
1879 Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1880 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1881 Values);
1882
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001883 std::string Name("\01L_OBJC_METACLASS_");
Chris Lattner8ec03f52008-11-24 03:54:41 +00001884 Name += ID->getNameAsCString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001885
1886 // Check for a forward reference.
1887 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
1888 if (GV) {
1889 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1890 "Forward metaclass reference has incorrect type.");
1891 GV->setLinkage(llvm::GlobalValue::InternalLinkage);
1892 GV->setInitializer(Init);
1893 } else {
1894 GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1895 llvm::GlobalValue::InternalLinkage,
1896 Init, Name,
1897 &CGM.getModule());
1898 }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001899 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001900 GV->setAlignment(4);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001901 UsedGlobals.push_back(GV);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001902
1903 return GV;
1904}
1905
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001906llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001907 std::string Name = "\01L_OBJC_METACLASS_" + ID->getNameAsString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001908
1909 // FIXME: Should we look these up somewhere other than the
1910 // module. Its a bit silly since we only generate these while
1911 // processing an implementation, so exactly one pointer would work
1912 // if know when we entered/exitted an implementation block.
1913
1914 // Check for an existing forward reference.
Fariborz Jahanianb0d27942009-01-07 20:11:22 +00001915 // Previously, metaclass with internal linkage may have been defined.
1916 // pass 'true' as 2nd argument so it is returned.
1917 if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true)) {
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001918 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1919 "Forward metaclass reference has incorrect type.");
1920 return GV;
1921 } else {
1922 // Generate as an external reference to keep a consistent
1923 // module. This will be patched up when we emit the metaclass.
1924 return new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1925 llvm::GlobalValue::ExternalLinkage,
1926 0,
1927 Name,
1928 &CGM.getModule());
1929 }
1930}
1931
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001932/*
1933 struct objc_class_ext {
1934 uint32_t size;
1935 const char *weak_ivar_layout;
1936 struct _objc_property_list *properties;
1937 };
1938*/
1939llvm::Constant *
1940CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
1941 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001942 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassExtensionTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001943
1944 std::vector<llvm::Constant*> Values(3);
1945 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001946 // FIXME: Output weak_ivar_layout string.
Fariborz Jahanian667423a2009-03-25 22:36:49 +00001947 // Values[1] = BuildIvarLayout(ID, false);
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00001948 Values[1] = GetIvarLayoutName(0, ObjCTypes);
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001949 Values[2] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001950 ID, ID->getClassInterface(), ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001951
1952 // Return null if no extension bits are used.
1953 if (Values[1]->isNullValue() && Values[2]->isNullValue())
1954 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1955
1956 llvm::Constant *Init =
1957 llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001958 return CreateMetadataVar("\01L_OBJC_CLASSEXT_" + ID->getNameAsString(),
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001959 Init, "__OBJC,__class_ext,regular,no_dead_strip",
1960 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001961}
1962
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001963/// getInterfaceDeclForIvar - Get the interface declaration node where
1964/// this ivar is declared in.
1965/// FIXME. Ideally, this info should be in the ivar node. But currently
1966/// it is not and prevailing wisdom is that ASTs should not have more
1967/// info than is absolutely needed, even though this info reflects the
1968/// source language.
1969///
1970static const ObjCInterfaceDecl *getInterfaceDeclForIvar(
1971 const ObjCInterfaceDecl *OI,
Douglas Gregor6ab35242009-04-09 21:40:53 +00001972 const ObjCIvarDecl *IVD,
1973 ASTContext &Context) {
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001974 if (!OI)
1975 return 0;
1976 assert(isa<ObjCInterfaceDecl>(OI) && "OI is not an interface");
1977 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1978 E = OI->ivar_end(); I != E; ++I)
1979 if ((*I)->getIdentifier() == IVD->getIdentifier())
1980 return OI;
Fariborz Jahanian5a4b4532009-03-31 17:00:52 +00001981 // look into properties.
Douglas Gregor6ab35242009-04-09 21:40:53 +00001982 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(Context),
1983 E = OI->prop_end(Context); I != E; ++I) {
Fariborz Jahanian5a4b4532009-03-31 17:00:52 +00001984 ObjCPropertyDecl *PDecl = (*I);
1985 if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl())
1986 if (IV->getIdentifier() == IVD->getIdentifier())
1987 return OI;
1988 }
Douglas Gregor6ab35242009-04-09 21:40:53 +00001989 return getInterfaceDeclForIvar(OI->getSuperClass(), IVD, Context);
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001990}
1991
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001992/*
1993 struct objc_ivar {
1994 char *ivar_name;
1995 char *ivar_type;
1996 int ivar_offset;
1997 };
1998
1999 struct objc_ivar_list {
2000 int ivar_count;
2001 struct objc_ivar list[count];
2002 };
2003 */
2004llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002005 bool ForClass) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002006 std::vector<llvm::Constant*> Ivars, Ivar(3);
2007
2008 // When emitting the root class GCC emits ivar entries for the
2009 // actual class structure. It is not clear if we need to follow this
2010 // behavior; for now lets try and get away with not doing it. If so,
2011 // the cleanest solution would be to make up an ObjCInterfaceDecl
2012 // for the class.
2013 if (ForClass)
2014 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002015
2016 ObjCInterfaceDecl *OID =
2017 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002018 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002019
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00002020 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
2021 GetNamedIvarList(OID, OIvars);
2022
2023 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
2024 ObjCIvarDecl *IVD = OIvars[i];
2025 const FieldDecl *Field = OID->lookupFieldDeclForIvar(CGM.getContext(), IVD);
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00002026 Ivar[0] = GetMethodVarName(Field->getIdentifier());
Devang Patel7794bb82009-03-04 18:21:39 +00002027 Ivar[1] = GetMethodVarType(Field);
Daniel Dunbar6c1aac82009-04-20 20:18:54 +00002028 Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy,
2029 GetIvarBaseOffset(Layout, Field));
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002030 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002031 }
2032
2033 // Return null for empty list.
2034 if (Ivars.empty())
2035 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
2036
2037 std::vector<llvm::Constant*> Values(2);
2038 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
2039 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
2040 Ivars.size());
2041 Values[1] = llvm::ConstantArray::get(AT, Ivars);
2042 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2043
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002044 llvm::GlobalVariable *GV;
2045 if (ForClass)
2046 GV = CreateMetadataVar("\01L_OBJC_CLASS_VARIABLES_" + ID->getNameAsString(),
Daniel Dunbar58a29122009-03-09 22:18:41 +00002047 Init, "__OBJC,__class_vars,regular,no_dead_strip",
2048 4, true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002049 else
2050 GV = CreateMetadataVar("\01L_OBJC_INSTANCE_VARIABLES_"
2051 + ID->getNameAsString(),
2052 Init, "__OBJC,__instance_vars,regular,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002053 4, true);
2054 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.IvarListPtrTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002055}
2056
2057/*
2058 struct objc_method {
2059 SEL method_name;
2060 char *method_types;
2061 void *method;
2062 };
2063
2064 struct objc_method_list {
2065 struct objc_method_list *obsolete;
2066 int count;
2067 struct objc_method methods_list[count];
2068 };
2069*/
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002070
2071/// GetMethodConstant - Return a struct objc_method constant for the
2072/// given method if it has been defined. The result is null if the
2073/// method has not been defined. The return value has type MethodPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +00002074llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002075 // FIXME: Use DenseMap::lookup
2076 llvm::Function *Fn = MethodDefinitions[MD];
2077 if (!Fn)
2078 return 0;
2079
2080 std::vector<llvm::Constant*> Method(3);
2081 Method[0] =
2082 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
2083 ObjCTypes.SelectorPtrTy);
2084 Method[1] = GetMethodVarType(MD);
2085 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
2086 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
2087}
2088
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002089llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name,
2090 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00002091 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002092 // Return null for empty list.
2093 if (Methods.empty())
2094 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
2095
2096 std::vector<llvm::Constant*> Values(3);
2097 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2098 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
2099 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
2100 Methods.size());
2101 Values[2] = llvm::ConstantArray::get(AT, Methods);
2102 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2103
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002104 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002105 return llvm::ConstantExpr::getBitCast(GV,
2106 ObjCTypes.MethodListPtrTy);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002107}
2108
Fariborz Jahanian493dab72009-01-26 21:38:32 +00002109llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD,
Daniel Dunbarbb36d332009-02-02 21:43:58 +00002110 const ObjCContainerDecl *CD) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002111 std::string Name;
Fariborz Jahanian679a5022009-01-10 21:06:09 +00002112 GetNameForMethod(OMD, CD, Name);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002113
Daniel Dunbar541b63b2009-02-02 23:23:47 +00002114 CodeGenTypes &Types = CGM.getTypes();
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00002115 const llvm::FunctionType *MethodTy =
Daniel Dunbar541b63b2009-02-02 23:23:47 +00002116 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002117 llvm::Function *Method =
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00002118 llvm::Function::Create(MethodTy,
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002119 llvm::GlobalValue::InternalLinkage,
2120 Name,
2121 &CGM.getModule());
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002122 MethodDefinitions.insert(std::make_pair(OMD, Method));
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002123
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002124 return Method;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00002125}
2126
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00002127uint64_t CGObjCCommonMac::GetIvarBaseOffset(const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +00002128 const FieldDecl *Field) {
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00002129 if (!Field->isBitField())
Daniel Dunbar48fa0642009-04-19 02:03:42 +00002130 return Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(Field));
2131
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00002132 // FIXME. Must be a better way of getting a bitfield base offset.
Daniel Dunbar48fa0642009-04-19 02:03:42 +00002133 CodeGenTypes::BitFieldInfo BFI = CGM.getTypes().getBitFieldInfo(Field);
2134 // FIXME: The "field no" for bitfields is something completely
2135 // different; it is the offset in multiples of the base type size!
2136 uint64_t Offset = CGM.getTypes().getLLVMFieldNo(Field);
2137 const llvm::Type *Ty =
2138 CGM.getTypes().ConvertTypeForMemRecursive(Field->getType());
2139 Offset *= CGM.getTypes().getTargetData().getTypePaddedSizeInBits(Ty);
2140 return (Offset + BFI.Begin) / 8;
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00002141}
2142
Daniel Dunbar48fa0642009-04-19 02:03:42 +00002143/// GetFieldBaseOffset - return the field's byte offset.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002144uint64_t CGObjCCommonMac::GetFieldBaseOffset(const ObjCInterfaceDecl *OI,
2145 const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +00002146 const FieldDecl *Field) {
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00002147 // Is this a c struct?
2148 if (!OI)
2149 return Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(Field));
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002150 const ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
Chris Lattnercd0ee142009-03-31 08:33:16 +00002151 const FieldDecl *FD = OI->lookupFieldDeclForIvar(CGM.getContext(), Ivar);
2152 return GetIvarBaseOffset(Layout, FD);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002153}
2154
Daniel Dunbarfd65d372009-03-09 20:09:19 +00002155llvm::GlobalVariable *
2156CGObjCCommonMac::CreateMetadataVar(const std::string &Name,
2157 llvm::Constant *Init,
2158 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +00002159 unsigned Align,
2160 bool AddToUsed) {
Daniel Dunbarfd65d372009-03-09 20:09:19 +00002161 const llvm::Type *Ty = Init->getType();
2162 llvm::GlobalVariable *GV =
2163 new llvm::GlobalVariable(Ty, false,
2164 llvm::GlobalValue::InternalLinkage,
2165 Init,
2166 Name,
2167 &CGM.getModule());
2168 if (Section)
2169 GV->setSection(Section);
Daniel Dunbar35bd7632009-03-09 20:50:13 +00002170 if (Align)
2171 GV->setAlignment(Align);
2172 if (AddToUsed)
Daniel Dunbarfd65d372009-03-09 20:09:19 +00002173 UsedGlobals.push_back(GV);
2174 return GV;
2175}
2176
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00002177llvm::Function *CGObjCMac::ModuleInitFunction() {
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002178 // Abuse this interface function as a place to finalize.
2179 FinishModule();
2180
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00002181 return NULL;
2182}
2183
Chris Lattner74391b42009-03-22 21:03:39 +00002184llvm::Constant *CGObjCMac::GetPropertyGetFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00002185 return ObjCTypes.getGetPropertyFn();
Daniel Dunbar49f66022008-09-24 03:38:44 +00002186}
2187
Chris Lattner74391b42009-03-22 21:03:39 +00002188llvm::Constant *CGObjCMac::GetPropertySetFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00002189 return ObjCTypes.getSetPropertyFn();
Daniel Dunbar49f66022008-09-24 03:38:44 +00002190}
2191
Chris Lattner74391b42009-03-22 21:03:39 +00002192llvm::Constant *CGObjCMac::EnumerationMutationFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00002193 return ObjCTypes.getEnumerationMutationFn();
Anders Carlsson2abd89c2008-08-31 04:05:03 +00002194}
2195
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002196/*
2197
2198Objective-C setjmp-longjmp (sjlj) Exception Handling
2199--
2200
2201The basic framework for a @try-catch-finally is as follows:
2202{
2203 objc_exception_data d;
2204 id _rethrow = null;
Anders Carlsson190d00e2009-02-07 21:26:04 +00002205 bool _call_try_exit = true;
2206
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002207 objc_exception_try_enter(&d);
2208 if (!setjmp(d.jmp_buf)) {
2209 ... try body ...
2210 } else {
2211 // exception path
2212 id _caught = objc_exception_extract(&d);
2213
2214 // enter new try scope for handlers
2215 if (!setjmp(d.jmp_buf)) {
2216 ... match exception and execute catch blocks ...
2217
2218 // fell off end, rethrow.
2219 _rethrow = _caught;
Daniel Dunbar898d5082008-09-30 01:06:03 +00002220 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002221 } else {
2222 // exception in catch block
2223 _rethrow = objc_exception_extract(&d);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002224 _call_try_exit = false;
2225 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002226 }
2227 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00002228 ... jump-through-finally to finally_end ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002229
2230finally:
Anders Carlsson190d00e2009-02-07 21:26:04 +00002231 if (_call_try_exit)
2232 objc_exception_try_exit(&d);
2233
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002234 ... finally block ....
Daniel Dunbar898d5082008-09-30 01:06:03 +00002235 ... dispatch to finally destination ...
2236
2237finally_rethrow:
2238 objc_exception_throw(_rethrow);
2239
2240finally_end:
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002241}
2242
2243This framework differs slightly from the one gcc uses, in that gcc
Daniel Dunbar898d5082008-09-30 01:06:03 +00002244uses _rethrow to determine if objc_exception_try_exit should be called
2245and if the object should be rethrown. This breaks in the face of
2246throwing nil and introduces unnecessary branches.
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002247
2248We specialize this framework for a few particular circumstances:
2249
2250 - If there are no catch blocks, then we avoid emitting the second
2251 exception handling context.
2252
2253 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
2254 e)) we avoid emitting the code to rethrow an uncaught exception.
2255
2256 - FIXME: If there is no @finally block we can do a few more
2257 simplifications.
2258
2259Rethrows and Jumps-Through-Finally
2260--
2261
2262Support for implicit rethrows and jumping through the finally block is
2263handled by storing the current exception-handling context in
2264ObjCEHStack.
2265
Daniel Dunbar898d5082008-09-30 01:06:03 +00002266In order to implement proper @finally semantics, we support one basic
2267mechanism for jumping through the finally block to an arbitrary
2268destination. Constructs which generate exits from a @try or @catch
2269block use this mechanism to implement the proper semantics by chaining
2270jumps, as necessary.
2271
2272This mechanism works like the one used for indirect goto: we
2273arbitrarily assign an ID to each destination and store the ID for the
2274destination in a variable prior to entering the finally block. At the
2275end of the finally block we simply create a switch to the proper
2276destination.
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002277
2278Code gen for @synchronized(expr) stmt;
2279Effectively generating code for:
2280objc_sync_enter(expr);
2281@try stmt @finally { objc_sync_exit(expr); }
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002282*/
2283
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002284void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
2285 const Stmt &S) {
2286 bool isTry = isa<ObjCAtTryStmt>(S);
Daniel Dunbar898d5082008-09-30 01:06:03 +00002287 // Create various blocks we refer to for handling @finally.
Daniel Dunbar55e87422008-11-11 02:29:29 +00002288 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002289 llvm::BasicBlock *FinallyExit = CGF.createBasicBlock("finally.exit");
Daniel Dunbar55e87422008-11-11 02:29:29 +00002290 llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
2291 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
2292 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
Daniel Dunbar1c566672009-02-24 01:43:46 +00002293
2294 // For @synchronized, call objc_sync_enter(sync.expr). The
2295 // evaluation of the expression must occur before we enter the
2296 // @synchronized. We can safely avoid a temp here because jumps into
2297 // @synchronized are illegal & this will dominate uses.
2298 llvm::Value *SyncArg = 0;
2299 if (!isTry) {
2300 SyncArg =
2301 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
2302 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00002303 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar1c566672009-02-24 01:43:46 +00002304 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00002305
2306 // Push an EH context entry, used for handling rethrows and jumps
2307 // through finally.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002308 CGF.PushCleanupBlock(FinallyBlock);
2309
Anders Carlsson273558f2009-02-07 21:37:21 +00002310 CGF.ObjCEHValueStack.push_back(0);
2311
Daniel Dunbar898d5082008-09-30 01:06:03 +00002312 // Allocate memory for the exception data and rethrow pointer.
Anders Carlsson80f25672008-09-09 17:59:25 +00002313 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
2314 "exceptiondata.ptr");
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002315 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
2316 "_rethrow");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002317 llvm::Value *CallTryExitPtr = CGF.CreateTempAlloca(llvm::Type::Int1Ty,
2318 "_call_try_exit");
2319 CGF.Builder.CreateStore(llvm::ConstantInt::getTrue(), CallTryExitPtr);
2320
Anders Carlsson80f25672008-09-09 17:59:25 +00002321 // Enter a new try block and call setjmp.
Chris Lattner34b02a12009-04-22 02:26:14 +00002322 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryEnterFn(), ExceptionData);
Anders Carlsson80f25672008-09-09 17:59:25 +00002323 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
2324 "jmpbufarray");
2325 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
Chris Lattner34b02a12009-04-22 02:26:14 +00002326 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.getSetJmpFn(),
Anders Carlsson80f25672008-09-09 17:59:25 +00002327 JmpBufPtr, "result");
Daniel Dunbar898d5082008-09-30 01:06:03 +00002328
Daniel Dunbar55e87422008-11-11 02:29:29 +00002329 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
2330 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002331 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002332 TryHandler, TryBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002333
2334 // Emit the @try block.
2335 CGF.EmitBlock(TryBlock);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002336 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
2337 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002338 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002339
2340 // Emit the "exception in @try" block.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002341 CGF.EmitBlock(TryHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002342
2343 // Retrieve the exception object. We may emit multiple blocks but
2344 // nothing can cross this so the value is already in SSA form.
Chris Lattner34b02a12009-04-22 02:26:14 +00002345 llvm::Value *Caught =
2346 CGF.Builder.CreateCall(ObjCTypes.getExceptionExtractFn(),
2347 ExceptionData, "caught");
Anders Carlsson273558f2009-02-07 21:37:21 +00002348 CGF.ObjCEHValueStack.back() = Caught;
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002349 if (!isTry)
2350 {
2351 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002352 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002353 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002354 }
2355 else if (const ObjCAtCatchStmt* CatchStmt =
2356 cast<ObjCAtTryStmt>(S).getCatchStmts())
2357 {
Daniel Dunbar55e40722008-09-27 07:03:52 +00002358 // Enter a new exception try block (in case a @catch block throws
2359 // an exception).
Chris Lattner34b02a12009-04-22 02:26:14 +00002360 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryEnterFn(), ExceptionData);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002361
Chris Lattner34b02a12009-04-22 02:26:14 +00002362 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.getSetJmpFn(),
Anders Carlsson80f25672008-09-09 17:59:25 +00002363 JmpBufPtr, "result");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002364 llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw");
Anders Carlsson80f25672008-09-09 17:59:25 +00002365
Daniel Dunbar55e87422008-11-11 02:29:29 +00002366 llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch");
2367 llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler");
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002368 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002369
2370 CGF.EmitBlock(CatchBlock);
2371
Daniel Dunbar55e40722008-09-27 07:03:52 +00002372 // Handle catch list. As a special case we check if everything is
2373 // matched and avoid generating code for falling off the end if
2374 // so.
2375 bool AllMatched = false;
Anders Carlsson80f25672008-09-09 17:59:25 +00002376 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbar55e87422008-11-11 02:29:29 +00002377 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch");
Anders Carlsson80f25672008-09-09 17:59:25 +00002378
Steve Naroff7ba138a2009-03-03 19:52:17 +00002379 const ParmVarDecl *CatchParam = CatchStmt->getCatchParamDecl();
Daniel Dunbar129271a2008-09-27 07:36:24 +00002380 const PointerType *PT = 0;
2381
Anders Carlsson80f25672008-09-09 17:59:25 +00002382 // catch(...) always matches.
Daniel Dunbar55e40722008-09-27 07:03:52 +00002383 if (!CatchParam) {
2384 AllMatched = true;
2385 } else {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002386 PT = CatchParam->getType()->getAsPointerType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002387
Daniel Dunbar97f61d12008-09-27 22:21:14 +00002388 // catch(id e) always matches.
2389 // FIXME: For the time being we also match id<X>; this should
2390 // be rejected by Sema instead.
Steve Naroff389bf462009-02-12 17:52:19 +00002391 if ((PT && CGF.getContext().isObjCIdStructType(PT->getPointeeType())) ||
Steve Naroff7ba138a2009-03-03 19:52:17 +00002392 CatchParam->getType()->isObjCQualifiedIdType())
Daniel Dunbar55e40722008-09-27 07:03:52 +00002393 AllMatched = true;
Anders Carlsson80f25672008-09-09 17:59:25 +00002394 }
2395
Daniel Dunbar55e40722008-09-27 07:03:52 +00002396 if (AllMatched) {
Anders Carlssondde0a942008-09-11 09:15:33 +00002397 if (CatchParam) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002398 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002399 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002400 CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002401 }
Anders Carlsson1452f552008-09-11 08:21:54 +00002402
Anders Carlssondde0a942008-09-11 09:15:33 +00002403 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002404 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002405 break;
2406 }
2407
Daniel Dunbar129271a2008-09-27 07:36:24 +00002408 assert(PT && "Unexpected non-pointer type in @catch");
2409 QualType T = PT->getPointeeType();
Anders Carlsson4b7ff6e2008-09-11 06:35:14 +00002410 const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002411 assert(ObjCType && "Catch parameter must have Objective-C type!");
2412
2413 // Check if the @catch block matches the exception object.
2414 llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl());
2415
Chris Lattner34b02a12009-04-22 02:26:14 +00002416 llvm::Value *Match =
2417 CGF.Builder.CreateCall2(ObjCTypes.getExceptionMatchFn(),
2418 Class, Caught, "match");
Anders Carlsson80f25672008-09-09 17:59:25 +00002419
Daniel Dunbar55e87422008-11-11 02:29:29 +00002420 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched");
Anders Carlsson80f25672008-09-09 17:59:25 +00002421
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002422 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002423 MatchedBlock, NextCatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002424
2425 // Emit the @catch block.
2426 CGF.EmitBlock(MatchedBlock);
Steve Naroff7ba138a2009-03-03 19:52:17 +00002427 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002428 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002429
2430 llvm::Value *Tmp =
Steve Naroff7ba138a2009-03-03 19:52:17 +00002431 CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(CatchParam->getType()),
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002432 "tmp");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002433 CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002434
2435 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002436 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002437
2438 CGF.EmitBlock(NextCatchBlock);
2439 }
2440
Daniel Dunbar55e40722008-09-27 07:03:52 +00002441 if (!AllMatched) {
2442 // None of the handlers caught the exception, so store it to be
2443 // rethrown at the end of the @finally block.
2444 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002445 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002446 }
2447
2448 // Emit the exception handler for the @catch blocks.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002449 CGF.EmitBlock(CatchHandler);
Chris Lattner34b02a12009-04-22 02:26:14 +00002450 CGF.Builder.CreateStore(
2451 CGF.Builder.CreateCall(ObjCTypes.getExceptionExtractFn(),
2452 ExceptionData),
Daniel Dunbar55e40722008-09-27 07:03:52 +00002453 RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002454 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002455 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002456 } else {
Anders Carlsson80f25672008-09-09 17:59:25 +00002457 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002458 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002459 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Anders Carlsson80f25672008-09-09 17:59:25 +00002460 }
2461
Daniel Dunbar898d5082008-09-30 01:06:03 +00002462 // Pop the exception-handling stack entry. It is important to do
2463 // this now, because the code in the @finally block is not in this
2464 // context.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002465 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
2466
Anders Carlsson273558f2009-02-07 21:37:21 +00002467 CGF.ObjCEHValueStack.pop_back();
2468
Anders Carlsson80f25672008-09-09 17:59:25 +00002469 // Emit the @finally block.
2470 CGF.EmitBlock(FinallyBlock);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002471 llvm::Value* CallTryExit = CGF.Builder.CreateLoad(CallTryExitPtr, "tmp");
2472
2473 CGF.Builder.CreateCondBr(CallTryExit, FinallyExit, FinallyNoExit);
2474
2475 CGF.EmitBlock(FinallyExit);
Chris Lattner34b02a12009-04-22 02:26:14 +00002476 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryExitFn(), ExceptionData);
Daniel Dunbar129271a2008-09-27 07:36:24 +00002477
2478 CGF.EmitBlock(FinallyNoExit);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002479 if (isTry) {
2480 if (const ObjCAtFinallyStmt* FinallyStmt =
2481 cast<ObjCAtTryStmt>(S).getFinallyStmt())
2482 CGF.EmitStmt(FinallyStmt->getFinallyBody());
Daniel Dunbar1c566672009-02-24 01:43:46 +00002483 } else {
2484 // Emit objc_sync_exit(expr); as finally's sole statement for
2485 // @synchronized.
Chris Lattnerbbccd612009-04-22 02:38:11 +00002486 CGF.Builder.CreateCall(ObjCTypes.getSyncExitFn(), SyncArg);
Fariborz Jahanianf2878e52008-11-21 19:21:53 +00002487 }
Anders Carlsson80f25672008-09-09 17:59:25 +00002488
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002489 // Emit the switch block
2490 if (Info.SwitchBlock)
2491 CGF.EmitBlock(Info.SwitchBlock);
2492 if (Info.EndBlock)
2493 CGF.EmitBlock(Info.EndBlock);
2494
Daniel Dunbar898d5082008-09-30 01:06:03 +00002495 CGF.EmitBlock(FinallyRethrow);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002496 CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(),
Daniel Dunbar898d5082008-09-30 01:06:03 +00002497 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002498 CGF.Builder.CreateUnreachable();
Daniel Dunbar898d5082008-09-30 01:06:03 +00002499
2500 CGF.EmitBlock(FinallyEnd);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002501}
2502
2503void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar898d5082008-09-30 01:06:03 +00002504 const ObjCAtThrowStmt &S) {
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002505 llvm::Value *ExceptionAsObject;
2506
2507 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2508 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
2509 ExceptionAsObject =
2510 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
2511 } else {
Anders Carlsson273558f2009-02-07 21:37:21 +00002512 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002513 "Unexpected rethrow outside @catch block.");
Anders Carlsson273558f2009-02-07 21:37:21 +00002514 ExceptionAsObject = CGF.ObjCEHValueStack.back();
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002515 }
2516
Chris Lattnerbbccd612009-04-22 02:38:11 +00002517 CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(), ExceptionAsObject);
Anders Carlsson80f25672008-09-09 17:59:25 +00002518 CGF.Builder.CreateUnreachable();
Daniel Dunbara448fb22008-11-11 23:11:34 +00002519
2520 // Clear the insertion point to indicate we are in unreachable code.
2521 CGF.Builder.ClearInsertionPoint();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002522}
2523
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002524/// EmitObjCWeakRead - Code gen for loading value of a __weak
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002525/// object: objc_read_weak (id *src)
2526///
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002527llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002528 llvm::Value *AddrWeakObj)
2529{
Eli Friedman8339b352009-03-07 03:57:15 +00002530 const llvm::Type* DestTy =
2531 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002532 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Chris Lattner72db6c32009-04-22 02:44:54 +00002533 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.getGcReadWeakFn(),
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002534 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00002535 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002536 return read_weak;
2537}
2538
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002539/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
2540/// objc_assign_weak (id src, id *dst)
2541///
2542void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
2543 llvm::Value *src, llvm::Value *dst)
2544{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002545 const llvm::Type * SrcTy = src->getType();
2546 if (!isa<llvm::PointerType>(SrcTy)) {
2547 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2548 assert(Size <= 8 && "does not support size > 8");
2549 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2550 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002551 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2552 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002553 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2554 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattner96508e12009-04-17 22:12:36 +00002555 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002556 src, dst, "weakassign");
2557 return;
2558}
2559
Fariborz Jahanian58626502008-11-19 00:59:10 +00002560/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
2561/// objc_assign_global (id src, id *dst)
2562///
2563void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
2564 llvm::Value *src, llvm::Value *dst)
2565{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002566 const llvm::Type * SrcTy = src->getType();
2567 if (!isa<llvm::PointerType>(SrcTy)) {
2568 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2569 assert(Size <= 8 && "does not support size > 8");
2570 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2571 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002572 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2573 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002574 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2575 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002576 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignGlobalFn(),
Fariborz Jahanian58626502008-11-19 00:59:10 +00002577 src, dst, "globalassign");
2578 return;
2579}
2580
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002581/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
2582/// objc_assign_ivar (id src, id *dst)
2583///
2584void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
2585 llvm::Value *src, llvm::Value *dst)
2586{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002587 const llvm::Type * SrcTy = src->getType();
2588 if (!isa<llvm::PointerType>(SrcTy)) {
2589 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2590 assert(Size <= 8 && "does not support size > 8");
2591 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2592 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002593 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2594 }
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002595 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2596 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002597 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignIvarFn(),
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002598 src, dst, "assignivar");
2599 return;
2600}
2601
Fariborz Jahanian58626502008-11-19 00:59:10 +00002602/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
2603/// objc_assign_strongCast (id src, id *dst)
2604///
2605void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
2606 llvm::Value *src, llvm::Value *dst)
2607{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002608 const llvm::Type * SrcTy = src->getType();
2609 if (!isa<llvm::PointerType>(SrcTy)) {
2610 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2611 assert(Size <= 8 && "does not support size > 8");
2612 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2613 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002614 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2615 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002616 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2617 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002618 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignStrongCastFn(),
Fariborz Jahanian58626502008-11-19 00:59:10 +00002619 src, dst, "weakassign");
2620 return;
2621}
2622
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002623/// EmitObjCValueForIvar - Code Gen for ivar reference.
2624///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002625LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
2626 QualType ObjectTy,
2627 llvm::Value *BaseValue,
2628 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002629 unsigned CVRQualifiers) {
Daniel Dunbar525c9b72009-04-21 01:19:28 +00002630 const ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
2631 const FieldDecl *Field = ID->lookupFieldDeclForIvar(CGM.getContext(), Ivar);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002632 if (Ivar->isBitField())
2633 return CGF.EmitLValueForBitfield(BaseValue, const_cast<FieldDecl *>(Field),
2634 CVRQualifiers);
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002635 // TODO: Add a special case for isa (index 0)
2636 unsigned Index = CGM.getTypes().getLLVMFieldNo(Field);
2637 llvm::Value *V = CGF.Builder.CreateStructGEP(BaseValue, Index, "tmp");
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002638 LValue LV = LValue::MakeAddr(V,
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00002639 Ivar->getType().getCVRQualifiers()|CVRQualifiers,
2640 CGM.getContext().getObjCGCAttrKind(Ivar->getType()));
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002641 LValue::SetObjCIvar(LV, true);
2642 return LV;
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002643}
2644
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002645llvm::Value *CGObjCMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
2646 ObjCInterfaceDecl *Interface,
2647 const ObjCIvarDecl *Ivar) {
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002648 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(Interface);
Daniel Dunbar60952f92009-04-20 00:37:55 +00002649 const FieldDecl *Field =
2650 Interface->lookupFieldDeclForIvar(CGM.getContext(), Ivar);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00002651 uint64_t Offset = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002652 return llvm::ConstantInt::get(
2653 CGM.getTypes().ConvertType(CGM.getContext().LongTy),
2654 Offset);
2655}
2656
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002657/* *** Private Interface *** */
2658
2659/// EmitImageInfo - Emit the image info marker used to encode some module
2660/// level information.
2661///
2662/// See: <rdr://4810609&4810587&4810587>
2663/// struct IMAGE_INFO {
2664/// unsigned version;
2665/// unsigned flags;
2666/// };
2667enum ImageInfoFlags {
Daniel Dunbarc7c6dc02009-04-20 07:11:47 +00002668 eImageInfo_FixAndContinue = (1 << 0), // FIXME: Not sure what
2669 // this implies.
2670 eImageInfo_GarbageCollected = (1 << 1),
2671 eImageInfo_GCOnly = (1 << 2),
2672 eImageInfo_OptimizedByDyld = (1 << 3), // FIXME: When is this set.
2673
2674 // A flag indicating that the module has no instances of an
2675 // @synthesize of a superclass variable. <rdar://problem/6803242>
2676 eImageInfo_CorrectedSynthesize = (1 << 4)
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002677};
2678
2679void CGObjCMac::EmitImageInfo() {
2680 unsigned version = 0; // Version is unused?
2681 unsigned flags = 0;
2682
2683 // FIXME: Fix and continue?
2684 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
2685 flags |= eImageInfo_GarbageCollected;
2686 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
2687 flags |= eImageInfo_GCOnly;
Daniel Dunbarc7c6dc02009-04-20 07:11:47 +00002688
2689 // We never allow @synthesize of a superclass property.
2690 flags |= eImageInfo_CorrectedSynthesize;
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002691
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002692 // Emitted as int[2];
2693 llvm::Constant *values[2] = {
2694 llvm::ConstantInt::get(llvm::Type::Int32Ty, version),
2695 llvm::ConstantInt::get(llvm::Type::Int32Ty, flags)
2696 };
2697 llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002698
2699 const char *Section;
2700 if (ObjCABI == 1)
2701 Section = "__OBJC, __image_info,regular";
2702 else
2703 Section = "__DATA, __objc_imageinfo, regular, no_dead_strip";
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002704 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002705 CreateMetadataVar("\01L_OBJC_IMAGE_INFO",
2706 llvm::ConstantArray::get(AT, values, 2),
2707 Section,
2708 0,
2709 true);
2710 GV->setConstant(true);
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002711}
2712
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002713
2714// struct objc_module {
2715// unsigned long version;
2716// unsigned long size;
2717// const char *name;
2718// Symtab symtab;
2719// };
2720
2721// FIXME: Get from somewhere
2722static const int ModuleVersion = 7;
2723
2724void CGObjCMac::EmitModuleInfo() {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00002725 uint64_t Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ModuleTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002726
2727 std::vector<llvm::Constant*> Values(4);
2728 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
2729 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002730 // This used to be the filename, now it is unused. <rdr://4327263>
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002731 Values[2] = GetClassName(&CGM.getContext().Idents.get(""));
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002732 Values[3] = EmitModuleSymbols();
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002733 CreateMetadataVar("\01L_OBJC_MODULES",
2734 llvm::ConstantStruct::get(ObjCTypes.ModuleTy, Values),
2735 "__OBJC,__module_info,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00002736 4, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002737}
2738
2739llvm::Constant *CGObjCMac::EmitModuleSymbols() {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002740 unsigned NumClasses = DefinedClasses.size();
2741 unsigned NumCategories = DefinedCategories.size();
2742
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002743 // Return null if no symbols were defined.
2744 if (!NumClasses && !NumCategories)
2745 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
2746
2747 std::vector<llvm::Constant*> Values(5);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002748 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2749 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
2750 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
2751 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
2752
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002753 // The runtime expects exactly the list of defined classes followed
2754 // by the list of defined categories, in a single array.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002755 std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002756 for (unsigned i=0; i<NumClasses; i++)
2757 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
2758 ObjCTypes.Int8PtrTy);
2759 for (unsigned i=0; i<NumCategories; i++)
2760 Symbols[NumClasses + i] =
2761 llvm::ConstantExpr::getBitCast(DefinedCategories[i],
2762 ObjCTypes.Int8PtrTy);
2763
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002764 Values[4] =
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002765 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002766 NumClasses + NumCategories),
2767 Symbols);
2768
2769 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2770
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002771 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002772 CreateMetadataVar("\01L_OBJC_SYMBOLS", Init,
2773 "__OBJC,__symbols,regular,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002774 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002775 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
2776}
2777
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002778llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002779 const ObjCInterfaceDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002780 LazySymbols.insert(ID->getIdentifier());
2781
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002782 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
2783
2784 if (!Entry) {
2785 llvm::Constant *Casted =
2786 llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()),
2787 ObjCTypes.ClassPtrTy);
2788 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002789 CreateMetadataVar("\01L_OBJC_CLASS_REFERENCES_", Casted,
2790 "__OBJC,__cls_refs,literal_pointers,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002791 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002792 }
2793
2794 return Builder.CreateLoad(Entry, false, "tmp");
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002795}
2796
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002797llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002798 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
2799
2800 if (!Entry) {
2801 llvm::Constant *Casted =
2802 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
2803 ObjCTypes.SelectorPtrTy);
2804 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002805 CreateMetadataVar("\01L_OBJC_SELECTOR_REFERENCES_", Casted,
2806 "__OBJC,__message_refs,literal_pointers,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002807 4, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002808 }
2809
2810 return Builder.CreateLoad(Entry, false, "tmp");
2811}
2812
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00002813llvm::Constant *CGObjCCommonMac::GetClassName(IdentifierInfo *Ident) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002814 llvm::GlobalVariable *&Entry = ClassNames[Ident];
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002815
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002816 if (!Entry)
2817 Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
2818 llvm::ConstantArray::get(Ident->getName()),
2819 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00002820 1, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002821
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002822 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002823}
2824
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002825/// GetInterfaceDeclStructLayout - Get layout for ivars of given
2826/// interface declaration.
2827const llvm::StructLayout *CGObjCCommonMac::GetInterfaceDeclStructLayout(
2828 const ObjCInterfaceDecl *OID) const {
Daniel Dunbar24c89912009-04-21 21:41:56 +00002829 assert(!OID->isForwardDecl() && "Invalid interface decl!");
Daniel Dunbar6c1aac82009-04-20 20:18:54 +00002830 QualType T =
2831 CGM.getContext().getObjCInterfaceType(const_cast<ObjCInterfaceDecl*>(OID));
2832 const llvm::StructType *InterfaceTy =
2833 cast<llvm::StructType>(CGM.getTypes().ConvertType(T));
2834 return CGM.getTargetData().getStructLayout(InterfaceTy);
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002835}
2836
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00002837/// GetIvarLayoutName - Returns a unique constant for the given
2838/// ivar layout bitmap.
2839llvm::Constant *CGObjCCommonMac::GetIvarLayoutName(IdentifierInfo *Ident,
2840 const ObjCCommonTypesHelper &ObjCTypes) {
2841 return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2842}
2843
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002844void CGObjCCommonMac::BuildAggrIvarLayout(const ObjCInterfaceDecl *OI,
2845 const llvm::StructLayout *Layout,
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002846 const RecordDecl *RD,
Chris Lattnerf1690852009-03-31 08:48:01 +00002847 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002848 unsigned int BytePos, bool ForStrongLayout,
2849 int &Index, int &SkIndex, bool &HasUnion) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002850 bool IsUnion = (RD && RD->isUnion());
2851 uint64_t MaxUnionIvarSize = 0;
2852 uint64_t MaxSkippedUnionIvarSize = 0;
2853 FieldDecl *MaxField = 0;
2854 FieldDecl *MaxSkippedField = 0;
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002855 FieldDecl *LastFieldBitfield = 0;
2856
Chris Lattnerf1690852009-03-31 08:48:01 +00002857 unsigned base = 0;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002858 if (RecFields.empty())
2859 return;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002860 if (IsUnion)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002861 base = BytePos + GetFieldBaseOffset(OI, Layout, RecFields[0]);
Chris Lattnerf1690852009-03-31 08:48:01 +00002862 unsigned WordSizeInBits = CGM.getContext().Target.getPointerWidth(0);
2863 unsigned ByteSizeInBits = CGM.getContext().Target.getCharWidth();
2864
2865 llvm::SmallVector<FieldDecl*, 16> TmpRecFields;
2866
2867 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002868 FieldDecl *Field = RecFields[i];
2869 // Skip over unnamed or bitfields
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002870 if (!Field->getIdentifier() || Field->isBitField()) {
2871 LastFieldBitfield = Field;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002872 continue;
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002873 }
2874 LastFieldBitfield = 0;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002875 QualType FQT = Field->getType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002876 if (FQT->isRecordType() || FQT->isUnionType()) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002877 if (FQT->isUnionType())
2878 HasUnion = true;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002879 else
2880 assert(FQT->isRecordType() &&
2881 "only union/record is supported for ivar layout bitmap");
2882
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002883 const RecordType *RT = FQT->getAsRecordType();
2884 const RecordDecl *RD = RT->getDecl();
Daniel Dunbarb02532a2009-04-19 23:41:48 +00002885 // FIXME - Find a more efficient way of passing records down.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002886 TmpRecFields.append(RD->field_begin(CGM.getContext()),
2887 RD->field_end(CGM.getContext()));
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00002888 const llvm::Type *Ty = CGM.getTypes().ConvertType(FQT);
2889 const llvm::StructLayout *RecLayout =
2890 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(Ty));
2891
2892 BuildAggrIvarLayout(0, RecLayout, RD, TmpRecFields,
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002893 BytePos + GetFieldBaseOffset(OI, Layout, Field),
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002894 ForStrongLayout, Index, SkIndex,
2895 HasUnion);
Chris Lattnerf1690852009-03-31 08:48:01 +00002896 TmpRecFields.clear();
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002897 continue;
2898 }
Chris Lattnerf1690852009-03-31 08:48:01 +00002899
2900 if (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002901 const ConstantArrayType *CArray =
2902 dyn_cast_or_null<ConstantArrayType>(Array);
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002903 uint64_t ElCount = CArray->getSize().getZExtValue();
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002904 assert(CArray && "only array with know element size is supported");
2905 FQT = CArray->getElementType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002906 while (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
2907 const ConstantArrayType *CArray =
2908 dyn_cast_or_null<ConstantArrayType>(Array);
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002909 ElCount *= CArray->getSize().getZExtValue();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002910 FQT = CArray->getElementType();
2911 }
2912
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002913 assert(!FQT->isUnionType() &&
2914 "layout for array of unions not supported");
2915 if (FQT->isRecordType()) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002916 int OldIndex = Index;
2917 int OldSkIndex = SkIndex;
2918
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002919 // FIXME - Use a common routine with the above!
2920 const RecordType *RT = FQT->getAsRecordType();
2921 const RecordDecl *RD = RT->getDecl();
2922 // FIXME - Find a more efficiant way of passing records down.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002923 TmpRecFields.append(RD->field_begin(CGM.getContext()),
2924 RD->field_end(CGM.getContext()));
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00002925 const llvm::Type *Ty = CGM.getTypes().ConvertType(FQT);
2926 const llvm::StructLayout *RecLayout =
2927 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(Ty));
Chris Lattnerf1690852009-03-31 08:48:01 +00002928
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00002929 BuildAggrIvarLayout(0, RecLayout, RD,
Chris Lattnerf1690852009-03-31 08:48:01 +00002930 TmpRecFields,
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002931 BytePos + GetFieldBaseOffset(OI, Layout, Field),
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002932 ForStrongLayout, Index, SkIndex,
2933 HasUnion);
Chris Lattnerf1690852009-03-31 08:48:01 +00002934 TmpRecFields.clear();
2935
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002936 // Replicate layout information for each array element. Note that
2937 // one element is already done.
2938 uint64_t ElIx = 1;
2939 for (int FirstIndex = Index, FirstSkIndex = SkIndex;
2940 ElIx < ElCount; ElIx++) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002941 uint64_t Size = CGM.getContext().getTypeSize(RT)/ByteSizeInBits;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002942 for (int i = OldIndex+1; i <= FirstIndex; ++i)
2943 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002944 GC_IVAR gcivar;
2945 gcivar.ivar_bytepos = IvarsInfo[i].ivar_bytepos + Size*ElIx;
2946 gcivar.ivar_size = IvarsInfo[i].ivar_size;
2947 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002948 }
2949
Chris Lattnerf1690852009-03-31 08:48:01 +00002950 for (int i = OldSkIndex+1; i <= FirstSkIndex; ++i) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002951 GC_IVAR skivar;
2952 skivar.ivar_bytepos = SkipIvars[i].ivar_bytepos + Size*ElIx;
2953 skivar.ivar_size = SkipIvars[i].ivar_size;
2954 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002955 }
2956 }
2957 continue;
2958 }
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002959 }
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002960 // At this point, we are done with Record/Union and array there of.
2961 // For other arrays we are down to its element type.
2962 QualType::GCAttrTypes GCAttr = QualType::GCNone;
2963 do {
2964 if (FQT.isObjCGCStrong() || FQT.isObjCGCWeak()) {
2965 GCAttr = FQT.isObjCGCStrong() ? QualType::Strong : QualType::Weak;
2966 break;
2967 }
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002968 else if (CGM.getContext().isObjCObjectPointerType(FQT)) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002969 GCAttr = QualType::Strong;
2970 break;
2971 }
2972 else if (const PointerType *PT = FQT->getAsPointerType()) {
2973 FQT = PT->getPointeeType();
2974 }
2975 else {
2976 break;
2977 }
2978 } while (true);
Chris Lattnerf1690852009-03-31 08:48:01 +00002979
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002980 if ((ForStrongLayout && GCAttr == QualType::Strong)
2981 || (!ForStrongLayout && GCAttr == QualType::Weak)) {
2982 if (IsUnion)
2983 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002984 uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType())
2985 / WordSizeInBits;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002986 if (UnionIvarSize > MaxUnionIvarSize)
2987 {
2988 MaxUnionIvarSize = UnionIvarSize;
2989 MaxField = Field;
2990 }
2991 }
2992 else
2993 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002994 GC_IVAR gcivar;
2995 gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field);
2996 gcivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) /
2997 WordSizeInBits;
2998 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002999 }
3000 }
3001 else if ((ForStrongLayout &&
3002 (GCAttr == QualType::GCNone || GCAttr == QualType::Weak))
3003 || (!ForStrongLayout && GCAttr != QualType::Weak)) {
3004 if (IsUnion)
3005 {
3006 uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType());
3007 if (UnionIvarSize > MaxSkippedUnionIvarSize)
3008 {
3009 MaxSkippedUnionIvarSize = UnionIvarSize;
3010 MaxSkippedField = Field;
3011 }
3012 }
3013 else
3014 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003015 GC_IVAR skivar;
3016 skivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field);
3017 skivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) /
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003018 ByteSizeInBits;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003019 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003020 }
3021 }
3022 }
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003023 if (LastFieldBitfield) {
3024 // Last field was a bitfield. Must update skip info.
3025 GC_IVAR skivar;
3026 skivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout,
3027 LastFieldBitfield);
3028 Expr *BitWidth = LastFieldBitfield->getBitWidth();
3029 uint64_t BitFieldSize =
3030 BitWidth->getIntegerConstantExprValue(CGM.getContext()).getZExtValue();
3031 skivar.ivar_size = (BitFieldSize / ByteSizeInBits)
3032 + ((BitFieldSize % ByteSizeInBits) != 0);
3033 SkipIvars.push_back(skivar); ++SkIndex;
3034 }
3035
Chris Lattnerf1690852009-03-31 08:48:01 +00003036 if (MaxField) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003037 GC_IVAR gcivar;
3038 gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, MaxField);
3039 gcivar.ivar_size = MaxUnionIvarSize;
3040 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003041 }
Chris Lattnerf1690852009-03-31 08:48:01 +00003042
3043 if (MaxSkippedField) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003044 GC_IVAR skivar;
3045 skivar.ivar_bytepos = BytePos +
3046 GetFieldBaseOffset(OI, Layout, MaxSkippedField);
3047 skivar.ivar_size = MaxSkippedUnionIvarSize;
3048 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003049 }
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003050}
3051
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003052static int
Chris Lattnerf1690852009-03-31 08:48:01 +00003053IvarBytePosCompare(const void *a, const void *b)
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003054{
3055 unsigned int sa = ((CGObjCCommonMac::GC_IVAR *)a)->ivar_bytepos;
3056 unsigned int sb = ((CGObjCCommonMac::GC_IVAR *)b)->ivar_bytepos;
3057
3058 if (sa < sb)
3059 return -1;
3060 if (sa > sb)
3061 return 1;
3062 return 0;
3063}
3064
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003065/// BuildIvarLayout - Builds ivar layout bitmap for the class
3066/// implementation for the __strong or __weak case.
3067/// The layout map displays which words in ivar list must be skipped
3068/// and which must be scanned by GC (see below). String is built of bytes.
3069/// Each byte is divided up in two nibbles (4-bit each). Left nibble is count
3070/// of words to skip and right nibble is count of words to scan. So, each
3071/// nibble represents up to 15 workds to skip or scan. Skipping the rest is
3072/// represented by a 0x00 byte which also ends the string.
3073/// 1. when ForStrongLayout is true, following ivars are scanned:
3074/// - id, Class
3075/// - object *
3076/// - __strong anything
3077///
3078/// 2. When ForStrongLayout is false, following ivars are scanned:
3079/// - __weak anything
3080///
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003081llvm::Constant *CGObjCCommonMac::BuildIvarLayout(
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003082 const ObjCImplementationDecl *OMD,
3083 bool ForStrongLayout) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003084 int Index = -1;
3085 int SkIndex = -1;
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003086 bool hasUnion = false;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003087 int SkipScan;
3088 unsigned int WordsToScan, WordsToSkip;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003089 const llvm::Type *PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3090 if (CGM.getLangOptions().getGCMode() == LangOptions::NonGC)
3091 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003092
Chris Lattnerf1690852009-03-31 08:48:01 +00003093 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003094 const ObjCInterfaceDecl *OI = OMD->getClassInterface();
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003095 CGM.getContext().CollectObjCIvars(OI, RecFields);
3096 if (RecFields.empty())
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003097 return llvm::Constant::getNullValue(PtrTy);
Chris Lattnerf1690852009-03-31 08:48:01 +00003098
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003099 SkipIvars.clear();
3100 IvarsInfo.clear();
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00003101
3102 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OI);
Chris Lattnerf1690852009-03-31 08:48:01 +00003103 BuildAggrIvarLayout(OI, Layout, 0, RecFields, 0, ForStrongLayout,
3104 Index, SkIndex, hasUnion);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003105 if (Index == -1)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003106 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003107
3108 // Sort on byte position in case we encounterred a union nested in
3109 // the ivar list.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003110 if (hasUnion && !IvarsInfo.empty())
3111 qsort(&IvarsInfo[0], Index+1, sizeof(GC_IVAR), IvarBytePosCompare);
3112 if (hasUnion && !SkipIvars.empty())
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003113 qsort(&SkipIvars[0], Index+1, sizeof(GC_IVAR), IvarBytePosCompare);
3114
3115 // Build the string of skip/scan nibbles
3116 SkipScan = -1;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003117 SkipScanIvars.clear();
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003118 unsigned int WordSize =
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003119 CGM.getTypes().getTargetData().getTypePaddedSize(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003120 if (IvarsInfo[0].ivar_bytepos == 0) {
3121 WordsToSkip = 0;
3122 WordsToScan = IvarsInfo[0].ivar_size;
3123 }
3124 else {
3125 WordsToSkip = IvarsInfo[0].ivar_bytepos/WordSize;
3126 WordsToScan = IvarsInfo[0].ivar_size;
3127 }
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003128 for (unsigned int i=1, Last=IvarsInfo.size(); i != Last; i++)
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003129 {
3130 unsigned int TailPrevGCObjC =
3131 IvarsInfo[i-1].ivar_bytepos + IvarsInfo[i-1].ivar_size * WordSize;
3132 if (IvarsInfo[i].ivar_bytepos == TailPrevGCObjC)
3133 {
3134 // consecutive 'scanned' object pointers.
3135 WordsToScan += IvarsInfo[i].ivar_size;
3136 }
3137 else
3138 {
3139 // Skip over 'gc'able object pointer which lay over each other.
3140 if (TailPrevGCObjC > IvarsInfo[i].ivar_bytepos)
3141 continue;
3142 // Must skip over 1 or more words. We save current skip/scan values
3143 // and start a new pair.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003144 SKIP_SCAN SkScan;
3145 SkScan.skip = WordsToSkip;
3146 SkScan.scan = WordsToScan;
3147 SkipScanIvars.push_back(SkScan); ++SkipScan;
3148
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003149 // Skip the hole.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003150 SkScan.skip = (IvarsInfo[i].ivar_bytepos - TailPrevGCObjC) / WordSize;
3151 SkScan.scan = 0;
3152 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003153 WordsToSkip = 0;
3154 WordsToScan = IvarsInfo[i].ivar_size;
3155 }
3156 }
3157 if (WordsToScan > 0)
3158 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003159 SKIP_SCAN SkScan;
3160 SkScan.skip = WordsToSkip;
3161 SkScan.scan = WordsToScan;
3162 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003163 }
3164
3165 bool BytesSkipped = false;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003166 if (!SkipIvars.empty())
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003167 {
3168 int LastByteSkipped =
3169 SkipIvars[SkIndex].ivar_bytepos + SkipIvars[SkIndex].ivar_size;
3170 int LastByteScanned =
3171 IvarsInfo[Index].ivar_bytepos + IvarsInfo[Index].ivar_size * WordSize;
3172 BytesSkipped = (LastByteSkipped > LastByteScanned);
3173 // Compute number of bytes to skip at the tail end of the last ivar scanned.
3174 if (BytesSkipped)
3175 {
3176 unsigned int TotalWords = (LastByteSkipped + (WordSize -1)) / WordSize;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003177 SKIP_SCAN SkScan;
3178 SkScan.skip = TotalWords - (LastByteScanned/WordSize);
3179 SkScan.scan = 0;
3180 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003181 }
3182 }
3183 // Mini optimization of nibbles such that an 0xM0 followed by 0x0N is produced
3184 // as 0xMN.
3185 for (int i = 0; i <= SkipScan; i++)
3186 {
3187 if ((i < SkipScan) && SkipScanIvars[i].skip && SkipScanIvars[i].scan == 0
3188 && SkipScanIvars[i+1].skip == 0 && SkipScanIvars[i+1].scan) {
3189 // 0xM0 followed by 0x0N detected.
3190 SkipScanIvars[i].scan = SkipScanIvars[i+1].scan;
3191 for (int j = i+1; j < SkipScan; j++)
3192 SkipScanIvars[j] = SkipScanIvars[j+1];
3193 --SkipScan;
3194 }
3195 }
3196
3197 // Generate the string.
3198 std::string BitMap;
3199 for (int i = 0; i <= SkipScan; i++)
3200 {
3201 unsigned char byte;
3202 unsigned int skip_small = SkipScanIvars[i].skip % 0xf;
3203 unsigned int scan_small = SkipScanIvars[i].scan % 0xf;
3204 unsigned int skip_big = SkipScanIvars[i].skip / 0xf;
3205 unsigned int scan_big = SkipScanIvars[i].scan / 0xf;
3206
3207 if (skip_small > 0 || skip_big > 0)
3208 BytesSkipped = true;
3209 // first skip big.
3210 for (unsigned int ix = 0; ix < skip_big; ix++)
3211 BitMap += (unsigned char)(0xf0);
3212
3213 // next (skip small, scan)
3214 if (skip_small)
3215 {
3216 byte = skip_small << 4;
3217 if (scan_big > 0)
3218 {
3219 byte |= 0xf;
3220 --scan_big;
3221 }
3222 else if (scan_small)
3223 {
3224 byte |= scan_small;
3225 scan_small = 0;
3226 }
3227 BitMap += byte;
3228 }
3229 // next scan big
3230 for (unsigned int ix = 0; ix < scan_big; ix++)
3231 BitMap += (unsigned char)(0x0f);
3232 // last scan small
3233 if (scan_small)
3234 {
3235 byte = scan_small;
3236 BitMap += byte;
3237 }
3238 }
3239 // null terminate string.
Fariborz Jahanian667423a2009-03-25 22:36:49 +00003240 unsigned char zero = 0;
3241 BitMap += zero;
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00003242
3243 if (CGM.getLangOptions().ObjCGCBitmapPrint) {
3244 printf("\n%s ivar layout for class '%s': ",
3245 ForStrongLayout ? "strong" : "weak",
3246 OMD->getClassInterface()->getNameAsCString());
3247 const unsigned char *s = (unsigned char*)BitMap.c_str();
3248 for (unsigned i = 0; i < BitMap.size(); i++)
3249 if (!(s[i] & 0xf0))
3250 printf("0x0%x%s", s[i], s[i] != 0 ? ", " : "");
3251 else
3252 printf("0x%x%s", s[i], s[i] != 0 ? ", " : "");
3253 printf("\n");
3254 }
3255
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003256 // if ivar_layout bitmap is all 1 bits (nothing skipped) then use NULL as
3257 // final layout.
3258 if (ForStrongLayout && !BytesSkipped)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003259 return llvm::Constant::getNullValue(PtrTy);
3260 llvm::GlobalVariable * Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
3261 llvm::ConstantArray::get(BitMap.c_str()),
3262 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003263 1, true);
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00003264 return getConstantGEP(Entry, 0, 0);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003265}
3266
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003267llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003268 llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
3269
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003270 // FIXME: Avoid std::string copying.
3271 if (!Entry)
3272 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_NAME_",
3273 llvm::ConstantArray::get(Sel.getAsString()),
3274 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003275 1, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003276
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003277 return getConstantGEP(Entry, 0, 0);
3278}
3279
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003280// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003281llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003282 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
3283}
3284
3285// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003286llvm::Constant *CGObjCCommonMac::GetMethodVarName(const std::string &Name) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003287 return GetMethodVarName(&CGM.getContext().Idents.get(Name));
3288}
3289
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00003290llvm::Constant *CGObjCCommonMac::GetMethodVarType(const FieldDecl *Field) {
Devang Patel7794bb82009-03-04 18:21:39 +00003291 std::string TypeStr;
3292 CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
3293
3294 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003295
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003296 if (!Entry)
3297 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3298 llvm::ConstantArray::get(TypeStr),
3299 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003300 1, true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003301
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003302 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003303}
3304
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003305llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003306 std::string TypeStr;
Daniel Dunbarc45ef602008-08-26 21:51:14 +00003307 CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D),
3308 TypeStr);
Devang Patel7794bb82009-03-04 18:21:39 +00003309
3310 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
3311
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003312 if (!Entry)
3313 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3314 llvm::ConstantArray::get(TypeStr),
3315 "__TEXT,__cstring,cstring_literals",
3316 1, true);
Devang Patel7794bb82009-03-04 18:21:39 +00003317
3318 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003319}
3320
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003321// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003322llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003323 llvm::GlobalVariable *&Entry = PropertyNames[Ident];
3324
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003325 if (!Entry)
3326 Entry = CreateMetadataVar("\01L_OBJC_PROP_NAME_ATTR_",
3327 llvm::ConstantArray::get(Ident->getName()),
3328 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003329 1, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003330
3331 return getConstantGEP(Entry, 0, 0);
3332}
3333
3334// FIXME: Merge into a single cstring creation function.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003335// FIXME: This Decl should be more precise.
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003336llvm::Constant *
3337 CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
3338 const Decl *Container) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003339 std::string TypeStr;
3340 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003341 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
3342}
3343
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003344void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D,
3345 const ObjCContainerDecl *CD,
3346 std::string &NameOut) {
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00003347 NameOut = '\01';
3348 NameOut += (D->isInstanceMethod() ? '-' : '+');
Chris Lattner077bf5e2008-11-24 03:33:13 +00003349 NameOut += '[';
Fariborz Jahanian679a5022009-01-10 21:06:09 +00003350 assert (CD && "Missing container decl in GetNameForMethod");
3351 NameOut += CD->getNameAsString();
Fariborz Jahanian1e9aef32009-04-16 18:34:20 +00003352 if (const ObjCCategoryImplDecl *CID =
3353 dyn_cast<ObjCCategoryImplDecl>(D->getDeclContext())) {
3354 NameOut += '(';
3355 NameOut += CID->getNameAsString();
3356 NameOut+= ')';
3357 }
Chris Lattner077bf5e2008-11-24 03:33:13 +00003358 NameOut += ' ';
3359 NameOut += D->getSelector().getAsString();
3360 NameOut += ']';
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00003361}
3362
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003363void CGObjCMac::FinishModule() {
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003364 EmitModuleInfo();
3365
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003366 // Emit the dummy bodies for any protocols which were referenced but
3367 // never defined.
3368 for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
3369 i = Protocols.begin(), e = Protocols.end(); i != e; ++i) {
3370 if (i->second->hasInitializer())
3371 continue;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003372
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003373 std::vector<llvm::Constant*> Values(5);
3374 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
3375 Values[1] = GetClassName(i->first);
3376 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
3377 Values[3] = Values[4] =
3378 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
3379 i->second->setLinkage(llvm::GlobalValue::InternalLinkage);
3380 i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
3381 Values));
3382 }
3383
3384 std::vector<llvm::Constant*> Used;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003385 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003386 e = UsedGlobals.end(); i != e; ++i) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003387 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003388 }
3389
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003390 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003391 llvm::GlobalValue *GV =
3392 new llvm::GlobalVariable(AT, false,
3393 llvm::GlobalValue::AppendingLinkage,
3394 llvm::ConstantArray::get(AT, Used),
3395 "llvm.used",
3396 &CGM.getModule());
3397
3398 GV->setSection("llvm.metadata");
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003399
3400 // Add assembler directives to add lazy undefined symbol references
3401 // for classes which are referenced but not defined. This is
3402 // important for correct linker interaction.
3403
3404 // FIXME: Uh, this isn't particularly portable.
3405 std::stringstream s;
Anders Carlsson565c99f2008-12-10 02:21:04 +00003406
3407 if (!CGM.getModule().getModuleInlineAsm().empty())
3408 s << "\n";
3409
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003410 for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(),
3411 e = LazySymbols.end(); i != e; ++i) {
3412 s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n";
3413 }
3414 for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(),
3415 e = DefinedSymbols.end(); i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003416 s << "\t.objc_class_name_" << (*i)->getName() << "=0\n"
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003417 << "\t.globl .objc_class_name_" << (*i)->getName() << "\n";
3418 }
Anders Carlsson565c99f2008-12-10 02:21:04 +00003419
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003420 CGM.getModule().appendModuleInlineAsm(s.str());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003421}
3422
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003423CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003424 : CGObjCCommonMac(cgm),
3425 ObjCTypes(cgm)
3426{
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003427 ObjCEmptyCacheVar = ObjCEmptyVtableVar = NULL;
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003428 ObjCABI = 2;
3429}
3430
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003431/* *** */
3432
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003433ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm)
3434: CGM(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003435{
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003436 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3437 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003438
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003439 ShortTy = Types.ConvertType(Ctx.ShortTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003440 IntTy = Types.ConvertType(Ctx.IntTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003441 LongTy = Types.ConvertType(Ctx.LongTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00003442 LongLongTy = Types.ConvertType(Ctx.LongLongTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003443 Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3444
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003445 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00003446 PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003447 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003448
3449 // FIXME: It would be nice to unify this with the opaque type, so
3450 // that the IR comes out a bit cleaner.
3451 const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
3452 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003453
3454 // I'm not sure I like this. The implicit coordination is a bit
3455 // gross. We should solve this in a reasonable fashion because this
3456 // is a pretty common task (match some runtime data structure with
3457 // an LLVM data structure).
3458
3459 // FIXME: This is leaked.
3460 // FIXME: Merge with rewriter code?
3461
3462 // struct _objc_super {
3463 // id self;
3464 // Class cls;
3465 // }
3466 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3467 SourceLocation(),
3468 &Ctx.Idents.get("_objc_super"));
Douglas Gregor6ab35242009-04-09 21:40:53 +00003469 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3470 Ctx.getObjCIdType(), 0, false));
3471 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3472 Ctx.getObjCClassType(), 0, false));
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003473 RD->completeDefinition(Ctx);
3474
3475 SuperCTy = Ctx.getTagDeclType(RD);
3476 SuperPtrCTy = Ctx.getPointerType(SuperCTy);
3477
3478 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003479 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
3480
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003481 // struct _prop_t {
3482 // char *name;
3483 // char *attributes;
3484 // }
Chris Lattner1c02f862009-04-22 02:53:24 +00003485 PropertyTy = llvm::StructType::get(Int8PtrTy, Int8PtrTy, NULL);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003486 CGM.getModule().addTypeName("struct._prop_t",
3487 PropertyTy);
3488
3489 // struct _prop_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003490 // uint32_t entsize; // sizeof(struct _prop_t)
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003491 // uint32_t count_of_properties;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003492 // struct _prop_t prop_list[count_of_properties];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003493 // }
3494 PropertyListTy = llvm::StructType::get(IntTy,
3495 IntTy,
3496 llvm::ArrayType::get(PropertyTy, 0),
3497 NULL);
3498 CGM.getModule().addTypeName("struct._prop_list_t",
3499 PropertyListTy);
3500 // struct _prop_list_t *
3501 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
3502
3503 // struct _objc_method {
3504 // SEL _cmd;
3505 // char *method_type;
3506 // char *_imp;
3507 // }
3508 MethodTy = llvm::StructType::get(SelectorPtrTy,
3509 Int8PtrTy,
3510 Int8PtrTy,
3511 NULL);
3512 CGM.getModule().addTypeName("struct._objc_method", MethodTy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003513
3514 // struct _objc_cache *
3515 CacheTy = llvm::OpaqueType::get();
3516 CGM.getModule().addTypeName("struct._objc_cache", CacheTy);
3517 CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003518}
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003519
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003520ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
3521 : ObjCCommonTypesHelper(cgm)
3522{
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003523 // struct _objc_method_description {
3524 // SEL name;
3525 // char *types;
3526 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003527 MethodDescriptionTy =
3528 llvm::StructType::get(SelectorPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003529 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003530 NULL);
3531 CGM.getModule().addTypeName("struct._objc_method_description",
3532 MethodDescriptionTy);
3533
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003534 // struct _objc_method_description_list {
3535 // int count;
3536 // struct _objc_method_description[1];
3537 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003538 MethodDescriptionListTy =
3539 llvm::StructType::get(IntTy,
3540 llvm::ArrayType::get(MethodDescriptionTy, 0),
3541 NULL);
3542 CGM.getModule().addTypeName("struct._objc_method_description_list",
3543 MethodDescriptionListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003544
3545 // struct _objc_method_description_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003546 MethodDescriptionListPtrTy =
3547 llvm::PointerType::getUnqual(MethodDescriptionListTy);
3548
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003549 // Protocol description structures
3550
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003551 // struct _objc_protocol_extension {
3552 // uint32_t size; // sizeof(struct _objc_protocol_extension)
3553 // struct _objc_method_description_list *optional_instance_methods;
3554 // struct _objc_method_description_list *optional_class_methods;
3555 // struct _objc_property_list *instance_properties;
3556 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003557 ProtocolExtensionTy =
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003558 llvm::StructType::get(IntTy,
3559 MethodDescriptionListPtrTy,
3560 MethodDescriptionListPtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003561 PropertyListPtrTy,
3562 NULL);
3563 CGM.getModule().addTypeName("struct._objc_protocol_extension",
3564 ProtocolExtensionTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003565
3566 // struct _objc_protocol_extension *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003567 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
3568
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003569 // Handle recursive construction of Protocol and ProtocolList types
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003570
3571 llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get();
3572 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3573
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003574 const llvm::Type *T =
3575 llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder),
3576 LongTy,
3577 llvm::ArrayType::get(ProtocolTyHolder, 0),
3578 NULL);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003579 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T);
3580
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003581 // struct _objc_protocol {
3582 // struct _objc_protocol_extension *isa;
3583 // char *protocol_name;
3584 // struct _objc_protocol **_objc_protocol_list;
3585 // struct _objc_method_description_list *instance_methods;
3586 // struct _objc_method_description_list *class_methods;
3587 // }
3588 T = llvm::StructType::get(ProtocolExtensionPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003589 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003590 llvm::PointerType::getUnqual(ProtocolListTyHolder),
3591 MethodDescriptionListPtrTy,
3592 MethodDescriptionListPtrTy,
3593 NULL);
3594 cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T);
3595
3596 ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get());
3597 CGM.getModule().addTypeName("struct._objc_protocol_list",
3598 ProtocolListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003599 // struct _objc_protocol_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003600 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
3601
3602 ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get());
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003603 CGM.getModule().addTypeName("struct._objc_protocol", ProtocolTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003604 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003605
3606 // Class description structures
3607
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003608 // struct _objc_ivar {
3609 // char *ivar_name;
3610 // char *ivar_type;
3611 // int ivar_offset;
3612 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003613 IvarTy = llvm::StructType::get(Int8PtrTy,
3614 Int8PtrTy,
3615 IntTy,
3616 NULL);
3617 CGM.getModule().addTypeName("struct._objc_ivar", IvarTy);
3618
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003619 // struct _objc_ivar_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003620 IvarListTy = llvm::OpaqueType::get();
3621 CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy);
3622 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
3623
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003624 // struct _objc_method_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003625 MethodListTy = llvm::OpaqueType::get();
3626 CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy);
3627 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
3628
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003629 // struct _objc_class_extension *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003630 ClassExtensionTy =
3631 llvm::StructType::get(IntTy,
3632 Int8PtrTy,
3633 PropertyListPtrTy,
3634 NULL);
3635 CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy);
3636 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
3637
3638 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3639
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003640 // struct _objc_class {
3641 // Class isa;
3642 // Class super_class;
3643 // char *name;
3644 // long version;
3645 // long info;
3646 // long instance_size;
3647 // struct _objc_ivar_list *ivars;
3648 // struct _objc_method_list *methods;
3649 // struct _objc_cache *cache;
3650 // struct _objc_protocol_list *protocols;
3651 // char *ivar_layout;
3652 // struct _objc_class_ext *ext;
3653 // };
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003654 T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3655 llvm::PointerType::getUnqual(ClassTyHolder),
3656 Int8PtrTy,
3657 LongTy,
3658 LongTy,
3659 LongTy,
3660 IvarListPtrTy,
3661 MethodListPtrTy,
3662 CachePtrTy,
3663 ProtocolListPtrTy,
3664 Int8PtrTy,
3665 ClassExtensionPtrTy,
3666 NULL);
3667 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T);
3668
3669 ClassTy = cast<llvm::StructType>(ClassTyHolder.get());
3670 CGM.getModule().addTypeName("struct._objc_class", ClassTy);
3671 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
3672
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003673 // struct _objc_category {
3674 // char *category_name;
3675 // char *class_name;
3676 // struct _objc_method_list *instance_method;
3677 // struct _objc_method_list *class_method;
3678 // uint32_t size; // sizeof(struct _objc_category)
3679 // struct _objc_property_list *instance_properties;// category's @property
3680 // }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003681 CategoryTy = llvm::StructType::get(Int8PtrTy,
3682 Int8PtrTy,
3683 MethodListPtrTy,
3684 MethodListPtrTy,
3685 ProtocolListPtrTy,
3686 IntTy,
3687 PropertyListPtrTy,
3688 NULL);
3689 CGM.getModule().addTypeName("struct._objc_category", CategoryTy);
3690
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003691 // Global metadata structures
3692
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003693 // struct _objc_symtab {
3694 // long sel_ref_cnt;
3695 // SEL *refs;
3696 // short cls_def_cnt;
3697 // short cat_def_cnt;
3698 // char *defs[cls_def_cnt + cat_def_cnt];
3699 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003700 SymtabTy = llvm::StructType::get(LongTy,
3701 SelectorPtrTy,
3702 ShortTy,
3703 ShortTy,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003704 llvm::ArrayType::get(Int8PtrTy, 0),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003705 NULL);
3706 CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy);
3707 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
3708
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003709 // struct _objc_module {
3710 // long version;
3711 // long size; // sizeof(struct _objc_module)
3712 // char *name;
3713 // struct _objc_symtab* symtab;
3714 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003715 ModuleTy =
3716 llvm::StructType::get(LongTy,
3717 LongTy,
3718 Int8PtrTy,
3719 SymtabPtrTy,
3720 NULL);
3721 CGM.getModule().addTypeName("struct._objc_module", ModuleTy);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003722
Anders Carlsson2abd89c2008-08-31 04:05:03 +00003723
Anders Carlsson124526b2008-09-09 10:10:21 +00003724 // FIXME: This is the size of the setjmp buffer and should be
3725 // target specific. 18 is what's used on 32-bit X86.
3726 uint64_t SetJmpBufferSize = 18;
3727
3728 // Exceptions
3729 const llvm::Type *StackPtrTy =
Daniel Dunbar10004912008-09-27 06:32:25 +00003730 llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4);
Anders Carlsson124526b2008-09-09 10:10:21 +00003731
3732 ExceptionDataTy =
3733 llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty,
3734 SetJmpBufferSize),
3735 StackPtrTy, NULL);
3736 CGM.getModule().addTypeName("struct._objc_exception_data",
3737 ExceptionDataTy);
3738
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003739}
3740
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003741ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003742: ObjCCommonTypesHelper(cgm)
3743{
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003744 // struct _method_list_t {
3745 // uint32_t entsize; // sizeof(struct _objc_method)
3746 // uint32_t method_count;
3747 // struct _objc_method method_list[method_count];
3748 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003749 MethodListnfABITy = llvm::StructType::get(IntTy,
3750 IntTy,
3751 llvm::ArrayType::get(MethodTy, 0),
3752 NULL);
3753 CGM.getModule().addTypeName("struct.__method_list_t",
3754 MethodListnfABITy);
3755 // struct method_list_t *
3756 MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003757
3758 // struct _protocol_t {
3759 // id isa; // NULL
3760 // const char * const protocol_name;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003761 // const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003762 // const struct method_list_t * const instance_methods;
3763 // const struct method_list_t * const class_methods;
3764 // const struct method_list_t *optionalInstanceMethods;
3765 // const struct method_list_t *optionalClassMethods;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003766 // const struct _prop_list_t * properties;
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003767 // const uint32_t size; // sizeof(struct _protocol_t)
3768 // const uint32_t flags; // = 0
3769 // }
3770
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003771 // Holder for struct _protocol_list_t *
3772 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3773
3774 ProtocolnfABITy = llvm::StructType::get(ObjectPtrTy,
3775 Int8PtrTy,
3776 llvm::PointerType::getUnqual(
3777 ProtocolListTyHolder),
3778 MethodListnfABIPtrTy,
3779 MethodListnfABIPtrTy,
3780 MethodListnfABIPtrTy,
3781 MethodListnfABIPtrTy,
3782 PropertyListPtrTy,
3783 IntTy,
3784 IntTy,
3785 NULL);
3786 CGM.getModule().addTypeName("struct._protocol_t",
3787 ProtocolnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003788
3789 // struct _protocol_t*
3790 ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003791
Fariborz Jahanianda320092009-01-29 19:24:30 +00003792 // struct _protocol_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003793 // long protocol_count; // Note, this is 32/64 bit
Daniel Dunbar948e2582009-02-15 07:36:20 +00003794 // struct _protocol_t *[protocol_count];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003795 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003796 ProtocolListnfABITy = llvm::StructType::get(LongTy,
3797 llvm::ArrayType::get(
Daniel Dunbar948e2582009-02-15 07:36:20 +00003798 ProtocolnfABIPtrTy, 0),
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003799 NULL);
3800 CGM.getModule().addTypeName("struct._objc_protocol_list",
3801 ProtocolListnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003802 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(
3803 ProtocolListnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003804
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003805 // struct _objc_protocol_list*
3806 ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003807
3808 // struct _ivar_t {
3809 // unsigned long int *offset; // pointer to ivar offset location
3810 // char *name;
3811 // char *type;
3812 // uint32_t alignment;
3813 // uint32_t size;
3814 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003815 IvarnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(LongTy),
3816 Int8PtrTy,
3817 Int8PtrTy,
3818 IntTy,
3819 IntTy,
3820 NULL);
3821 CGM.getModule().addTypeName("struct._ivar_t", IvarnfABITy);
3822
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003823 // struct _ivar_list_t {
3824 // uint32 entsize; // sizeof(struct _ivar_t)
3825 // uint32 count;
3826 // struct _iver_t list[count];
3827 // }
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003828 IvarListnfABITy = llvm::StructType::get(IntTy,
3829 IntTy,
3830 llvm::ArrayType::get(
3831 IvarnfABITy, 0),
3832 NULL);
3833 CGM.getModule().addTypeName("struct._ivar_list_t", IvarListnfABITy);
3834
3835 IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003836
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003837 // struct _class_ro_t {
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003838 // uint32_t const flags;
3839 // uint32_t const instanceStart;
3840 // uint32_t const instanceSize;
3841 // uint32_t const reserved; // only when building for 64bit targets
3842 // const uint8_t * const ivarLayout;
3843 // const char *const name;
3844 // const struct _method_list_t * const baseMethods;
3845 // const struct _objc_protocol_list *const baseProtocols;
3846 // const struct _ivar_list_t *const ivars;
3847 // const uint8_t * const weakIvarLayout;
3848 // const struct _prop_list_t * const properties;
3849 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003850
3851 // FIXME. Add 'reserved' field in 64bit abi mode!
3852 ClassRonfABITy = llvm::StructType::get(IntTy,
3853 IntTy,
3854 IntTy,
3855 Int8PtrTy,
3856 Int8PtrTy,
3857 MethodListnfABIPtrTy,
3858 ProtocolListnfABIPtrTy,
3859 IvarListnfABIPtrTy,
3860 Int8PtrTy,
3861 PropertyListPtrTy,
3862 NULL);
3863 CGM.getModule().addTypeName("struct._class_ro_t",
3864 ClassRonfABITy);
3865
3866 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
3867 std::vector<const llvm::Type*> Params;
3868 Params.push_back(ObjectPtrTy);
3869 Params.push_back(SelectorPtrTy);
3870 ImpnfABITy = llvm::PointerType::getUnqual(
3871 llvm::FunctionType::get(ObjectPtrTy, Params, false));
3872
3873 // struct _class_t {
3874 // struct _class_t *isa;
3875 // struct _class_t * const superclass;
3876 // void *cache;
3877 // IMP *vtable;
3878 // struct class_ro_t *ro;
3879 // }
3880
3881 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3882 ClassnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3883 llvm::PointerType::getUnqual(ClassTyHolder),
3884 CachePtrTy,
3885 llvm::PointerType::getUnqual(ImpnfABITy),
3886 llvm::PointerType::getUnqual(
3887 ClassRonfABITy),
3888 NULL);
3889 CGM.getModule().addTypeName("struct._class_t", ClassnfABITy);
3890
3891 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(
3892 ClassnfABITy);
3893
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003894 // LLVM for struct _class_t *
3895 ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy);
3896
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003897 // struct _category_t {
3898 // const char * const name;
3899 // struct _class_t *const cls;
3900 // const struct _method_list_t * const instance_methods;
3901 // const struct _method_list_t * const class_methods;
3902 // const struct _protocol_list_t * const protocols;
3903 // const struct _prop_list_t * const properties;
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003904 // }
3905 CategorynfABITy = llvm::StructType::get(Int8PtrTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003906 ClassnfABIPtrTy,
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003907 MethodListnfABIPtrTy,
3908 MethodListnfABIPtrTy,
3909 ProtocolListnfABIPtrTy,
3910 PropertyListPtrTy,
3911 NULL);
3912 CGM.getModule().addTypeName("struct._category_t", CategorynfABITy);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003913
3914 // New types for nonfragile abi messaging.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003915 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3916 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003917
3918 // MessageRefTy - LLVM for:
3919 // struct _message_ref_t {
3920 // IMP messenger;
3921 // SEL name;
3922 // };
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003923
3924 // First the clang type for struct _message_ref_t
3925 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3926 SourceLocation(),
3927 &Ctx.Idents.get("_message_ref_t"));
Douglas Gregor6ab35242009-04-09 21:40:53 +00003928 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3929 Ctx.VoidPtrTy, 0, false));
3930 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3931 Ctx.getObjCSelType(), 0, false));
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003932 RD->completeDefinition(Ctx);
3933
3934 MessageRefCTy = Ctx.getTagDeclType(RD);
3935 MessageRefCPtrTy = Ctx.getPointerType(MessageRefCTy);
3936 MessageRefTy = cast<llvm::StructType>(Types.ConvertType(MessageRefCTy));
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003937
3938 // MessageRefPtrTy - LLVM for struct _message_ref_t*
3939 MessageRefPtrTy = llvm::PointerType::getUnqual(MessageRefTy);
3940
3941 // SuperMessageRefTy - LLVM for:
3942 // struct _super_message_ref_t {
3943 // SUPER_IMP messenger;
3944 // SEL name;
3945 // };
3946 SuperMessageRefTy = llvm::StructType::get(ImpnfABITy,
3947 SelectorPtrTy,
3948 NULL);
3949 CGM.getModule().addTypeName("struct._super_message_ref_t", SuperMessageRefTy);
3950
3951 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
3952 SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy);
3953
Daniel Dunbare588b992009-03-01 04:46:24 +00003954
3955 // struct objc_typeinfo {
3956 // const void** vtable; // objc_ehtype_vtable + 2
3957 // const char* name; // c++ typeinfo string
3958 // Class cls;
3959 // };
3960 EHTypeTy = llvm::StructType::get(llvm::PointerType::getUnqual(Int8PtrTy),
3961 Int8PtrTy,
3962 ClassnfABIPtrTy,
3963 NULL);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00003964 CGM.getModule().addTypeName("struct._objc_typeinfo", EHTypeTy);
Daniel Dunbare588b992009-03-01 04:46:24 +00003965 EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy);
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003966}
3967
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003968llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() {
3969 FinishNonFragileABIModule();
3970
3971 return NULL;
3972}
3973
3974void CGObjCNonFragileABIMac::FinishNonFragileABIModule() {
3975 // nonfragile abi has no module definition.
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003976
3977 // Build list of all implemented classe addresses in array
3978 // L_OBJC_LABEL_CLASS_$.
3979 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CLASS_$
3980 // list of 'nonlazy' implementations (defined as those with a +load{}
3981 // method!!).
3982 unsigned NumClasses = DefinedClasses.size();
3983 if (NumClasses) {
3984 std::vector<llvm::Constant*> Symbols(NumClasses);
3985 for (unsigned i=0; i<NumClasses; i++)
3986 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
3987 ObjCTypes.Int8PtrTy);
3988 llvm::Constant* Init =
3989 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
3990 NumClasses),
3991 Symbols);
3992
3993 llvm::GlobalVariable *GV =
3994 new llvm::GlobalVariable(Init->getType(), false,
3995 llvm::GlobalValue::InternalLinkage,
3996 Init,
3997 "\01L_OBJC_LABEL_CLASS_$",
3998 &CGM.getModule());
Daniel Dunbar58a29122009-03-09 22:18:41 +00003999 GV->setAlignment(8);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004000 GV->setSection("__DATA, __objc_classlist, regular, no_dead_strip");
4001 UsedGlobals.push_back(GV);
4002 }
4003
4004 // Build list of all implemented category addresses in array
4005 // L_OBJC_LABEL_CATEGORY_$.
4006 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CATEGORY_$
4007 // list of 'nonlazy' category implementations (defined as those with a +load{}
4008 // method!!).
4009 unsigned NumCategory = DefinedCategories.size();
4010 if (NumCategory) {
4011 std::vector<llvm::Constant*> Symbols(NumCategory);
4012 for (unsigned i=0; i<NumCategory; i++)
4013 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedCategories[i],
4014 ObjCTypes.Int8PtrTy);
4015 llvm::Constant* Init =
4016 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
4017 NumCategory),
4018 Symbols);
4019
4020 llvm::GlobalVariable *GV =
4021 new llvm::GlobalVariable(Init->getType(), false,
4022 llvm::GlobalValue::InternalLinkage,
4023 Init,
4024 "\01L_OBJC_LABEL_CATEGORY_$",
4025 &CGM.getModule());
Daniel Dunbar58a29122009-03-09 22:18:41 +00004026 GV->setAlignment(8);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004027 GV->setSection("__DATA, __objc_catlist, regular, no_dead_strip");
4028 UsedGlobals.push_back(GV);
4029 }
4030
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004031 // static int L_OBJC_IMAGE_INFO[2] = { 0, flags };
4032 // FIXME. flags can be 0 | 1 | 2 | 6. For now just use 0
4033 std::vector<llvm::Constant*> Values(2);
4034 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, 0);
Fariborz Jahanian067986e2009-02-24 21:08:09 +00004035 unsigned int flags = 0;
Fariborz Jahanian66a5c2c2009-02-24 23:34:44 +00004036 // FIXME: Fix and continue?
4037 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
4038 flags |= eImageInfo_GarbageCollected;
4039 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
4040 flags |= eImageInfo_GCOnly;
Fariborz Jahanian067986e2009-02-24 21:08:09 +00004041 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004042 llvm::Constant* Init = llvm::ConstantArray::get(
4043 llvm::ArrayType::get(ObjCTypes.IntTy, 2),
4044 Values);
4045 llvm::GlobalVariable *IMGV =
4046 new llvm::GlobalVariable(Init->getType(), false,
4047 llvm::GlobalValue::InternalLinkage,
4048 Init,
4049 "\01L_OBJC_IMAGE_INFO",
4050 &CGM.getModule());
4051 IMGV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
4052 UsedGlobals.push_back(IMGV);
4053
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004054 std::vector<llvm::Constant*> Used;
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004055
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004056 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
4057 e = UsedGlobals.end(); i != e; ++i) {
4058 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
4059 }
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004060
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004061 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
4062 llvm::GlobalValue *GV =
4063 new llvm::GlobalVariable(AT, false,
4064 llvm::GlobalValue::AppendingLinkage,
4065 llvm::ConstantArray::get(AT, Used),
4066 "llvm.used",
4067 &CGM.getModule());
4068
4069 GV->setSection("llvm.metadata");
4070
4071}
4072
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004073// Metadata flags
4074enum MetaDataDlags {
4075 CLS = 0x0,
4076 CLS_META = 0x1,
4077 CLS_ROOT = 0x2,
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004078 OBJC2_CLS_HIDDEN = 0x10,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004079 CLS_EXCEPTION = 0x20
4080};
4081/// BuildClassRoTInitializer - generate meta-data for:
4082/// struct _class_ro_t {
4083/// uint32_t const flags;
4084/// uint32_t const instanceStart;
4085/// uint32_t const instanceSize;
4086/// uint32_t const reserved; // only when building for 64bit targets
4087/// const uint8_t * const ivarLayout;
4088/// const char *const name;
4089/// const struct _method_list_t * const baseMethods;
Fariborz Jahanianda320092009-01-29 19:24:30 +00004090/// const struct _protocol_list_t *const baseProtocols;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004091/// const struct _ivar_list_t *const ivars;
4092/// const uint8_t * const weakIvarLayout;
4093/// const struct _prop_list_t * const properties;
4094/// }
4095///
4096llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer(
4097 unsigned flags,
4098 unsigned InstanceStart,
4099 unsigned InstanceSize,
4100 const ObjCImplementationDecl *ID) {
4101 std::string ClassName = ID->getNameAsString();
4102 std::vector<llvm::Constant*> Values(10); // 11 for 64bit targets!
4103 Values[ 0] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
4104 Values[ 1] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceStart);
4105 Values[ 2] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceSize);
4106 // FIXME. For 64bit targets add 0 here.
Fariborz Jahanianda320092009-01-29 19:24:30 +00004107 // FIXME. ivarLayout is currently null!
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00004108 // Values[ 3] = (flags & CLS_META) ? GetIvarLayoutName(0, ObjCTypes)
4109 // : BuildIvarLayout(ID, true);
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00004110 Values[ 3] = GetIvarLayoutName(0, ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004111 Values[ 4] = GetClassName(ID->getIdentifier());
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004112 // const struct _method_list_t * const baseMethods;
4113 std::vector<llvm::Constant*> Methods;
4114 std::string MethodListName("\01l_OBJC_$_");
4115 if (flags & CLS_META) {
4116 MethodListName += "CLASS_METHODS_" + ID->getNameAsString();
4117 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
4118 e = ID->classmeth_end(); i != e; ++i) {
4119 // Class methods should always be defined.
4120 Methods.push_back(GetMethodConstant(*i));
4121 }
4122 } else {
4123 MethodListName += "INSTANCE_METHODS_" + ID->getNameAsString();
4124 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
4125 e = ID->instmeth_end(); i != e; ++i) {
4126 // Instance methods should always be defined.
4127 Methods.push_back(GetMethodConstant(*i));
4128 }
Fariborz Jahanian939abce2009-01-28 22:46:49 +00004129 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
4130 e = ID->propimpl_end(); i != e; ++i) {
4131 ObjCPropertyImplDecl *PID = *i;
4132
4133 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize){
4134 ObjCPropertyDecl *PD = PID->getPropertyDecl();
4135
4136 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
4137 if (llvm::Constant *C = GetMethodConstant(MD))
4138 Methods.push_back(C);
4139 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
4140 if (llvm::Constant *C = GetMethodConstant(MD))
4141 Methods.push_back(C);
4142 }
4143 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004144 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004145 Values[ 5] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004146 "__DATA, __objc_const", Methods);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004147
4148 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4149 assert(OID && "CGObjCNonFragileABIMac::BuildClassRoTInitializer");
4150 Values[ 6] = EmitProtocolList("\01l_OBJC_CLASS_PROTOCOLS_$_"
4151 + OID->getNameAsString(),
4152 OID->protocol_begin(),
4153 OID->protocol_end());
4154
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004155 if (flags & CLS_META)
4156 Values[ 7] = llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4157 else
4158 Values[ 7] = EmitIvarList(ID);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004159 // FIXME. weakIvarLayout is currently null.
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00004160 // Values[ 8] = (flags & CLS_META) ? GetIvarLayoutName(0, ObjCTypes)
4161 // : BuildIvarLayout(ID, false);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00004162 Values[ 8] = GetIvarLayoutName(0, ObjCTypes);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004163 if (flags & CLS_META)
4164 Values[ 9] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4165 else
4166 Values[ 9] =
4167 EmitPropertyList(
4168 "\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
4169 ID, ID->getClassInterface(), ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004170 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassRonfABITy,
4171 Values);
4172 llvm::GlobalVariable *CLASS_RO_GV =
4173 new llvm::GlobalVariable(ObjCTypes.ClassRonfABITy, false,
4174 llvm::GlobalValue::InternalLinkage,
4175 Init,
4176 (flags & CLS_META) ?
4177 std::string("\01l_OBJC_METACLASS_RO_$_")+ClassName :
4178 std::string("\01l_OBJC_CLASS_RO_$_")+ClassName,
4179 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004180 CLASS_RO_GV->setAlignment(
4181 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassRonfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004182 CLASS_RO_GV->setSection("__DATA, __objc_const");
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004183 return CLASS_RO_GV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004184
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004185}
4186
4187/// BuildClassMetaData - This routine defines that to-level meta-data
4188/// for the given ClassName for:
4189/// struct _class_t {
4190/// struct _class_t *isa;
4191/// struct _class_t * const superclass;
4192/// void *cache;
4193/// IMP *vtable;
4194/// struct class_ro_t *ro;
4195/// }
4196///
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004197llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassMetaData(
4198 std::string &ClassName,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004199 llvm::Constant *IsAGV,
4200 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004201 llvm::Constant *ClassRoGV,
4202 bool HiddenVisibility) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004203 std::vector<llvm::Constant*> Values(5);
4204 Values[0] = IsAGV;
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004205 Values[1] = SuperClassGV
4206 ? SuperClassGV
4207 : llvm::Constant::getNullValue(ObjCTypes.ClassnfABIPtrTy);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004208 Values[2] = ObjCEmptyCacheVar; // &ObjCEmptyCacheVar
4209 Values[3] = ObjCEmptyVtableVar; // &ObjCEmptyVtableVar
4210 Values[4] = ClassRoGV; // &CLASS_RO_GV
4211 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassnfABITy,
4212 Values);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004213 llvm::GlobalVariable *GV = GetClassGlobal(ClassName);
4214 GV->setInitializer(Init);
Fariborz Jahaniandd0db2a2009-01-31 01:07:39 +00004215 GV->setSection("__DATA, __objc_data");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004216 GV->setAlignment(
4217 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassnfABITy));
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004218 if (HiddenVisibility)
4219 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004220 return GV;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004221}
4222
Daniel Dunbar6c1aac82009-04-20 20:18:54 +00004223/// countInheritedIvars - count number of ivars in class and its super class(s)
4224///
4225static int countInheritedIvars(const ObjCInterfaceDecl *OI,
4226 ASTContext &Context) {
4227 int count = 0;
4228 if (!OI)
4229 return 0;
4230 const ObjCInterfaceDecl *SuperClass = OI->getSuperClass();
4231 if (SuperClass)
4232 count += countInheritedIvars(SuperClass, Context);
4233 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
4234 E = OI->ivar_end(); I != E; ++I)
4235 ++count;
4236 // look into properties.
4237 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(Context),
4238 E = OI->prop_end(Context); I != E; ++I) {
4239 if ((*I)->getPropertyIvarDecl())
4240 ++count;
4241 }
4242 return count;
4243}
4244
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004245void CGObjCNonFragileABIMac::GetClassSizeInfo(const ObjCInterfaceDecl *OID,
4246 uint32_t &InstanceStart,
4247 uint32_t &InstanceSize) {
Daniel Dunbar24c89912009-04-21 21:41:56 +00004248 assert(!OID->isForwardDecl() && "Invalid interface decl!");
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004249 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID);
4250
Daniel Dunbar6ec07162009-04-20 07:18:49 +00004251 int countSuperClassIvars = countInheritedIvars(OID->getSuperClass(),
4252 CGM.getContext());
4253 const RecordDecl *RD = CGM.getContext().addRecordToClass(OID);
4254 RecordDecl::field_iterator firstField = RD->field_begin(CGM.getContext());
4255 RecordDecl::field_iterator lastField = RD->field_end(CGM.getContext());
4256 while (countSuperClassIvars-- > 0) {
4257 lastField = firstField;
4258 ++firstField;
4259 }
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004260
4261 for (RecordDecl::field_iterator e = RD->field_end(CGM.getContext()),
4262 ifield = firstField; ifield != e; ++ifield)
4263 lastField = ifield;
4264
4265 InstanceStart = InstanceSize = 0;
4266 if (lastField != RD->field_end(CGM.getContext())) {
4267 FieldDecl *Field = *lastField;
4268 const llvm::Type *FieldTy =
4269 CGM.getTypes().ConvertTypeForMem(Field->getType());
4270 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
4271 InstanceSize = GetIvarBaseOffset(Layout, Field) + Size;
4272 if (firstField == RD->field_end(CGM.getContext()))
4273 InstanceStart = InstanceSize;
4274 else {
4275 Field = *firstField;
4276 InstanceStart = GetIvarBaseOffset(Layout, Field);
4277 }
4278 }
4279}
4280
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004281void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) {
4282 std::string ClassName = ID->getNameAsString();
4283 if (!ObjCEmptyCacheVar) {
4284 ObjCEmptyCacheVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004285 ObjCTypes.CacheTy,
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_cache",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004290 &CGM.getModule());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004291
4292 ObjCEmptyVtableVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004293 ObjCTypes.ImpnfABITy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004294 false,
4295 llvm::GlobalValue::ExternalLinkage,
4296 0,
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004297 "_objc_empty_vtable",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004298 &CGM.getModule());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004299 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004300 assert(ID->getClassInterface() &&
4301 "CGObjCNonFragileABIMac::GenerateClass - class is 0");
Daniel Dunbar6c1aac82009-04-20 20:18:54 +00004302 // FIXME: Is this correct (that meta class size is never computed)?
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004303 uint32_t InstanceStart =
4304 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassnfABITy);
4305 uint32_t InstanceSize = InstanceStart;
4306 uint32_t flags = CLS_META;
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004307 std::string ObjCMetaClassName(getMetaclassSymbolPrefix());
4308 std::string ObjCClassName(getClassSymbolPrefix());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004309
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004310 llvm::GlobalVariable *SuperClassGV, *IsAGV;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004311
Daniel Dunbar04d40782009-04-14 06:00:08 +00004312 bool classIsHidden =
4313 CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004314 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004315 flags |= OBJC2_CLS_HIDDEN;
4316 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004317 // class is root
4318 flags |= CLS_ROOT;
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004319 SuperClassGV = GetClassGlobal(ObjCClassName + ClassName);
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004320 IsAGV = GetClassGlobal(ObjCMetaClassName + ClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004321 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004322 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004323 const ObjCInterfaceDecl *Root = ID->getClassInterface();
4324 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
4325 Root = Super;
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004326 IsAGV = GetClassGlobal(ObjCMetaClassName + Root->getNameAsString());
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004327 // work on super class metadata symbol.
4328 std::string SuperClassName =
4329 ObjCMetaClassName + ID->getClassInterface()->getSuperClass()->getNameAsString();
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004330 SuperClassGV = GetClassGlobal(SuperClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004331 }
4332 llvm::GlobalVariable *CLASS_RO_GV = BuildClassRoTInitializer(flags,
4333 InstanceStart,
4334 InstanceSize,ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004335 std::string TClassName = ObjCMetaClassName + ClassName;
4336 llvm::GlobalVariable *MetaTClass =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004337 BuildClassMetaData(TClassName, IsAGV, SuperClassGV, CLASS_RO_GV,
4338 classIsHidden);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004339
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004340 // Metadata for the class
4341 flags = CLS;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004342 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004343 flags |= OBJC2_CLS_HIDDEN;
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004344
4345 if (hasObjCExceptionAttribute(ID->getClassInterface()))
4346 flags |= CLS_EXCEPTION;
4347
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004348 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004349 flags |= CLS_ROOT;
4350 SuperClassGV = 0;
Chris Lattnerb7b58b12009-04-19 06:02:28 +00004351 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004352 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004353 std::string RootClassName =
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004354 ID->getClassInterface()->getSuperClass()->getNameAsString();
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004355 SuperClassGV = GetClassGlobal(ObjCClassName + RootClassName);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004356 }
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004357 GetClassSizeInfo(ID->getClassInterface(), InstanceStart, InstanceSize);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004358 CLASS_RO_GV = BuildClassRoTInitializer(flags,
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004359 InstanceStart,
4360 InstanceSize,
4361 ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004362
4363 TClassName = ObjCClassName + ClassName;
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004364 llvm::GlobalVariable *ClassMD =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004365 BuildClassMetaData(TClassName, MetaTClass, SuperClassGV, CLASS_RO_GV,
4366 classIsHidden);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004367 DefinedClasses.push_back(ClassMD);
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004368
4369 // Force the definition of the EHType if necessary.
4370 if (flags & CLS_EXCEPTION)
4371 GetInterfaceEHType(ID->getClassInterface(), true);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004372}
4373
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004374/// GenerateProtocolRef - This routine is called to generate code for
4375/// a protocol reference expression; as in:
4376/// @code
4377/// @protocol(Proto1);
4378/// @endcode
4379/// It generates a weak reference to l_OBJC_PROTOCOL_REFERENCE_$_Proto1
4380/// which will hold address of the protocol meta-data.
4381///
4382llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CGBuilderTy &Builder,
4383 const ObjCProtocolDecl *PD) {
4384
Fariborz Jahanian960cd062009-04-10 18:47:34 +00004385 // This routine is called for @protocol only. So, we must build definition
4386 // of protocol's meta-data (not a reference to it!)
4387 //
4388 llvm::Constant *Init = llvm::ConstantExpr::getBitCast(GetOrEmitProtocol(PD),
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004389 ObjCTypes.ExternalProtocolPtrTy);
4390
4391 std::string ProtocolName("\01l_OBJC_PROTOCOL_REFERENCE_$_");
4392 ProtocolName += PD->getNameAsCString();
4393
4394 llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName);
4395 if (PTGV)
4396 return Builder.CreateLoad(PTGV, false, "tmp");
4397 PTGV = new llvm::GlobalVariable(
4398 Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00004399 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004400 Init,
4401 ProtocolName,
4402 &CGM.getModule());
4403 PTGV->setSection("__DATA, __objc_protorefs, coalesced, no_dead_strip");
4404 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4405 UsedGlobals.push_back(PTGV);
4406 return Builder.CreateLoad(PTGV, false, "tmp");
4407}
4408
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004409/// GenerateCategory - Build metadata for a category implementation.
4410/// struct _category_t {
4411/// const char * const name;
4412/// struct _class_t *const cls;
4413/// const struct _method_list_t * const instance_methods;
4414/// const struct _method_list_t * const class_methods;
4415/// const struct _protocol_list_t * const protocols;
4416/// const struct _prop_list_t * const properties;
4417/// }
4418///
4419void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD)
4420{
4421 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004422 const char *Prefix = "\01l_OBJC_$_CATEGORY_";
4423 std::string ExtCatName(Prefix + Interface->getNameAsString()+
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004424 "_$_" + OCD->getNameAsString());
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004425 std::string ExtClassName(getClassSymbolPrefix() +
4426 Interface->getNameAsString());
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004427
4428 std::vector<llvm::Constant*> Values(6);
4429 Values[0] = GetClassName(OCD->getIdentifier());
4430 // meta-class entry symbol
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004431 llvm::GlobalVariable *ClassGV = GetClassGlobal(ExtClassName);
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004432 Values[1] = ClassGV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004433 std::vector<llvm::Constant*> Methods;
4434 std::string MethodListName(Prefix);
4435 MethodListName += "INSTANCE_METHODS_" + Interface->getNameAsString() +
4436 "_$_" + OCD->getNameAsString();
4437
4438 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
4439 e = OCD->instmeth_end(); i != e; ++i) {
4440 // Instance methods should always be defined.
4441 Methods.push_back(GetMethodConstant(*i));
4442 }
4443
4444 Values[2] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004445 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004446 Methods);
4447
4448 MethodListName = Prefix;
4449 MethodListName += "CLASS_METHODS_" + Interface->getNameAsString() + "_$_" +
4450 OCD->getNameAsString();
4451 Methods.clear();
4452 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
4453 e = OCD->classmeth_end(); i != e; ++i) {
4454 // Class methods should always be defined.
4455 Methods.push_back(GetMethodConstant(*i));
4456 }
4457
4458 Values[3] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004459 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004460 Methods);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004461 const ObjCCategoryDecl *Category =
4462 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Fariborz Jahanian943ed6f2009-02-13 17:52:22 +00004463 if (Category) {
4464 std::string ExtName(Interface->getNameAsString() + "_$_" +
4465 OCD->getNameAsString());
4466 Values[4] = EmitProtocolList("\01l_OBJC_CATEGORY_PROTOCOLS_$_"
4467 + Interface->getNameAsString() + "_$_"
4468 + Category->getNameAsString(),
4469 Category->protocol_begin(),
4470 Category->protocol_end());
4471 Values[5] =
4472 EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
4473 OCD, Category, ObjCTypes);
4474 }
4475 else {
4476 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4477 Values[5] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4478 }
4479
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004480 llvm::Constant *Init =
4481 llvm::ConstantStruct::get(ObjCTypes.CategorynfABITy,
4482 Values);
4483 llvm::GlobalVariable *GCATV
4484 = new llvm::GlobalVariable(ObjCTypes.CategorynfABITy,
4485 false,
4486 llvm::GlobalValue::InternalLinkage,
4487 Init,
4488 ExtCatName,
4489 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004490 GCATV->setAlignment(
4491 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.CategorynfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004492 GCATV->setSection("__DATA, __objc_const");
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004493 UsedGlobals.push_back(GCATV);
4494 DefinedCategories.push_back(GCATV);
4495}
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004496
4497/// GetMethodConstant - Return a struct objc_method constant for the
4498/// given method if it has been defined. The result is null if the
4499/// method has not been defined. The return value has type MethodPtrTy.
4500llvm::Constant *CGObjCNonFragileABIMac::GetMethodConstant(
4501 const ObjCMethodDecl *MD) {
4502 // FIXME: Use DenseMap::lookup
4503 llvm::Function *Fn = MethodDefinitions[MD];
4504 if (!Fn)
4505 return 0;
4506
4507 std::vector<llvm::Constant*> Method(3);
4508 Method[0] =
4509 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4510 ObjCTypes.SelectorPtrTy);
4511 Method[1] = GetMethodVarType(MD);
4512 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
4513 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
4514}
4515
4516/// EmitMethodList - Build meta-data for method declarations
4517/// struct _method_list_t {
4518/// uint32_t entsize; // sizeof(struct _objc_method)
4519/// uint32_t method_count;
4520/// struct _objc_method method_list[method_count];
4521/// }
4522///
4523llvm::Constant *CGObjCNonFragileABIMac::EmitMethodList(
4524 const std::string &Name,
4525 const char *Section,
4526 const ConstantVector &Methods) {
4527 // Return null for empty list.
4528 if (Methods.empty())
4529 return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy);
4530
4531 std::vector<llvm::Constant*> Values(3);
4532 // sizeof(struct _objc_method)
4533 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.MethodTy);
4534 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4535 // method_count
4536 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
4537 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
4538 Methods.size());
4539 Values[2] = llvm::ConstantArray::get(AT, Methods);
4540 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4541
4542 llvm::GlobalVariable *GV =
4543 new llvm::GlobalVariable(Init->getType(), false,
4544 llvm::GlobalValue::InternalLinkage,
4545 Init,
4546 Name,
4547 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004548 GV->setAlignment(
4549 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004550 GV->setSection(Section);
4551 UsedGlobals.push_back(GV);
4552 return llvm::ConstantExpr::getBitCast(GV,
4553 ObjCTypes.MethodListnfABIPtrTy);
4554}
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004555
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004556/// ObjCIvarOffsetVariable - Returns the ivar offset variable for
4557/// the given ivar.
4558///
4559llvm::GlobalVariable * CGObjCNonFragileABIMac::ObjCIvarOffsetVariable(
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004560 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004561 const ObjCIvarDecl *Ivar) {
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00004562 std::string Name = "OBJC_IVAR_$_" +
Douglas Gregor6ab35242009-04-09 21:40:53 +00004563 getInterfaceDeclForIvar(ID, Ivar, CGM.getContext())->getNameAsString() +
4564 '.' + Ivar->getNameAsString();
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004565 llvm::GlobalVariable *IvarOffsetGV =
4566 CGM.getModule().getGlobalVariable(Name);
4567 if (!IvarOffsetGV)
4568 IvarOffsetGV =
4569 new llvm::GlobalVariable(ObjCTypes.LongTy,
4570 false,
4571 llvm::GlobalValue::ExternalLinkage,
4572 0,
4573 Name,
4574 &CGM.getModule());
4575 return IvarOffsetGV;
4576}
4577
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004578llvm::Constant * CGObjCNonFragileABIMac::EmitIvarOffsetVar(
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004579 const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004580 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004581 unsigned long int Offset) {
Daniel Dunbar737c5022009-04-19 00:44:02 +00004582 llvm::GlobalVariable *IvarOffsetGV = ObjCIvarOffsetVariable(ID, Ivar);
4583 IvarOffsetGV->setInitializer(llvm::ConstantInt::get(ObjCTypes.LongTy,
4584 Offset));
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004585 IvarOffsetGV->setAlignment(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004586 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.LongTy));
Daniel Dunbar737c5022009-04-19 00:44:02 +00004587
4588 // FIXME: This matches gcc, but shouldn't the visibility be set on
4589 // the use as well (i.e., in ObjCIvarOffsetVariable).
4590 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
4591 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
4592 CGM.getDeclVisibilityMode(ID) == LangOptions::Hidden)
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004593 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar04d40782009-04-14 06:00:08 +00004594 else
Fariborz Jahanian77c9fd22009-04-06 18:30:00 +00004595 IvarOffsetGV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004596 IvarOffsetGV->setSection("__DATA, __objc_const");
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004597 return IvarOffsetGV;
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004598}
4599
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004600/// EmitIvarList - Emit the ivar list for the given
Daniel Dunbar11394522009-04-18 08:51:00 +00004601/// implementation. The return value has type
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004602/// IvarListnfABIPtrTy.
4603/// struct _ivar_t {
4604/// unsigned long int *offset; // pointer to ivar offset location
4605/// char *name;
4606/// char *type;
4607/// uint32_t alignment;
4608/// uint32_t size;
4609/// }
4610/// struct _ivar_list_t {
4611/// uint32 entsize; // sizeof(struct _ivar_t)
4612/// uint32 count;
4613/// struct _iver_t list[count];
4614/// }
4615///
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004616
4617void CGObjCCommonMac::GetNamedIvarList(const ObjCInterfaceDecl *OID,
4618 llvm::SmallVector<ObjCIvarDecl*, 16> &Res) const {
4619 for (ObjCInterfaceDecl::ivar_iterator I = OID->ivar_begin(),
4620 E = OID->ivar_end(); I != E; ++I) {
4621 // Ignore unnamed bit-fields.
4622 if (!(*I)->getDeclName())
4623 continue;
4624
4625 Res.push_back(*I);
4626 }
4627
4628 for (ObjCInterfaceDecl::prop_iterator I = OID->prop_begin(CGM.getContext()),
4629 E = OID->prop_end(CGM.getContext()); I != E; ++I)
4630 if (ObjCIvarDecl *IV = (*I)->getPropertyIvarDecl())
4631 Res.push_back(IV);
4632}
4633
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004634llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList(
4635 const ObjCImplementationDecl *ID) {
4636
4637 std::vector<llvm::Constant*> Ivars, Ivar(5);
4638
4639 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4640 assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface");
4641
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004642 // FIXME. Consolidate this with similar code in GenerateClass.
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00004643 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00004644
Daniel Dunbar91636d62009-04-20 00:33:43 +00004645 // Collect declared and synthesized ivars in a small vector.
Fariborz Jahanian18191882009-03-31 18:11:23 +00004646 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004647 GetNamedIvarList(OID, OIvars);
Fariborz Jahanian99eee362009-04-01 19:37:34 +00004648
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004649 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
4650 ObjCIvarDecl *IVD = OIvars[i];
4651 const FieldDecl *Field = OID->lookupFieldDeclForIvar(CGM.getContext(), IVD);
Daniel Dunbar3eec8aa2009-04-20 05:53:40 +00004652 Ivar[0] = EmitIvarOffsetVar(ID->getClassInterface(), IVD,
Daniel Dunbar48fa0642009-04-19 02:03:42 +00004653 GetIvarBaseOffset(Layout, Field));
Daniel Dunbar3eec8aa2009-04-20 05:53:40 +00004654 Ivar[1] = GetMethodVarName(Field->getIdentifier());
Devang Patel7794bb82009-03-04 18:21:39 +00004655 Ivar[2] = GetMethodVarType(Field);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004656 const llvm::Type *FieldTy =
4657 CGM.getTypes().ConvertTypeForMem(Field->getType());
4658 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
4659 unsigned Align = CGM.getContext().getPreferredTypeAlign(
4660 Field->getType().getTypePtr()) >> 3;
4661 Align = llvm::Log2_32(Align);
4662 Ivar[3] = llvm::ConstantInt::get(ObjCTypes.IntTy, Align);
Daniel Dunbar91636d62009-04-20 00:33:43 +00004663 // NOTE. Size of a bitfield does not match gcc's, because of the
4664 // way bitfields are treated special in each. But I am told that
4665 // 'size' for bitfield ivars is ignored by the runtime so it does
4666 // not matter. If it matters, there is enough info to get the
4667 // bitfield right!
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004668 Ivar[4] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4669 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarnfABITy, Ivar));
4670 }
4671 // Return null for empty list.
4672 if (Ivars.empty())
4673 return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4674 std::vector<llvm::Constant*> Values(3);
4675 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.IvarnfABITy);
4676 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4677 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
4678 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarnfABITy,
4679 Ivars.size());
4680 Values[2] = llvm::ConstantArray::get(AT, Ivars);
4681 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4682 const char *Prefix = "\01l_OBJC_$_INSTANCE_VARIABLES_";
4683 llvm::GlobalVariable *GV =
4684 new llvm::GlobalVariable(Init->getType(), false,
4685 llvm::GlobalValue::InternalLinkage,
4686 Init,
4687 Prefix + OID->getNameAsString(),
4688 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004689 GV->setAlignment(
4690 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004691 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004692
4693 UsedGlobals.push_back(GV);
4694 return llvm::ConstantExpr::getBitCast(GV,
4695 ObjCTypes.IvarListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004696}
4697
4698llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef(
4699 const ObjCProtocolDecl *PD) {
4700 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4701
4702 if (!Entry) {
4703 // We use the initializer as a marker of whether this is a forward
4704 // reference or not. At module finalization we add the empty
4705 // contents for protocols which were referenced but never defined.
4706 Entry =
4707 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
4708 llvm::GlobalValue::ExternalLinkage,
4709 0,
4710 "\01l_OBJC_PROTOCOL_$_" + PD->getNameAsString(),
4711 &CGM.getModule());
4712 Entry->setSection("__DATA,__datacoal_nt,coalesced");
4713 UsedGlobals.push_back(Entry);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004714 }
4715
4716 return Entry;
4717}
4718
4719/// GetOrEmitProtocol - Generate the protocol meta-data:
4720/// @code
4721/// struct _protocol_t {
4722/// id isa; // NULL
4723/// const char * const protocol_name;
4724/// const struct _protocol_list_t * protocol_list; // super protocols
4725/// const struct method_list_t * const instance_methods;
4726/// const struct method_list_t * const class_methods;
4727/// const struct method_list_t *optionalInstanceMethods;
4728/// const struct method_list_t *optionalClassMethods;
4729/// const struct _prop_list_t * properties;
4730/// const uint32_t size; // sizeof(struct _protocol_t)
4731/// const uint32_t flags; // = 0
4732/// }
4733/// @endcode
4734///
4735
4736llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol(
4737 const ObjCProtocolDecl *PD) {
4738 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4739
4740 // Early exit if a defining object has already been generated.
4741 if (Entry && Entry->hasInitializer())
4742 return Entry;
4743
4744 const char *ProtocolName = PD->getNameAsCString();
4745
4746 // Construct method lists.
4747 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
4748 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregor6ab35242009-04-09 21:40:53 +00004749 for (ObjCProtocolDecl::instmeth_iterator
4750 i = PD->instmeth_begin(CGM.getContext()),
4751 e = PD->instmeth_end(CGM.getContext());
4752 i != e; ++i) {
Fariborz Jahanianda320092009-01-29 19:24:30 +00004753 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004754 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004755 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4756 OptInstanceMethods.push_back(C);
4757 } else {
4758 InstanceMethods.push_back(C);
4759 }
4760 }
4761
Douglas Gregor6ab35242009-04-09 21:40:53 +00004762 for (ObjCProtocolDecl::classmeth_iterator
4763 i = PD->classmeth_begin(CGM.getContext()),
4764 e = PD->classmeth_end(CGM.getContext());
4765 i != e; ++i) {
Fariborz Jahanianda320092009-01-29 19:24:30 +00004766 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004767 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004768 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4769 OptClassMethods.push_back(C);
4770 } else {
4771 ClassMethods.push_back(C);
4772 }
4773 }
4774
4775 std::vector<llvm::Constant*> Values(10);
4776 // isa is NULL
4777 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ObjectPtrTy);
4778 Values[1] = GetClassName(PD->getIdentifier());
4779 Values[2] = EmitProtocolList(
4780 "\01l_OBJC_$_PROTOCOL_REFS_" + PD->getNameAsString(),
4781 PD->protocol_begin(),
4782 PD->protocol_end());
4783
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004784 Values[3] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004785 + PD->getNameAsString(),
4786 "__DATA, __objc_const",
4787 InstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004788 Values[4] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004789 + PD->getNameAsString(),
4790 "__DATA, __objc_const",
4791 ClassMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004792 Values[5] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004793 + PD->getNameAsString(),
4794 "__DATA, __objc_const",
4795 OptInstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004796 Values[6] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004797 + PD->getNameAsString(),
4798 "__DATA, __objc_const",
4799 OptClassMethods);
4800 Values[7] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + PD->getNameAsString(),
4801 0, PD, ObjCTypes);
4802 uint32_t Size =
4803 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolnfABITy);
4804 Values[8] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4805 Values[9] = llvm::Constant::getNullValue(ObjCTypes.IntTy);
4806 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolnfABITy,
4807 Values);
4808
4809 if (Entry) {
4810 // Already created, fix the linkage and update the initializer.
Mike Stump286acbd2009-03-07 16:33:28 +00004811 Entry->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004812 Entry->setInitializer(Init);
4813 } else {
4814 Entry =
4815 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004816 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004817 Init,
4818 std::string("\01l_OBJC_PROTOCOL_$_")+ProtocolName,
4819 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004820 Entry->setAlignment(
4821 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABITy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004822 Entry->setSection("__DATA,__datacoal_nt,coalesced");
Fariborz Jahanianda320092009-01-29 19:24:30 +00004823 }
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004824 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
4825
4826 // Use this protocol meta-data to build protocol list table in section
4827 // __DATA, __objc_protolist
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004828 llvm::GlobalVariable *PTGV = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004829 ObjCTypes.ProtocolnfABIPtrTy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004830 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004831 Entry,
4832 std::string("\01l_OBJC_LABEL_PROTOCOL_$_")
4833 +ProtocolName,
4834 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004835 PTGV->setAlignment(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004836 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABIPtrTy));
Daniel Dunbar0bf21992009-04-15 02:56:18 +00004837 PTGV->setSection("__DATA, __objc_protolist, coalesced, no_dead_strip");
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004838 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4839 UsedGlobals.push_back(PTGV);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004840 return Entry;
4841}
4842
4843/// EmitProtocolList - Generate protocol list meta-data:
4844/// @code
4845/// struct _protocol_list_t {
4846/// long protocol_count; // Note, this is 32/64 bit
4847/// struct _protocol_t[protocol_count];
4848/// }
4849/// @endcode
4850///
4851llvm::Constant *
4852CGObjCNonFragileABIMac::EmitProtocolList(const std::string &Name,
4853 ObjCProtocolDecl::protocol_iterator begin,
4854 ObjCProtocolDecl::protocol_iterator end) {
4855 std::vector<llvm::Constant*> ProtocolRefs;
4856
Fariborz Jahanianda320092009-01-29 19:24:30 +00004857 // Just return null for empty protocol lists
Daniel Dunbar948e2582009-02-15 07:36:20 +00004858 if (begin == end)
Fariborz Jahanianda320092009-01-29 19:24:30 +00004859 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4860
Daniel Dunbar948e2582009-02-15 07:36:20 +00004861 // FIXME: We shouldn't need to do this lookup here, should we?
Fariborz Jahanianda320092009-01-29 19:24:30 +00004862 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
4863 if (GV)
Daniel Dunbar948e2582009-02-15 07:36:20 +00004864 return llvm::ConstantExpr::getBitCast(GV,
4865 ObjCTypes.ProtocolListnfABIPtrTy);
4866
4867 for (; begin != end; ++begin)
4868 ProtocolRefs.push_back(GetProtocolRef(*begin)); // Implemented???
4869
Fariborz Jahanianda320092009-01-29 19:24:30 +00004870 // This list is null terminated.
4871 ProtocolRefs.push_back(llvm::Constant::getNullValue(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004872 ObjCTypes.ProtocolnfABIPtrTy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004873
4874 std::vector<llvm::Constant*> Values(2);
4875 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
4876 Values[1] =
Daniel Dunbar948e2582009-02-15 07:36:20 +00004877 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolnfABIPtrTy,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004878 ProtocolRefs.size()),
4879 ProtocolRefs);
4880
4881 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4882 GV = new llvm::GlobalVariable(Init->getType(), false,
4883 llvm::GlobalValue::InternalLinkage,
4884 Init,
4885 Name,
4886 &CGM.getModule());
4887 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004888 GV->setAlignment(
4889 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004890 UsedGlobals.push_back(GV);
Daniel Dunbar948e2582009-02-15 07:36:20 +00004891 return llvm::ConstantExpr::getBitCast(GV,
4892 ObjCTypes.ProtocolListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004893}
4894
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004895/// GetMethodDescriptionConstant - This routine build following meta-data:
4896/// struct _objc_method {
4897/// SEL _cmd;
4898/// char *method_type;
4899/// char *_imp;
4900/// }
4901
4902llvm::Constant *
4903CGObjCNonFragileABIMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
4904 std::vector<llvm::Constant*> Desc(3);
4905 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4906 ObjCTypes.SelectorPtrTy);
4907 Desc[1] = GetMethodVarType(MD);
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004908 // Protocol methods have no implementation. So, this entry is always NULL.
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004909 Desc[2] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
4910 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Desc);
4911}
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004912
4913/// EmitObjCValueForIvar - Code Gen for nonfragile ivar reference.
4914/// This code gen. amounts to generating code for:
4915/// @code
4916/// (type *)((char *)base + _OBJC_IVAR_$_.ivar;
4917/// @encode
4918///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004919LValue CGObjCNonFragileABIMac::EmitObjCValueForIvar(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004920 CodeGen::CodeGenFunction &CGF,
4921 QualType ObjectTy,
4922 llvm::Value *BaseValue,
4923 const ObjCIvarDecl *Ivar,
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004924 unsigned CVRQualifiers) {
Daniel Dunbar525c9b72009-04-21 01:19:28 +00004925 const ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
4926 const FieldDecl *Field = ID->lookupFieldDeclForIvar(CGM.getContext(), Ivar);
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00004927 llvm::GlobalVariable *IvarOffsetGV = ObjCIvarOffsetVariable(ID, Ivar);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004928
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004929 // (char *) BaseValue
Chris Lattner51123fe2009-04-17 17:46:19 +00004930 llvm::Value *V = CGF.Builder.CreateBitCast(BaseValue, ObjCTypes.Int8PtrTy);
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004931 llvm::Value *Offset = CGF.Builder.CreateLoad(IvarOffsetGV);
4932 // (char*)BaseValue + Offset_symbol
4933 V = CGF.Builder.CreateGEP(V, Offset, "add.ptr");
4934 // (type *)((char*)BaseValue + Offset_symbol)
4935 const llvm::Type *IvarTy =
Chris Lattner51123fe2009-04-17 17:46:19 +00004936 CGM.getTypes().ConvertTypeForMem(Ivar->getType());
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004937 llvm::Type *ptrIvarTy = llvm::PointerType::getUnqual(IvarTy);
4938 V = CGF.Builder.CreateBitCast(V, ptrIvarTy);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004939
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00004940 if (Ivar->isBitField()) {
Chris Lattner51123fe2009-04-17 17:46:19 +00004941 QualType FieldTy = Field->getType();
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00004942 CodeGenTypes::BitFieldInfo bitFieldInfo =
4943 CGM.getTypes().getBitFieldInfo(Field);
4944 return LValue::MakeBitfield(V, bitFieldInfo.Begin, bitFieldInfo.Size,
Chris Lattner51123fe2009-04-17 17:46:19 +00004945 FieldTy->isSignedIntegerType(),
4946 FieldTy.getCVRQualifiers()|CVRQualifiers);
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00004947 }
4948
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004949 LValue LV = LValue::MakeAddr(V,
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004950 Ivar->getType().getCVRQualifiers()|CVRQualifiers,
4951 CGM.getContext().getObjCGCAttrKind(Ivar->getType()));
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004952 LValue::SetObjCIvar(LV, true);
4953 return LV;
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004954}
4955
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004956llvm::Value *CGObjCNonFragileABIMac::EmitIvarOffset(
4957 CodeGen::CodeGenFunction &CGF,
4958 ObjCInterfaceDecl *Interface,
4959 const ObjCIvarDecl *Ivar) {
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00004960 return CGF.Builder.CreateLoad(ObjCIvarOffsetVariable(Interface, Ivar),
4961 false, "ivar");
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004962}
4963
Fariborz Jahanian46551122009-02-04 00:22:57 +00004964CodeGen::RValue CGObjCNonFragileABIMac::EmitMessageSend(
4965 CodeGen::CodeGenFunction &CGF,
4966 QualType ResultType,
4967 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004968 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +00004969 QualType Arg0Ty,
4970 bool IsSuper,
4971 const CallArgList &CallArgs) {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004972 // FIXME. Even though IsSuper is passes. This function doese not
4973 // handle calls to 'super' receivers.
4974 CodeGenTypes &Types = CGM.getTypes();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004975 llvm::Value *Arg0 = Receiver;
4976 if (!IsSuper)
4977 Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy, "tmp");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004978
4979 // Find the message function name.
Fariborz Jahanianef163782009-02-05 01:13:09 +00004980 // FIXME. This is too much work to get the ABI-specific result type
4981 // needed to find the message name.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004982 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType,
4983 llvm::SmallVector<QualType, 16>());
4984 llvm::Constant *Fn;
4985 std::string Name("\01l_");
4986 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004987#if 0
4988 // unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004989 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
Chris Lattner1c02f862009-04-22 02:53:24 +00004990 Fn = ObjCTypes.getMessageSendIdStretFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004991 // FIXME. Is there a better way of getting these names.
4992 // They are available in RuntimeFunctions vector pair.
4993 Name += "objc_msgSendId_stret_fixup";
4994 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004995 else
4996#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004997 if (IsSuper) {
Chris Lattner1c02f862009-04-22 02:53:24 +00004998 Fn = ObjCTypes.getMessageSendSuper2StretFixupFn();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004999 Name += "objc_msgSendSuper2_stret_fixup";
5000 }
5001 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005002 {
Chris Lattner1c02f862009-04-22 02:53:24 +00005003 Fn = ObjCTypes.getMessageSendStretFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005004 Name += "objc_msgSend_stret_fixup";
5005 }
5006 }
Fariborz Jahanian1a6b3682009-02-05 19:35:43 +00005007 else if (ResultType->isFloatingType() &&
5008 // Selection of frret API only happens in 32bit nonfragile ABI.
5009 CGM.getTargetData().getTypePaddedSize(ObjCTypes.LongTy) == 4) {
Chris Lattner1c02f862009-04-22 02:53:24 +00005010 Fn = ObjCTypes.getMessageSendFpretFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005011 Name += "objc_msgSend_fpret_fixup";
5012 }
5013 else {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005014#if 0
5015// unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005016 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
Chris Lattner1c02f862009-04-22 02:53:24 +00005017 Fn = ObjCTypes.getMessageSendIdFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005018 Name += "objc_msgSendId_fixup";
5019 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005020 else
5021#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005022 if (IsSuper) {
Chris Lattner1c02f862009-04-22 02:53:24 +00005023 Fn = ObjCTypes.getMessageSendSuper2FixupFn();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005024 Name += "objc_msgSendSuper2_fixup";
5025 }
5026 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005027 {
Chris Lattner1c02f862009-04-22 02:53:24 +00005028 Fn = ObjCTypes.getMessageSendFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005029 Name += "objc_msgSend_fixup";
5030 }
5031 }
5032 Name += '_';
5033 std::string SelName(Sel.getAsString());
5034 // Replace all ':' in selector name with '_' ouch!
5035 for(unsigned i = 0; i < SelName.size(); i++)
5036 if (SelName[i] == ':')
5037 SelName[i] = '_';
5038 Name += SelName;
5039 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5040 if (!GV) {
Daniel Dunbar33af70f2009-04-15 19:03:14 +00005041 // Build message ref table entry.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005042 std::vector<llvm::Constant*> Values(2);
5043 Values[0] = Fn;
5044 Values[1] = GetMethodVarName(Sel);
5045 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
5046 GV = new llvm::GlobalVariable(Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00005047 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005048 Init,
5049 Name,
5050 &CGM.getModule());
5051 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbarf59c1a62009-04-15 19:04:46 +00005052 GV->setAlignment(16);
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005053 GV->setSection("__DATA, __objc_msgrefs, coalesced");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005054 }
5055 llvm::Value *Arg1 = CGF.Builder.CreateBitCast(GV, ObjCTypes.MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00005056
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005057 CallArgList ActualArgs;
5058 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
5059 ActualArgs.push_back(std::make_pair(RValue::get(Arg1),
5060 ObjCTypes.MessageRefCPtrTy));
5061 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Fariborz Jahanianef163782009-02-05 01:13:09 +00005062 const CGFunctionInfo &FnInfo1 = Types.getFunctionInfo(ResultType, ActualArgs);
5063 llvm::Value *Callee = CGF.Builder.CreateStructGEP(Arg1, 0);
5064 Callee = CGF.Builder.CreateLoad(Callee);
Fariborz Jahanian3ab75bd2009-02-14 21:25:36 +00005065 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo1, true);
Fariborz Jahanianef163782009-02-05 01:13:09 +00005066 Callee = CGF.Builder.CreateBitCast(Callee,
5067 llvm::PointerType::getUnqual(FTy));
5068 return CGF.EmitCall(FnInfo1, Callee, ActualArgs);
Fariborz Jahanian46551122009-02-04 00:22:57 +00005069}
5070
5071/// Generate code for a message send expression in the nonfragile abi.
5072CodeGen::RValue CGObjCNonFragileABIMac::GenerateMessageSend(
5073 CodeGen::CodeGenFunction &CGF,
5074 QualType ResultType,
5075 Selector Sel,
5076 llvm::Value *Receiver,
5077 bool IsClassMessage,
5078 const CallArgList &CallArgs) {
Fariborz Jahanian46551122009-02-04 00:22:57 +00005079 return EmitMessageSend(CGF, ResultType, Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005080 Receiver, CGF.getContext().getObjCIdType(),
Fariborz Jahanian46551122009-02-04 00:22:57 +00005081 false, CallArgs);
5082}
5083
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005084llvm::GlobalVariable *
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005085CGObjCNonFragileABIMac::GetClassGlobal(const std::string &Name) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005086 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5087
Daniel Dunbardfff2302009-03-02 05:18:14 +00005088 if (!GV) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005089 GV = new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
5090 llvm::GlobalValue::ExternalLinkage,
5091 0, Name, &CGM.getModule());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005092 }
5093
5094 return GV;
5095}
5096
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005097llvm::Value *CGObjCNonFragileABIMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar11394522009-04-18 08:51:00 +00005098 const ObjCInterfaceDecl *ID) {
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005099 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
5100
5101 if (!Entry) {
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005102 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005103 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005104 Entry =
5105 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5106 llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005107 ClassGV,
Daniel Dunbar11394522009-04-18 08:51:00 +00005108 "\01L_OBJC_CLASSLIST_REFERENCES_$_",
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005109 &CGM.getModule());
5110 Entry->setAlignment(
5111 CGM.getTargetData().getPrefTypeAlignment(
5112 ObjCTypes.ClassnfABIPtrTy));
Daniel Dunbar11394522009-04-18 08:51:00 +00005113 Entry->setSection("__DATA, __objc_classrefs, regular, no_dead_strip");
5114 UsedGlobals.push_back(Entry);
5115 }
5116
5117 return Builder.CreateLoad(Entry, false, "tmp");
5118}
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005119
Daniel Dunbar11394522009-04-18 08:51:00 +00005120llvm::Value *
5121CGObjCNonFragileABIMac::EmitSuperClassRef(CGBuilderTy &Builder,
5122 const ObjCInterfaceDecl *ID) {
5123 llvm::GlobalVariable *&Entry = SuperClassReferences[ID->getIdentifier()];
5124
5125 if (!Entry) {
5126 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
5127 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
5128 Entry =
5129 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5130 llvm::GlobalValue::InternalLinkage,
5131 ClassGV,
5132 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5133 &CGM.getModule());
5134 Entry->setAlignment(
5135 CGM.getTargetData().getPrefTypeAlignment(
5136 ObjCTypes.ClassnfABIPtrTy));
5137 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005138 UsedGlobals.push_back(Entry);
5139 }
5140
5141 return Builder.CreateLoad(Entry, false, "tmp");
5142}
5143
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005144/// EmitMetaClassRef - Return a Value * of the address of _class_t
5145/// meta-data
5146///
5147llvm::Value *CGObjCNonFragileABIMac::EmitMetaClassRef(CGBuilderTy &Builder,
5148 const ObjCInterfaceDecl *ID) {
5149 llvm::GlobalVariable * &Entry = MetaClassReferences[ID->getIdentifier()];
5150 if (Entry)
5151 return Builder.CreateLoad(Entry, false, "tmp");
5152
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005153 std::string MetaClassName(getMetaclassSymbolPrefix() + ID->getNameAsString());
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005154 llvm::GlobalVariable *MetaClassGV = GetClassGlobal(MetaClassName);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005155 Entry =
5156 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5157 llvm::GlobalValue::InternalLinkage,
5158 MetaClassGV,
5159 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5160 &CGM.getModule());
5161 Entry->setAlignment(
5162 CGM.getTargetData().getPrefTypeAlignment(
5163 ObjCTypes.ClassnfABIPtrTy));
5164
Daniel Dunbar33af70f2009-04-15 19:03:14 +00005165 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005166 UsedGlobals.push_back(Entry);
5167
5168 return Builder.CreateLoad(Entry, false, "tmp");
5169}
5170
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005171/// GetClass - Return a reference to the class for the given interface
5172/// decl.
5173llvm::Value *CGObjCNonFragileABIMac::GetClass(CGBuilderTy &Builder,
5174 const ObjCInterfaceDecl *ID) {
5175 return EmitClassRef(Builder, ID);
5176}
5177
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005178/// Generates a message send where the super is the receiver. This is
5179/// a message send to self with special delivery semantics indicating
5180/// which class's method should be called.
5181CodeGen::RValue
5182CGObjCNonFragileABIMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
5183 QualType ResultType,
5184 Selector Sel,
5185 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005186 bool isCategoryImpl,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005187 llvm::Value *Receiver,
5188 bool IsClassMessage,
5189 const CodeGen::CallArgList &CallArgs) {
5190 // ...
5191 // Create and init a super structure; this is a (receiver, class)
5192 // pair we will pass to objc_msgSendSuper.
5193 llvm::Value *ObjCSuper =
5194 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
5195
5196 llvm::Value *ReceiverAsObject =
5197 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
5198 CGF.Builder.CreateStore(ReceiverAsObject,
5199 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
5200
5201 // If this is a class message the metaclass is passed as the target.
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005202 llvm::Value *Target;
5203 if (IsClassMessage) {
5204 if (isCategoryImpl) {
5205 // Message sent to "super' in a class method defined in
5206 // a category implementation.
Daniel Dunbar11394522009-04-18 08:51:00 +00005207 Target = EmitClassRef(CGF.Builder, Class);
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005208 Target = CGF.Builder.CreateStructGEP(Target, 0);
5209 Target = CGF.Builder.CreateLoad(Target);
5210 }
5211 else
5212 Target = EmitMetaClassRef(CGF.Builder, Class);
5213 }
5214 else
Daniel Dunbar11394522009-04-18 08:51:00 +00005215 Target = EmitSuperClassRef(CGF.Builder, Class);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005216
5217 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
5218 // and ObjCTypes types.
5219 const llvm::Type *ClassTy =
5220 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
5221 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
5222 CGF.Builder.CreateStore(Target,
5223 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
5224
5225 return EmitMessageSend(CGF, ResultType, Sel,
5226 ObjCSuper, ObjCTypes.SuperPtrCTy,
5227 true, CallArgs);
5228}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005229
5230llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CGBuilderTy &Builder,
5231 Selector Sel) {
5232 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
5233
5234 if (!Entry) {
5235 llvm::Constant *Casted =
5236 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
5237 ObjCTypes.SelectorPtrTy);
5238 Entry =
5239 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
5240 llvm::GlobalValue::InternalLinkage,
5241 Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
5242 &CGM.getModule());
5243 Entry->setSection("__DATA,__objc_selrefs,literal_pointers,no_dead_strip");
5244 UsedGlobals.push_back(Entry);
5245 }
5246
5247 return Builder.CreateLoad(Entry, false, "tmp");
5248}
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005249/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
5250/// objc_assign_ivar (id src, id *dst)
5251///
5252void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
5253 llvm::Value *src, llvm::Value *dst)
5254{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005255 const llvm::Type * SrcTy = src->getType();
5256 if (!isa<llvm::PointerType>(SrcTy)) {
5257 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5258 assert(Size <= 8 && "does not support size > 8");
5259 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5260 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005261 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5262 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005263 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5264 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00005265 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignIvarFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005266 src, dst, "assignivar");
5267 return;
5268}
5269
5270/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
5271/// objc_assign_strongCast (id src, id *dst)
5272///
5273void CGObjCNonFragileABIMac::EmitObjCStrongCastAssign(
5274 CodeGen::CodeGenFunction &CGF,
5275 llvm::Value *src, llvm::Value *dst)
5276{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005277 const llvm::Type * SrcTy = src->getType();
5278 if (!isa<llvm::PointerType>(SrcTy)) {
5279 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5280 assert(Size <= 8 && "does not support size > 8");
5281 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5282 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005283 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5284 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005285 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5286 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00005287 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignStrongCastFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005288 src, dst, "weakassign");
5289 return;
5290}
5291
5292/// EmitObjCWeakRead - Code gen for loading value of a __weak
5293/// object: objc_read_weak (id *src)
5294///
5295llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead(
5296 CodeGen::CodeGenFunction &CGF,
5297 llvm::Value *AddrWeakObj)
5298{
Eli Friedman8339b352009-03-07 03:57:15 +00005299 const llvm::Type* DestTy =
5300 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005301 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Chris Lattner72db6c32009-04-22 02:44:54 +00005302 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.getGcReadWeakFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005303 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00005304 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005305 return read_weak;
5306}
5307
5308/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
5309/// objc_assign_weak (id src, id *dst)
5310///
5311void CGObjCNonFragileABIMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
5312 llvm::Value *src, llvm::Value *dst)
5313{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005314 const llvm::Type * SrcTy = src->getType();
5315 if (!isa<llvm::PointerType>(SrcTy)) {
5316 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5317 assert(Size <= 8 && "does not support size > 8");
5318 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5319 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005320 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5321 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005322 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5323 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattner96508e12009-04-17 22:12:36 +00005324 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005325 src, dst, "weakassign");
5326 return;
5327}
5328
5329/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
5330/// objc_assign_global (id src, id *dst)
5331///
5332void CGObjCNonFragileABIMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
5333 llvm::Value *src, llvm::Value *dst)
5334{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005335 const llvm::Type * SrcTy = src->getType();
5336 if (!isa<llvm::PointerType>(SrcTy)) {
5337 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5338 assert(Size <= 8 && "does not support size > 8");
5339 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5340 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005341 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5342 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005343 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5344 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00005345 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignGlobalFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005346 src, dst, "globalassign");
5347 return;
5348}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005349
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005350void
5351CGObjCNonFragileABIMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
5352 const Stmt &S) {
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005353 bool isTry = isa<ObjCAtTryStmt>(S);
5354 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
5355 llvm::BasicBlock *PrevLandingPad = CGF.getInvokeDest();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005356 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005357 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005358 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005359 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
5360
5361 // For @synchronized, call objc_sync_enter(sync.expr). The
5362 // evaluation of the expression must occur before we enter the
5363 // @synchronized. We can safely avoid a temp here because jumps into
5364 // @synchronized are illegal & this will dominate uses.
5365 llvm::Value *SyncArg = 0;
5366 if (!isTry) {
5367 SyncArg =
5368 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
5369 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005370 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005371 }
5372
5373 // Push an EH context entry, used for handling rethrows and jumps
5374 // through finally.
5375 CGF.PushCleanupBlock(FinallyBlock);
5376
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005377 CGF.setInvokeDest(TryHandler);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005378
5379 CGF.EmitBlock(TryBlock);
5380 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
5381 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
5382 CGF.EmitBranchThroughCleanup(FinallyEnd);
5383
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005384 // Emit the exception handler.
5385
5386 CGF.EmitBlock(TryHandler);
5387
5388 llvm::Value *llvm_eh_exception =
5389 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_exception);
5390 llvm::Value *llvm_eh_selector_i64 =
5391 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector_i64);
5392 llvm::Value *llvm_eh_typeid_for_i64 =
5393 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for_i64);
5394 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5395 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(Exc->getType(), "_rethrow");
5396
5397 llvm::SmallVector<llvm::Value*, 8> SelectorArgs;
5398 SelectorArgs.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005399 SelectorArgs.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005400
5401 // Construct the lists of (type, catch body) to handle.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005402 llvm::SmallVector<std::pair<const ParmVarDecl*, const Stmt*>, 8> Handlers;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005403 bool HasCatchAll = false;
5404 if (isTry) {
5405 if (const ObjCAtCatchStmt* CatchStmt =
5406 cast<ObjCAtTryStmt>(S).getCatchStmts()) {
5407 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005408 const ParmVarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
Steve Naroff7ba138a2009-03-03 19:52:17 +00005409 Handlers.push_back(std::make_pair(CatchDecl, CatchStmt->getCatchBody()));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005410
5411 // catch(...) always matches.
Steve Naroff7ba138a2009-03-03 19:52:17 +00005412 if (!CatchDecl) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005413 // Use i8* null here to signal this is a catch all, not a cleanup.
5414 llvm::Value *Null = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
5415 SelectorArgs.push_back(Null);
5416 HasCatchAll = true;
5417 break;
5418 }
5419
Daniel Dunbarede8de92009-03-06 00:01:21 +00005420 if (CGF.getContext().isObjCIdType(CatchDecl->getType()) ||
5421 CatchDecl->getType()->isObjCQualifiedIdType()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005422 llvm::Value *IDEHType =
5423 CGM.getModule().getGlobalVariable("OBJC_EHTYPE_id");
5424 if (!IDEHType)
5425 IDEHType =
5426 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5427 llvm::GlobalValue::ExternalLinkage,
5428 0, "OBJC_EHTYPE_id", &CGM.getModule());
5429 SelectorArgs.push_back(IDEHType);
5430 HasCatchAll = true;
5431 break;
5432 }
5433
5434 // All other types should be Objective-C interface pointer types.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005435 const PointerType *PT = CatchDecl->getType()->getAsPointerType();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005436 assert(PT && "Invalid @catch type.");
5437 const ObjCInterfaceType *IT =
5438 PT->getPointeeType()->getAsObjCInterfaceType();
5439 assert(IT && "Invalid @catch type.");
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005440 llvm::Value *EHType = GetInterfaceEHType(IT->getDecl(), false);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005441 SelectorArgs.push_back(EHType);
5442 }
5443 }
5444 }
5445
5446 // We use a cleanup unless there was already a catch all.
5447 if (!HasCatchAll) {
5448 SelectorArgs.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
Daniel Dunbarede8de92009-03-06 00:01:21 +00005449 Handlers.push_back(std::make_pair((const ParmVarDecl*) 0, (const Stmt*) 0));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005450 }
5451
5452 llvm::Value *Selector =
5453 CGF.Builder.CreateCall(llvm_eh_selector_i64,
5454 SelectorArgs.begin(), SelectorArgs.end(),
5455 "selector");
5456 for (unsigned i = 0, e = Handlers.size(); i != e; ++i) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005457 const ParmVarDecl *CatchParam = Handlers[i].first;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005458 const Stmt *CatchBody = Handlers[i].second;
5459
5460 llvm::BasicBlock *Next = 0;
5461
5462 // The last handler always matches.
5463 if (i + 1 != e) {
5464 assert(CatchParam && "Only last handler can be a catch all.");
5465
5466 llvm::BasicBlock *Match = CGF.createBasicBlock("match");
5467 Next = CGF.createBasicBlock("catch.next");
5468 llvm::Value *Id =
5469 CGF.Builder.CreateCall(llvm_eh_typeid_for_i64,
5470 CGF.Builder.CreateBitCast(SelectorArgs[i+2],
5471 ObjCTypes.Int8PtrTy));
5472 CGF.Builder.CreateCondBr(CGF.Builder.CreateICmpEQ(Selector, Id),
5473 Match, Next);
5474
5475 CGF.EmitBlock(Match);
5476 }
5477
5478 if (CatchBody) {
5479 llvm::BasicBlock *MatchEnd = CGF.createBasicBlock("match.end");
5480 llvm::BasicBlock *MatchHandler = CGF.createBasicBlock("match.handler");
5481
5482 // Cleanups must call objc_end_catch.
5483 //
5484 // FIXME: It seems incorrect for objc_begin_catch to be inside
5485 // this context, but this matches gcc.
5486 CGF.PushCleanupBlock(MatchEnd);
5487 CGF.setInvokeDest(MatchHandler);
5488
5489 llvm::Value *ExcObject =
Chris Lattner8a569112009-04-22 02:15:23 +00005490 CGF.Builder.CreateCall(ObjCTypes.getObjCBeginCatchFn(), Exc);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005491
5492 // Bind the catch parameter if it exists.
5493 if (CatchParam) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005494 ExcObject =
5495 CGF.Builder.CreateBitCast(ExcObject,
5496 CGF.ConvertType(CatchParam->getType()));
5497 // CatchParam is a ParmVarDecl because of the grammar
5498 // construction used to handle this, but for codegen purposes
5499 // we treat this as a local decl.
5500 CGF.EmitLocalBlockVarDecl(*CatchParam);
5501 CGF.Builder.CreateStore(ExcObject, CGF.GetAddrOfLocalVar(CatchParam));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005502 }
5503
5504 CGF.ObjCEHValueStack.push_back(ExcObject);
5505 CGF.EmitStmt(CatchBody);
5506 CGF.ObjCEHValueStack.pop_back();
5507
5508 CGF.EmitBranchThroughCleanup(FinallyEnd);
5509
5510 CGF.EmitBlock(MatchHandler);
5511
5512 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5513 // We are required to emit this call to satisfy LLVM, even
5514 // though we don't use the result.
5515 llvm::SmallVector<llvm::Value*, 8> Args;
5516 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005517 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005518 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5519 0));
5520 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5521 CGF.Builder.CreateStore(Exc, RethrowPtr);
5522 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5523
5524 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5525
5526 CGF.EmitBlock(MatchEnd);
5527
5528 // Unfortunately, we also have to generate another EH frame here
5529 // in case this throws.
5530 llvm::BasicBlock *MatchEndHandler =
5531 CGF.createBasicBlock("match.end.handler");
5532 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
Chris Lattner8a569112009-04-22 02:15:23 +00005533 CGF.Builder.CreateInvoke(ObjCTypes.getObjCEndCatchFn(),
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005534 Cont, MatchEndHandler,
5535 Args.begin(), Args.begin());
5536
5537 CGF.EmitBlock(Cont);
5538 if (Info.SwitchBlock)
5539 CGF.EmitBlock(Info.SwitchBlock);
5540 if (Info.EndBlock)
5541 CGF.EmitBlock(Info.EndBlock);
5542
5543 CGF.EmitBlock(MatchEndHandler);
5544 Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5545 // We are required to emit this call to satisfy LLVM, even
5546 // though we don't use the result.
5547 Args.clear();
5548 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005549 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005550 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5551 0));
5552 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5553 CGF.Builder.CreateStore(Exc, RethrowPtr);
5554 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5555
5556 if (Next)
5557 CGF.EmitBlock(Next);
5558 } else {
5559 assert(!Next && "catchup should be last handler.");
5560
5561 CGF.Builder.CreateStore(Exc, RethrowPtr);
5562 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5563 }
5564 }
5565
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005566 // Pop the cleanup entry, the @finally is outside this cleanup
5567 // scope.
5568 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5569 CGF.setInvokeDest(PrevLandingPad);
5570
5571 CGF.EmitBlock(FinallyBlock);
5572
5573 if (isTry) {
5574 if (const ObjCAtFinallyStmt* FinallyStmt =
5575 cast<ObjCAtTryStmt>(S).getFinallyStmt())
5576 CGF.EmitStmt(FinallyStmt->getFinallyBody());
5577 } else {
5578 // Emit 'objc_sync_exit(expr)' as finally's sole statement for
5579 // @synchronized.
Chris Lattnerbbccd612009-04-22 02:38:11 +00005580 CGF.Builder.CreateCall(ObjCTypes.getSyncExitFn(), SyncArg);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005581 }
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005582
5583 if (Info.SwitchBlock)
5584 CGF.EmitBlock(Info.SwitchBlock);
5585 if (Info.EndBlock)
5586 CGF.EmitBlock(Info.EndBlock);
5587
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005588 // Branch around the rethrow code.
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005589 CGF.EmitBranch(FinallyEnd);
5590
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005591 CGF.EmitBlock(FinallyRethrow);
Chris Lattner8a569112009-04-22 02:15:23 +00005592 CGF.Builder.CreateCall(ObjCTypes.getUnwindResumeOrRethrowFn(),
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005593 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005594 CGF.Builder.CreateUnreachable();
5595
5596 CGF.EmitBlock(FinallyEnd);
5597}
5598
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005599/// EmitThrowStmt - Generate code for a throw statement.
5600void CGObjCNonFragileABIMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
5601 const ObjCAtThrowStmt &S) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005602 llvm::Value *Exception;
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005603 if (const Expr *ThrowExpr = S.getThrowExpr()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005604 Exception = CGF.EmitScalarExpr(ThrowExpr);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005605 } else {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005606 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
5607 "Unexpected rethrow outside @catch block.");
5608 Exception = CGF.ObjCEHValueStack.back();
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005609 }
5610
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005611 llvm::Value *ExceptionAsObject =
5612 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
5613 llvm::BasicBlock *InvokeDest = CGF.getInvokeDest();
5614 if (InvokeDest) {
5615 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
Chris Lattnerbbccd612009-04-22 02:38:11 +00005616 CGF.Builder.CreateInvoke(ObjCTypes.getExceptionThrowFn(),
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005617 Cont, InvokeDest,
5618 &ExceptionAsObject, &ExceptionAsObject + 1);
5619 CGF.EmitBlock(Cont);
5620 } else
Chris Lattnerbbccd612009-04-22 02:38:11 +00005621 CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(), ExceptionAsObject);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005622 CGF.Builder.CreateUnreachable();
5623
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005624 // Clear the insertion point to indicate we are in unreachable code.
5625 CGF.Builder.ClearInsertionPoint();
5626}
Daniel Dunbare588b992009-03-01 04:46:24 +00005627
5628llvm::Value *
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005629CGObjCNonFragileABIMac::GetInterfaceEHType(const ObjCInterfaceDecl *ID,
5630 bool ForDefinition) {
Daniel Dunbare588b992009-03-01 04:46:24 +00005631 llvm::GlobalVariable * &Entry = EHTypeReferences[ID->getIdentifier()];
Daniel Dunbare588b992009-03-01 04:46:24 +00005632
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005633 // If we don't need a definition, return the entry if found or check
5634 // if we use an external reference.
5635 if (!ForDefinition) {
5636 if (Entry)
5637 return Entry;
Daniel Dunbar7e075cb2009-04-07 06:43:45 +00005638
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005639 // If this type (or a super class) has the __objc_exception__
5640 // attribute, emit an external reference.
5641 if (hasObjCExceptionAttribute(ID))
5642 return Entry =
5643 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5644 llvm::GlobalValue::ExternalLinkage,
5645 0,
5646 (std::string("OBJC_EHTYPE_$_") +
5647 ID->getIdentifier()->getName()),
5648 &CGM.getModule());
5649 }
5650
5651 // Otherwise we need to either make a new entry or fill in the
5652 // initializer.
5653 assert((!Entry || !Entry->hasInitializer()) && "Duplicate EHType definition");
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005654 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbare588b992009-03-01 04:46:24 +00005655 std::string VTableName = "objc_ehtype_vtable";
5656 llvm::GlobalVariable *VTableGV =
5657 CGM.getModule().getGlobalVariable(VTableName);
5658 if (!VTableGV)
5659 VTableGV = new llvm::GlobalVariable(ObjCTypes.Int8PtrTy, false,
5660 llvm::GlobalValue::ExternalLinkage,
5661 0, VTableName, &CGM.getModule());
5662
5663 llvm::Value *VTableIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, 2);
5664
5665 std::vector<llvm::Constant*> Values(3);
5666 Values[0] = llvm::ConstantExpr::getGetElementPtr(VTableGV, &VTableIdx, 1);
5667 Values[1] = GetClassName(ID->getIdentifier());
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005668 Values[2] = GetClassGlobal(ClassName);
Daniel Dunbare588b992009-03-01 04:46:24 +00005669 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.EHTypeTy, Values);
5670
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005671 if (Entry) {
5672 Entry->setInitializer(Init);
5673 } else {
5674 Entry = new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5675 llvm::GlobalValue::WeakAnyLinkage,
5676 Init,
5677 (std::string("OBJC_EHTYPE_$_") +
5678 ID->getIdentifier()->getName()),
5679 &CGM.getModule());
5680 }
5681
Daniel Dunbar04d40782009-04-14 06:00:08 +00005682 if (CGM.getLangOptions().getVisibilityMode() == LangOptions::Hidden)
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005683 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005684 Entry->setAlignment(8);
5685
5686 if (ForDefinition) {
5687 Entry->setSection("__DATA,__objc_const");
5688 Entry->setLinkage(llvm::GlobalValue::ExternalLinkage);
5689 } else {
5690 Entry->setSection("__DATA,__datacoal_nt,coalesced");
5691 }
Daniel Dunbare588b992009-03-01 04:46:24 +00005692
5693 return Entry;
5694}
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005695
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00005696/* *** */
5697
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00005698CodeGen::CGObjCRuntime *
5699CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00005700 return new CGObjCMac(CGM);
5701}
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005702
5703CodeGen::CGObjCRuntime *
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00005704CodeGen::CreateMacNonFragileABIObjCRuntime(CodeGen::CodeGenModule &CGM) {
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00005705 return new CGObjCNonFragileABIMac(CGM);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005706}