blob: 4294ddf8e4859c81665b3cae12ebdc5ac7425772 [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:
Chris Lattner74391b42009-03-22 21:03:39 +0000402 llvm::Constant *MessageSendFixupFn, *MessageSendFpretFixupFn,
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000403 *MessageSendStretFixupFn, *MessageSendIdFixupFn,
404 *MessageSendIdStretFixupFn, *MessageSendSuper2FixupFn,
405 *MessageSendSuper2StretFixupFn;
406
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000407 // MethodListnfABITy - LLVM for struct _method_list_t
408 const llvm::StructType *MethodListnfABITy;
409
410 // MethodListnfABIPtrTy - LLVM for struct _method_list_t*
411 const llvm::Type *MethodListnfABIPtrTy;
412
413 // ProtocolnfABITy = LLVM for struct _protocol_t
414 const llvm::StructType *ProtocolnfABITy;
415
Daniel Dunbar948e2582009-02-15 07:36:20 +0000416 // ProtocolnfABIPtrTy = LLVM for struct _protocol_t*
417 const llvm::Type *ProtocolnfABIPtrTy;
418
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000419 // ProtocolListnfABITy - LLVM for struct _objc_protocol_list
420 const llvm::StructType *ProtocolListnfABITy;
421
422 // ProtocolListnfABIPtrTy - LLVM for struct _objc_protocol_list*
423 const llvm::Type *ProtocolListnfABIPtrTy;
424
425 // ClassnfABITy - LLVM for struct _class_t
426 const llvm::StructType *ClassnfABITy;
427
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000428 // ClassnfABIPtrTy - LLVM for struct _class_t*
429 const llvm::Type *ClassnfABIPtrTy;
430
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000431 // IvarnfABITy - LLVM for struct _ivar_t
432 const llvm::StructType *IvarnfABITy;
433
434 // IvarListnfABITy - LLVM for struct _ivar_list_t
435 const llvm::StructType *IvarListnfABITy;
436
437 // IvarListnfABIPtrTy = LLVM for struct _ivar_list_t*
438 const llvm::Type *IvarListnfABIPtrTy;
439
440 // ClassRonfABITy - LLVM for struct _class_ro_t
441 const llvm::StructType *ClassRonfABITy;
442
443 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
444 const llvm::Type *ImpnfABITy;
445
446 // CategorynfABITy - LLVM for struct _category_t
447 const llvm::StructType *CategorynfABITy;
448
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000449 // New types for nonfragile abi messaging.
450
451 // MessageRefTy - LLVM for:
452 // struct _message_ref_t {
453 // IMP messenger;
454 // SEL name;
455 // };
456 const llvm::StructType *MessageRefTy;
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000457 // MessageRefCTy - clang type for struct _message_ref_t
458 QualType MessageRefCTy;
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000459
460 // MessageRefPtrTy - LLVM for struct _message_ref_t*
461 const llvm::Type *MessageRefPtrTy;
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000462 // MessageRefCPtrTy - clang type for struct _message_ref_t*
463 QualType MessageRefCPtrTy;
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000464
Fariborz Jahanianef163782009-02-05 01:13:09 +0000465 // MessengerTy - Type of the messenger (shown as IMP above)
466 const llvm::FunctionType *MessengerTy;
467
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000468 // SuperMessageRefTy - LLVM for:
469 // struct _super_message_ref_t {
470 // SUPER_IMP messenger;
471 // SEL name;
472 // };
473 const llvm::StructType *SuperMessageRefTy;
474
475 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
476 const llvm::Type *SuperMessageRefPtrTy;
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000477
478 /// EHPersonalityPtr - LLVM value for an i8* to the Objective-C
479 /// exception personality function.
Chris Lattnerb02e53b2009-04-06 16:53:45 +0000480 llvm::Value *getEHPersonalityPtr() {
481 llvm::Constant *Personality =
482 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
483 std::vector<const llvm::Type*>(),
484 true),
485 "__objc_personality_v0");
486 return llvm::ConstantExpr::getBitCast(Personality, Int8PtrTy);
487 }
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000488
Chris Lattner8a569112009-04-22 02:15:23 +0000489 llvm::Constant *getUnwindResumeOrRethrowFn() {
490 std::vector<const llvm::Type*> Params;
491 Params.push_back(Int8PtrTy);
492 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
493 Params, false),
494 "_Unwind_Resume_or_Rethrow");
495 }
496
497 llvm::Constant *getObjCEndCatchFn() {
498 std::vector<const llvm::Type*> Params;
499 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
500 Params, false),
501 "objc_end_catch");
502
503 }
504
505 llvm::Constant *getObjCBeginCatchFn() {
506 std::vector<const llvm::Type*> Params;
507 Params.push_back(Int8PtrTy);
508 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(Int8PtrTy,
509 Params, false),
510 "objc_begin_catch");
511 }
Daniel Dunbare588b992009-03-01 04:46:24 +0000512
513 const llvm::StructType *EHTypeTy;
514 const llvm::Type *EHTypePtrTy;
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000515
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000516 ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm);
517 ~ObjCNonFragileABITypesHelper(){}
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000518};
519
520class CGObjCCommonMac : public CodeGen::CGObjCRuntime {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000521public:
522 // FIXME - accessibility
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000523 class GC_IVAR {
Fariborz Jahanian820e0202009-03-11 00:07:04 +0000524 public:
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000525 unsigned int ivar_bytepos;
526 unsigned int ivar_size;
527 GC_IVAR() : ivar_bytepos(0), ivar_size(0) {}
528 };
529
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000530 class SKIP_SCAN {
531 public:
532 unsigned int skip;
533 unsigned int scan;
534 SKIP_SCAN() : skip(0), scan(0) {}
535 };
536
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000537protected:
538 CodeGen::CodeGenModule &CGM;
539 // FIXME! May not be needing this after all.
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000540 unsigned ObjCABI;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000541
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000542 // gc ivar layout bitmap calculation helper caches.
543 llvm::SmallVector<GC_IVAR, 16> SkipIvars;
544 llvm::SmallVector<GC_IVAR, 16> IvarsInfo;
545 llvm::SmallVector<SKIP_SCAN, 32> SkipScanIvars;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000546
Daniel Dunbar242d4dc2008-08-25 06:02:07 +0000547 /// LazySymbols - Symbols to generate a lazy reference for. See
548 /// DefinedSymbols and FinishModule().
549 std::set<IdentifierInfo*> LazySymbols;
550
551 /// DefinedSymbols - External symbols which are defined by this
552 /// module. The symbols in this list and LazySymbols are used to add
553 /// special linker symbols which ensure that Objective-C modules are
554 /// linked properly.
555 std::set<IdentifierInfo*> DefinedSymbols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000556
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000557 /// ClassNames - uniqued class names.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000558 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000559
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000560 /// MethodVarNames - uniqued method variable names.
561 llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000562
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000563 /// MethodVarTypes - uniqued method type signatures. We have to use
564 /// a StringMap here because have no other unique reference.
565 llvm::StringMap<llvm::GlobalVariable*> MethodVarTypes;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000566
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000567 /// MethodDefinitions - map of methods which have been defined in
568 /// this translation unit.
569 llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> MethodDefinitions;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000570
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000571 /// PropertyNames - uniqued method variable names.
572 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000573
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000574 /// ClassReferences - uniqued class references.
575 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000576
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000577 /// SelectorReferences - uniqued selector references.
578 llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000579
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000580 /// Protocols - Protocols for which an objc_protocol structure has
581 /// been emitted. Forward declarations are handled by creating an
582 /// empty structure whose initializer is filled in when/if defined.
583 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> Protocols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000584
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000585 /// DefinedProtocols - Protocols which have actually been
586 /// defined. We should not need this, see FIXME in GenerateProtocol.
587 llvm::DenseSet<IdentifierInfo*> DefinedProtocols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000588
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000589 /// DefinedClasses - List of defined classes.
590 std::vector<llvm::GlobalValue*> DefinedClasses;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000591
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000592 /// DefinedCategories - List of defined categories.
593 std::vector<llvm::GlobalValue*> DefinedCategories;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000594
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000595 /// UsedGlobals - List of globals to pack into the llvm.used metadata
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000596 /// to prevent them from being clobbered.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000597 std::vector<llvm::GlobalVariable*> UsedGlobals;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000598
Fariborz Jahanian56210f72009-01-21 23:34:32 +0000599 /// GetNameForMethod - Return a name for the given method.
600 /// \param[out] NameOut - The return value.
601 void GetNameForMethod(const ObjCMethodDecl *OMD,
602 const ObjCContainerDecl *CD,
603 std::string &NameOut);
604
605 /// GetMethodVarName - Return a unique constant for the given
606 /// selector's name. The return value has type char *.
607 llvm::Constant *GetMethodVarName(Selector Sel);
608 llvm::Constant *GetMethodVarName(IdentifierInfo *Ident);
609 llvm::Constant *GetMethodVarName(const std::string &Name);
610
611 /// GetMethodVarType - Return a unique constant for the given
612 /// selector's name. The return value has type char *.
613
614 // FIXME: This is a horrible name.
615 llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D);
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +0000616 llvm::Constant *GetMethodVarType(const FieldDecl *D);
Fariborz Jahanian56210f72009-01-21 23:34:32 +0000617
618 /// GetPropertyName - Return a unique constant for the given
619 /// name. The return value has type char *.
620 llvm::Constant *GetPropertyName(IdentifierInfo *Ident);
621
622 // FIXME: This can be dropped once string functions are unified.
623 llvm::Constant *GetPropertyTypeString(const ObjCPropertyDecl *PD,
624 const Decl *Container);
625
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000626 /// GetClassName - Return a unique constant for the given selector's
627 /// name. The return value has type char *.
628 llvm::Constant *GetClassName(IdentifierInfo *Ident);
629
Fariborz Jahanian21e6f172009-03-11 21:42:00 +0000630 /// GetInterfaceDeclStructLayout - Get layout for ivars of given
631 /// interface declaration.
632 const llvm::StructLayout *GetInterfaceDeclStructLayout(
633 const ObjCInterfaceDecl *ID) const;
634
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000635 /// BuildIvarLayout - Builds ivar layout bitmap for the class
636 /// implementation for the __strong or __weak case.
637 ///
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000638 llvm::Constant *BuildIvarLayout(const ObjCImplementationDecl *OI,
639 bool ForStrongLayout);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000640
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000641 void BuildAggrIvarLayout(const ObjCInterfaceDecl *OI,
642 const llvm::StructLayout *Layout,
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000643 const RecordDecl *RD,
Chris Lattnerf1690852009-03-31 08:48:01 +0000644 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000645 unsigned int BytePos, bool ForStrongLayout,
646 int &Index, int &SkIndex, bool &HasUnion);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000647
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +0000648 /// GetIvarLayoutName - Returns a unique constant for the given
649 /// ivar layout bitmap.
650 llvm::Constant *GetIvarLayoutName(IdentifierInfo *Ident,
651 const ObjCCommonTypesHelper &ObjCTypes);
652
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +0000653 /// EmitPropertyList - Emit the given property list. The return
654 /// value has type PropertyListPtrTy.
655 llvm::Constant *EmitPropertyList(const std::string &Name,
656 const Decl *Container,
657 const ObjCContainerDecl *OCD,
658 const ObjCCommonTypesHelper &ObjCTypes);
659
Fariborz Jahanianda320092009-01-29 19:24:30 +0000660 /// GetProtocolRef - Return a reference to the internal protocol
661 /// description, creating an empty one if it has not been
662 /// defined. The return value has type ProtocolPtrTy.
663 llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +0000664
665 /// GetIvarBaseOffset - returns ivars byte offset.
666 uint64_t GetIvarBaseOffset(const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +0000667 const FieldDecl *Field);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000668
Chris Lattnercd0ee142009-03-31 08:33:16 +0000669 /// GetFieldBaseOffset - return's field byte offset.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000670 uint64_t GetFieldBaseOffset(const ObjCInterfaceDecl *OI,
671 const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +0000672 const FieldDecl *Field);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000673
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000674 /// CreateMetadataVar - Create a global variable with internal
675 /// linkage for use by the Objective-C runtime.
676 ///
677 /// This is a convenience wrapper which not only creates the
678 /// variable, but also sets the section and alignment and adds the
679 /// global to the UsedGlobals list.
Daniel Dunbar35bd7632009-03-09 20:50:13 +0000680 ///
681 /// \param Name - The variable name.
682 /// \param Init - The variable initializer; this is also used to
683 /// define the type of the variable.
684 /// \param Section - The section the variable should go into, or 0.
685 /// \param Align - The alignment for the variable, or 0.
686 /// \param AddToUsed - Whether the variable should be added to
Daniel Dunbarc1583062009-04-14 17:42:51 +0000687 /// "llvm.used".
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000688 llvm::GlobalVariable *CreateMetadataVar(const std::string &Name,
689 llvm::Constant *Init,
690 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +0000691 unsigned Align,
692 bool AddToUsed);
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000693
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +0000694 /// GetNamedIvarList - Return the list of ivars in the interface
695 /// itself (not including super classes and not including unnamed
696 /// bitfields).
697 ///
698 /// For the non-fragile ABI, this also includes synthesized property
699 /// ivars.
700 void GetNamedIvarList(const ObjCInterfaceDecl *OID,
701 llvm::SmallVector<ObjCIvarDecl*, 16> &Res) const;
702
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000703public:
704 CGObjCCommonMac(CodeGen::CodeGenModule &cgm) : CGM(cgm)
705 { }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000706
Steve Naroff33fdb732009-03-31 16:53:37 +0000707 virtual llvm::Constant *GenerateConstantString(const ObjCStringLiteral *SL);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000708
709 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
710 const ObjCContainerDecl *CD=0);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000711
712 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
713
714 /// GetOrEmitProtocol - Get the protocol object for the given
715 /// declaration, emitting it if necessary. The return value has type
716 /// ProtocolPtrTy.
717 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD)=0;
718
719 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
720 /// object for the given declaration, emitting it if needed. These
721 /// forward references will be filled in with empty bodies if no
722 /// definition is seen. The return value has type ProtocolPtrTy.
723 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD)=0;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000724};
725
726class CGObjCMac : public CGObjCCommonMac {
727private:
728 ObjCTypesHelper ObjCTypes;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000729 /// EmitImageInfo - Emit the image info marker used to encode some module
730 /// level information.
731 void EmitImageInfo();
732
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000733 /// EmitModuleInfo - Another marker encoding module level
734 /// information.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000735 void EmitModuleInfo();
736
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000737 /// EmitModuleSymols - Emit module symbols, the list of defined
738 /// classes and categories. The result has type SymtabPtrTy.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000739 llvm::Constant *EmitModuleSymbols();
740
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000741 /// FinishModule - Write out global data structures at the end of
742 /// processing a translation unit.
743 void FinishModule();
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000744
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000745 /// EmitClassExtension - Generate the class extension structure used
746 /// to store the weak ivar layout and properties. The return value
747 /// has type ClassExtensionPtrTy.
748 llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID);
749
750 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
751 /// for the given class.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000752 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000753 const ObjCInterfaceDecl *ID);
754
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000755 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000756 QualType ResultType,
757 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000758 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000759 QualType Arg0Ty,
760 bool IsSuper,
761 const CallArgList &CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000762
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000763 /// EmitIvarList - Emit the ivar list for the given
764 /// implementation. If ForClass is true the list of class ivars
765 /// (i.e. metaclass ivars) is emitted, otherwise the list of
766 /// interface ivars will be emitted. The return value has type
767 /// IvarListPtrTy.
768 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +0000769 bool ForClass);
770
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000771 /// EmitMetaClass - Emit a forward reference to the class structure
772 /// for the metaclass of the given interface. The return value has
773 /// type ClassPtrTy.
774 llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
775
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000776 /// EmitMetaClass - Emit a class structure for the metaclass of the
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000777 /// given implementation. The return value has type ClassPtrTy.
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000778 llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
779 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000780 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000781 const ConstantVector &Methods);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000782
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000783 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000784
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000785 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000786
787 /// EmitMethodList - Emit the method list for the given
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000788 /// implementation. The return value has type MethodListPtrTy.
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000789 llvm::Constant *EmitMethodList(const std::string &Name,
790 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000791 const ConstantVector &Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000792
793 /// EmitMethodDescList - Emit a method description list for a list of
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000794 /// method declarations.
795 /// - TypeName: The name for the type containing the methods.
796 /// - IsProtocol: True iff these methods are for a protocol.
797 /// - ClassMethds: True iff these are class methods.
798 /// - Required: When true, only "required" methods are
799 /// listed. Similarly, when false only "optional" methods are
800 /// listed. For classes this should always be true.
801 /// - begin, end: The method list to output.
802 ///
803 /// The return value has type MethodDescriptionListPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000804 llvm::Constant *EmitMethodDescList(const std::string &Name,
805 const char *Section,
806 const ConstantVector &Methods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000807
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000808 /// GetOrEmitProtocol - Get the protocol object for the given
809 /// declaration, emitting it if necessary. The return value has type
810 /// ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +0000811 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000812
813 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
814 /// object for the given declaration, emitting it if needed. These
815 /// forward references will be filled in with empty bodies if no
816 /// definition is seen. The return value has type ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +0000817 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000818
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000819 /// EmitProtocolExtension - Generate the protocol extension
820 /// structure used to store optional instance and class methods, and
821 /// protocol properties. The return value has type
822 /// ProtocolExtensionPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000823 llvm::Constant *
824 EmitProtocolExtension(const ObjCProtocolDecl *PD,
825 const ConstantVector &OptInstanceMethods,
826 const ConstantVector &OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000827
828 /// EmitProtocolList - Generate the list of referenced
829 /// protocols. The return value has type ProtocolListPtrTy.
Daniel Dunbardbc933702008-08-21 21:57:41 +0000830 llvm::Constant *EmitProtocolList(const std::string &Name,
831 ObjCProtocolDecl::protocol_iterator begin,
832 ObjCProtocolDecl::protocol_iterator end);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000833
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000834 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
835 /// for the given selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000836 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000837
Fariborz Jahanianda320092009-01-29 19:24:30 +0000838 public:
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000839 CGObjCMac(CodeGen::CodeGenModule &cgm);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000840
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000841 virtual llvm::Function *ModuleInitFunction();
842
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000843 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000844 QualType ResultType,
845 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000846 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000847 bool IsClassMessage,
848 const CallArgList &CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000849
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000850 virtual CodeGen::RValue
851 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000852 QualType ResultType,
853 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000854 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000855 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000856 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000857 bool IsClassMessage,
858 const CallArgList &CallArgs);
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000859
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000860 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000861 const ObjCInterfaceDecl *ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000862
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000863 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000864
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000865 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000866
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000867 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000868
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000869 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000870 const ObjCProtocolDecl *PD);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000871
Chris Lattner74391b42009-03-22 21:03:39 +0000872 virtual llvm::Constant *GetPropertyGetFunction();
873 virtual llvm::Constant *GetPropertySetFunction();
874 virtual llvm::Constant *EnumerationMutationFunction();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000875
Fariborz Jahanianbd71be42008-11-21 00:49:24 +0000876 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
877 const Stmt &S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000878 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
879 const ObjCAtThrowStmt &S);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000880 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +0000881 llvm::Value *AddrWeakObj);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000882 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
883 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000884 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
885 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian7eda8362008-11-20 19:23:36 +0000886 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
887 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000888 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
889 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian0bb20362009-02-02 20:02:29 +0000890
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000891 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
892 QualType ObjectTy,
893 llvm::Value *BaseValue,
894 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000895 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000896 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
897 ObjCInterfaceDecl *Interface,
898 const ObjCIvarDecl *Ivar);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000899};
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000900
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000901class CGObjCNonFragileABIMac : public CGObjCCommonMac {
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000902private:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000903 ObjCNonFragileABITypesHelper ObjCTypes;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000904 llvm::GlobalVariable* ObjCEmptyCacheVar;
905 llvm::GlobalVariable* ObjCEmptyVtableVar;
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000906
Daniel Dunbar11394522009-04-18 08:51:00 +0000907 /// SuperClassReferences - uniqued super class references.
908 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> SuperClassReferences;
909
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000910 /// MetaClassReferences - uniqued meta class references.
911 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> MetaClassReferences;
Daniel Dunbare588b992009-03-01 04:46:24 +0000912
913 /// EHTypeReferences - uniqued class ehtype references.
914 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> EHTypeReferences;
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000915
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000916 /// FinishNonFragileABIModule - Write out global data structures at the end of
917 /// processing a translation unit.
918 void FinishNonFragileABIModule();
Daniel Dunbar8158a2f2009-04-08 04:21:03 +0000919
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000920 llvm::GlobalVariable * BuildClassRoTInitializer(unsigned flags,
921 unsigned InstanceStart,
922 unsigned InstanceSize,
923 const ObjCImplementationDecl *ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +0000924 llvm::GlobalVariable * BuildClassMetaData(std::string &ClassName,
925 llvm::Constant *IsAGV,
926 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +0000927 llvm::Constant *ClassRoGV,
928 bool HiddenVisibility);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000929
930 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
931
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +0000932 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
933
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000934 /// EmitMethodList - Emit the method list for the given
935 /// implementation. The return value has type MethodListnfABITy.
936 llvm::Constant *EmitMethodList(const std::string &Name,
937 const char *Section,
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +0000938 const ConstantVector &Methods);
939 /// EmitIvarList - Emit the ivar list for the given
940 /// implementation. If ForClass is true the list of class ivars
941 /// (i.e. metaclass ivars) is emitted, otherwise the list of
942 /// interface ivars will be emitted. The return value has type
943 /// IvarListnfABIPtrTy.
944 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000945
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000946 llvm::Constant *EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +0000947 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +0000948 unsigned long int offset);
949
Fariborz Jahanianda320092009-01-29 19:24:30 +0000950 /// GetOrEmitProtocol - Get the protocol object for the given
951 /// declaration, emitting it if necessary. The return value has type
952 /// ProtocolPtrTy.
953 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
954
955 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
956 /// object for the given declaration, emitting it if needed. These
957 /// forward references will be filled in with empty bodies if no
958 /// definition is seen. The return value has type ProtocolPtrTy.
959 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
960
961 /// EmitProtocolList - Generate the list of referenced
962 /// protocols. The return value has type ProtocolListPtrTy.
963 llvm::Constant *EmitProtocolList(const std::string &Name,
964 ObjCProtocolDecl::protocol_iterator begin,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000965 ObjCProtocolDecl::protocol_iterator end);
966
967 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
968 QualType ResultType,
969 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000970 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000971 QualType Arg0Ty,
972 bool IsSuper,
973 const CallArgList &CallArgs);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +0000974
975 /// GetClassGlobal - Return the global variable for the Objective-C
976 /// class of the given name.
Fariborz Jahanian0f902942009-04-14 18:41:56 +0000977 llvm::GlobalVariable *GetClassGlobal(const std::string &Name);
978
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000979 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
Daniel Dunbar11394522009-04-18 08:51:00 +0000980 /// for the given class reference.
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000981 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar11394522009-04-18 08:51:00 +0000982 const ObjCInterfaceDecl *ID);
983
984 /// EmitSuperClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
985 /// for the given super class reference.
986 llvm::Value *EmitSuperClassRef(CGBuilderTy &Builder,
987 const ObjCInterfaceDecl *ID);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000988
989 /// EmitMetaClassRef - Return a Value * of the address of _class_t
990 /// meta-data
991 llvm::Value *EmitMetaClassRef(CGBuilderTy &Builder,
992 const ObjCInterfaceDecl *ID);
993
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000994 /// ObjCIvarOffsetVariable - Returns the ivar offset variable for
995 /// the given ivar.
996 ///
Daniel Dunbar5e88bea2009-04-19 00:31:15 +0000997 llvm::GlobalVariable * ObjCIvarOffsetVariable(
Fariborz Jahanian01a0c362009-02-12 18:51:23 +0000998 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000999 const ObjCIvarDecl *Ivar);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00001000
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00001001 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
1002 /// for the given selector.
1003 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbare588b992009-03-01 04:46:24 +00001004
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001005 /// GetInterfaceEHType - Get the cached ehtype for the given Objective-C
Daniel Dunbare588b992009-03-01 04:46:24 +00001006 /// interface. The return value has type EHTypePtrTy.
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001007 llvm::Value *GetInterfaceEHType(const ObjCInterfaceDecl *ID,
1008 bool ForDefinition);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00001009
1010 const char *getMetaclassSymbolPrefix() const {
1011 return "OBJC_METACLASS_$_";
1012 }
Daniel Dunbar4ff36842009-03-02 06:08:11 +00001013
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00001014 const char *getClassSymbolPrefix() const {
1015 return "OBJC_CLASS_$_";
1016 }
1017
Daniel Dunbarb02532a2009-04-19 23:41:48 +00001018 void GetClassSizeInfo(const ObjCInterfaceDecl *OID,
1019 uint32_t &InstanceStart,
1020 uint32_t &InstanceSize);
1021
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001022public:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00001023 CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001024 // FIXME. All stubs for now!
1025 virtual llvm::Function *ModuleInitFunction();
1026
1027 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
1028 QualType ResultType,
1029 Selector Sel,
1030 llvm::Value *Receiver,
1031 bool IsClassMessage,
Fariborz Jahanian46551122009-02-04 00:22:57 +00001032 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001033
1034 virtual CodeGen::RValue
1035 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
1036 QualType ResultType,
1037 Selector Sel,
1038 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00001039 bool isCategoryImpl,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001040 llvm::Value *Receiver,
1041 bool IsClassMessage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00001042 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001043
1044 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00001045 const ObjCInterfaceDecl *ID);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001046
1047 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel)
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00001048 { return EmitSelector(Builder, Sel); }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001049
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00001050 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001051
1052 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001053 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00001054 const ObjCProtocolDecl *PD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001055
Chris Lattner74391b42009-03-22 21:03:39 +00001056 virtual llvm::Constant *GetPropertyGetFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00001057 return ObjCTypes.getGetPropertyFn();
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001058 }
Chris Lattner74391b42009-03-22 21:03:39 +00001059 virtual llvm::Constant *GetPropertySetFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00001060 return ObjCTypes.getSetPropertyFn();
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001061 }
Chris Lattner74391b42009-03-22 21:03:39 +00001062 virtual llvm::Constant *EnumerationMutationFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00001063 return ObjCTypes.getEnumerationMutationFn();
Daniel Dunbar28ed0842009-02-16 18:48:45 +00001064 }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001065
1066 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00001067 const Stmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001068 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Anders Carlssonf57c5b22009-02-16 22:59:18 +00001069 const ObjCAtThrowStmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001070 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001071 llvm::Value *AddrWeakObj);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001072 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001073 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001074 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001075 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001076 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001077 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001078 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001079 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00001080 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
1081 QualType ObjectTy,
1082 llvm::Value *BaseValue,
1083 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00001084 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001085 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
1086 ObjCInterfaceDecl *Interface,
1087 const ObjCIvarDecl *Ivar);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001088};
1089
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001090} // end anonymous namespace
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001091
1092/* *** Helper Functions *** */
1093
1094/// getConstantGEP() - Help routine to construct simple GEPs.
1095static llvm::Constant *getConstantGEP(llvm::Constant *C,
1096 unsigned idx0,
1097 unsigned idx1) {
1098 llvm::Value *Idxs[] = {
1099 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx0),
1100 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx1)
1101 };
1102 return llvm::ConstantExpr::getGetElementPtr(C, Idxs, 2);
1103}
1104
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001105/// hasObjCExceptionAttribute - Return true if this class or any super
1106/// class has the __objc_exception__ attribute.
1107static bool hasObjCExceptionAttribute(const ObjCInterfaceDecl *OID) {
Daniel Dunbarb11fa0d2009-04-13 21:08:27 +00001108 if (OID->hasAttr<ObjCExceptionAttr>())
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001109 return true;
1110 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
1111 return hasObjCExceptionAttribute(Super);
1112 return false;
1113}
1114
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001115/* *** CGObjCMac Public Interface *** */
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001116
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001117CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm),
1118 ObjCTypes(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001119{
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001120 ObjCABI = 1;
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001121 EmitImageInfo();
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001122}
1123
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +00001124/// GetClass - Return a reference to the class for the given interface
1125/// decl.
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001126llvm::Value *CGObjCMac::GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001127 const ObjCInterfaceDecl *ID) {
1128 return EmitClassRef(Builder, ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001129}
1130
1131/// GetSelector - Return the pointer to the unique'd string for this selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001132llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00001133 return EmitSelector(Builder, Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001134}
1135
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001136/// Generate a constant CFString object.
1137/*
1138 struct __builtin_CFString {
1139 const int *isa; // point to __CFConstantStringClassReference
1140 int flags;
1141 const char *str;
1142 long length;
1143 };
1144*/
1145
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001146llvm::Constant *CGObjCCommonMac::GenerateConstantString(
Steve Naroff33fdb732009-03-31 16:53:37 +00001147 const ObjCStringLiteral *SL) {
Steve Naroff8d4141f2009-04-01 13:55:36 +00001148 return CGM.GetAddrOfConstantCFString(SL->getString());
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001149}
1150
1151/// Generates a message send where the super is the receiver. This is
1152/// a message send to self with special delivery semantics indicating
1153/// which class's method should be called.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +00001154CodeGen::RValue
1155CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001156 QualType ResultType,
1157 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001158 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00001159 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001160 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001161 bool IsClassMessage,
Daniel Dunbar46f45b92008-09-09 01:06:48 +00001162 const CodeGen::CallArgList &CallArgs) {
Daniel Dunbare8b470d2008-08-23 04:28:29 +00001163 // Create and init a super structure; this is a (receiver, class)
1164 // pair we will pass to objc_msgSendSuper.
1165 llvm::Value *ObjCSuper =
1166 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
1167 llvm::Value *ReceiverAsObject =
1168 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
1169 CGF.Builder.CreateStore(ReceiverAsObject,
1170 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
Daniel Dunbare8b470d2008-08-23 04:28:29 +00001171
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001172 // If this is a class message the metaclass is passed as the target.
1173 llvm::Value *Target;
1174 if (IsClassMessage) {
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00001175 if (isCategoryImpl) {
1176 // Message sent to 'super' in a class method defined in a category
1177 // implementation requires an odd treatment.
1178 // If we are in a class method, we must retrieve the
1179 // _metaclass_ for the current class, pointed at by
1180 // the class's "isa" pointer. The following assumes that
1181 // isa" is the first ivar in a class (which it must be).
1182 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
1183 Target = CGF.Builder.CreateStructGEP(Target, 0);
1184 Target = CGF.Builder.CreateLoad(Target);
1185 }
1186 else {
1187 llvm::Value *MetaClassPtr = EmitMetaClassRef(Class);
1188 llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1);
1189 llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr);
1190 Target = Super;
1191 }
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001192 } else {
1193 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
1194 }
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001195 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
1196 // and ObjCTypes types.
1197 const llvm::Type *ClassTy =
1198 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001199 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001200 CGF.Builder.CreateStore(Target,
1201 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
1202
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001203 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001204 ObjCSuper, ObjCTypes.SuperPtrCTy,
1205 true, CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001206}
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001207
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001208/// Generate code for a message send expression.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +00001209CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001210 QualType ResultType,
1211 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001212 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001213 bool IsClassMessage,
1214 const CallArgList &CallArgs) {
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001215 llvm::Value *Arg0 =
1216 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy, "tmp");
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001217 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001218 Arg0, CGF.getContext().getObjCIdType(),
1219 false, CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001220}
1221
1222CodeGen::RValue CGObjCMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001223 QualType ResultType,
1224 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001225 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001226 QualType Arg0Ty,
1227 bool IsSuper,
1228 const CallArgList &CallArgs) {
1229 CallArgList ActualArgs;
Daniel Dunbar46f45b92008-09-09 01:06:48 +00001230 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
1231 ActualArgs.push_back(std::make_pair(RValue::get(EmitSelector(CGF.Builder,
1232 Sel)),
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001233 CGF.getContext().getObjCSelType()));
1234 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001235
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001236 CodeGenTypes &Types = CGM.getTypes();
1237 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs);
1238 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo, false);
Daniel Dunbar5669e572008-10-17 03:24:53 +00001239
1240 llvm::Constant *Fn;
Daniel Dunbar88b53962009-02-02 22:03:45 +00001241 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Daniel Dunbar5669e572008-10-17 03:24:53 +00001242 Fn = ObjCTypes.getSendStretFn(IsSuper);
1243 } else if (ResultType->isFloatingType()) {
1244 // FIXME: Sadly, this is wrong. This actually depends on the
1245 // architecture. This happens to be right for x86-32 though.
1246 Fn = ObjCTypes.getSendFpretFn(IsSuper);
1247 } else {
1248 Fn = ObjCTypes.getSendFn(IsSuper);
1249 }
Daniel Dunbar62d5c1b2008-09-10 07:00:50 +00001250 Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy));
Daniel Dunbar88b53962009-02-02 22:03:45 +00001251 return CGF.EmitCall(FnInfo, Fn, ActualArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001252}
1253
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001254llvm::Value *CGObjCMac::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001255 const ObjCProtocolDecl *PD) {
Daniel Dunbarc67876d2008-09-04 04:33:15 +00001256 // FIXME: I don't understand why gcc generates this, or where it is
1257 // resolved. Investigate. Its also wasteful to look this up over and
1258 // over.
1259 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1260
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001261 return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
1262 ObjCTypes.ExternalProtocolPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001263}
1264
Fariborz Jahanianda320092009-01-29 19:24:30 +00001265void CGObjCCommonMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001266 // FIXME: We shouldn't need this, the protocol decl should contain
1267 // enough information to tell us whether this was a declaration or a
1268 // definition.
1269 DefinedProtocols.insert(PD->getIdentifier());
1270
1271 // If we have generated a forward reference to this protocol, emit
1272 // it now. Otherwise do nothing, the protocol objects are lazily
1273 // emitted.
1274 if (Protocols.count(PD->getIdentifier()))
1275 GetOrEmitProtocol(PD);
1276}
1277
Fariborz Jahanianda320092009-01-29 19:24:30 +00001278llvm::Constant *CGObjCCommonMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001279 if (DefinedProtocols.count(PD->getIdentifier()))
1280 return GetOrEmitProtocol(PD);
1281 return GetOrEmitProtocolRef(PD);
1282}
1283
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001284/*
1285 // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions
1286 struct _objc_protocol {
1287 struct _objc_protocol_extension *isa;
1288 char *protocol_name;
1289 struct _objc_protocol_list *protocol_list;
1290 struct _objc__method_prototype_list *instance_methods;
1291 struct _objc__method_prototype_list *class_methods
1292 };
1293
1294 See EmitProtocolExtension().
1295*/
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001296llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
1297 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1298
1299 // Early exit if a defining object has already been generated.
1300 if (Entry && Entry->hasInitializer())
1301 return Entry;
1302
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001303 // FIXME: I don't understand why gcc generates this, or where it is
1304 // resolved. Investigate. Its also wasteful to look this up over and
1305 // over.
1306 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1307
Chris Lattner8ec03f52008-11-24 03:54:41 +00001308 const char *ProtocolName = PD->getNameAsCString();
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001309
1310 // Construct method lists.
1311 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1312 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregor6ab35242009-04-09 21:40:53 +00001313 for (ObjCProtocolDecl::instmeth_iterator
1314 i = PD->instmeth_begin(CGM.getContext()),
1315 e = PD->instmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001316 ObjCMethodDecl *MD = *i;
1317 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1318 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1319 OptInstanceMethods.push_back(C);
1320 } else {
1321 InstanceMethods.push_back(C);
1322 }
1323 }
1324
Douglas Gregor6ab35242009-04-09 21:40:53 +00001325 for (ObjCProtocolDecl::classmeth_iterator
1326 i = PD->classmeth_begin(CGM.getContext()),
1327 e = PD->classmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001328 ObjCMethodDecl *MD = *i;
1329 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1330 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1331 OptClassMethods.push_back(C);
1332 } else {
1333 ClassMethods.push_back(C);
1334 }
1335 }
1336
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001337 std::vector<llvm::Constant*> Values(5);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001338 Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001339 Values[1] = GetClassName(PD->getIdentifier());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001340 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001341 EmitProtocolList("\01L_OBJC_PROTOCOL_REFS_" + PD->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001342 PD->protocol_begin(),
1343 PD->protocol_end());
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001344 Values[3] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001345 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_"
1346 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001347 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1348 InstanceMethods);
1349 Values[4] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001350 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_"
1351 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001352 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1353 ClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001354 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
1355 Values);
1356
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001357 if (Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001358 // Already created, fix the linkage and update the initializer.
1359 Entry->setLinkage(llvm::GlobalValue::InternalLinkage);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001360 Entry->setInitializer(Init);
1361 } else {
1362 Entry =
1363 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
1364 llvm::GlobalValue::InternalLinkage,
1365 Init,
1366 std::string("\01L_OBJC_PROTOCOL_")+ProtocolName,
1367 &CGM.getModule());
1368 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001369 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001370 UsedGlobals.push_back(Entry);
1371 // FIXME: Is this necessary? Why only for protocol?
1372 Entry->setAlignment(4);
1373 }
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001374
1375 return Entry;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001376}
1377
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001378llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001379 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1380
1381 if (!Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001382 // We use the initializer as a marker of whether this is a forward
1383 // reference or not. At module finalization we add the empty
1384 // contents for protocols which were referenced but never defined.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001385 Entry =
1386 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001387 llvm::GlobalValue::ExternalLinkage,
1388 0,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001389 "\01L_OBJC_PROTOCOL_" + PD->getNameAsString(),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001390 &CGM.getModule());
1391 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001392 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001393 UsedGlobals.push_back(Entry);
1394 // FIXME: Is this necessary? Why only for protocol?
1395 Entry->setAlignment(4);
1396 }
1397
1398 return Entry;
1399}
1400
1401/*
1402 struct _objc_protocol_extension {
1403 uint32_t size;
1404 struct objc_method_description_list *optional_instance_methods;
1405 struct objc_method_description_list *optional_class_methods;
1406 struct objc_property_list *instance_properties;
1407 };
1408*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001409llvm::Constant *
1410CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
1411 const ConstantVector &OptInstanceMethods,
1412 const ConstantVector &OptClassMethods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001413 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001414 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolExtensionTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001415 std::vector<llvm::Constant*> Values(4);
1416 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001417 Values[1] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001418 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_"
1419 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001420 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1421 OptInstanceMethods);
1422 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001423 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_"
1424 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001425 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1426 OptClassMethods);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001427 Values[3] = EmitPropertyList("\01L_OBJC_$_PROP_PROTO_LIST_" +
1428 PD->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001429 0, PD, ObjCTypes);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001430
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001431 // Return null if no extension bits are used.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001432 if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
1433 Values[3]->isNullValue())
1434 return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
1435
1436 llvm::Constant *Init =
1437 llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001438
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001439 // No special section, but goes in llvm.used
1440 return CreateMetadataVar("\01L_OBJC_PROTOCOLEXT_" + PD->getNameAsString(),
1441 Init,
1442 0, 0, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001443}
1444
1445/*
1446 struct objc_protocol_list {
1447 struct objc_protocol_list *next;
1448 long count;
1449 Protocol *list[];
1450 };
1451*/
Daniel Dunbardbc933702008-08-21 21:57:41 +00001452llvm::Constant *
1453CGObjCMac::EmitProtocolList(const std::string &Name,
1454 ObjCProtocolDecl::protocol_iterator begin,
1455 ObjCProtocolDecl::protocol_iterator end) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001456 std::vector<llvm::Constant*> ProtocolRefs;
1457
Daniel Dunbardbc933702008-08-21 21:57:41 +00001458 for (; begin != end; ++begin)
1459 ProtocolRefs.push_back(GetProtocolRef(*begin));
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001460
1461 // Just return null for empty protocol lists
1462 if (ProtocolRefs.empty())
1463 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1464
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001465 // This list is null terminated.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001466 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
1467
1468 std::vector<llvm::Constant*> Values(3);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001469 // This field is only used by the runtime.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001470 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1471 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
1472 Values[2] =
1473 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
1474 ProtocolRefs.size()),
1475 ProtocolRefs);
1476
1477 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1478 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001479 CreateMetadataVar(Name, Init, "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001480 4, false);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001481 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
1482}
1483
1484/*
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001485 struct _objc_property {
1486 const char * const name;
1487 const char * const attributes;
1488 };
1489
1490 struct _objc_property_list {
1491 uint32_t entsize; // sizeof (struct _objc_property)
1492 uint32_t prop_count;
1493 struct _objc_property[prop_count];
1494 };
1495*/
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001496llvm::Constant *CGObjCCommonMac::EmitPropertyList(const std::string &Name,
1497 const Decl *Container,
1498 const ObjCContainerDecl *OCD,
1499 const ObjCCommonTypesHelper &ObjCTypes) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001500 std::vector<llvm::Constant*> Properties, Prop(2);
Douglas Gregor6ab35242009-04-09 21:40:53 +00001501 for (ObjCContainerDecl::prop_iterator I = OCD->prop_begin(CGM.getContext()),
1502 E = OCD->prop_end(CGM.getContext()); I != E; ++I) {
Steve Naroff93983f82009-01-11 12:47:58 +00001503 const ObjCPropertyDecl *PD = *I;
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001504 Prop[0] = GetPropertyName(PD->getIdentifier());
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00001505 Prop[1] = GetPropertyTypeString(PD, Container);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001506 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
1507 Prop));
1508 }
1509
1510 // Return null for empty list.
1511 if (Properties.empty())
1512 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1513
1514 unsigned PropertySize =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001515 CGM.getTargetData().getTypePaddedSize(ObjCTypes.PropertyTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001516 std::vector<llvm::Constant*> Values(3);
1517 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
1518 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
1519 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
1520 Properties.size());
1521 Values[2] = llvm::ConstantArray::get(AT, Properties);
1522 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1523
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001524 llvm::GlobalVariable *GV =
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001525 CreateMetadataVar(Name, Init,
1526 (ObjCABI == 2) ? "__DATA, __objc_const" :
1527 "__OBJC,__property,regular,no_dead_strip",
1528 (ObjCABI == 2) ? 8 : 4,
1529 true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001530 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.PropertyListPtrTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001531}
1532
1533/*
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001534 struct objc_method_description_list {
1535 int count;
1536 struct objc_method_description list[];
1537 };
1538*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001539llvm::Constant *
1540CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
1541 std::vector<llvm::Constant*> Desc(2);
1542 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1543 ObjCTypes.SelectorPtrTy);
1544 Desc[1] = GetMethodVarType(MD);
1545 return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
1546 Desc);
1547}
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001548
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001549llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name,
1550 const char *Section,
1551 const ConstantVector &Methods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001552 // Return null for empty list.
1553 if (Methods.empty())
1554 return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
1555
1556 std::vector<llvm::Constant*> Values(2);
1557 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1558 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
1559 Methods.size());
1560 Values[1] = llvm::ConstantArray::get(AT, Methods);
1561 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1562
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001563 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001564 return llvm::ConstantExpr::getBitCast(GV,
1565 ObjCTypes.MethodDescriptionListPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001566}
1567
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001568/*
1569 struct _objc_category {
1570 char *category_name;
1571 char *class_name;
1572 struct _objc_method_list *instance_methods;
1573 struct _objc_method_list *class_methods;
1574 struct _objc_protocol_list *protocols;
1575 uint32_t size; // <rdar://4585769>
1576 struct _objc_property_list *instance_properties;
1577 };
1578 */
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001579void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001580 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.CategoryTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001581
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001582 // FIXME: This is poor design, the OCD should have a pointer to the
1583 // category decl. Additionally, note that Category can be null for
1584 // the @implementation w/o an @interface case. Sema should just
1585 // create one for us as it does for @implementation so everyone else
1586 // can live life under a clear blue sky.
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001587 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001588 const ObjCCategoryDecl *Category =
1589 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001590 std::string ExtName(Interface->getNameAsString() + "_" +
1591 OCD->getNameAsString());
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001592
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001593 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1594 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
1595 e = OCD->instmeth_end(); i != e; ++i) {
1596 // Instance methods should always be defined.
1597 InstanceMethods.push_back(GetMethodConstant(*i));
1598 }
1599 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
1600 e = OCD->classmeth_end(); i != e; ++i) {
1601 // Class methods should always be defined.
1602 ClassMethods.push_back(GetMethodConstant(*i));
1603 }
1604
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001605 std::vector<llvm::Constant*> Values(7);
1606 Values[0] = GetClassName(OCD->getIdentifier());
1607 Values[1] = GetClassName(Interface->getIdentifier());
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001608 Values[2] =
1609 EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") +
1610 ExtName,
1611 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001612 InstanceMethods);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001613 Values[3] =
1614 EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName,
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001615 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001616 ClassMethods);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001617 if (Category) {
1618 Values[4] =
1619 EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName,
1620 Category->protocol_begin(),
1621 Category->protocol_end());
1622 } else {
1623 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1624 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001625 Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001626
1627 // If there is no category @interface then there can be no properties.
1628 if (Category) {
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001629 Values[6] = EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001630 OCD, Category, ObjCTypes);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001631 } else {
1632 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1633 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001634
1635 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
1636 Values);
1637
1638 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001639 CreateMetadataVar(std::string("\01L_OBJC_CATEGORY_")+ExtName, Init,
1640 "__OBJC,__category,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001641 4, true);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001642 DefinedCategories.push_back(GV);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001643}
1644
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001645// FIXME: Get from somewhere?
1646enum ClassFlags {
1647 eClassFlags_Factory = 0x00001,
1648 eClassFlags_Meta = 0x00002,
1649 // <rdr://5142207>
1650 eClassFlags_HasCXXStructors = 0x02000,
1651 eClassFlags_Hidden = 0x20000,
1652 eClassFlags_ABI2_Hidden = 0x00010,
1653 eClassFlags_ABI2_HasCXXStructors = 0x00004 // <rdr://4923634>
1654};
1655
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001656/*
1657 struct _objc_class {
1658 Class isa;
1659 Class super_class;
1660 const char *name;
1661 long version;
1662 long info;
1663 long instance_size;
1664 struct _objc_ivar_list *ivars;
1665 struct _objc_method_list *methods;
1666 struct _objc_cache *cache;
1667 struct _objc_protocol_list *protocols;
1668 // Objective-C 1.0 extensions (<rdr://4585769>)
1669 const char *ivar_layout;
1670 struct _objc_class_ext *ext;
1671 };
1672
1673 See EmitClassExtension();
1674 */
1675void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001676 DefinedSymbols.insert(ID->getIdentifier());
1677
Chris Lattner8ec03f52008-11-24 03:54:41 +00001678 std::string ClassName = ID->getNameAsString();
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001679 // FIXME: Gross
1680 ObjCInterfaceDecl *Interface =
1681 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001682 llvm::Constant *Protocols =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001683 EmitProtocolList("\01L_OBJC_CLASS_PROTOCOLS_" + ID->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001684 Interface->protocol_begin(),
1685 Interface->protocol_end());
Chris Lattnerb7b58b12009-04-19 06:02:28 +00001686 const llvm::Type *InterfaceTy;
1687 if (Interface->isForwardDecl())
1688 InterfaceTy = llvm::StructType::get(NULL, NULL);
1689 else
1690 InterfaceTy =
Chris Lattner03d9f342009-04-01 06:23:52 +00001691 CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(Interface));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001692 unsigned Flags = eClassFlags_Factory;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001693 unsigned Size = CGM.getTargetData().getTypePaddedSize(InterfaceTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001694
1695 // FIXME: Set CXX-structors flag.
Daniel Dunbar04d40782009-04-14 06:00:08 +00001696 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001697 Flags |= eClassFlags_Hidden;
1698
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001699 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1700 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
1701 e = ID->instmeth_end(); i != e; ++i) {
1702 // Instance methods should always be defined.
1703 InstanceMethods.push_back(GetMethodConstant(*i));
1704 }
1705 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
1706 e = ID->classmeth_end(); i != e; ++i) {
1707 // Class methods should always be defined.
1708 ClassMethods.push_back(GetMethodConstant(*i));
1709 }
1710
1711 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
1712 e = ID->propimpl_end(); i != e; ++i) {
1713 ObjCPropertyImplDecl *PID = *i;
1714
1715 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1716 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1717
1718 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
1719 if (llvm::Constant *C = GetMethodConstant(MD))
1720 InstanceMethods.push_back(C);
1721 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
1722 if (llvm::Constant *C = GetMethodConstant(MD))
1723 InstanceMethods.push_back(C);
1724 }
1725 }
1726
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001727 std::vector<llvm::Constant*> Values(12);
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001728 Values[ 0] = EmitMetaClass(ID, Protocols, InterfaceTy, ClassMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001729 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001730 // Record a reference to the super class.
1731 LazySymbols.insert(Super->getIdentifier());
1732
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001733 Values[ 1] =
1734 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1735 ObjCTypes.ClassPtrTy);
1736 } else {
1737 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1738 }
1739 Values[ 2] = GetClassName(ID->getIdentifier());
1740 // Version is always 0.
1741 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1742 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1743 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001744 Values[ 6] = EmitIvarList(ID, false);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001745 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001746 EmitMethodList("\01L_OBJC_INSTANCE_METHODS_" + ID->getNameAsString(),
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001747 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001748 InstanceMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001749 // cache is always NULL.
1750 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1751 Values[ 9] = Protocols;
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001752 // FIXME: Set ivar_layout
Fariborz Jahanian667423a2009-03-25 22:36:49 +00001753 // Values[10] = BuildIvarLayout(ID, true);
1754 Values[10] = GetIvarLayoutName(0, ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001755 Values[11] = EmitClassExtension(ID);
1756 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1757 Values);
1758
1759 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001760 CreateMetadataVar(std::string("\01L_OBJC_CLASS_")+ClassName, Init,
1761 "__OBJC,__class,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001762 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001763 DefinedClasses.push_back(GV);
1764}
1765
1766llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
1767 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001768 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001769 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001770 unsigned Flags = eClassFlags_Meta;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001771 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001772
Daniel Dunbar04d40782009-04-14 06:00:08 +00001773 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001774 Flags |= eClassFlags_Hidden;
1775
1776 std::vector<llvm::Constant*> Values(12);
1777 // The isa for the metaclass is the root of the hierarchy.
1778 const ObjCInterfaceDecl *Root = ID->getClassInterface();
1779 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
1780 Root = Super;
1781 Values[ 0] =
1782 llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
1783 ObjCTypes.ClassPtrTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001784 // The super class for the metaclass is emitted as the name of the
1785 // super class. The runtime fixes this up to point to the
1786 // *metaclass* for the super class.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001787 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
1788 Values[ 1] =
1789 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1790 ObjCTypes.ClassPtrTy);
1791 } else {
1792 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1793 }
1794 Values[ 2] = GetClassName(ID->getIdentifier());
1795 // Version is always 0.
1796 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1797 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1798 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001799 Values[ 6] = EmitIvarList(ID, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001800 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001801 EmitMethodList("\01L_OBJC_CLASS_METHODS_" + ID->getNameAsString(),
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001802 "__OBJC,__cls_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001803 Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001804 // cache is always NULL.
1805 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1806 Values[ 9] = Protocols;
1807 // ivar_layout for metaclass is always NULL.
1808 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1809 // The class extension is always unused for metaclasses.
1810 Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1811 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1812 Values);
1813
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001814 std::string Name("\01L_OBJC_METACLASS_");
Chris Lattner8ec03f52008-11-24 03:54:41 +00001815 Name += ID->getNameAsCString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001816
1817 // Check for a forward reference.
1818 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
1819 if (GV) {
1820 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1821 "Forward metaclass reference has incorrect type.");
1822 GV->setLinkage(llvm::GlobalValue::InternalLinkage);
1823 GV->setInitializer(Init);
1824 } else {
1825 GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1826 llvm::GlobalValue::InternalLinkage,
1827 Init, Name,
1828 &CGM.getModule());
1829 }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001830 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001831 GV->setAlignment(4);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001832 UsedGlobals.push_back(GV);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001833
1834 return GV;
1835}
1836
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001837llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001838 std::string Name = "\01L_OBJC_METACLASS_" + ID->getNameAsString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001839
1840 // FIXME: Should we look these up somewhere other than the
1841 // module. Its a bit silly since we only generate these while
1842 // processing an implementation, so exactly one pointer would work
1843 // if know when we entered/exitted an implementation block.
1844
1845 // Check for an existing forward reference.
Fariborz Jahanianb0d27942009-01-07 20:11:22 +00001846 // Previously, metaclass with internal linkage may have been defined.
1847 // pass 'true' as 2nd argument so it is returned.
1848 if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true)) {
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001849 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1850 "Forward metaclass reference has incorrect type.");
1851 return GV;
1852 } else {
1853 // Generate as an external reference to keep a consistent
1854 // module. This will be patched up when we emit the metaclass.
1855 return new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1856 llvm::GlobalValue::ExternalLinkage,
1857 0,
1858 Name,
1859 &CGM.getModule());
1860 }
1861}
1862
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001863/*
1864 struct objc_class_ext {
1865 uint32_t size;
1866 const char *weak_ivar_layout;
1867 struct _objc_property_list *properties;
1868 };
1869*/
1870llvm::Constant *
1871CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
1872 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001873 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassExtensionTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001874
1875 std::vector<llvm::Constant*> Values(3);
1876 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001877 // FIXME: Output weak_ivar_layout string.
Fariborz Jahanian667423a2009-03-25 22:36:49 +00001878 // Values[1] = BuildIvarLayout(ID, false);
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00001879 Values[1] = GetIvarLayoutName(0, ObjCTypes);
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001880 Values[2] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001881 ID, ID->getClassInterface(), ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001882
1883 // Return null if no extension bits are used.
1884 if (Values[1]->isNullValue() && Values[2]->isNullValue())
1885 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1886
1887 llvm::Constant *Init =
1888 llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001889 return CreateMetadataVar("\01L_OBJC_CLASSEXT_" + ID->getNameAsString(),
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001890 Init, "__OBJC,__class_ext,regular,no_dead_strip",
1891 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001892}
1893
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001894/// getInterfaceDeclForIvar - Get the interface declaration node where
1895/// this ivar is declared in.
1896/// FIXME. Ideally, this info should be in the ivar node. But currently
1897/// it is not and prevailing wisdom is that ASTs should not have more
1898/// info than is absolutely needed, even though this info reflects the
1899/// source language.
1900///
1901static const ObjCInterfaceDecl *getInterfaceDeclForIvar(
1902 const ObjCInterfaceDecl *OI,
Douglas Gregor6ab35242009-04-09 21:40:53 +00001903 const ObjCIvarDecl *IVD,
1904 ASTContext &Context) {
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001905 if (!OI)
1906 return 0;
1907 assert(isa<ObjCInterfaceDecl>(OI) && "OI is not an interface");
1908 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1909 E = OI->ivar_end(); I != E; ++I)
1910 if ((*I)->getIdentifier() == IVD->getIdentifier())
1911 return OI;
Fariborz Jahanian5a4b4532009-03-31 17:00:52 +00001912 // look into properties.
Douglas Gregor6ab35242009-04-09 21:40:53 +00001913 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(Context),
1914 E = OI->prop_end(Context); I != E; ++I) {
Fariborz Jahanian5a4b4532009-03-31 17:00:52 +00001915 ObjCPropertyDecl *PDecl = (*I);
1916 if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl())
1917 if (IV->getIdentifier() == IVD->getIdentifier())
1918 return OI;
1919 }
Douglas Gregor6ab35242009-04-09 21:40:53 +00001920 return getInterfaceDeclForIvar(OI->getSuperClass(), IVD, Context);
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001921}
1922
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001923/*
1924 struct objc_ivar {
1925 char *ivar_name;
1926 char *ivar_type;
1927 int ivar_offset;
1928 };
1929
1930 struct objc_ivar_list {
1931 int ivar_count;
1932 struct objc_ivar list[count];
1933 };
1934 */
1935llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001936 bool ForClass) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001937 std::vector<llvm::Constant*> Ivars, Ivar(3);
1938
1939 // When emitting the root class GCC emits ivar entries for the
1940 // actual class structure. It is not clear if we need to follow this
1941 // behavior; for now lets try and get away with not doing it. If so,
1942 // the cleanest solution would be to make up an ObjCInterfaceDecl
1943 // for the class.
1944 if (ForClass)
1945 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001946
1947 ObjCInterfaceDecl *OID =
1948 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00001949 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001950
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00001951 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
1952 GetNamedIvarList(OID, OIvars);
1953
1954 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
1955 ObjCIvarDecl *IVD = OIvars[i];
1956 const FieldDecl *Field = OID->lookupFieldDeclForIvar(CGM.getContext(), IVD);
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00001957 Ivar[0] = GetMethodVarName(Field->getIdentifier());
Devang Patel7794bb82009-03-04 18:21:39 +00001958 Ivar[1] = GetMethodVarType(Field);
Daniel Dunbar6c1aac82009-04-20 20:18:54 +00001959 Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy,
1960 GetIvarBaseOffset(Layout, Field));
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001961 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001962 }
1963
1964 // Return null for empty list.
1965 if (Ivars.empty())
1966 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
1967
1968 std::vector<llvm::Constant*> Values(2);
1969 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
1970 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
1971 Ivars.size());
1972 Values[1] = llvm::ConstantArray::get(AT, Ivars);
1973 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1974
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001975 llvm::GlobalVariable *GV;
1976 if (ForClass)
1977 GV = CreateMetadataVar("\01L_OBJC_CLASS_VARIABLES_" + ID->getNameAsString(),
Daniel Dunbar58a29122009-03-09 22:18:41 +00001978 Init, "__OBJC,__class_vars,regular,no_dead_strip",
1979 4, true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001980 else
1981 GV = CreateMetadataVar("\01L_OBJC_INSTANCE_VARIABLES_"
1982 + ID->getNameAsString(),
1983 Init, "__OBJC,__instance_vars,regular,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001984 4, true);
1985 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.IvarListPtrTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001986}
1987
1988/*
1989 struct objc_method {
1990 SEL method_name;
1991 char *method_types;
1992 void *method;
1993 };
1994
1995 struct objc_method_list {
1996 struct objc_method_list *obsolete;
1997 int count;
1998 struct objc_method methods_list[count];
1999 };
2000*/
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002001
2002/// GetMethodConstant - Return a struct objc_method constant for the
2003/// given method if it has been defined. The result is null if the
2004/// method has not been defined. The return value has type MethodPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +00002005llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002006 // FIXME: Use DenseMap::lookup
2007 llvm::Function *Fn = MethodDefinitions[MD];
2008 if (!Fn)
2009 return 0;
2010
2011 std::vector<llvm::Constant*> Method(3);
2012 Method[0] =
2013 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
2014 ObjCTypes.SelectorPtrTy);
2015 Method[1] = GetMethodVarType(MD);
2016 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
2017 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
2018}
2019
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002020llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name,
2021 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00002022 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002023 // Return null for empty list.
2024 if (Methods.empty())
2025 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
2026
2027 std::vector<llvm::Constant*> Values(3);
2028 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2029 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
2030 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
2031 Methods.size());
2032 Values[2] = llvm::ConstantArray::get(AT, Methods);
2033 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2034
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002035 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002036 return llvm::ConstantExpr::getBitCast(GV,
2037 ObjCTypes.MethodListPtrTy);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002038}
2039
Fariborz Jahanian493dab72009-01-26 21:38:32 +00002040llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD,
Daniel Dunbarbb36d332009-02-02 21:43:58 +00002041 const ObjCContainerDecl *CD) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002042 std::string Name;
Fariborz Jahanian679a5022009-01-10 21:06:09 +00002043 GetNameForMethod(OMD, CD, Name);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002044
Daniel Dunbar541b63b2009-02-02 23:23:47 +00002045 CodeGenTypes &Types = CGM.getTypes();
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00002046 const llvm::FunctionType *MethodTy =
Daniel Dunbar541b63b2009-02-02 23:23:47 +00002047 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002048 llvm::Function *Method =
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00002049 llvm::Function::Create(MethodTy,
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002050 llvm::GlobalValue::InternalLinkage,
2051 Name,
2052 &CGM.getModule());
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002053 MethodDefinitions.insert(std::make_pair(OMD, Method));
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002054
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002055 return Method;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00002056}
2057
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00002058uint64_t CGObjCCommonMac::GetIvarBaseOffset(const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +00002059 const FieldDecl *Field) {
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00002060 if (!Field->isBitField())
Daniel Dunbar48fa0642009-04-19 02:03:42 +00002061 return Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(Field));
2062
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00002063 // FIXME. Must be a better way of getting a bitfield base offset.
Daniel Dunbar48fa0642009-04-19 02:03:42 +00002064 CodeGenTypes::BitFieldInfo BFI = CGM.getTypes().getBitFieldInfo(Field);
2065 // FIXME: The "field no" for bitfields is something completely
2066 // different; it is the offset in multiples of the base type size!
2067 uint64_t Offset = CGM.getTypes().getLLVMFieldNo(Field);
2068 const llvm::Type *Ty =
2069 CGM.getTypes().ConvertTypeForMemRecursive(Field->getType());
2070 Offset *= CGM.getTypes().getTargetData().getTypePaddedSizeInBits(Ty);
2071 return (Offset + BFI.Begin) / 8;
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00002072}
2073
Daniel Dunbar48fa0642009-04-19 02:03:42 +00002074/// GetFieldBaseOffset - return the field's byte offset.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002075uint64_t CGObjCCommonMac::GetFieldBaseOffset(const ObjCInterfaceDecl *OI,
2076 const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +00002077 const FieldDecl *Field) {
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00002078 // Is this a c struct?
2079 if (!OI)
2080 return Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(Field));
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002081 const ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
Chris Lattnercd0ee142009-03-31 08:33:16 +00002082 const FieldDecl *FD = OI->lookupFieldDeclForIvar(CGM.getContext(), Ivar);
2083 return GetIvarBaseOffset(Layout, FD);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002084}
2085
Daniel Dunbarfd65d372009-03-09 20:09:19 +00002086llvm::GlobalVariable *
2087CGObjCCommonMac::CreateMetadataVar(const std::string &Name,
2088 llvm::Constant *Init,
2089 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +00002090 unsigned Align,
2091 bool AddToUsed) {
Daniel Dunbarfd65d372009-03-09 20:09:19 +00002092 const llvm::Type *Ty = Init->getType();
2093 llvm::GlobalVariable *GV =
2094 new llvm::GlobalVariable(Ty, false,
2095 llvm::GlobalValue::InternalLinkage,
2096 Init,
2097 Name,
2098 &CGM.getModule());
2099 if (Section)
2100 GV->setSection(Section);
Daniel Dunbar35bd7632009-03-09 20:50:13 +00002101 if (Align)
2102 GV->setAlignment(Align);
2103 if (AddToUsed)
Daniel Dunbarfd65d372009-03-09 20:09:19 +00002104 UsedGlobals.push_back(GV);
2105 return GV;
2106}
2107
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00002108llvm::Function *CGObjCMac::ModuleInitFunction() {
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002109 // Abuse this interface function as a place to finalize.
2110 FinishModule();
2111
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00002112 return NULL;
2113}
2114
Chris Lattner74391b42009-03-22 21:03:39 +00002115llvm::Constant *CGObjCMac::GetPropertyGetFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00002116 return ObjCTypes.getGetPropertyFn();
Daniel Dunbar49f66022008-09-24 03:38:44 +00002117}
2118
Chris Lattner74391b42009-03-22 21:03:39 +00002119llvm::Constant *CGObjCMac::GetPropertySetFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00002120 return ObjCTypes.getSetPropertyFn();
Daniel Dunbar49f66022008-09-24 03:38:44 +00002121}
2122
Chris Lattner74391b42009-03-22 21:03:39 +00002123llvm::Constant *CGObjCMac::EnumerationMutationFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00002124 return ObjCTypes.getEnumerationMutationFn();
Anders Carlsson2abd89c2008-08-31 04:05:03 +00002125}
2126
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002127/*
2128
2129Objective-C setjmp-longjmp (sjlj) Exception Handling
2130--
2131
2132The basic framework for a @try-catch-finally is as follows:
2133{
2134 objc_exception_data d;
2135 id _rethrow = null;
Anders Carlsson190d00e2009-02-07 21:26:04 +00002136 bool _call_try_exit = true;
2137
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002138 objc_exception_try_enter(&d);
2139 if (!setjmp(d.jmp_buf)) {
2140 ... try body ...
2141 } else {
2142 // exception path
2143 id _caught = objc_exception_extract(&d);
2144
2145 // enter new try scope for handlers
2146 if (!setjmp(d.jmp_buf)) {
2147 ... match exception and execute catch blocks ...
2148
2149 // fell off end, rethrow.
2150 _rethrow = _caught;
Daniel Dunbar898d5082008-09-30 01:06:03 +00002151 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002152 } else {
2153 // exception in catch block
2154 _rethrow = objc_exception_extract(&d);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002155 _call_try_exit = false;
2156 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002157 }
2158 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00002159 ... jump-through-finally to finally_end ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002160
2161finally:
Anders Carlsson190d00e2009-02-07 21:26:04 +00002162 if (_call_try_exit)
2163 objc_exception_try_exit(&d);
2164
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002165 ... finally block ....
Daniel Dunbar898d5082008-09-30 01:06:03 +00002166 ... dispatch to finally destination ...
2167
2168finally_rethrow:
2169 objc_exception_throw(_rethrow);
2170
2171finally_end:
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002172}
2173
2174This framework differs slightly from the one gcc uses, in that gcc
Daniel Dunbar898d5082008-09-30 01:06:03 +00002175uses _rethrow to determine if objc_exception_try_exit should be called
2176and if the object should be rethrown. This breaks in the face of
2177throwing nil and introduces unnecessary branches.
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002178
2179We specialize this framework for a few particular circumstances:
2180
2181 - If there are no catch blocks, then we avoid emitting the second
2182 exception handling context.
2183
2184 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
2185 e)) we avoid emitting the code to rethrow an uncaught exception.
2186
2187 - FIXME: If there is no @finally block we can do a few more
2188 simplifications.
2189
2190Rethrows and Jumps-Through-Finally
2191--
2192
2193Support for implicit rethrows and jumping through the finally block is
2194handled by storing the current exception-handling context in
2195ObjCEHStack.
2196
Daniel Dunbar898d5082008-09-30 01:06:03 +00002197In order to implement proper @finally semantics, we support one basic
2198mechanism for jumping through the finally block to an arbitrary
2199destination. Constructs which generate exits from a @try or @catch
2200block use this mechanism to implement the proper semantics by chaining
2201jumps, as necessary.
2202
2203This mechanism works like the one used for indirect goto: we
2204arbitrarily assign an ID to each destination and store the ID for the
2205destination in a variable prior to entering the finally block. At the
2206end of the finally block we simply create a switch to the proper
2207destination.
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002208
2209Code gen for @synchronized(expr) stmt;
2210Effectively generating code for:
2211objc_sync_enter(expr);
2212@try stmt @finally { objc_sync_exit(expr); }
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002213*/
2214
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002215void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
2216 const Stmt &S) {
2217 bool isTry = isa<ObjCAtTryStmt>(S);
Daniel Dunbar898d5082008-09-30 01:06:03 +00002218 // Create various blocks we refer to for handling @finally.
Daniel Dunbar55e87422008-11-11 02:29:29 +00002219 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002220 llvm::BasicBlock *FinallyExit = CGF.createBasicBlock("finally.exit");
Daniel Dunbar55e87422008-11-11 02:29:29 +00002221 llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
2222 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
2223 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
Daniel Dunbar1c566672009-02-24 01:43:46 +00002224
2225 // For @synchronized, call objc_sync_enter(sync.expr). The
2226 // evaluation of the expression must occur before we enter the
2227 // @synchronized. We can safely avoid a temp here because jumps into
2228 // @synchronized are illegal & this will dominate uses.
2229 llvm::Value *SyncArg = 0;
2230 if (!isTry) {
2231 SyncArg =
2232 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
2233 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00002234 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar1c566672009-02-24 01:43:46 +00002235 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00002236
2237 // Push an EH context entry, used for handling rethrows and jumps
2238 // through finally.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002239 CGF.PushCleanupBlock(FinallyBlock);
2240
Anders Carlsson273558f2009-02-07 21:37:21 +00002241 CGF.ObjCEHValueStack.push_back(0);
2242
Daniel Dunbar898d5082008-09-30 01:06:03 +00002243 // Allocate memory for the exception data and rethrow pointer.
Anders Carlsson80f25672008-09-09 17:59:25 +00002244 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
2245 "exceptiondata.ptr");
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002246 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
2247 "_rethrow");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002248 llvm::Value *CallTryExitPtr = CGF.CreateTempAlloca(llvm::Type::Int1Ty,
2249 "_call_try_exit");
2250 CGF.Builder.CreateStore(llvm::ConstantInt::getTrue(), CallTryExitPtr);
2251
Anders Carlsson80f25672008-09-09 17:59:25 +00002252 // Enter a new try block and call setjmp.
Chris Lattner34b02a12009-04-22 02:26:14 +00002253 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryEnterFn(), ExceptionData);
Anders Carlsson80f25672008-09-09 17:59:25 +00002254 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
2255 "jmpbufarray");
2256 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
Chris Lattner34b02a12009-04-22 02:26:14 +00002257 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.getSetJmpFn(),
Anders Carlsson80f25672008-09-09 17:59:25 +00002258 JmpBufPtr, "result");
Daniel Dunbar898d5082008-09-30 01:06:03 +00002259
Daniel Dunbar55e87422008-11-11 02:29:29 +00002260 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
2261 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002262 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002263 TryHandler, TryBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002264
2265 // Emit the @try block.
2266 CGF.EmitBlock(TryBlock);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002267 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
2268 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002269 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002270
2271 // Emit the "exception in @try" block.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002272 CGF.EmitBlock(TryHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002273
2274 // Retrieve the exception object. We may emit multiple blocks but
2275 // nothing can cross this so the value is already in SSA form.
Chris Lattner34b02a12009-04-22 02:26:14 +00002276 llvm::Value *Caught =
2277 CGF.Builder.CreateCall(ObjCTypes.getExceptionExtractFn(),
2278 ExceptionData, "caught");
Anders Carlsson273558f2009-02-07 21:37:21 +00002279 CGF.ObjCEHValueStack.back() = Caught;
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002280 if (!isTry)
2281 {
2282 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002283 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002284 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002285 }
2286 else if (const ObjCAtCatchStmt* CatchStmt =
2287 cast<ObjCAtTryStmt>(S).getCatchStmts())
2288 {
Daniel Dunbar55e40722008-09-27 07:03:52 +00002289 // Enter a new exception try block (in case a @catch block throws
2290 // an exception).
Chris Lattner34b02a12009-04-22 02:26:14 +00002291 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryEnterFn(), ExceptionData);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002292
Chris Lattner34b02a12009-04-22 02:26:14 +00002293 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.getSetJmpFn(),
Anders Carlsson80f25672008-09-09 17:59:25 +00002294 JmpBufPtr, "result");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002295 llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw");
Anders Carlsson80f25672008-09-09 17:59:25 +00002296
Daniel Dunbar55e87422008-11-11 02:29:29 +00002297 llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch");
2298 llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler");
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002299 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002300
2301 CGF.EmitBlock(CatchBlock);
2302
Daniel Dunbar55e40722008-09-27 07:03:52 +00002303 // Handle catch list. As a special case we check if everything is
2304 // matched and avoid generating code for falling off the end if
2305 // so.
2306 bool AllMatched = false;
Anders Carlsson80f25672008-09-09 17:59:25 +00002307 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbar55e87422008-11-11 02:29:29 +00002308 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch");
Anders Carlsson80f25672008-09-09 17:59:25 +00002309
Steve Naroff7ba138a2009-03-03 19:52:17 +00002310 const ParmVarDecl *CatchParam = CatchStmt->getCatchParamDecl();
Daniel Dunbar129271a2008-09-27 07:36:24 +00002311 const PointerType *PT = 0;
2312
Anders Carlsson80f25672008-09-09 17:59:25 +00002313 // catch(...) always matches.
Daniel Dunbar55e40722008-09-27 07:03:52 +00002314 if (!CatchParam) {
2315 AllMatched = true;
2316 } else {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002317 PT = CatchParam->getType()->getAsPointerType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002318
Daniel Dunbar97f61d12008-09-27 22:21:14 +00002319 // catch(id e) always matches.
2320 // FIXME: For the time being we also match id<X>; this should
2321 // be rejected by Sema instead.
Steve Naroff389bf462009-02-12 17:52:19 +00002322 if ((PT && CGF.getContext().isObjCIdStructType(PT->getPointeeType())) ||
Steve Naroff7ba138a2009-03-03 19:52:17 +00002323 CatchParam->getType()->isObjCQualifiedIdType())
Daniel Dunbar55e40722008-09-27 07:03:52 +00002324 AllMatched = true;
Anders Carlsson80f25672008-09-09 17:59:25 +00002325 }
2326
Daniel Dunbar55e40722008-09-27 07:03:52 +00002327 if (AllMatched) {
Anders Carlssondde0a942008-09-11 09:15:33 +00002328 if (CatchParam) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002329 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002330 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002331 CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002332 }
Anders Carlsson1452f552008-09-11 08:21:54 +00002333
Anders Carlssondde0a942008-09-11 09:15:33 +00002334 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002335 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002336 break;
2337 }
2338
Daniel Dunbar129271a2008-09-27 07:36:24 +00002339 assert(PT && "Unexpected non-pointer type in @catch");
2340 QualType T = PT->getPointeeType();
Anders Carlsson4b7ff6e2008-09-11 06:35:14 +00002341 const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002342 assert(ObjCType && "Catch parameter must have Objective-C type!");
2343
2344 // Check if the @catch block matches the exception object.
2345 llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl());
2346
Chris Lattner34b02a12009-04-22 02:26:14 +00002347 llvm::Value *Match =
2348 CGF.Builder.CreateCall2(ObjCTypes.getExceptionMatchFn(),
2349 Class, Caught, "match");
Anders Carlsson80f25672008-09-09 17:59:25 +00002350
Daniel Dunbar55e87422008-11-11 02:29:29 +00002351 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched");
Anders Carlsson80f25672008-09-09 17:59:25 +00002352
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002353 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002354 MatchedBlock, NextCatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002355
2356 // Emit the @catch block.
2357 CGF.EmitBlock(MatchedBlock);
Steve Naroff7ba138a2009-03-03 19:52:17 +00002358 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002359 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002360
2361 llvm::Value *Tmp =
Steve Naroff7ba138a2009-03-03 19:52:17 +00002362 CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(CatchParam->getType()),
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002363 "tmp");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002364 CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002365
2366 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002367 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002368
2369 CGF.EmitBlock(NextCatchBlock);
2370 }
2371
Daniel Dunbar55e40722008-09-27 07:03:52 +00002372 if (!AllMatched) {
2373 // None of the handlers caught the exception, so store it to be
2374 // rethrown at the end of the @finally block.
2375 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002376 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002377 }
2378
2379 // Emit the exception handler for the @catch blocks.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002380 CGF.EmitBlock(CatchHandler);
Chris Lattner34b02a12009-04-22 02:26:14 +00002381 CGF.Builder.CreateStore(
2382 CGF.Builder.CreateCall(ObjCTypes.getExceptionExtractFn(),
2383 ExceptionData),
Daniel Dunbar55e40722008-09-27 07:03:52 +00002384 RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002385 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002386 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002387 } else {
Anders Carlsson80f25672008-09-09 17:59:25 +00002388 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002389 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002390 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Anders Carlsson80f25672008-09-09 17:59:25 +00002391 }
2392
Daniel Dunbar898d5082008-09-30 01:06:03 +00002393 // Pop the exception-handling stack entry. It is important to do
2394 // this now, because the code in the @finally block is not in this
2395 // context.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002396 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
2397
Anders Carlsson273558f2009-02-07 21:37:21 +00002398 CGF.ObjCEHValueStack.pop_back();
2399
Anders Carlsson80f25672008-09-09 17:59:25 +00002400 // Emit the @finally block.
2401 CGF.EmitBlock(FinallyBlock);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002402 llvm::Value* CallTryExit = CGF.Builder.CreateLoad(CallTryExitPtr, "tmp");
2403
2404 CGF.Builder.CreateCondBr(CallTryExit, FinallyExit, FinallyNoExit);
2405
2406 CGF.EmitBlock(FinallyExit);
Chris Lattner34b02a12009-04-22 02:26:14 +00002407 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryExitFn(), ExceptionData);
Daniel Dunbar129271a2008-09-27 07:36:24 +00002408
2409 CGF.EmitBlock(FinallyNoExit);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002410 if (isTry) {
2411 if (const ObjCAtFinallyStmt* FinallyStmt =
2412 cast<ObjCAtTryStmt>(S).getFinallyStmt())
2413 CGF.EmitStmt(FinallyStmt->getFinallyBody());
Daniel Dunbar1c566672009-02-24 01:43:46 +00002414 } else {
2415 // Emit objc_sync_exit(expr); as finally's sole statement for
2416 // @synchronized.
Chris Lattnerbbccd612009-04-22 02:38:11 +00002417 CGF.Builder.CreateCall(ObjCTypes.getSyncExitFn(), SyncArg);
Fariborz Jahanianf2878e52008-11-21 19:21:53 +00002418 }
Anders Carlsson80f25672008-09-09 17:59:25 +00002419
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002420 // Emit the switch block
2421 if (Info.SwitchBlock)
2422 CGF.EmitBlock(Info.SwitchBlock);
2423 if (Info.EndBlock)
2424 CGF.EmitBlock(Info.EndBlock);
2425
Daniel Dunbar898d5082008-09-30 01:06:03 +00002426 CGF.EmitBlock(FinallyRethrow);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002427 CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(),
Daniel Dunbar898d5082008-09-30 01:06:03 +00002428 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002429 CGF.Builder.CreateUnreachable();
Daniel Dunbar898d5082008-09-30 01:06:03 +00002430
2431 CGF.EmitBlock(FinallyEnd);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002432}
2433
2434void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar898d5082008-09-30 01:06:03 +00002435 const ObjCAtThrowStmt &S) {
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002436 llvm::Value *ExceptionAsObject;
2437
2438 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2439 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
2440 ExceptionAsObject =
2441 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
2442 } else {
Anders Carlsson273558f2009-02-07 21:37:21 +00002443 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002444 "Unexpected rethrow outside @catch block.");
Anders Carlsson273558f2009-02-07 21:37:21 +00002445 ExceptionAsObject = CGF.ObjCEHValueStack.back();
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002446 }
2447
Chris Lattnerbbccd612009-04-22 02:38:11 +00002448 CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(), ExceptionAsObject);
Anders Carlsson80f25672008-09-09 17:59:25 +00002449 CGF.Builder.CreateUnreachable();
Daniel Dunbara448fb22008-11-11 23:11:34 +00002450
2451 // Clear the insertion point to indicate we are in unreachable code.
2452 CGF.Builder.ClearInsertionPoint();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002453}
2454
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002455/// EmitObjCWeakRead - Code gen for loading value of a __weak
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002456/// object: objc_read_weak (id *src)
2457///
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002458llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002459 llvm::Value *AddrWeakObj)
2460{
Eli Friedman8339b352009-03-07 03:57:15 +00002461 const llvm::Type* DestTy =
2462 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002463 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Chris Lattner72db6c32009-04-22 02:44:54 +00002464 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.getGcReadWeakFn(),
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002465 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00002466 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002467 return read_weak;
2468}
2469
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002470/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
2471/// objc_assign_weak (id src, id *dst)
2472///
2473void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
2474 llvm::Value *src, llvm::Value *dst)
2475{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002476 const llvm::Type * SrcTy = src->getType();
2477 if (!isa<llvm::PointerType>(SrcTy)) {
2478 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2479 assert(Size <= 8 && "does not support size > 8");
2480 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2481 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002482 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2483 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002484 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2485 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattner96508e12009-04-17 22:12:36 +00002486 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002487 src, dst, "weakassign");
2488 return;
2489}
2490
Fariborz Jahanian58626502008-11-19 00:59:10 +00002491/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
2492/// objc_assign_global (id src, id *dst)
2493///
2494void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
2495 llvm::Value *src, llvm::Value *dst)
2496{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002497 const llvm::Type * SrcTy = src->getType();
2498 if (!isa<llvm::PointerType>(SrcTy)) {
2499 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2500 assert(Size <= 8 && "does not support size > 8");
2501 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2502 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002503 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2504 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002505 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2506 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002507 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignGlobalFn(),
Fariborz Jahanian58626502008-11-19 00:59:10 +00002508 src, dst, "globalassign");
2509 return;
2510}
2511
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002512/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
2513/// objc_assign_ivar (id src, id *dst)
2514///
2515void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
2516 llvm::Value *src, llvm::Value *dst)
2517{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002518 const llvm::Type * SrcTy = src->getType();
2519 if (!isa<llvm::PointerType>(SrcTy)) {
2520 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2521 assert(Size <= 8 && "does not support size > 8");
2522 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2523 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002524 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2525 }
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002526 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2527 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002528 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignIvarFn(),
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002529 src, dst, "assignivar");
2530 return;
2531}
2532
Fariborz Jahanian58626502008-11-19 00:59:10 +00002533/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
2534/// objc_assign_strongCast (id src, id *dst)
2535///
2536void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
2537 llvm::Value *src, llvm::Value *dst)
2538{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002539 const llvm::Type * SrcTy = src->getType();
2540 if (!isa<llvm::PointerType>(SrcTy)) {
2541 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2542 assert(Size <= 8 && "does not support size > 8");
2543 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2544 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002545 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2546 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002547 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2548 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002549 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignStrongCastFn(),
Fariborz Jahanian58626502008-11-19 00:59:10 +00002550 src, dst, "weakassign");
2551 return;
2552}
2553
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002554/// EmitObjCValueForIvar - Code Gen for ivar reference.
2555///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002556LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
2557 QualType ObjectTy,
2558 llvm::Value *BaseValue,
2559 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002560 unsigned CVRQualifiers) {
Daniel Dunbar525c9b72009-04-21 01:19:28 +00002561 const ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
2562 const FieldDecl *Field = ID->lookupFieldDeclForIvar(CGM.getContext(), Ivar);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002563 if (Ivar->isBitField())
2564 return CGF.EmitLValueForBitfield(BaseValue, const_cast<FieldDecl *>(Field),
2565 CVRQualifiers);
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002566 // TODO: Add a special case for isa (index 0)
2567 unsigned Index = CGM.getTypes().getLLVMFieldNo(Field);
2568 llvm::Value *V = CGF.Builder.CreateStructGEP(BaseValue, Index, "tmp");
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002569 LValue LV = LValue::MakeAddr(V,
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00002570 Ivar->getType().getCVRQualifiers()|CVRQualifiers,
2571 CGM.getContext().getObjCGCAttrKind(Ivar->getType()));
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002572 LValue::SetObjCIvar(LV, true);
2573 return LV;
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002574}
2575
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002576llvm::Value *CGObjCMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
2577 ObjCInterfaceDecl *Interface,
2578 const ObjCIvarDecl *Ivar) {
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002579 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(Interface);
Daniel Dunbar60952f92009-04-20 00:37:55 +00002580 const FieldDecl *Field =
2581 Interface->lookupFieldDeclForIvar(CGM.getContext(), Ivar);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00002582 uint64_t Offset = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002583 return llvm::ConstantInt::get(
2584 CGM.getTypes().ConvertType(CGM.getContext().LongTy),
2585 Offset);
2586}
2587
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002588/* *** Private Interface *** */
2589
2590/// EmitImageInfo - Emit the image info marker used to encode some module
2591/// level information.
2592///
2593/// See: <rdr://4810609&4810587&4810587>
2594/// struct IMAGE_INFO {
2595/// unsigned version;
2596/// unsigned flags;
2597/// };
2598enum ImageInfoFlags {
Daniel Dunbarc7c6dc02009-04-20 07:11:47 +00002599 eImageInfo_FixAndContinue = (1 << 0), // FIXME: Not sure what
2600 // this implies.
2601 eImageInfo_GarbageCollected = (1 << 1),
2602 eImageInfo_GCOnly = (1 << 2),
2603 eImageInfo_OptimizedByDyld = (1 << 3), // FIXME: When is this set.
2604
2605 // A flag indicating that the module has no instances of an
2606 // @synthesize of a superclass variable. <rdar://problem/6803242>
2607 eImageInfo_CorrectedSynthesize = (1 << 4)
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002608};
2609
2610void CGObjCMac::EmitImageInfo() {
2611 unsigned version = 0; // Version is unused?
2612 unsigned flags = 0;
2613
2614 // FIXME: Fix and continue?
2615 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
2616 flags |= eImageInfo_GarbageCollected;
2617 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
2618 flags |= eImageInfo_GCOnly;
Daniel Dunbarc7c6dc02009-04-20 07:11:47 +00002619
2620 // We never allow @synthesize of a superclass property.
2621 flags |= eImageInfo_CorrectedSynthesize;
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002622
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002623 // Emitted as int[2];
2624 llvm::Constant *values[2] = {
2625 llvm::ConstantInt::get(llvm::Type::Int32Ty, version),
2626 llvm::ConstantInt::get(llvm::Type::Int32Ty, flags)
2627 };
2628 llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002629
2630 const char *Section;
2631 if (ObjCABI == 1)
2632 Section = "__OBJC, __image_info,regular";
2633 else
2634 Section = "__DATA, __objc_imageinfo, regular, no_dead_strip";
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002635 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002636 CreateMetadataVar("\01L_OBJC_IMAGE_INFO",
2637 llvm::ConstantArray::get(AT, values, 2),
2638 Section,
2639 0,
2640 true);
2641 GV->setConstant(true);
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002642}
2643
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002644
2645// struct objc_module {
2646// unsigned long version;
2647// unsigned long size;
2648// const char *name;
2649// Symtab symtab;
2650// };
2651
2652// FIXME: Get from somewhere
2653static const int ModuleVersion = 7;
2654
2655void CGObjCMac::EmitModuleInfo() {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00002656 uint64_t Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ModuleTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002657
2658 std::vector<llvm::Constant*> Values(4);
2659 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
2660 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002661 // This used to be the filename, now it is unused. <rdr://4327263>
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002662 Values[2] = GetClassName(&CGM.getContext().Idents.get(""));
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002663 Values[3] = EmitModuleSymbols();
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002664 CreateMetadataVar("\01L_OBJC_MODULES",
2665 llvm::ConstantStruct::get(ObjCTypes.ModuleTy, Values),
2666 "__OBJC,__module_info,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00002667 4, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002668}
2669
2670llvm::Constant *CGObjCMac::EmitModuleSymbols() {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002671 unsigned NumClasses = DefinedClasses.size();
2672 unsigned NumCategories = DefinedCategories.size();
2673
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002674 // Return null if no symbols were defined.
2675 if (!NumClasses && !NumCategories)
2676 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
2677
2678 std::vector<llvm::Constant*> Values(5);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002679 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2680 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
2681 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
2682 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
2683
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002684 // The runtime expects exactly the list of defined classes followed
2685 // by the list of defined categories, in a single array.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002686 std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002687 for (unsigned i=0; i<NumClasses; i++)
2688 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
2689 ObjCTypes.Int8PtrTy);
2690 for (unsigned i=0; i<NumCategories; i++)
2691 Symbols[NumClasses + i] =
2692 llvm::ConstantExpr::getBitCast(DefinedCategories[i],
2693 ObjCTypes.Int8PtrTy);
2694
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002695 Values[4] =
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002696 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002697 NumClasses + NumCategories),
2698 Symbols);
2699
2700 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2701
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002702 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002703 CreateMetadataVar("\01L_OBJC_SYMBOLS", Init,
2704 "__OBJC,__symbols,regular,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002705 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002706 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
2707}
2708
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002709llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002710 const ObjCInterfaceDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002711 LazySymbols.insert(ID->getIdentifier());
2712
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002713 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
2714
2715 if (!Entry) {
2716 llvm::Constant *Casted =
2717 llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()),
2718 ObjCTypes.ClassPtrTy);
2719 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002720 CreateMetadataVar("\01L_OBJC_CLASS_REFERENCES_", Casted,
2721 "__OBJC,__cls_refs,literal_pointers,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002722 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002723 }
2724
2725 return Builder.CreateLoad(Entry, false, "tmp");
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002726}
2727
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002728llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002729 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
2730
2731 if (!Entry) {
2732 llvm::Constant *Casted =
2733 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
2734 ObjCTypes.SelectorPtrTy);
2735 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002736 CreateMetadataVar("\01L_OBJC_SELECTOR_REFERENCES_", Casted,
2737 "__OBJC,__message_refs,literal_pointers,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002738 4, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002739 }
2740
2741 return Builder.CreateLoad(Entry, false, "tmp");
2742}
2743
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00002744llvm::Constant *CGObjCCommonMac::GetClassName(IdentifierInfo *Ident) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002745 llvm::GlobalVariable *&Entry = ClassNames[Ident];
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002746
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002747 if (!Entry)
2748 Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
2749 llvm::ConstantArray::get(Ident->getName()),
2750 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00002751 1, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002752
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002753 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002754}
2755
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002756/// GetInterfaceDeclStructLayout - Get layout for ivars of given
2757/// interface declaration.
2758const llvm::StructLayout *CGObjCCommonMac::GetInterfaceDeclStructLayout(
2759 const ObjCInterfaceDecl *OID) const {
Daniel Dunbar24c89912009-04-21 21:41:56 +00002760 assert(!OID->isForwardDecl() && "Invalid interface decl!");
Daniel Dunbar6c1aac82009-04-20 20:18:54 +00002761 QualType T =
2762 CGM.getContext().getObjCInterfaceType(const_cast<ObjCInterfaceDecl*>(OID));
2763 const llvm::StructType *InterfaceTy =
2764 cast<llvm::StructType>(CGM.getTypes().ConvertType(T));
2765 return CGM.getTargetData().getStructLayout(InterfaceTy);
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002766}
2767
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00002768/// GetIvarLayoutName - Returns a unique constant for the given
2769/// ivar layout bitmap.
2770llvm::Constant *CGObjCCommonMac::GetIvarLayoutName(IdentifierInfo *Ident,
2771 const ObjCCommonTypesHelper &ObjCTypes) {
2772 return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2773}
2774
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002775void CGObjCCommonMac::BuildAggrIvarLayout(const ObjCInterfaceDecl *OI,
2776 const llvm::StructLayout *Layout,
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002777 const RecordDecl *RD,
Chris Lattnerf1690852009-03-31 08:48:01 +00002778 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002779 unsigned int BytePos, bool ForStrongLayout,
2780 int &Index, int &SkIndex, bool &HasUnion) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002781 bool IsUnion = (RD && RD->isUnion());
2782 uint64_t MaxUnionIvarSize = 0;
2783 uint64_t MaxSkippedUnionIvarSize = 0;
2784 FieldDecl *MaxField = 0;
2785 FieldDecl *MaxSkippedField = 0;
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002786 FieldDecl *LastFieldBitfield = 0;
2787
Chris Lattnerf1690852009-03-31 08:48:01 +00002788 unsigned base = 0;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002789 if (RecFields.empty())
2790 return;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002791 if (IsUnion)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002792 base = BytePos + GetFieldBaseOffset(OI, Layout, RecFields[0]);
Chris Lattnerf1690852009-03-31 08:48:01 +00002793 unsigned WordSizeInBits = CGM.getContext().Target.getPointerWidth(0);
2794 unsigned ByteSizeInBits = CGM.getContext().Target.getCharWidth();
2795
2796 llvm::SmallVector<FieldDecl*, 16> TmpRecFields;
2797
2798 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002799 FieldDecl *Field = RecFields[i];
2800 // Skip over unnamed or bitfields
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002801 if (!Field->getIdentifier() || Field->isBitField()) {
2802 LastFieldBitfield = Field;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002803 continue;
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002804 }
2805 LastFieldBitfield = 0;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002806 QualType FQT = Field->getType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002807 if (FQT->isRecordType() || FQT->isUnionType()) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002808 if (FQT->isUnionType())
2809 HasUnion = true;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002810 else
2811 assert(FQT->isRecordType() &&
2812 "only union/record is supported for ivar layout bitmap");
2813
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002814 const RecordType *RT = FQT->getAsRecordType();
2815 const RecordDecl *RD = RT->getDecl();
Daniel Dunbarb02532a2009-04-19 23:41:48 +00002816 // FIXME - Find a more efficient way of passing records down.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002817 TmpRecFields.append(RD->field_begin(CGM.getContext()),
2818 RD->field_end(CGM.getContext()));
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00002819 const llvm::Type *Ty = CGM.getTypes().ConvertType(FQT);
2820 const llvm::StructLayout *RecLayout =
2821 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(Ty));
2822
2823 BuildAggrIvarLayout(0, RecLayout, RD, TmpRecFields,
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002824 BytePos + GetFieldBaseOffset(OI, Layout, Field),
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002825 ForStrongLayout, Index, SkIndex,
2826 HasUnion);
Chris Lattnerf1690852009-03-31 08:48:01 +00002827 TmpRecFields.clear();
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002828 continue;
2829 }
Chris Lattnerf1690852009-03-31 08:48:01 +00002830
2831 if (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002832 const ConstantArrayType *CArray =
2833 dyn_cast_or_null<ConstantArrayType>(Array);
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002834 uint64_t ElCount = CArray->getSize().getZExtValue();
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002835 assert(CArray && "only array with know element size is supported");
2836 FQT = CArray->getElementType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002837 while (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
2838 const ConstantArrayType *CArray =
2839 dyn_cast_or_null<ConstantArrayType>(Array);
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002840 ElCount *= CArray->getSize().getZExtValue();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002841 FQT = CArray->getElementType();
2842 }
2843
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002844 assert(!FQT->isUnionType() &&
2845 "layout for array of unions not supported");
2846 if (FQT->isRecordType()) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002847 int OldIndex = Index;
2848 int OldSkIndex = SkIndex;
2849
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002850 // FIXME - Use a common routine with the above!
2851 const RecordType *RT = FQT->getAsRecordType();
2852 const RecordDecl *RD = RT->getDecl();
2853 // FIXME - Find a more efficiant way of passing records down.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002854 TmpRecFields.append(RD->field_begin(CGM.getContext()),
2855 RD->field_end(CGM.getContext()));
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00002856 const llvm::Type *Ty = CGM.getTypes().ConvertType(FQT);
2857 const llvm::StructLayout *RecLayout =
2858 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(Ty));
Chris Lattnerf1690852009-03-31 08:48:01 +00002859
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00002860 BuildAggrIvarLayout(0, RecLayout, RD,
Chris Lattnerf1690852009-03-31 08:48:01 +00002861 TmpRecFields,
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002862 BytePos + GetFieldBaseOffset(OI, Layout, Field),
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002863 ForStrongLayout, Index, SkIndex,
2864 HasUnion);
Chris Lattnerf1690852009-03-31 08:48:01 +00002865 TmpRecFields.clear();
2866
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002867 // Replicate layout information for each array element. Note that
2868 // one element is already done.
2869 uint64_t ElIx = 1;
2870 for (int FirstIndex = Index, FirstSkIndex = SkIndex;
2871 ElIx < ElCount; ElIx++) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002872 uint64_t Size = CGM.getContext().getTypeSize(RT)/ByteSizeInBits;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002873 for (int i = OldIndex+1; i <= FirstIndex; ++i)
2874 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002875 GC_IVAR gcivar;
2876 gcivar.ivar_bytepos = IvarsInfo[i].ivar_bytepos + Size*ElIx;
2877 gcivar.ivar_size = IvarsInfo[i].ivar_size;
2878 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002879 }
2880
Chris Lattnerf1690852009-03-31 08:48:01 +00002881 for (int i = OldSkIndex+1; i <= FirstSkIndex; ++i) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002882 GC_IVAR skivar;
2883 skivar.ivar_bytepos = SkipIvars[i].ivar_bytepos + Size*ElIx;
2884 skivar.ivar_size = SkipIvars[i].ivar_size;
2885 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002886 }
2887 }
2888 continue;
2889 }
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002890 }
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002891 // At this point, we are done with Record/Union and array there of.
2892 // For other arrays we are down to its element type.
2893 QualType::GCAttrTypes GCAttr = QualType::GCNone;
2894 do {
2895 if (FQT.isObjCGCStrong() || FQT.isObjCGCWeak()) {
2896 GCAttr = FQT.isObjCGCStrong() ? QualType::Strong : QualType::Weak;
2897 break;
2898 }
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002899 else if (CGM.getContext().isObjCObjectPointerType(FQT)) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002900 GCAttr = QualType::Strong;
2901 break;
2902 }
2903 else if (const PointerType *PT = FQT->getAsPointerType()) {
2904 FQT = PT->getPointeeType();
2905 }
2906 else {
2907 break;
2908 }
2909 } while (true);
Chris Lattnerf1690852009-03-31 08:48:01 +00002910
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002911 if ((ForStrongLayout && GCAttr == QualType::Strong)
2912 || (!ForStrongLayout && GCAttr == QualType::Weak)) {
2913 if (IsUnion)
2914 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002915 uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType())
2916 / WordSizeInBits;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002917 if (UnionIvarSize > MaxUnionIvarSize)
2918 {
2919 MaxUnionIvarSize = UnionIvarSize;
2920 MaxField = Field;
2921 }
2922 }
2923 else
2924 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002925 GC_IVAR gcivar;
2926 gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field);
2927 gcivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) /
2928 WordSizeInBits;
2929 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002930 }
2931 }
2932 else if ((ForStrongLayout &&
2933 (GCAttr == QualType::GCNone || GCAttr == QualType::Weak))
2934 || (!ForStrongLayout && GCAttr != QualType::Weak)) {
2935 if (IsUnion)
2936 {
2937 uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType());
2938 if (UnionIvarSize > MaxSkippedUnionIvarSize)
2939 {
2940 MaxSkippedUnionIvarSize = UnionIvarSize;
2941 MaxSkippedField = Field;
2942 }
2943 }
2944 else
2945 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002946 GC_IVAR skivar;
2947 skivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field);
2948 skivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) /
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002949 ByteSizeInBits;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002950 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002951 }
2952 }
2953 }
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002954 if (LastFieldBitfield) {
2955 // Last field was a bitfield. Must update skip info.
2956 GC_IVAR skivar;
2957 skivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout,
2958 LastFieldBitfield);
2959 Expr *BitWidth = LastFieldBitfield->getBitWidth();
2960 uint64_t BitFieldSize =
2961 BitWidth->getIntegerConstantExprValue(CGM.getContext()).getZExtValue();
2962 skivar.ivar_size = (BitFieldSize / ByteSizeInBits)
2963 + ((BitFieldSize % ByteSizeInBits) != 0);
2964 SkipIvars.push_back(skivar); ++SkIndex;
2965 }
2966
Chris Lattnerf1690852009-03-31 08:48:01 +00002967 if (MaxField) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002968 GC_IVAR gcivar;
2969 gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, MaxField);
2970 gcivar.ivar_size = MaxUnionIvarSize;
2971 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002972 }
Chris Lattnerf1690852009-03-31 08:48:01 +00002973
2974 if (MaxSkippedField) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002975 GC_IVAR skivar;
2976 skivar.ivar_bytepos = BytePos +
2977 GetFieldBaseOffset(OI, Layout, MaxSkippedField);
2978 skivar.ivar_size = MaxSkippedUnionIvarSize;
2979 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002980 }
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002981}
2982
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002983static int
Chris Lattnerf1690852009-03-31 08:48:01 +00002984IvarBytePosCompare(const void *a, const void *b)
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002985{
2986 unsigned int sa = ((CGObjCCommonMac::GC_IVAR *)a)->ivar_bytepos;
2987 unsigned int sb = ((CGObjCCommonMac::GC_IVAR *)b)->ivar_bytepos;
2988
2989 if (sa < sb)
2990 return -1;
2991 if (sa > sb)
2992 return 1;
2993 return 0;
2994}
2995
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002996/// BuildIvarLayout - Builds ivar layout bitmap for the class
2997/// implementation for the __strong or __weak case.
2998/// The layout map displays which words in ivar list must be skipped
2999/// and which must be scanned by GC (see below). String is built of bytes.
3000/// Each byte is divided up in two nibbles (4-bit each). Left nibble is count
3001/// of words to skip and right nibble is count of words to scan. So, each
3002/// nibble represents up to 15 workds to skip or scan. Skipping the rest is
3003/// represented by a 0x00 byte which also ends the string.
3004/// 1. when ForStrongLayout is true, following ivars are scanned:
3005/// - id, Class
3006/// - object *
3007/// - __strong anything
3008///
3009/// 2. When ForStrongLayout is false, following ivars are scanned:
3010/// - __weak anything
3011///
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003012llvm::Constant *CGObjCCommonMac::BuildIvarLayout(
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003013 const ObjCImplementationDecl *OMD,
3014 bool ForStrongLayout) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003015 int Index = -1;
3016 int SkIndex = -1;
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003017 bool hasUnion = false;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003018 int SkipScan;
3019 unsigned int WordsToScan, WordsToSkip;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003020 const llvm::Type *PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3021 if (CGM.getLangOptions().getGCMode() == LangOptions::NonGC)
3022 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003023
Chris Lattnerf1690852009-03-31 08:48:01 +00003024 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003025 const ObjCInterfaceDecl *OI = OMD->getClassInterface();
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003026 CGM.getContext().CollectObjCIvars(OI, RecFields);
3027 if (RecFields.empty())
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003028 return llvm::Constant::getNullValue(PtrTy);
Chris Lattnerf1690852009-03-31 08:48:01 +00003029
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003030 SkipIvars.clear();
3031 IvarsInfo.clear();
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00003032
3033 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OI);
Chris Lattnerf1690852009-03-31 08:48:01 +00003034 BuildAggrIvarLayout(OI, Layout, 0, RecFields, 0, ForStrongLayout,
3035 Index, SkIndex, hasUnion);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003036 if (Index == -1)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003037 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003038
3039 // Sort on byte position in case we encounterred a union nested in
3040 // the ivar list.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003041 if (hasUnion && !IvarsInfo.empty())
3042 qsort(&IvarsInfo[0], Index+1, sizeof(GC_IVAR), IvarBytePosCompare);
3043 if (hasUnion && !SkipIvars.empty())
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003044 qsort(&SkipIvars[0], Index+1, sizeof(GC_IVAR), IvarBytePosCompare);
3045
3046 // Build the string of skip/scan nibbles
3047 SkipScan = -1;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003048 SkipScanIvars.clear();
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003049 unsigned int WordSize =
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003050 CGM.getTypes().getTargetData().getTypePaddedSize(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003051 if (IvarsInfo[0].ivar_bytepos == 0) {
3052 WordsToSkip = 0;
3053 WordsToScan = IvarsInfo[0].ivar_size;
3054 }
3055 else {
3056 WordsToSkip = IvarsInfo[0].ivar_bytepos/WordSize;
3057 WordsToScan = IvarsInfo[0].ivar_size;
3058 }
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003059 for (unsigned int i=1, Last=IvarsInfo.size(); i != Last; i++)
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003060 {
3061 unsigned int TailPrevGCObjC =
3062 IvarsInfo[i-1].ivar_bytepos + IvarsInfo[i-1].ivar_size * WordSize;
3063 if (IvarsInfo[i].ivar_bytepos == TailPrevGCObjC)
3064 {
3065 // consecutive 'scanned' object pointers.
3066 WordsToScan += IvarsInfo[i].ivar_size;
3067 }
3068 else
3069 {
3070 // Skip over 'gc'able object pointer which lay over each other.
3071 if (TailPrevGCObjC > IvarsInfo[i].ivar_bytepos)
3072 continue;
3073 // Must skip over 1 or more words. We save current skip/scan values
3074 // and start a new pair.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003075 SKIP_SCAN SkScan;
3076 SkScan.skip = WordsToSkip;
3077 SkScan.scan = WordsToScan;
3078 SkipScanIvars.push_back(SkScan); ++SkipScan;
3079
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003080 // Skip the hole.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003081 SkScan.skip = (IvarsInfo[i].ivar_bytepos - TailPrevGCObjC) / WordSize;
3082 SkScan.scan = 0;
3083 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003084 WordsToSkip = 0;
3085 WordsToScan = IvarsInfo[i].ivar_size;
3086 }
3087 }
3088 if (WordsToScan > 0)
3089 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003090 SKIP_SCAN SkScan;
3091 SkScan.skip = WordsToSkip;
3092 SkScan.scan = WordsToScan;
3093 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003094 }
3095
3096 bool BytesSkipped = false;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003097 if (!SkipIvars.empty())
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003098 {
3099 int LastByteSkipped =
3100 SkipIvars[SkIndex].ivar_bytepos + SkipIvars[SkIndex].ivar_size;
3101 int LastByteScanned =
3102 IvarsInfo[Index].ivar_bytepos + IvarsInfo[Index].ivar_size * WordSize;
3103 BytesSkipped = (LastByteSkipped > LastByteScanned);
3104 // Compute number of bytes to skip at the tail end of the last ivar scanned.
3105 if (BytesSkipped)
3106 {
3107 unsigned int TotalWords = (LastByteSkipped + (WordSize -1)) / WordSize;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003108 SKIP_SCAN SkScan;
3109 SkScan.skip = TotalWords - (LastByteScanned/WordSize);
3110 SkScan.scan = 0;
3111 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003112 }
3113 }
3114 // Mini optimization of nibbles such that an 0xM0 followed by 0x0N is produced
3115 // as 0xMN.
3116 for (int i = 0; i <= SkipScan; i++)
3117 {
3118 if ((i < SkipScan) && SkipScanIvars[i].skip && SkipScanIvars[i].scan == 0
3119 && SkipScanIvars[i+1].skip == 0 && SkipScanIvars[i+1].scan) {
3120 // 0xM0 followed by 0x0N detected.
3121 SkipScanIvars[i].scan = SkipScanIvars[i+1].scan;
3122 for (int j = i+1; j < SkipScan; j++)
3123 SkipScanIvars[j] = SkipScanIvars[j+1];
3124 --SkipScan;
3125 }
3126 }
3127
3128 // Generate the string.
3129 std::string BitMap;
3130 for (int i = 0; i <= SkipScan; i++)
3131 {
3132 unsigned char byte;
3133 unsigned int skip_small = SkipScanIvars[i].skip % 0xf;
3134 unsigned int scan_small = SkipScanIvars[i].scan % 0xf;
3135 unsigned int skip_big = SkipScanIvars[i].skip / 0xf;
3136 unsigned int scan_big = SkipScanIvars[i].scan / 0xf;
3137
3138 if (skip_small > 0 || skip_big > 0)
3139 BytesSkipped = true;
3140 // first skip big.
3141 for (unsigned int ix = 0; ix < skip_big; ix++)
3142 BitMap += (unsigned char)(0xf0);
3143
3144 // next (skip small, scan)
3145 if (skip_small)
3146 {
3147 byte = skip_small << 4;
3148 if (scan_big > 0)
3149 {
3150 byte |= 0xf;
3151 --scan_big;
3152 }
3153 else if (scan_small)
3154 {
3155 byte |= scan_small;
3156 scan_small = 0;
3157 }
3158 BitMap += byte;
3159 }
3160 // next scan big
3161 for (unsigned int ix = 0; ix < scan_big; ix++)
3162 BitMap += (unsigned char)(0x0f);
3163 // last scan small
3164 if (scan_small)
3165 {
3166 byte = scan_small;
3167 BitMap += byte;
3168 }
3169 }
3170 // null terminate string.
Fariborz Jahanian667423a2009-03-25 22:36:49 +00003171 unsigned char zero = 0;
3172 BitMap += zero;
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00003173
3174 if (CGM.getLangOptions().ObjCGCBitmapPrint) {
3175 printf("\n%s ivar layout for class '%s': ",
3176 ForStrongLayout ? "strong" : "weak",
3177 OMD->getClassInterface()->getNameAsCString());
3178 const unsigned char *s = (unsigned char*)BitMap.c_str();
3179 for (unsigned i = 0; i < BitMap.size(); i++)
3180 if (!(s[i] & 0xf0))
3181 printf("0x0%x%s", s[i], s[i] != 0 ? ", " : "");
3182 else
3183 printf("0x%x%s", s[i], s[i] != 0 ? ", " : "");
3184 printf("\n");
3185 }
3186
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003187 // if ivar_layout bitmap is all 1 bits (nothing skipped) then use NULL as
3188 // final layout.
3189 if (ForStrongLayout && !BytesSkipped)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003190 return llvm::Constant::getNullValue(PtrTy);
3191 llvm::GlobalVariable * Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
3192 llvm::ConstantArray::get(BitMap.c_str()),
3193 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003194 1, true);
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00003195 return getConstantGEP(Entry, 0, 0);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003196}
3197
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003198llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003199 llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
3200
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003201 // FIXME: Avoid std::string copying.
3202 if (!Entry)
3203 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_NAME_",
3204 llvm::ConstantArray::get(Sel.getAsString()),
3205 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003206 1, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003207
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003208 return getConstantGEP(Entry, 0, 0);
3209}
3210
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003211// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003212llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003213 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
3214}
3215
3216// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003217llvm::Constant *CGObjCCommonMac::GetMethodVarName(const std::string &Name) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003218 return GetMethodVarName(&CGM.getContext().Idents.get(Name));
3219}
3220
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00003221llvm::Constant *CGObjCCommonMac::GetMethodVarType(const FieldDecl *Field) {
Devang Patel7794bb82009-03-04 18:21:39 +00003222 std::string TypeStr;
3223 CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
3224
3225 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003226
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003227 if (!Entry)
3228 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3229 llvm::ConstantArray::get(TypeStr),
3230 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003231 1, true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003232
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003233 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003234}
3235
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003236llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003237 std::string TypeStr;
Daniel Dunbarc45ef602008-08-26 21:51:14 +00003238 CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D),
3239 TypeStr);
Devang Patel7794bb82009-03-04 18:21:39 +00003240
3241 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
3242
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003243 if (!Entry)
3244 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3245 llvm::ConstantArray::get(TypeStr),
3246 "__TEXT,__cstring,cstring_literals",
3247 1, true);
Devang Patel7794bb82009-03-04 18:21:39 +00003248
3249 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003250}
3251
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003252// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003253llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003254 llvm::GlobalVariable *&Entry = PropertyNames[Ident];
3255
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003256 if (!Entry)
3257 Entry = CreateMetadataVar("\01L_OBJC_PROP_NAME_ATTR_",
3258 llvm::ConstantArray::get(Ident->getName()),
3259 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003260 1, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003261
3262 return getConstantGEP(Entry, 0, 0);
3263}
3264
3265// FIXME: Merge into a single cstring creation function.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003266// FIXME: This Decl should be more precise.
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003267llvm::Constant *
3268 CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
3269 const Decl *Container) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003270 std::string TypeStr;
3271 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003272 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
3273}
3274
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003275void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D,
3276 const ObjCContainerDecl *CD,
3277 std::string &NameOut) {
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00003278 NameOut = '\01';
3279 NameOut += (D->isInstanceMethod() ? '-' : '+');
Chris Lattner077bf5e2008-11-24 03:33:13 +00003280 NameOut += '[';
Fariborz Jahanian679a5022009-01-10 21:06:09 +00003281 assert (CD && "Missing container decl in GetNameForMethod");
3282 NameOut += CD->getNameAsString();
Fariborz Jahanian1e9aef32009-04-16 18:34:20 +00003283 if (const ObjCCategoryImplDecl *CID =
3284 dyn_cast<ObjCCategoryImplDecl>(D->getDeclContext())) {
3285 NameOut += '(';
3286 NameOut += CID->getNameAsString();
3287 NameOut+= ')';
3288 }
Chris Lattner077bf5e2008-11-24 03:33:13 +00003289 NameOut += ' ';
3290 NameOut += D->getSelector().getAsString();
3291 NameOut += ']';
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00003292}
3293
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003294void CGObjCMac::FinishModule() {
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003295 EmitModuleInfo();
3296
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003297 // Emit the dummy bodies for any protocols which were referenced but
3298 // never defined.
3299 for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
3300 i = Protocols.begin(), e = Protocols.end(); i != e; ++i) {
3301 if (i->second->hasInitializer())
3302 continue;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003303
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003304 std::vector<llvm::Constant*> Values(5);
3305 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
3306 Values[1] = GetClassName(i->first);
3307 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
3308 Values[3] = Values[4] =
3309 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
3310 i->second->setLinkage(llvm::GlobalValue::InternalLinkage);
3311 i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
3312 Values));
3313 }
3314
3315 std::vector<llvm::Constant*> Used;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003316 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003317 e = UsedGlobals.end(); i != e; ++i) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003318 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003319 }
3320
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003321 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003322 llvm::GlobalValue *GV =
3323 new llvm::GlobalVariable(AT, false,
3324 llvm::GlobalValue::AppendingLinkage,
3325 llvm::ConstantArray::get(AT, Used),
3326 "llvm.used",
3327 &CGM.getModule());
3328
3329 GV->setSection("llvm.metadata");
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003330
3331 // Add assembler directives to add lazy undefined symbol references
3332 // for classes which are referenced but not defined. This is
3333 // important for correct linker interaction.
3334
3335 // FIXME: Uh, this isn't particularly portable.
3336 std::stringstream s;
Anders Carlsson565c99f2008-12-10 02:21:04 +00003337
3338 if (!CGM.getModule().getModuleInlineAsm().empty())
3339 s << "\n";
3340
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003341 for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(),
3342 e = LazySymbols.end(); i != e; ++i) {
3343 s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n";
3344 }
3345 for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(),
3346 e = DefinedSymbols.end(); i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003347 s << "\t.objc_class_name_" << (*i)->getName() << "=0\n"
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003348 << "\t.globl .objc_class_name_" << (*i)->getName() << "\n";
3349 }
Anders Carlsson565c99f2008-12-10 02:21:04 +00003350
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003351 CGM.getModule().appendModuleInlineAsm(s.str());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003352}
3353
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003354CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003355 : CGObjCCommonMac(cgm),
3356 ObjCTypes(cgm)
3357{
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003358 ObjCEmptyCacheVar = ObjCEmptyVtableVar = NULL;
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003359 ObjCABI = 2;
3360}
3361
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003362/* *** */
3363
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003364ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm)
3365: CGM(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003366{
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003367 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3368 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003369
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003370 ShortTy = Types.ConvertType(Ctx.ShortTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003371 IntTy = Types.ConvertType(Ctx.IntTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003372 LongTy = Types.ConvertType(Ctx.LongTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00003373 LongLongTy = Types.ConvertType(Ctx.LongLongTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003374 Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3375
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003376 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00003377 PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003378 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003379
3380 // FIXME: It would be nice to unify this with the opaque type, so
3381 // that the IR comes out a bit cleaner.
3382 const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
3383 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003384
3385 // I'm not sure I like this. The implicit coordination is a bit
3386 // gross. We should solve this in a reasonable fashion because this
3387 // is a pretty common task (match some runtime data structure with
3388 // an LLVM data structure).
3389
3390 // FIXME: This is leaked.
3391 // FIXME: Merge with rewriter code?
3392
3393 // struct _objc_super {
3394 // id self;
3395 // Class cls;
3396 // }
3397 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3398 SourceLocation(),
3399 &Ctx.Idents.get("_objc_super"));
Douglas Gregor6ab35242009-04-09 21:40:53 +00003400 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3401 Ctx.getObjCIdType(), 0, false));
3402 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3403 Ctx.getObjCClassType(), 0, false));
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003404 RD->completeDefinition(Ctx);
3405
3406 SuperCTy = Ctx.getTagDeclType(RD);
3407 SuperPtrCTy = Ctx.getPointerType(SuperCTy);
3408
3409 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003410 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
3411
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003412 // struct _prop_t {
3413 // char *name;
3414 // char *attributes;
3415 // }
3416 PropertyTy = llvm::StructType::get(Int8PtrTy,
3417 Int8PtrTy,
3418 NULL);
3419 CGM.getModule().addTypeName("struct._prop_t",
3420 PropertyTy);
3421
3422 // struct _prop_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003423 // uint32_t entsize; // sizeof(struct _prop_t)
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003424 // uint32_t count_of_properties;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003425 // struct _prop_t prop_list[count_of_properties];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003426 // }
3427 PropertyListTy = llvm::StructType::get(IntTy,
3428 IntTy,
3429 llvm::ArrayType::get(PropertyTy, 0),
3430 NULL);
3431 CGM.getModule().addTypeName("struct._prop_list_t",
3432 PropertyListTy);
3433 // struct _prop_list_t *
3434 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
3435
3436 // struct _objc_method {
3437 // SEL _cmd;
3438 // char *method_type;
3439 // char *_imp;
3440 // }
3441 MethodTy = llvm::StructType::get(SelectorPtrTy,
3442 Int8PtrTy,
3443 Int8PtrTy,
3444 NULL);
3445 CGM.getModule().addTypeName("struct._objc_method", MethodTy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003446
3447 // struct _objc_cache *
3448 CacheTy = llvm::OpaqueType::get();
3449 CGM.getModule().addTypeName("struct._objc_cache", CacheTy);
3450 CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003451}
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003452
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003453ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
3454 : ObjCCommonTypesHelper(cgm)
3455{
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003456 // struct _objc_method_description {
3457 // SEL name;
3458 // char *types;
3459 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003460 MethodDescriptionTy =
3461 llvm::StructType::get(SelectorPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003462 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003463 NULL);
3464 CGM.getModule().addTypeName("struct._objc_method_description",
3465 MethodDescriptionTy);
3466
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003467 // struct _objc_method_description_list {
3468 // int count;
3469 // struct _objc_method_description[1];
3470 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003471 MethodDescriptionListTy =
3472 llvm::StructType::get(IntTy,
3473 llvm::ArrayType::get(MethodDescriptionTy, 0),
3474 NULL);
3475 CGM.getModule().addTypeName("struct._objc_method_description_list",
3476 MethodDescriptionListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003477
3478 // struct _objc_method_description_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003479 MethodDescriptionListPtrTy =
3480 llvm::PointerType::getUnqual(MethodDescriptionListTy);
3481
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003482 // Protocol description structures
3483
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003484 // struct _objc_protocol_extension {
3485 // uint32_t size; // sizeof(struct _objc_protocol_extension)
3486 // struct _objc_method_description_list *optional_instance_methods;
3487 // struct _objc_method_description_list *optional_class_methods;
3488 // struct _objc_property_list *instance_properties;
3489 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003490 ProtocolExtensionTy =
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003491 llvm::StructType::get(IntTy,
3492 MethodDescriptionListPtrTy,
3493 MethodDescriptionListPtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003494 PropertyListPtrTy,
3495 NULL);
3496 CGM.getModule().addTypeName("struct._objc_protocol_extension",
3497 ProtocolExtensionTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003498
3499 // struct _objc_protocol_extension *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003500 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
3501
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003502 // Handle recursive construction of Protocol and ProtocolList types
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003503
3504 llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get();
3505 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3506
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003507 const llvm::Type *T =
3508 llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder),
3509 LongTy,
3510 llvm::ArrayType::get(ProtocolTyHolder, 0),
3511 NULL);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003512 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T);
3513
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003514 // struct _objc_protocol {
3515 // struct _objc_protocol_extension *isa;
3516 // char *protocol_name;
3517 // struct _objc_protocol **_objc_protocol_list;
3518 // struct _objc_method_description_list *instance_methods;
3519 // struct _objc_method_description_list *class_methods;
3520 // }
3521 T = llvm::StructType::get(ProtocolExtensionPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003522 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003523 llvm::PointerType::getUnqual(ProtocolListTyHolder),
3524 MethodDescriptionListPtrTy,
3525 MethodDescriptionListPtrTy,
3526 NULL);
3527 cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T);
3528
3529 ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get());
3530 CGM.getModule().addTypeName("struct._objc_protocol_list",
3531 ProtocolListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003532 // struct _objc_protocol_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003533 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
3534
3535 ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get());
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003536 CGM.getModule().addTypeName("struct._objc_protocol", ProtocolTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003537 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003538
3539 // Class description structures
3540
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003541 // struct _objc_ivar {
3542 // char *ivar_name;
3543 // char *ivar_type;
3544 // int ivar_offset;
3545 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003546 IvarTy = llvm::StructType::get(Int8PtrTy,
3547 Int8PtrTy,
3548 IntTy,
3549 NULL);
3550 CGM.getModule().addTypeName("struct._objc_ivar", IvarTy);
3551
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003552 // struct _objc_ivar_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003553 IvarListTy = llvm::OpaqueType::get();
3554 CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy);
3555 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
3556
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003557 // struct _objc_method_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003558 MethodListTy = llvm::OpaqueType::get();
3559 CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy);
3560 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
3561
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003562 // struct _objc_class_extension *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003563 ClassExtensionTy =
3564 llvm::StructType::get(IntTy,
3565 Int8PtrTy,
3566 PropertyListPtrTy,
3567 NULL);
3568 CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy);
3569 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
3570
3571 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3572
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003573 // struct _objc_class {
3574 // Class isa;
3575 // Class super_class;
3576 // char *name;
3577 // long version;
3578 // long info;
3579 // long instance_size;
3580 // struct _objc_ivar_list *ivars;
3581 // struct _objc_method_list *methods;
3582 // struct _objc_cache *cache;
3583 // struct _objc_protocol_list *protocols;
3584 // char *ivar_layout;
3585 // struct _objc_class_ext *ext;
3586 // };
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003587 T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3588 llvm::PointerType::getUnqual(ClassTyHolder),
3589 Int8PtrTy,
3590 LongTy,
3591 LongTy,
3592 LongTy,
3593 IvarListPtrTy,
3594 MethodListPtrTy,
3595 CachePtrTy,
3596 ProtocolListPtrTy,
3597 Int8PtrTy,
3598 ClassExtensionPtrTy,
3599 NULL);
3600 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T);
3601
3602 ClassTy = cast<llvm::StructType>(ClassTyHolder.get());
3603 CGM.getModule().addTypeName("struct._objc_class", ClassTy);
3604 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
3605
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003606 // struct _objc_category {
3607 // char *category_name;
3608 // char *class_name;
3609 // struct _objc_method_list *instance_method;
3610 // struct _objc_method_list *class_method;
3611 // uint32_t size; // sizeof(struct _objc_category)
3612 // struct _objc_property_list *instance_properties;// category's @property
3613 // }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003614 CategoryTy = llvm::StructType::get(Int8PtrTy,
3615 Int8PtrTy,
3616 MethodListPtrTy,
3617 MethodListPtrTy,
3618 ProtocolListPtrTy,
3619 IntTy,
3620 PropertyListPtrTy,
3621 NULL);
3622 CGM.getModule().addTypeName("struct._objc_category", CategoryTy);
3623
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003624 // Global metadata structures
3625
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003626 // struct _objc_symtab {
3627 // long sel_ref_cnt;
3628 // SEL *refs;
3629 // short cls_def_cnt;
3630 // short cat_def_cnt;
3631 // char *defs[cls_def_cnt + cat_def_cnt];
3632 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003633 SymtabTy = llvm::StructType::get(LongTy,
3634 SelectorPtrTy,
3635 ShortTy,
3636 ShortTy,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003637 llvm::ArrayType::get(Int8PtrTy, 0),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003638 NULL);
3639 CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy);
3640 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
3641
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003642 // struct _objc_module {
3643 // long version;
3644 // long size; // sizeof(struct _objc_module)
3645 // char *name;
3646 // struct _objc_symtab* symtab;
3647 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003648 ModuleTy =
3649 llvm::StructType::get(LongTy,
3650 LongTy,
3651 Int8PtrTy,
3652 SymtabPtrTy,
3653 NULL);
3654 CGM.getModule().addTypeName("struct._objc_module", ModuleTy);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003655
Anders Carlsson2abd89c2008-08-31 04:05:03 +00003656
Anders Carlsson124526b2008-09-09 10:10:21 +00003657 // FIXME: This is the size of the setjmp buffer and should be
3658 // target specific. 18 is what's used on 32-bit X86.
3659 uint64_t SetJmpBufferSize = 18;
3660
3661 // Exceptions
3662 const llvm::Type *StackPtrTy =
Daniel Dunbar10004912008-09-27 06:32:25 +00003663 llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4);
Anders Carlsson124526b2008-09-09 10:10:21 +00003664
3665 ExceptionDataTy =
3666 llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty,
3667 SetJmpBufferSize),
3668 StackPtrTy, NULL);
3669 CGM.getModule().addTypeName("struct._objc_exception_data",
3670 ExceptionDataTy);
3671
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003672}
3673
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003674ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003675: ObjCCommonTypesHelper(cgm)
3676{
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003677 // struct _method_list_t {
3678 // uint32_t entsize; // sizeof(struct _objc_method)
3679 // uint32_t method_count;
3680 // struct _objc_method method_list[method_count];
3681 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003682 MethodListnfABITy = llvm::StructType::get(IntTy,
3683 IntTy,
3684 llvm::ArrayType::get(MethodTy, 0),
3685 NULL);
3686 CGM.getModule().addTypeName("struct.__method_list_t",
3687 MethodListnfABITy);
3688 // struct method_list_t *
3689 MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003690
3691 // struct _protocol_t {
3692 // id isa; // NULL
3693 // const char * const protocol_name;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003694 // const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003695 // const struct method_list_t * const instance_methods;
3696 // const struct method_list_t * const class_methods;
3697 // const struct method_list_t *optionalInstanceMethods;
3698 // const struct method_list_t *optionalClassMethods;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003699 // const struct _prop_list_t * properties;
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003700 // const uint32_t size; // sizeof(struct _protocol_t)
3701 // const uint32_t flags; // = 0
3702 // }
3703
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003704 // Holder for struct _protocol_list_t *
3705 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3706
3707 ProtocolnfABITy = llvm::StructType::get(ObjectPtrTy,
3708 Int8PtrTy,
3709 llvm::PointerType::getUnqual(
3710 ProtocolListTyHolder),
3711 MethodListnfABIPtrTy,
3712 MethodListnfABIPtrTy,
3713 MethodListnfABIPtrTy,
3714 MethodListnfABIPtrTy,
3715 PropertyListPtrTy,
3716 IntTy,
3717 IntTy,
3718 NULL);
3719 CGM.getModule().addTypeName("struct._protocol_t",
3720 ProtocolnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003721
3722 // struct _protocol_t*
3723 ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003724
Fariborz Jahanianda320092009-01-29 19:24:30 +00003725 // struct _protocol_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003726 // long protocol_count; // Note, this is 32/64 bit
Daniel Dunbar948e2582009-02-15 07:36:20 +00003727 // struct _protocol_t *[protocol_count];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003728 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003729 ProtocolListnfABITy = llvm::StructType::get(LongTy,
3730 llvm::ArrayType::get(
Daniel Dunbar948e2582009-02-15 07:36:20 +00003731 ProtocolnfABIPtrTy, 0),
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003732 NULL);
3733 CGM.getModule().addTypeName("struct._objc_protocol_list",
3734 ProtocolListnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003735 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(
3736 ProtocolListnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003737
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003738 // struct _objc_protocol_list*
3739 ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003740
3741 // struct _ivar_t {
3742 // unsigned long int *offset; // pointer to ivar offset location
3743 // char *name;
3744 // char *type;
3745 // uint32_t alignment;
3746 // uint32_t size;
3747 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003748 IvarnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(LongTy),
3749 Int8PtrTy,
3750 Int8PtrTy,
3751 IntTy,
3752 IntTy,
3753 NULL);
3754 CGM.getModule().addTypeName("struct._ivar_t", IvarnfABITy);
3755
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003756 // struct _ivar_list_t {
3757 // uint32 entsize; // sizeof(struct _ivar_t)
3758 // uint32 count;
3759 // struct _iver_t list[count];
3760 // }
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003761 IvarListnfABITy = llvm::StructType::get(IntTy,
3762 IntTy,
3763 llvm::ArrayType::get(
3764 IvarnfABITy, 0),
3765 NULL);
3766 CGM.getModule().addTypeName("struct._ivar_list_t", IvarListnfABITy);
3767
3768 IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003769
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003770 // struct _class_ro_t {
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003771 // uint32_t const flags;
3772 // uint32_t const instanceStart;
3773 // uint32_t const instanceSize;
3774 // uint32_t const reserved; // only when building for 64bit targets
3775 // const uint8_t * const ivarLayout;
3776 // const char *const name;
3777 // const struct _method_list_t * const baseMethods;
3778 // const struct _objc_protocol_list *const baseProtocols;
3779 // const struct _ivar_list_t *const ivars;
3780 // const uint8_t * const weakIvarLayout;
3781 // const struct _prop_list_t * const properties;
3782 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003783
3784 // FIXME. Add 'reserved' field in 64bit abi mode!
3785 ClassRonfABITy = llvm::StructType::get(IntTy,
3786 IntTy,
3787 IntTy,
3788 Int8PtrTy,
3789 Int8PtrTy,
3790 MethodListnfABIPtrTy,
3791 ProtocolListnfABIPtrTy,
3792 IvarListnfABIPtrTy,
3793 Int8PtrTy,
3794 PropertyListPtrTy,
3795 NULL);
3796 CGM.getModule().addTypeName("struct._class_ro_t",
3797 ClassRonfABITy);
3798
3799 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
3800 std::vector<const llvm::Type*> Params;
3801 Params.push_back(ObjectPtrTy);
3802 Params.push_back(SelectorPtrTy);
3803 ImpnfABITy = llvm::PointerType::getUnqual(
3804 llvm::FunctionType::get(ObjectPtrTy, Params, false));
3805
3806 // struct _class_t {
3807 // struct _class_t *isa;
3808 // struct _class_t * const superclass;
3809 // void *cache;
3810 // IMP *vtable;
3811 // struct class_ro_t *ro;
3812 // }
3813
3814 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3815 ClassnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3816 llvm::PointerType::getUnqual(ClassTyHolder),
3817 CachePtrTy,
3818 llvm::PointerType::getUnqual(ImpnfABITy),
3819 llvm::PointerType::getUnqual(
3820 ClassRonfABITy),
3821 NULL);
3822 CGM.getModule().addTypeName("struct._class_t", ClassnfABITy);
3823
3824 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(
3825 ClassnfABITy);
3826
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003827 // LLVM for struct _class_t *
3828 ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy);
3829
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003830 // struct _category_t {
3831 // const char * const name;
3832 // struct _class_t *const cls;
3833 // const struct _method_list_t * const instance_methods;
3834 // const struct _method_list_t * const class_methods;
3835 // const struct _protocol_list_t * const protocols;
3836 // const struct _prop_list_t * const properties;
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003837 // }
3838 CategorynfABITy = llvm::StructType::get(Int8PtrTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003839 ClassnfABIPtrTy,
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003840 MethodListnfABIPtrTy,
3841 MethodListnfABIPtrTy,
3842 ProtocolListnfABIPtrTy,
3843 PropertyListPtrTy,
3844 NULL);
3845 CGM.getModule().addTypeName("struct._category_t", CategorynfABITy);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003846
3847 // New types for nonfragile abi messaging.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003848 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3849 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003850
3851 // MessageRefTy - LLVM for:
3852 // struct _message_ref_t {
3853 // IMP messenger;
3854 // SEL name;
3855 // };
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003856
3857 // First the clang type for struct _message_ref_t
3858 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3859 SourceLocation(),
3860 &Ctx.Idents.get("_message_ref_t"));
Douglas Gregor6ab35242009-04-09 21:40:53 +00003861 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3862 Ctx.VoidPtrTy, 0, false));
3863 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3864 Ctx.getObjCSelType(), 0, false));
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003865 RD->completeDefinition(Ctx);
3866
3867 MessageRefCTy = Ctx.getTagDeclType(RD);
3868 MessageRefCPtrTy = Ctx.getPointerType(MessageRefCTy);
3869 MessageRefTy = cast<llvm::StructType>(Types.ConvertType(MessageRefCTy));
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003870
3871 // MessageRefPtrTy - LLVM for struct _message_ref_t*
3872 MessageRefPtrTy = llvm::PointerType::getUnqual(MessageRefTy);
3873
3874 // SuperMessageRefTy - LLVM for:
3875 // struct _super_message_ref_t {
3876 // SUPER_IMP messenger;
3877 // SEL name;
3878 // };
3879 SuperMessageRefTy = llvm::StructType::get(ImpnfABITy,
3880 SelectorPtrTy,
3881 NULL);
3882 CGM.getModule().addTypeName("struct._super_message_ref_t", SuperMessageRefTy);
3883
3884 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
3885 SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy);
3886
3887 // id objc_msgSend_fixup (id, struct message_ref_t*, ...)
3888 Params.clear();
3889 Params.push_back(ObjectPtrTy);
3890 Params.push_back(MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00003891 MessengerTy = llvm::FunctionType::get(ObjectPtrTy,
3892 Params,
3893 true);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003894 MessageSendFixupFn =
Fariborz Jahanianef163782009-02-05 01:13:09 +00003895 CGM.CreateRuntimeFunction(MessengerTy,
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003896 "objc_msgSend_fixup");
3897
3898 // id objc_msgSend_fpret_fixup (id, struct message_ref_t*, ...)
3899 MessageSendFpretFixupFn =
3900 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3901 Params,
3902 true),
3903 "objc_msgSend_fpret_fixup");
3904
3905 // id objc_msgSend_stret_fixup (id, struct message_ref_t*, ...)
3906 MessageSendStretFixupFn =
3907 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3908 Params,
3909 true),
3910 "objc_msgSend_stret_fixup");
3911
3912 // id objc_msgSendId_fixup (id, struct message_ref_t*, ...)
3913 MessageSendIdFixupFn =
3914 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3915 Params,
3916 true),
3917 "objc_msgSendId_fixup");
3918
3919
3920 // id objc_msgSendId_stret_fixup (id, struct message_ref_t*, ...)
3921 MessageSendIdStretFixupFn =
3922 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3923 Params,
3924 true),
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003925 "objc_msgSendId_stret_fixup");
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003926
3927 // id objc_msgSendSuper2_fixup (struct objc_super *,
3928 // struct _super_message_ref_t*, ...)
3929 Params.clear();
3930 Params.push_back(SuperPtrTy);
3931 Params.push_back(SuperMessageRefPtrTy);
3932 MessageSendSuper2FixupFn =
3933 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3934 Params,
3935 true),
3936 "objc_msgSendSuper2_fixup");
3937
3938
3939 // id objc_msgSendSuper2_stret_fixup (struct objc_super *,
3940 // struct _super_message_ref_t*, ...)
3941 MessageSendSuper2StretFixupFn =
3942 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3943 Params,
3944 true),
3945 "objc_msgSendSuper2_stret_fixup");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00003946
3947 Params.clear();
Daniel Dunbare588b992009-03-01 04:46:24 +00003948
3949 // struct objc_typeinfo {
3950 // const void** vtable; // objc_ehtype_vtable + 2
3951 // const char* name; // c++ typeinfo string
3952 // Class cls;
3953 // };
3954 EHTypeTy = llvm::StructType::get(llvm::PointerType::getUnqual(Int8PtrTy),
3955 Int8PtrTy,
3956 ClassnfABIPtrTy,
3957 NULL);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00003958 CGM.getModule().addTypeName("struct._objc_typeinfo", EHTypeTy);
Daniel Dunbare588b992009-03-01 04:46:24 +00003959 EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy);
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003960}
3961
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003962llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() {
3963 FinishNonFragileABIModule();
3964
3965 return NULL;
3966}
3967
3968void CGObjCNonFragileABIMac::FinishNonFragileABIModule() {
3969 // nonfragile abi has no module definition.
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003970
3971 // Build list of all implemented classe addresses in array
3972 // L_OBJC_LABEL_CLASS_$.
3973 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CLASS_$
3974 // list of 'nonlazy' implementations (defined as those with a +load{}
3975 // method!!).
3976 unsigned NumClasses = DefinedClasses.size();
3977 if (NumClasses) {
3978 std::vector<llvm::Constant*> Symbols(NumClasses);
3979 for (unsigned i=0; i<NumClasses; i++)
3980 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
3981 ObjCTypes.Int8PtrTy);
3982 llvm::Constant* Init =
3983 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
3984 NumClasses),
3985 Symbols);
3986
3987 llvm::GlobalVariable *GV =
3988 new llvm::GlobalVariable(Init->getType(), false,
3989 llvm::GlobalValue::InternalLinkage,
3990 Init,
3991 "\01L_OBJC_LABEL_CLASS_$",
3992 &CGM.getModule());
Daniel Dunbar58a29122009-03-09 22:18:41 +00003993 GV->setAlignment(8);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003994 GV->setSection("__DATA, __objc_classlist, regular, no_dead_strip");
3995 UsedGlobals.push_back(GV);
3996 }
3997
3998 // Build list of all implemented category addresses in array
3999 // L_OBJC_LABEL_CATEGORY_$.
4000 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CATEGORY_$
4001 // list of 'nonlazy' category implementations (defined as those with a +load{}
4002 // method!!).
4003 unsigned NumCategory = DefinedCategories.size();
4004 if (NumCategory) {
4005 std::vector<llvm::Constant*> Symbols(NumCategory);
4006 for (unsigned i=0; i<NumCategory; i++)
4007 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedCategories[i],
4008 ObjCTypes.Int8PtrTy);
4009 llvm::Constant* Init =
4010 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
4011 NumCategory),
4012 Symbols);
4013
4014 llvm::GlobalVariable *GV =
4015 new llvm::GlobalVariable(Init->getType(), false,
4016 llvm::GlobalValue::InternalLinkage,
4017 Init,
4018 "\01L_OBJC_LABEL_CATEGORY_$",
4019 &CGM.getModule());
Daniel Dunbar58a29122009-03-09 22:18:41 +00004020 GV->setAlignment(8);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004021 GV->setSection("__DATA, __objc_catlist, regular, no_dead_strip");
4022 UsedGlobals.push_back(GV);
4023 }
4024
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004025 // static int L_OBJC_IMAGE_INFO[2] = { 0, flags };
4026 // FIXME. flags can be 0 | 1 | 2 | 6. For now just use 0
4027 std::vector<llvm::Constant*> Values(2);
4028 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, 0);
Fariborz Jahanian067986e2009-02-24 21:08:09 +00004029 unsigned int flags = 0;
Fariborz Jahanian66a5c2c2009-02-24 23:34:44 +00004030 // FIXME: Fix and continue?
4031 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
4032 flags |= eImageInfo_GarbageCollected;
4033 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
4034 flags |= eImageInfo_GCOnly;
Fariborz Jahanian067986e2009-02-24 21:08:09 +00004035 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004036 llvm::Constant* Init = llvm::ConstantArray::get(
4037 llvm::ArrayType::get(ObjCTypes.IntTy, 2),
4038 Values);
4039 llvm::GlobalVariable *IMGV =
4040 new llvm::GlobalVariable(Init->getType(), false,
4041 llvm::GlobalValue::InternalLinkage,
4042 Init,
4043 "\01L_OBJC_IMAGE_INFO",
4044 &CGM.getModule());
4045 IMGV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
4046 UsedGlobals.push_back(IMGV);
4047
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004048 std::vector<llvm::Constant*> Used;
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004049
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004050 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
4051 e = UsedGlobals.end(); i != e; ++i) {
4052 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
4053 }
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004054
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004055 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
4056 llvm::GlobalValue *GV =
4057 new llvm::GlobalVariable(AT, false,
4058 llvm::GlobalValue::AppendingLinkage,
4059 llvm::ConstantArray::get(AT, Used),
4060 "llvm.used",
4061 &CGM.getModule());
4062
4063 GV->setSection("llvm.metadata");
4064
4065}
4066
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004067// Metadata flags
4068enum MetaDataDlags {
4069 CLS = 0x0,
4070 CLS_META = 0x1,
4071 CLS_ROOT = 0x2,
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004072 OBJC2_CLS_HIDDEN = 0x10,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004073 CLS_EXCEPTION = 0x20
4074};
4075/// BuildClassRoTInitializer - generate meta-data for:
4076/// struct _class_ro_t {
4077/// uint32_t const flags;
4078/// uint32_t const instanceStart;
4079/// uint32_t const instanceSize;
4080/// uint32_t const reserved; // only when building for 64bit targets
4081/// const uint8_t * const ivarLayout;
4082/// const char *const name;
4083/// const struct _method_list_t * const baseMethods;
Fariborz Jahanianda320092009-01-29 19:24:30 +00004084/// const struct _protocol_list_t *const baseProtocols;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004085/// const struct _ivar_list_t *const ivars;
4086/// const uint8_t * const weakIvarLayout;
4087/// const struct _prop_list_t * const properties;
4088/// }
4089///
4090llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer(
4091 unsigned flags,
4092 unsigned InstanceStart,
4093 unsigned InstanceSize,
4094 const ObjCImplementationDecl *ID) {
4095 std::string ClassName = ID->getNameAsString();
4096 std::vector<llvm::Constant*> Values(10); // 11 for 64bit targets!
4097 Values[ 0] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
4098 Values[ 1] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceStart);
4099 Values[ 2] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceSize);
4100 // FIXME. For 64bit targets add 0 here.
Fariborz Jahanianda320092009-01-29 19:24:30 +00004101 // FIXME. ivarLayout is currently null!
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00004102 // Values[ 3] = (flags & CLS_META) ? GetIvarLayoutName(0, ObjCTypes)
4103 // : BuildIvarLayout(ID, true);
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00004104 Values[ 3] = GetIvarLayoutName(0, ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004105 Values[ 4] = GetClassName(ID->getIdentifier());
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004106 // const struct _method_list_t * const baseMethods;
4107 std::vector<llvm::Constant*> Methods;
4108 std::string MethodListName("\01l_OBJC_$_");
4109 if (flags & CLS_META) {
4110 MethodListName += "CLASS_METHODS_" + ID->getNameAsString();
4111 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
4112 e = ID->classmeth_end(); i != e; ++i) {
4113 // Class methods should always be defined.
4114 Methods.push_back(GetMethodConstant(*i));
4115 }
4116 } else {
4117 MethodListName += "INSTANCE_METHODS_" + ID->getNameAsString();
4118 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
4119 e = ID->instmeth_end(); i != e; ++i) {
4120 // Instance methods should always be defined.
4121 Methods.push_back(GetMethodConstant(*i));
4122 }
Fariborz Jahanian939abce2009-01-28 22:46:49 +00004123 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
4124 e = ID->propimpl_end(); i != e; ++i) {
4125 ObjCPropertyImplDecl *PID = *i;
4126
4127 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize){
4128 ObjCPropertyDecl *PD = PID->getPropertyDecl();
4129
4130 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
4131 if (llvm::Constant *C = GetMethodConstant(MD))
4132 Methods.push_back(C);
4133 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
4134 if (llvm::Constant *C = GetMethodConstant(MD))
4135 Methods.push_back(C);
4136 }
4137 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004138 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004139 Values[ 5] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004140 "__DATA, __objc_const", Methods);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004141
4142 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4143 assert(OID && "CGObjCNonFragileABIMac::BuildClassRoTInitializer");
4144 Values[ 6] = EmitProtocolList("\01l_OBJC_CLASS_PROTOCOLS_$_"
4145 + OID->getNameAsString(),
4146 OID->protocol_begin(),
4147 OID->protocol_end());
4148
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004149 if (flags & CLS_META)
4150 Values[ 7] = llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4151 else
4152 Values[ 7] = EmitIvarList(ID);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004153 // FIXME. weakIvarLayout is currently null.
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00004154 // Values[ 8] = (flags & CLS_META) ? GetIvarLayoutName(0, ObjCTypes)
4155 // : BuildIvarLayout(ID, false);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00004156 Values[ 8] = GetIvarLayoutName(0, ObjCTypes);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004157 if (flags & CLS_META)
4158 Values[ 9] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4159 else
4160 Values[ 9] =
4161 EmitPropertyList(
4162 "\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
4163 ID, ID->getClassInterface(), ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004164 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassRonfABITy,
4165 Values);
4166 llvm::GlobalVariable *CLASS_RO_GV =
4167 new llvm::GlobalVariable(ObjCTypes.ClassRonfABITy, false,
4168 llvm::GlobalValue::InternalLinkage,
4169 Init,
4170 (flags & CLS_META) ?
4171 std::string("\01l_OBJC_METACLASS_RO_$_")+ClassName :
4172 std::string("\01l_OBJC_CLASS_RO_$_")+ClassName,
4173 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004174 CLASS_RO_GV->setAlignment(
4175 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassRonfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004176 CLASS_RO_GV->setSection("__DATA, __objc_const");
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004177 return CLASS_RO_GV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004178
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004179}
4180
4181/// BuildClassMetaData - This routine defines that to-level meta-data
4182/// for the given ClassName for:
4183/// struct _class_t {
4184/// struct _class_t *isa;
4185/// struct _class_t * const superclass;
4186/// void *cache;
4187/// IMP *vtable;
4188/// struct class_ro_t *ro;
4189/// }
4190///
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004191llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassMetaData(
4192 std::string &ClassName,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004193 llvm::Constant *IsAGV,
4194 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004195 llvm::Constant *ClassRoGV,
4196 bool HiddenVisibility) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004197 std::vector<llvm::Constant*> Values(5);
4198 Values[0] = IsAGV;
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004199 Values[1] = SuperClassGV
4200 ? SuperClassGV
4201 : llvm::Constant::getNullValue(ObjCTypes.ClassnfABIPtrTy);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004202 Values[2] = ObjCEmptyCacheVar; // &ObjCEmptyCacheVar
4203 Values[3] = ObjCEmptyVtableVar; // &ObjCEmptyVtableVar
4204 Values[4] = ClassRoGV; // &CLASS_RO_GV
4205 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassnfABITy,
4206 Values);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004207 llvm::GlobalVariable *GV = GetClassGlobal(ClassName);
4208 GV->setInitializer(Init);
Fariborz Jahaniandd0db2a2009-01-31 01:07:39 +00004209 GV->setSection("__DATA, __objc_data");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004210 GV->setAlignment(
4211 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassnfABITy));
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004212 if (HiddenVisibility)
4213 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004214 return GV;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004215}
4216
Daniel Dunbar6c1aac82009-04-20 20:18:54 +00004217/// countInheritedIvars - count number of ivars in class and its super class(s)
4218///
4219static int countInheritedIvars(const ObjCInterfaceDecl *OI,
4220 ASTContext &Context) {
4221 int count = 0;
4222 if (!OI)
4223 return 0;
4224 const ObjCInterfaceDecl *SuperClass = OI->getSuperClass();
4225 if (SuperClass)
4226 count += countInheritedIvars(SuperClass, Context);
4227 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
4228 E = OI->ivar_end(); I != E; ++I)
4229 ++count;
4230 // look into properties.
4231 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(Context),
4232 E = OI->prop_end(Context); I != E; ++I) {
4233 if ((*I)->getPropertyIvarDecl())
4234 ++count;
4235 }
4236 return count;
4237}
4238
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004239void CGObjCNonFragileABIMac::GetClassSizeInfo(const ObjCInterfaceDecl *OID,
4240 uint32_t &InstanceStart,
4241 uint32_t &InstanceSize) {
Daniel Dunbar24c89912009-04-21 21:41:56 +00004242 assert(!OID->isForwardDecl() && "Invalid interface decl!");
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004243 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID);
4244
Daniel Dunbar6ec07162009-04-20 07:18:49 +00004245 int countSuperClassIvars = countInheritedIvars(OID->getSuperClass(),
4246 CGM.getContext());
4247 const RecordDecl *RD = CGM.getContext().addRecordToClass(OID);
4248 RecordDecl::field_iterator firstField = RD->field_begin(CGM.getContext());
4249 RecordDecl::field_iterator lastField = RD->field_end(CGM.getContext());
4250 while (countSuperClassIvars-- > 0) {
4251 lastField = firstField;
4252 ++firstField;
4253 }
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004254
4255 for (RecordDecl::field_iterator e = RD->field_end(CGM.getContext()),
4256 ifield = firstField; ifield != e; ++ifield)
4257 lastField = ifield;
4258
4259 InstanceStart = InstanceSize = 0;
4260 if (lastField != RD->field_end(CGM.getContext())) {
4261 FieldDecl *Field = *lastField;
4262 const llvm::Type *FieldTy =
4263 CGM.getTypes().ConvertTypeForMem(Field->getType());
4264 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
4265 InstanceSize = GetIvarBaseOffset(Layout, Field) + Size;
4266 if (firstField == RD->field_end(CGM.getContext()))
4267 InstanceStart = InstanceSize;
4268 else {
4269 Field = *firstField;
4270 InstanceStart = GetIvarBaseOffset(Layout, Field);
4271 }
4272 }
4273}
4274
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004275void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) {
4276 std::string ClassName = ID->getNameAsString();
4277 if (!ObjCEmptyCacheVar) {
4278 ObjCEmptyCacheVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004279 ObjCTypes.CacheTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004280 false,
4281 llvm::GlobalValue::ExternalLinkage,
4282 0,
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004283 "_objc_empty_cache",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004284 &CGM.getModule());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004285
4286 ObjCEmptyVtableVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004287 ObjCTypes.ImpnfABITy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004288 false,
4289 llvm::GlobalValue::ExternalLinkage,
4290 0,
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004291 "_objc_empty_vtable",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004292 &CGM.getModule());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004293 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004294 assert(ID->getClassInterface() &&
4295 "CGObjCNonFragileABIMac::GenerateClass - class is 0");
Daniel Dunbar6c1aac82009-04-20 20:18:54 +00004296 // FIXME: Is this correct (that meta class size is never computed)?
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004297 uint32_t InstanceStart =
4298 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassnfABITy);
4299 uint32_t InstanceSize = InstanceStart;
4300 uint32_t flags = CLS_META;
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004301 std::string ObjCMetaClassName(getMetaclassSymbolPrefix());
4302 std::string ObjCClassName(getClassSymbolPrefix());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004303
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004304 llvm::GlobalVariable *SuperClassGV, *IsAGV;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004305
Daniel Dunbar04d40782009-04-14 06:00:08 +00004306 bool classIsHidden =
4307 CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004308 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004309 flags |= OBJC2_CLS_HIDDEN;
4310 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004311 // class is root
4312 flags |= CLS_ROOT;
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004313 SuperClassGV = GetClassGlobal(ObjCClassName + ClassName);
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004314 IsAGV = GetClassGlobal(ObjCMetaClassName + ClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004315 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004316 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004317 const ObjCInterfaceDecl *Root = ID->getClassInterface();
4318 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
4319 Root = Super;
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004320 IsAGV = GetClassGlobal(ObjCMetaClassName + Root->getNameAsString());
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004321 // work on super class metadata symbol.
4322 std::string SuperClassName =
4323 ObjCMetaClassName + ID->getClassInterface()->getSuperClass()->getNameAsString();
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004324 SuperClassGV = GetClassGlobal(SuperClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004325 }
4326 llvm::GlobalVariable *CLASS_RO_GV = BuildClassRoTInitializer(flags,
4327 InstanceStart,
4328 InstanceSize,ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004329 std::string TClassName = ObjCMetaClassName + ClassName;
4330 llvm::GlobalVariable *MetaTClass =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004331 BuildClassMetaData(TClassName, IsAGV, SuperClassGV, CLASS_RO_GV,
4332 classIsHidden);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004333
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004334 // Metadata for the class
4335 flags = CLS;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004336 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004337 flags |= OBJC2_CLS_HIDDEN;
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004338
4339 if (hasObjCExceptionAttribute(ID->getClassInterface()))
4340 flags |= CLS_EXCEPTION;
4341
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004342 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004343 flags |= CLS_ROOT;
4344 SuperClassGV = 0;
Chris Lattnerb7b58b12009-04-19 06:02:28 +00004345 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004346 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004347 std::string RootClassName =
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004348 ID->getClassInterface()->getSuperClass()->getNameAsString();
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004349 SuperClassGV = GetClassGlobal(ObjCClassName + RootClassName);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004350 }
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004351 GetClassSizeInfo(ID->getClassInterface(), InstanceStart, InstanceSize);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004352 CLASS_RO_GV = BuildClassRoTInitializer(flags,
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004353 InstanceStart,
4354 InstanceSize,
4355 ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004356
4357 TClassName = ObjCClassName + ClassName;
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004358 llvm::GlobalVariable *ClassMD =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004359 BuildClassMetaData(TClassName, MetaTClass, SuperClassGV, CLASS_RO_GV,
4360 classIsHidden);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004361 DefinedClasses.push_back(ClassMD);
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004362
4363 // Force the definition of the EHType if necessary.
4364 if (flags & CLS_EXCEPTION)
4365 GetInterfaceEHType(ID->getClassInterface(), true);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004366}
4367
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004368/// GenerateProtocolRef - This routine is called to generate code for
4369/// a protocol reference expression; as in:
4370/// @code
4371/// @protocol(Proto1);
4372/// @endcode
4373/// It generates a weak reference to l_OBJC_PROTOCOL_REFERENCE_$_Proto1
4374/// which will hold address of the protocol meta-data.
4375///
4376llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CGBuilderTy &Builder,
4377 const ObjCProtocolDecl *PD) {
4378
Fariborz Jahanian960cd062009-04-10 18:47:34 +00004379 // This routine is called for @protocol only. So, we must build definition
4380 // of protocol's meta-data (not a reference to it!)
4381 //
4382 llvm::Constant *Init = llvm::ConstantExpr::getBitCast(GetOrEmitProtocol(PD),
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004383 ObjCTypes.ExternalProtocolPtrTy);
4384
4385 std::string ProtocolName("\01l_OBJC_PROTOCOL_REFERENCE_$_");
4386 ProtocolName += PD->getNameAsCString();
4387
4388 llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName);
4389 if (PTGV)
4390 return Builder.CreateLoad(PTGV, false, "tmp");
4391 PTGV = new llvm::GlobalVariable(
4392 Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00004393 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004394 Init,
4395 ProtocolName,
4396 &CGM.getModule());
4397 PTGV->setSection("__DATA, __objc_protorefs, coalesced, no_dead_strip");
4398 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4399 UsedGlobals.push_back(PTGV);
4400 return Builder.CreateLoad(PTGV, false, "tmp");
4401}
4402
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004403/// GenerateCategory - Build metadata for a category implementation.
4404/// struct _category_t {
4405/// const char * const name;
4406/// struct _class_t *const cls;
4407/// const struct _method_list_t * const instance_methods;
4408/// const struct _method_list_t * const class_methods;
4409/// const struct _protocol_list_t * const protocols;
4410/// const struct _prop_list_t * const properties;
4411/// }
4412///
4413void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD)
4414{
4415 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004416 const char *Prefix = "\01l_OBJC_$_CATEGORY_";
4417 std::string ExtCatName(Prefix + Interface->getNameAsString()+
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004418 "_$_" + OCD->getNameAsString());
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004419 std::string ExtClassName(getClassSymbolPrefix() +
4420 Interface->getNameAsString());
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004421
4422 std::vector<llvm::Constant*> Values(6);
4423 Values[0] = GetClassName(OCD->getIdentifier());
4424 // meta-class entry symbol
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004425 llvm::GlobalVariable *ClassGV = GetClassGlobal(ExtClassName);
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004426 Values[1] = ClassGV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004427 std::vector<llvm::Constant*> Methods;
4428 std::string MethodListName(Prefix);
4429 MethodListName += "INSTANCE_METHODS_" + Interface->getNameAsString() +
4430 "_$_" + OCD->getNameAsString();
4431
4432 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
4433 e = OCD->instmeth_end(); i != e; ++i) {
4434 // Instance methods should always be defined.
4435 Methods.push_back(GetMethodConstant(*i));
4436 }
4437
4438 Values[2] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004439 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004440 Methods);
4441
4442 MethodListName = Prefix;
4443 MethodListName += "CLASS_METHODS_" + Interface->getNameAsString() + "_$_" +
4444 OCD->getNameAsString();
4445 Methods.clear();
4446 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
4447 e = OCD->classmeth_end(); i != e; ++i) {
4448 // Class methods should always be defined.
4449 Methods.push_back(GetMethodConstant(*i));
4450 }
4451
4452 Values[3] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004453 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004454 Methods);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004455 const ObjCCategoryDecl *Category =
4456 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Fariborz Jahanian943ed6f2009-02-13 17:52:22 +00004457 if (Category) {
4458 std::string ExtName(Interface->getNameAsString() + "_$_" +
4459 OCD->getNameAsString());
4460 Values[4] = EmitProtocolList("\01l_OBJC_CATEGORY_PROTOCOLS_$_"
4461 + Interface->getNameAsString() + "_$_"
4462 + Category->getNameAsString(),
4463 Category->protocol_begin(),
4464 Category->protocol_end());
4465 Values[5] =
4466 EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
4467 OCD, Category, ObjCTypes);
4468 }
4469 else {
4470 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4471 Values[5] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4472 }
4473
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004474 llvm::Constant *Init =
4475 llvm::ConstantStruct::get(ObjCTypes.CategorynfABITy,
4476 Values);
4477 llvm::GlobalVariable *GCATV
4478 = new llvm::GlobalVariable(ObjCTypes.CategorynfABITy,
4479 false,
4480 llvm::GlobalValue::InternalLinkage,
4481 Init,
4482 ExtCatName,
4483 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004484 GCATV->setAlignment(
4485 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.CategorynfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004486 GCATV->setSection("__DATA, __objc_const");
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004487 UsedGlobals.push_back(GCATV);
4488 DefinedCategories.push_back(GCATV);
4489}
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004490
4491/// GetMethodConstant - Return a struct objc_method constant for the
4492/// given method if it has been defined. The result is null if the
4493/// method has not been defined. The return value has type MethodPtrTy.
4494llvm::Constant *CGObjCNonFragileABIMac::GetMethodConstant(
4495 const ObjCMethodDecl *MD) {
4496 // FIXME: Use DenseMap::lookup
4497 llvm::Function *Fn = MethodDefinitions[MD];
4498 if (!Fn)
4499 return 0;
4500
4501 std::vector<llvm::Constant*> Method(3);
4502 Method[0] =
4503 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4504 ObjCTypes.SelectorPtrTy);
4505 Method[1] = GetMethodVarType(MD);
4506 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
4507 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
4508}
4509
4510/// EmitMethodList - Build meta-data for method declarations
4511/// struct _method_list_t {
4512/// uint32_t entsize; // sizeof(struct _objc_method)
4513/// uint32_t method_count;
4514/// struct _objc_method method_list[method_count];
4515/// }
4516///
4517llvm::Constant *CGObjCNonFragileABIMac::EmitMethodList(
4518 const std::string &Name,
4519 const char *Section,
4520 const ConstantVector &Methods) {
4521 // Return null for empty list.
4522 if (Methods.empty())
4523 return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy);
4524
4525 std::vector<llvm::Constant*> Values(3);
4526 // sizeof(struct _objc_method)
4527 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.MethodTy);
4528 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4529 // method_count
4530 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
4531 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
4532 Methods.size());
4533 Values[2] = llvm::ConstantArray::get(AT, Methods);
4534 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4535
4536 llvm::GlobalVariable *GV =
4537 new llvm::GlobalVariable(Init->getType(), false,
4538 llvm::GlobalValue::InternalLinkage,
4539 Init,
4540 Name,
4541 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004542 GV->setAlignment(
4543 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004544 GV->setSection(Section);
4545 UsedGlobals.push_back(GV);
4546 return llvm::ConstantExpr::getBitCast(GV,
4547 ObjCTypes.MethodListnfABIPtrTy);
4548}
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004549
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004550/// ObjCIvarOffsetVariable - Returns the ivar offset variable for
4551/// the given ivar.
4552///
4553llvm::GlobalVariable * CGObjCNonFragileABIMac::ObjCIvarOffsetVariable(
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004554 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004555 const ObjCIvarDecl *Ivar) {
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00004556 std::string Name = "OBJC_IVAR_$_" +
Douglas Gregor6ab35242009-04-09 21:40:53 +00004557 getInterfaceDeclForIvar(ID, Ivar, CGM.getContext())->getNameAsString() +
4558 '.' + Ivar->getNameAsString();
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004559 llvm::GlobalVariable *IvarOffsetGV =
4560 CGM.getModule().getGlobalVariable(Name);
4561 if (!IvarOffsetGV)
4562 IvarOffsetGV =
4563 new llvm::GlobalVariable(ObjCTypes.LongTy,
4564 false,
4565 llvm::GlobalValue::ExternalLinkage,
4566 0,
4567 Name,
4568 &CGM.getModule());
4569 return IvarOffsetGV;
4570}
4571
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004572llvm::Constant * CGObjCNonFragileABIMac::EmitIvarOffsetVar(
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004573 const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004574 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004575 unsigned long int Offset) {
Daniel Dunbar737c5022009-04-19 00:44:02 +00004576 llvm::GlobalVariable *IvarOffsetGV = ObjCIvarOffsetVariable(ID, Ivar);
4577 IvarOffsetGV->setInitializer(llvm::ConstantInt::get(ObjCTypes.LongTy,
4578 Offset));
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004579 IvarOffsetGV->setAlignment(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004580 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.LongTy));
Daniel Dunbar737c5022009-04-19 00:44:02 +00004581
4582 // FIXME: This matches gcc, but shouldn't the visibility be set on
4583 // the use as well (i.e., in ObjCIvarOffsetVariable).
4584 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
4585 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
4586 CGM.getDeclVisibilityMode(ID) == LangOptions::Hidden)
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004587 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar04d40782009-04-14 06:00:08 +00004588 else
Fariborz Jahanian77c9fd22009-04-06 18:30:00 +00004589 IvarOffsetGV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004590 IvarOffsetGV->setSection("__DATA, __objc_const");
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004591 return IvarOffsetGV;
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004592}
4593
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004594/// EmitIvarList - Emit the ivar list for the given
Daniel Dunbar11394522009-04-18 08:51:00 +00004595/// implementation. The return value has type
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004596/// IvarListnfABIPtrTy.
4597/// struct _ivar_t {
4598/// unsigned long int *offset; // pointer to ivar offset location
4599/// char *name;
4600/// char *type;
4601/// uint32_t alignment;
4602/// uint32_t size;
4603/// }
4604/// struct _ivar_list_t {
4605/// uint32 entsize; // sizeof(struct _ivar_t)
4606/// uint32 count;
4607/// struct _iver_t list[count];
4608/// }
4609///
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004610
4611void CGObjCCommonMac::GetNamedIvarList(const ObjCInterfaceDecl *OID,
4612 llvm::SmallVector<ObjCIvarDecl*, 16> &Res) const {
4613 for (ObjCInterfaceDecl::ivar_iterator I = OID->ivar_begin(),
4614 E = OID->ivar_end(); I != E; ++I) {
4615 // Ignore unnamed bit-fields.
4616 if (!(*I)->getDeclName())
4617 continue;
4618
4619 Res.push_back(*I);
4620 }
4621
4622 for (ObjCInterfaceDecl::prop_iterator I = OID->prop_begin(CGM.getContext()),
4623 E = OID->prop_end(CGM.getContext()); I != E; ++I)
4624 if (ObjCIvarDecl *IV = (*I)->getPropertyIvarDecl())
4625 Res.push_back(IV);
4626}
4627
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004628llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList(
4629 const ObjCImplementationDecl *ID) {
4630
4631 std::vector<llvm::Constant*> Ivars, Ivar(5);
4632
4633 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4634 assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface");
4635
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004636 // FIXME. Consolidate this with similar code in GenerateClass.
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00004637 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00004638
Daniel Dunbar91636d62009-04-20 00:33:43 +00004639 // Collect declared and synthesized ivars in a small vector.
Fariborz Jahanian18191882009-03-31 18:11:23 +00004640 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004641 GetNamedIvarList(OID, OIvars);
Fariborz Jahanian99eee362009-04-01 19:37:34 +00004642
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004643 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
4644 ObjCIvarDecl *IVD = OIvars[i];
4645 const FieldDecl *Field = OID->lookupFieldDeclForIvar(CGM.getContext(), IVD);
Daniel Dunbar3eec8aa2009-04-20 05:53:40 +00004646 Ivar[0] = EmitIvarOffsetVar(ID->getClassInterface(), IVD,
Daniel Dunbar48fa0642009-04-19 02:03:42 +00004647 GetIvarBaseOffset(Layout, Field));
Daniel Dunbar3eec8aa2009-04-20 05:53:40 +00004648 Ivar[1] = GetMethodVarName(Field->getIdentifier());
Devang Patel7794bb82009-03-04 18:21:39 +00004649 Ivar[2] = GetMethodVarType(Field);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004650 const llvm::Type *FieldTy =
4651 CGM.getTypes().ConvertTypeForMem(Field->getType());
4652 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
4653 unsigned Align = CGM.getContext().getPreferredTypeAlign(
4654 Field->getType().getTypePtr()) >> 3;
4655 Align = llvm::Log2_32(Align);
4656 Ivar[3] = llvm::ConstantInt::get(ObjCTypes.IntTy, Align);
Daniel Dunbar91636d62009-04-20 00:33:43 +00004657 // NOTE. Size of a bitfield does not match gcc's, because of the
4658 // way bitfields are treated special in each. But I am told that
4659 // 'size' for bitfield ivars is ignored by the runtime so it does
4660 // not matter. If it matters, there is enough info to get the
4661 // bitfield right!
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004662 Ivar[4] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4663 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarnfABITy, Ivar));
4664 }
4665 // Return null for empty list.
4666 if (Ivars.empty())
4667 return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4668 std::vector<llvm::Constant*> Values(3);
4669 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.IvarnfABITy);
4670 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4671 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
4672 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarnfABITy,
4673 Ivars.size());
4674 Values[2] = llvm::ConstantArray::get(AT, Ivars);
4675 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4676 const char *Prefix = "\01l_OBJC_$_INSTANCE_VARIABLES_";
4677 llvm::GlobalVariable *GV =
4678 new llvm::GlobalVariable(Init->getType(), false,
4679 llvm::GlobalValue::InternalLinkage,
4680 Init,
4681 Prefix + OID->getNameAsString(),
4682 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004683 GV->setAlignment(
4684 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004685 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004686
4687 UsedGlobals.push_back(GV);
4688 return llvm::ConstantExpr::getBitCast(GV,
4689 ObjCTypes.IvarListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004690}
4691
4692llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef(
4693 const ObjCProtocolDecl *PD) {
4694 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4695
4696 if (!Entry) {
4697 // We use the initializer as a marker of whether this is a forward
4698 // reference or not. At module finalization we add the empty
4699 // contents for protocols which were referenced but never defined.
4700 Entry =
4701 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
4702 llvm::GlobalValue::ExternalLinkage,
4703 0,
4704 "\01l_OBJC_PROTOCOL_$_" + PD->getNameAsString(),
4705 &CGM.getModule());
4706 Entry->setSection("__DATA,__datacoal_nt,coalesced");
4707 UsedGlobals.push_back(Entry);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004708 }
4709
4710 return Entry;
4711}
4712
4713/// GetOrEmitProtocol - Generate the protocol meta-data:
4714/// @code
4715/// struct _protocol_t {
4716/// id isa; // NULL
4717/// const char * const protocol_name;
4718/// const struct _protocol_list_t * protocol_list; // super protocols
4719/// const struct method_list_t * const instance_methods;
4720/// const struct method_list_t * const class_methods;
4721/// const struct method_list_t *optionalInstanceMethods;
4722/// const struct method_list_t *optionalClassMethods;
4723/// const struct _prop_list_t * properties;
4724/// const uint32_t size; // sizeof(struct _protocol_t)
4725/// const uint32_t flags; // = 0
4726/// }
4727/// @endcode
4728///
4729
4730llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol(
4731 const ObjCProtocolDecl *PD) {
4732 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4733
4734 // Early exit if a defining object has already been generated.
4735 if (Entry && Entry->hasInitializer())
4736 return Entry;
4737
4738 const char *ProtocolName = PD->getNameAsCString();
4739
4740 // Construct method lists.
4741 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
4742 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregor6ab35242009-04-09 21:40:53 +00004743 for (ObjCProtocolDecl::instmeth_iterator
4744 i = PD->instmeth_begin(CGM.getContext()),
4745 e = PD->instmeth_end(CGM.getContext());
4746 i != e; ++i) {
Fariborz Jahanianda320092009-01-29 19:24:30 +00004747 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004748 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004749 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4750 OptInstanceMethods.push_back(C);
4751 } else {
4752 InstanceMethods.push_back(C);
4753 }
4754 }
4755
Douglas Gregor6ab35242009-04-09 21:40:53 +00004756 for (ObjCProtocolDecl::classmeth_iterator
4757 i = PD->classmeth_begin(CGM.getContext()),
4758 e = PD->classmeth_end(CGM.getContext());
4759 i != e; ++i) {
Fariborz Jahanianda320092009-01-29 19:24:30 +00004760 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004761 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004762 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4763 OptClassMethods.push_back(C);
4764 } else {
4765 ClassMethods.push_back(C);
4766 }
4767 }
4768
4769 std::vector<llvm::Constant*> Values(10);
4770 // isa is NULL
4771 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ObjectPtrTy);
4772 Values[1] = GetClassName(PD->getIdentifier());
4773 Values[2] = EmitProtocolList(
4774 "\01l_OBJC_$_PROTOCOL_REFS_" + PD->getNameAsString(),
4775 PD->protocol_begin(),
4776 PD->protocol_end());
4777
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004778 Values[3] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004779 + PD->getNameAsString(),
4780 "__DATA, __objc_const",
4781 InstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004782 Values[4] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004783 + PD->getNameAsString(),
4784 "__DATA, __objc_const",
4785 ClassMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004786 Values[5] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004787 + PD->getNameAsString(),
4788 "__DATA, __objc_const",
4789 OptInstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004790 Values[6] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004791 + PD->getNameAsString(),
4792 "__DATA, __objc_const",
4793 OptClassMethods);
4794 Values[7] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + PD->getNameAsString(),
4795 0, PD, ObjCTypes);
4796 uint32_t Size =
4797 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolnfABITy);
4798 Values[8] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4799 Values[9] = llvm::Constant::getNullValue(ObjCTypes.IntTy);
4800 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolnfABITy,
4801 Values);
4802
4803 if (Entry) {
4804 // Already created, fix the linkage and update the initializer.
Mike Stump286acbd2009-03-07 16:33:28 +00004805 Entry->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004806 Entry->setInitializer(Init);
4807 } else {
4808 Entry =
4809 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004810 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004811 Init,
4812 std::string("\01l_OBJC_PROTOCOL_$_")+ProtocolName,
4813 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004814 Entry->setAlignment(
4815 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABITy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004816 Entry->setSection("__DATA,__datacoal_nt,coalesced");
Fariborz Jahanianda320092009-01-29 19:24:30 +00004817 }
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004818 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
4819
4820 // Use this protocol meta-data to build protocol list table in section
4821 // __DATA, __objc_protolist
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004822 llvm::GlobalVariable *PTGV = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004823 ObjCTypes.ProtocolnfABIPtrTy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004824 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004825 Entry,
4826 std::string("\01l_OBJC_LABEL_PROTOCOL_$_")
4827 +ProtocolName,
4828 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004829 PTGV->setAlignment(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004830 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABIPtrTy));
Daniel Dunbar0bf21992009-04-15 02:56:18 +00004831 PTGV->setSection("__DATA, __objc_protolist, coalesced, no_dead_strip");
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004832 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4833 UsedGlobals.push_back(PTGV);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004834 return Entry;
4835}
4836
4837/// EmitProtocolList - Generate protocol list meta-data:
4838/// @code
4839/// struct _protocol_list_t {
4840/// long protocol_count; // Note, this is 32/64 bit
4841/// struct _protocol_t[protocol_count];
4842/// }
4843/// @endcode
4844///
4845llvm::Constant *
4846CGObjCNonFragileABIMac::EmitProtocolList(const std::string &Name,
4847 ObjCProtocolDecl::protocol_iterator begin,
4848 ObjCProtocolDecl::protocol_iterator end) {
4849 std::vector<llvm::Constant*> ProtocolRefs;
4850
Fariborz Jahanianda320092009-01-29 19:24:30 +00004851 // Just return null for empty protocol lists
Daniel Dunbar948e2582009-02-15 07:36:20 +00004852 if (begin == end)
Fariborz Jahanianda320092009-01-29 19:24:30 +00004853 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4854
Daniel Dunbar948e2582009-02-15 07:36:20 +00004855 // FIXME: We shouldn't need to do this lookup here, should we?
Fariborz Jahanianda320092009-01-29 19:24:30 +00004856 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
4857 if (GV)
Daniel Dunbar948e2582009-02-15 07:36:20 +00004858 return llvm::ConstantExpr::getBitCast(GV,
4859 ObjCTypes.ProtocolListnfABIPtrTy);
4860
4861 for (; begin != end; ++begin)
4862 ProtocolRefs.push_back(GetProtocolRef(*begin)); // Implemented???
4863
Fariborz Jahanianda320092009-01-29 19:24:30 +00004864 // This list is null terminated.
4865 ProtocolRefs.push_back(llvm::Constant::getNullValue(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004866 ObjCTypes.ProtocolnfABIPtrTy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004867
4868 std::vector<llvm::Constant*> Values(2);
4869 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
4870 Values[1] =
Daniel Dunbar948e2582009-02-15 07:36:20 +00004871 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolnfABIPtrTy,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004872 ProtocolRefs.size()),
4873 ProtocolRefs);
4874
4875 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4876 GV = new llvm::GlobalVariable(Init->getType(), false,
4877 llvm::GlobalValue::InternalLinkage,
4878 Init,
4879 Name,
4880 &CGM.getModule());
4881 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004882 GV->setAlignment(
4883 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004884 UsedGlobals.push_back(GV);
Daniel Dunbar948e2582009-02-15 07:36:20 +00004885 return llvm::ConstantExpr::getBitCast(GV,
4886 ObjCTypes.ProtocolListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004887}
4888
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004889/// GetMethodDescriptionConstant - This routine build following meta-data:
4890/// struct _objc_method {
4891/// SEL _cmd;
4892/// char *method_type;
4893/// char *_imp;
4894/// }
4895
4896llvm::Constant *
4897CGObjCNonFragileABIMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
4898 std::vector<llvm::Constant*> Desc(3);
4899 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4900 ObjCTypes.SelectorPtrTy);
4901 Desc[1] = GetMethodVarType(MD);
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004902 // Protocol methods have no implementation. So, this entry is always NULL.
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004903 Desc[2] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
4904 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Desc);
4905}
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004906
4907/// EmitObjCValueForIvar - Code Gen for nonfragile ivar reference.
4908/// This code gen. amounts to generating code for:
4909/// @code
4910/// (type *)((char *)base + _OBJC_IVAR_$_.ivar;
4911/// @encode
4912///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004913LValue CGObjCNonFragileABIMac::EmitObjCValueForIvar(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004914 CodeGen::CodeGenFunction &CGF,
4915 QualType ObjectTy,
4916 llvm::Value *BaseValue,
4917 const ObjCIvarDecl *Ivar,
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004918 unsigned CVRQualifiers) {
Daniel Dunbar525c9b72009-04-21 01:19:28 +00004919 const ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
4920 const FieldDecl *Field = ID->lookupFieldDeclForIvar(CGM.getContext(), Ivar);
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00004921 llvm::GlobalVariable *IvarOffsetGV = ObjCIvarOffsetVariable(ID, Ivar);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004922
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004923 // (char *) BaseValue
Chris Lattner51123fe2009-04-17 17:46:19 +00004924 llvm::Value *V = CGF.Builder.CreateBitCast(BaseValue, ObjCTypes.Int8PtrTy);
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004925 llvm::Value *Offset = CGF.Builder.CreateLoad(IvarOffsetGV);
4926 // (char*)BaseValue + Offset_symbol
4927 V = CGF.Builder.CreateGEP(V, Offset, "add.ptr");
4928 // (type *)((char*)BaseValue + Offset_symbol)
4929 const llvm::Type *IvarTy =
Chris Lattner51123fe2009-04-17 17:46:19 +00004930 CGM.getTypes().ConvertTypeForMem(Ivar->getType());
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004931 llvm::Type *ptrIvarTy = llvm::PointerType::getUnqual(IvarTy);
4932 V = CGF.Builder.CreateBitCast(V, ptrIvarTy);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004933
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00004934 if (Ivar->isBitField()) {
Chris Lattner51123fe2009-04-17 17:46:19 +00004935 QualType FieldTy = Field->getType();
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00004936 CodeGenTypes::BitFieldInfo bitFieldInfo =
4937 CGM.getTypes().getBitFieldInfo(Field);
4938 return LValue::MakeBitfield(V, bitFieldInfo.Begin, bitFieldInfo.Size,
Chris Lattner51123fe2009-04-17 17:46:19 +00004939 FieldTy->isSignedIntegerType(),
4940 FieldTy.getCVRQualifiers()|CVRQualifiers);
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00004941 }
4942
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004943 LValue LV = LValue::MakeAddr(V,
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004944 Ivar->getType().getCVRQualifiers()|CVRQualifiers,
4945 CGM.getContext().getObjCGCAttrKind(Ivar->getType()));
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004946 LValue::SetObjCIvar(LV, true);
4947 return LV;
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004948}
4949
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004950llvm::Value *CGObjCNonFragileABIMac::EmitIvarOffset(
4951 CodeGen::CodeGenFunction &CGF,
4952 ObjCInterfaceDecl *Interface,
4953 const ObjCIvarDecl *Ivar) {
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00004954 return CGF.Builder.CreateLoad(ObjCIvarOffsetVariable(Interface, Ivar),
4955 false, "ivar");
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004956}
4957
Fariborz Jahanian46551122009-02-04 00:22:57 +00004958CodeGen::RValue CGObjCNonFragileABIMac::EmitMessageSend(
4959 CodeGen::CodeGenFunction &CGF,
4960 QualType ResultType,
4961 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004962 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +00004963 QualType Arg0Ty,
4964 bool IsSuper,
4965 const CallArgList &CallArgs) {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004966 // FIXME. Even though IsSuper is passes. This function doese not
4967 // handle calls to 'super' receivers.
4968 CodeGenTypes &Types = CGM.getTypes();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004969 llvm::Value *Arg0 = Receiver;
4970 if (!IsSuper)
4971 Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy, "tmp");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004972
4973 // Find the message function name.
Fariborz Jahanianef163782009-02-05 01:13:09 +00004974 // FIXME. This is too much work to get the ABI-specific result type
4975 // needed to find the message name.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004976 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType,
4977 llvm::SmallVector<QualType, 16>());
4978 llvm::Constant *Fn;
4979 std::string Name("\01l_");
4980 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004981#if 0
4982 // unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004983 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
4984 Fn = ObjCTypes.MessageSendIdStretFixupFn;
4985 // FIXME. Is there a better way of getting these names.
4986 // They are available in RuntimeFunctions vector pair.
4987 Name += "objc_msgSendId_stret_fixup";
4988 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004989 else
4990#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004991 if (IsSuper) {
4992 Fn = ObjCTypes.MessageSendSuper2StretFixupFn;
4993 Name += "objc_msgSendSuper2_stret_fixup";
4994 }
4995 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004996 {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004997 Fn = ObjCTypes.MessageSendStretFixupFn;
4998 Name += "objc_msgSend_stret_fixup";
4999 }
5000 }
Fariborz Jahanian1a6b3682009-02-05 19:35:43 +00005001 else if (ResultType->isFloatingType() &&
5002 // Selection of frret API only happens in 32bit nonfragile ABI.
5003 CGM.getTargetData().getTypePaddedSize(ObjCTypes.LongTy) == 4) {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005004 Fn = ObjCTypes.MessageSendFpretFixupFn;
5005 Name += "objc_msgSend_fpret_fixup";
5006 }
5007 else {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005008#if 0
5009// unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005010 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
5011 Fn = ObjCTypes.MessageSendIdFixupFn;
5012 Name += "objc_msgSendId_fixup";
5013 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005014 else
5015#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005016 if (IsSuper) {
5017 Fn = ObjCTypes.MessageSendSuper2FixupFn;
5018 Name += "objc_msgSendSuper2_fixup";
5019 }
5020 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005021 {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005022 Fn = ObjCTypes.MessageSendFixupFn;
5023 Name += "objc_msgSend_fixup";
5024 }
5025 }
5026 Name += '_';
5027 std::string SelName(Sel.getAsString());
5028 // Replace all ':' in selector name with '_' ouch!
5029 for(unsigned i = 0; i < SelName.size(); i++)
5030 if (SelName[i] == ':')
5031 SelName[i] = '_';
5032 Name += SelName;
5033 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5034 if (!GV) {
Daniel Dunbar33af70f2009-04-15 19:03:14 +00005035 // Build message ref table entry.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005036 std::vector<llvm::Constant*> Values(2);
5037 Values[0] = Fn;
5038 Values[1] = GetMethodVarName(Sel);
5039 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
5040 GV = new llvm::GlobalVariable(Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00005041 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005042 Init,
5043 Name,
5044 &CGM.getModule());
5045 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbarf59c1a62009-04-15 19:04:46 +00005046 GV->setAlignment(16);
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005047 GV->setSection("__DATA, __objc_msgrefs, coalesced");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005048 }
5049 llvm::Value *Arg1 = CGF.Builder.CreateBitCast(GV, ObjCTypes.MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00005050
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005051 CallArgList ActualArgs;
5052 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
5053 ActualArgs.push_back(std::make_pair(RValue::get(Arg1),
5054 ObjCTypes.MessageRefCPtrTy));
5055 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Fariborz Jahanianef163782009-02-05 01:13:09 +00005056 const CGFunctionInfo &FnInfo1 = Types.getFunctionInfo(ResultType, ActualArgs);
5057 llvm::Value *Callee = CGF.Builder.CreateStructGEP(Arg1, 0);
5058 Callee = CGF.Builder.CreateLoad(Callee);
Fariborz Jahanian3ab75bd2009-02-14 21:25:36 +00005059 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo1, true);
Fariborz Jahanianef163782009-02-05 01:13:09 +00005060 Callee = CGF.Builder.CreateBitCast(Callee,
5061 llvm::PointerType::getUnqual(FTy));
5062 return CGF.EmitCall(FnInfo1, Callee, ActualArgs);
Fariborz Jahanian46551122009-02-04 00:22:57 +00005063}
5064
5065/// Generate code for a message send expression in the nonfragile abi.
5066CodeGen::RValue CGObjCNonFragileABIMac::GenerateMessageSend(
5067 CodeGen::CodeGenFunction &CGF,
5068 QualType ResultType,
5069 Selector Sel,
5070 llvm::Value *Receiver,
5071 bool IsClassMessage,
5072 const CallArgList &CallArgs) {
Fariborz Jahanian46551122009-02-04 00:22:57 +00005073 return EmitMessageSend(CGF, ResultType, Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005074 Receiver, CGF.getContext().getObjCIdType(),
Fariborz Jahanian46551122009-02-04 00:22:57 +00005075 false, CallArgs);
5076}
5077
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005078llvm::GlobalVariable *
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005079CGObjCNonFragileABIMac::GetClassGlobal(const std::string &Name) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005080 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5081
Daniel Dunbardfff2302009-03-02 05:18:14 +00005082 if (!GV) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005083 GV = new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
5084 llvm::GlobalValue::ExternalLinkage,
5085 0, Name, &CGM.getModule());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005086 }
5087
5088 return GV;
5089}
5090
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005091llvm::Value *CGObjCNonFragileABIMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar11394522009-04-18 08:51:00 +00005092 const ObjCInterfaceDecl *ID) {
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005093 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
5094
5095 if (!Entry) {
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005096 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005097 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005098 Entry =
5099 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5100 llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005101 ClassGV,
Daniel Dunbar11394522009-04-18 08:51:00 +00005102 "\01L_OBJC_CLASSLIST_REFERENCES_$_",
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005103 &CGM.getModule());
5104 Entry->setAlignment(
5105 CGM.getTargetData().getPrefTypeAlignment(
5106 ObjCTypes.ClassnfABIPtrTy));
Daniel Dunbar11394522009-04-18 08:51:00 +00005107 Entry->setSection("__DATA, __objc_classrefs, regular, no_dead_strip");
5108 UsedGlobals.push_back(Entry);
5109 }
5110
5111 return Builder.CreateLoad(Entry, false, "tmp");
5112}
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005113
Daniel Dunbar11394522009-04-18 08:51:00 +00005114llvm::Value *
5115CGObjCNonFragileABIMac::EmitSuperClassRef(CGBuilderTy &Builder,
5116 const ObjCInterfaceDecl *ID) {
5117 llvm::GlobalVariable *&Entry = SuperClassReferences[ID->getIdentifier()];
5118
5119 if (!Entry) {
5120 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
5121 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
5122 Entry =
5123 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5124 llvm::GlobalValue::InternalLinkage,
5125 ClassGV,
5126 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5127 &CGM.getModule());
5128 Entry->setAlignment(
5129 CGM.getTargetData().getPrefTypeAlignment(
5130 ObjCTypes.ClassnfABIPtrTy));
5131 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005132 UsedGlobals.push_back(Entry);
5133 }
5134
5135 return Builder.CreateLoad(Entry, false, "tmp");
5136}
5137
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005138/// EmitMetaClassRef - Return a Value * of the address of _class_t
5139/// meta-data
5140///
5141llvm::Value *CGObjCNonFragileABIMac::EmitMetaClassRef(CGBuilderTy &Builder,
5142 const ObjCInterfaceDecl *ID) {
5143 llvm::GlobalVariable * &Entry = MetaClassReferences[ID->getIdentifier()];
5144 if (Entry)
5145 return Builder.CreateLoad(Entry, false, "tmp");
5146
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005147 std::string MetaClassName(getMetaclassSymbolPrefix() + ID->getNameAsString());
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005148 llvm::GlobalVariable *MetaClassGV = GetClassGlobal(MetaClassName);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005149 Entry =
5150 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5151 llvm::GlobalValue::InternalLinkage,
5152 MetaClassGV,
5153 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5154 &CGM.getModule());
5155 Entry->setAlignment(
5156 CGM.getTargetData().getPrefTypeAlignment(
5157 ObjCTypes.ClassnfABIPtrTy));
5158
Daniel Dunbar33af70f2009-04-15 19:03:14 +00005159 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005160 UsedGlobals.push_back(Entry);
5161
5162 return Builder.CreateLoad(Entry, false, "tmp");
5163}
5164
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005165/// GetClass - Return a reference to the class for the given interface
5166/// decl.
5167llvm::Value *CGObjCNonFragileABIMac::GetClass(CGBuilderTy &Builder,
5168 const ObjCInterfaceDecl *ID) {
5169 return EmitClassRef(Builder, ID);
5170}
5171
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005172/// Generates a message send where the super is the receiver. This is
5173/// a message send to self with special delivery semantics indicating
5174/// which class's method should be called.
5175CodeGen::RValue
5176CGObjCNonFragileABIMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
5177 QualType ResultType,
5178 Selector Sel,
5179 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005180 bool isCategoryImpl,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005181 llvm::Value *Receiver,
5182 bool IsClassMessage,
5183 const CodeGen::CallArgList &CallArgs) {
5184 // ...
5185 // Create and init a super structure; this is a (receiver, class)
5186 // pair we will pass to objc_msgSendSuper.
5187 llvm::Value *ObjCSuper =
5188 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
5189
5190 llvm::Value *ReceiverAsObject =
5191 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
5192 CGF.Builder.CreateStore(ReceiverAsObject,
5193 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
5194
5195 // If this is a class message the metaclass is passed as the target.
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005196 llvm::Value *Target;
5197 if (IsClassMessage) {
5198 if (isCategoryImpl) {
5199 // Message sent to "super' in a class method defined in
5200 // a category implementation.
Daniel Dunbar11394522009-04-18 08:51:00 +00005201 Target = EmitClassRef(CGF.Builder, Class);
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005202 Target = CGF.Builder.CreateStructGEP(Target, 0);
5203 Target = CGF.Builder.CreateLoad(Target);
5204 }
5205 else
5206 Target = EmitMetaClassRef(CGF.Builder, Class);
5207 }
5208 else
Daniel Dunbar11394522009-04-18 08:51:00 +00005209 Target = EmitSuperClassRef(CGF.Builder, Class);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005210
5211 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
5212 // and ObjCTypes types.
5213 const llvm::Type *ClassTy =
5214 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
5215 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
5216 CGF.Builder.CreateStore(Target,
5217 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
5218
5219 return EmitMessageSend(CGF, ResultType, Sel,
5220 ObjCSuper, ObjCTypes.SuperPtrCTy,
5221 true, CallArgs);
5222}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005223
5224llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CGBuilderTy &Builder,
5225 Selector Sel) {
5226 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
5227
5228 if (!Entry) {
5229 llvm::Constant *Casted =
5230 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
5231 ObjCTypes.SelectorPtrTy);
5232 Entry =
5233 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
5234 llvm::GlobalValue::InternalLinkage,
5235 Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
5236 &CGM.getModule());
5237 Entry->setSection("__DATA,__objc_selrefs,literal_pointers,no_dead_strip");
5238 UsedGlobals.push_back(Entry);
5239 }
5240
5241 return Builder.CreateLoad(Entry, false, "tmp");
5242}
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005243/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
5244/// objc_assign_ivar (id src, id *dst)
5245///
5246void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
5247 llvm::Value *src, llvm::Value *dst)
5248{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005249 const llvm::Type * SrcTy = src->getType();
5250 if (!isa<llvm::PointerType>(SrcTy)) {
5251 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5252 assert(Size <= 8 && "does not support size > 8");
5253 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5254 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005255 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5256 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005257 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5258 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00005259 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignIvarFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005260 src, dst, "assignivar");
5261 return;
5262}
5263
5264/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
5265/// objc_assign_strongCast (id src, id *dst)
5266///
5267void CGObjCNonFragileABIMac::EmitObjCStrongCastAssign(
5268 CodeGen::CodeGenFunction &CGF,
5269 llvm::Value *src, llvm::Value *dst)
5270{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005271 const llvm::Type * SrcTy = src->getType();
5272 if (!isa<llvm::PointerType>(SrcTy)) {
5273 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5274 assert(Size <= 8 && "does not support size > 8");
5275 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5276 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005277 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5278 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005279 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5280 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00005281 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignStrongCastFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005282 src, dst, "weakassign");
5283 return;
5284}
5285
5286/// EmitObjCWeakRead - Code gen for loading value of a __weak
5287/// object: objc_read_weak (id *src)
5288///
5289llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead(
5290 CodeGen::CodeGenFunction &CGF,
5291 llvm::Value *AddrWeakObj)
5292{
Eli Friedman8339b352009-03-07 03:57:15 +00005293 const llvm::Type* DestTy =
5294 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005295 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Chris Lattner72db6c32009-04-22 02:44:54 +00005296 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.getGcReadWeakFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005297 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00005298 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005299 return read_weak;
5300}
5301
5302/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
5303/// objc_assign_weak (id src, id *dst)
5304///
5305void CGObjCNonFragileABIMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
5306 llvm::Value *src, llvm::Value *dst)
5307{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005308 const llvm::Type * SrcTy = src->getType();
5309 if (!isa<llvm::PointerType>(SrcTy)) {
5310 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5311 assert(Size <= 8 && "does not support size > 8");
5312 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5313 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005314 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5315 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005316 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5317 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattner96508e12009-04-17 22:12:36 +00005318 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005319 src, dst, "weakassign");
5320 return;
5321}
5322
5323/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
5324/// objc_assign_global (id src, id *dst)
5325///
5326void CGObjCNonFragileABIMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
5327 llvm::Value *src, llvm::Value *dst)
5328{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005329 const llvm::Type * SrcTy = src->getType();
5330 if (!isa<llvm::PointerType>(SrcTy)) {
5331 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5332 assert(Size <= 8 && "does not support size > 8");
5333 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5334 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005335 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5336 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005337 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5338 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00005339 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignGlobalFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005340 src, dst, "globalassign");
5341 return;
5342}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005343
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005344void
5345CGObjCNonFragileABIMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
5346 const Stmt &S) {
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005347 bool isTry = isa<ObjCAtTryStmt>(S);
5348 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
5349 llvm::BasicBlock *PrevLandingPad = CGF.getInvokeDest();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005350 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005351 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005352 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005353 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
5354
5355 // For @synchronized, call objc_sync_enter(sync.expr). The
5356 // evaluation of the expression must occur before we enter the
5357 // @synchronized. We can safely avoid a temp here because jumps into
5358 // @synchronized are illegal & this will dominate uses.
5359 llvm::Value *SyncArg = 0;
5360 if (!isTry) {
5361 SyncArg =
5362 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
5363 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005364 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005365 }
5366
5367 // Push an EH context entry, used for handling rethrows and jumps
5368 // through finally.
5369 CGF.PushCleanupBlock(FinallyBlock);
5370
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005371 CGF.setInvokeDest(TryHandler);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005372
5373 CGF.EmitBlock(TryBlock);
5374 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
5375 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
5376 CGF.EmitBranchThroughCleanup(FinallyEnd);
5377
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005378 // Emit the exception handler.
5379
5380 CGF.EmitBlock(TryHandler);
5381
5382 llvm::Value *llvm_eh_exception =
5383 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_exception);
5384 llvm::Value *llvm_eh_selector_i64 =
5385 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector_i64);
5386 llvm::Value *llvm_eh_typeid_for_i64 =
5387 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for_i64);
5388 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5389 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(Exc->getType(), "_rethrow");
5390
5391 llvm::SmallVector<llvm::Value*, 8> SelectorArgs;
5392 SelectorArgs.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005393 SelectorArgs.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005394
5395 // Construct the lists of (type, catch body) to handle.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005396 llvm::SmallVector<std::pair<const ParmVarDecl*, const Stmt*>, 8> Handlers;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005397 bool HasCatchAll = false;
5398 if (isTry) {
5399 if (const ObjCAtCatchStmt* CatchStmt =
5400 cast<ObjCAtTryStmt>(S).getCatchStmts()) {
5401 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005402 const ParmVarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
Steve Naroff7ba138a2009-03-03 19:52:17 +00005403 Handlers.push_back(std::make_pair(CatchDecl, CatchStmt->getCatchBody()));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005404
5405 // catch(...) always matches.
Steve Naroff7ba138a2009-03-03 19:52:17 +00005406 if (!CatchDecl) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005407 // Use i8* null here to signal this is a catch all, not a cleanup.
5408 llvm::Value *Null = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
5409 SelectorArgs.push_back(Null);
5410 HasCatchAll = true;
5411 break;
5412 }
5413
Daniel Dunbarede8de92009-03-06 00:01:21 +00005414 if (CGF.getContext().isObjCIdType(CatchDecl->getType()) ||
5415 CatchDecl->getType()->isObjCQualifiedIdType()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005416 llvm::Value *IDEHType =
5417 CGM.getModule().getGlobalVariable("OBJC_EHTYPE_id");
5418 if (!IDEHType)
5419 IDEHType =
5420 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5421 llvm::GlobalValue::ExternalLinkage,
5422 0, "OBJC_EHTYPE_id", &CGM.getModule());
5423 SelectorArgs.push_back(IDEHType);
5424 HasCatchAll = true;
5425 break;
5426 }
5427
5428 // All other types should be Objective-C interface pointer types.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005429 const PointerType *PT = CatchDecl->getType()->getAsPointerType();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005430 assert(PT && "Invalid @catch type.");
5431 const ObjCInterfaceType *IT =
5432 PT->getPointeeType()->getAsObjCInterfaceType();
5433 assert(IT && "Invalid @catch type.");
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005434 llvm::Value *EHType = GetInterfaceEHType(IT->getDecl(), false);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005435 SelectorArgs.push_back(EHType);
5436 }
5437 }
5438 }
5439
5440 // We use a cleanup unless there was already a catch all.
5441 if (!HasCatchAll) {
5442 SelectorArgs.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
Daniel Dunbarede8de92009-03-06 00:01:21 +00005443 Handlers.push_back(std::make_pair((const ParmVarDecl*) 0, (const Stmt*) 0));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005444 }
5445
5446 llvm::Value *Selector =
5447 CGF.Builder.CreateCall(llvm_eh_selector_i64,
5448 SelectorArgs.begin(), SelectorArgs.end(),
5449 "selector");
5450 for (unsigned i = 0, e = Handlers.size(); i != e; ++i) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005451 const ParmVarDecl *CatchParam = Handlers[i].first;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005452 const Stmt *CatchBody = Handlers[i].second;
5453
5454 llvm::BasicBlock *Next = 0;
5455
5456 // The last handler always matches.
5457 if (i + 1 != e) {
5458 assert(CatchParam && "Only last handler can be a catch all.");
5459
5460 llvm::BasicBlock *Match = CGF.createBasicBlock("match");
5461 Next = CGF.createBasicBlock("catch.next");
5462 llvm::Value *Id =
5463 CGF.Builder.CreateCall(llvm_eh_typeid_for_i64,
5464 CGF.Builder.CreateBitCast(SelectorArgs[i+2],
5465 ObjCTypes.Int8PtrTy));
5466 CGF.Builder.CreateCondBr(CGF.Builder.CreateICmpEQ(Selector, Id),
5467 Match, Next);
5468
5469 CGF.EmitBlock(Match);
5470 }
5471
5472 if (CatchBody) {
5473 llvm::BasicBlock *MatchEnd = CGF.createBasicBlock("match.end");
5474 llvm::BasicBlock *MatchHandler = CGF.createBasicBlock("match.handler");
5475
5476 // Cleanups must call objc_end_catch.
5477 //
5478 // FIXME: It seems incorrect for objc_begin_catch to be inside
5479 // this context, but this matches gcc.
5480 CGF.PushCleanupBlock(MatchEnd);
5481 CGF.setInvokeDest(MatchHandler);
5482
5483 llvm::Value *ExcObject =
Chris Lattner8a569112009-04-22 02:15:23 +00005484 CGF.Builder.CreateCall(ObjCTypes.getObjCBeginCatchFn(), Exc);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005485
5486 // Bind the catch parameter if it exists.
5487 if (CatchParam) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005488 ExcObject =
5489 CGF.Builder.CreateBitCast(ExcObject,
5490 CGF.ConvertType(CatchParam->getType()));
5491 // CatchParam is a ParmVarDecl because of the grammar
5492 // construction used to handle this, but for codegen purposes
5493 // we treat this as a local decl.
5494 CGF.EmitLocalBlockVarDecl(*CatchParam);
5495 CGF.Builder.CreateStore(ExcObject, CGF.GetAddrOfLocalVar(CatchParam));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005496 }
5497
5498 CGF.ObjCEHValueStack.push_back(ExcObject);
5499 CGF.EmitStmt(CatchBody);
5500 CGF.ObjCEHValueStack.pop_back();
5501
5502 CGF.EmitBranchThroughCleanup(FinallyEnd);
5503
5504 CGF.EmitBlock(MatchHandler);
5505
5506 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5507 // We are required to emit this call to satisfy LLVM, even
5508 // though we don't use the result.
5509 llvm::SmallVector<llvm::Value*, 8> Args;
5510 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005511 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005512 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5513 0));
5514 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5515 CGF.Builder.CreateStore(Exc, RethrowPtr);
5516 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5517
5518 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5519
5520 CGF.EmitBlock(MatchEnd);
5521
5522 // Unfortunately, we also have to generate another EH frame here
5523 // in case this throws.
5524 llvm::BasicBlock *MatchEndHandler =
5525 CGF.createBasicBlock("match.end.handler");
5526 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
Chris Lattner8a569112009-04-22 02:15:23 +00005527 CGF.Builder.CreateInvoke(ObjCTypes.getObjCEndCatchFn(),
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005528 Cont, MatchEndHandler,
5529 Args.begin(), Args.begin());
5530
5531 CGF.EmitBlock(Cont);
5532 if (Info.SwitchBlock)
5533 CGF.EmitBlock(Info.SwitchBlock);
5534 if (Info.EndBlock)
5535 CGF.EmitBlock(Info.EndBlock);
5536
5537 CGF.EmitBlock(MatchEndHandler);
5538 Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5539 // We are required to emit this call to satisfy LLVM, even
5540 // though we don't use the result.
5541 Args.clear();
5542 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005543 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005544 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5545 0));
5546 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5547 CGF.Builder.CreateStore(Exc, RethrowPtr);
5548 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5549
5550 if (Next)
5551 CGF.EmitBlock(Next);
5552 } else {
5553 assert(!Next && "catchup should be last handler.");
5554
5555 CGF.Builder.CreateStore(Exc, RethrowPtr);
5556 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5557 }
5558 }
5559
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005560 // Pop the cleanup entry, the @finally is outside this cleanup
5561 // scope.
5562 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5563 CGF.setInvokeDest(PrevLandingPad);
5564
5565 CGF.EmitBlock(FinallyBlock);
5566
5567 if (isTry) {
5568 if (const ObjCAtFinallyStmt* FinallyStmt =
5569 cast<ObjCAtTryStmt>(S).getFinallyStmt())
5570 CGF.EmitStmt(FinallyStmt->getFinallyBody());
5571 } else {
5572 // Emit 'objc_sync_exit(expr)' as finally's sole statement for
5573 // @synchronized.
Chris Lattnerbbccd612009-04-22 02:38:11 +00005574 CGF.Builder.CreateCall(ObjCTypes.getSyncExitFn(), SyncArg);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005575 }
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005576
5577 if (Info.SwitchBlock)
5578 CGF.EmitBlock(Info.SwitchBlock);
5579 if (Info.EndBlock)
5580 CGF.EmitBlock(Info.EndBlock);
5581
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005582 // Branch around the rethrow code.
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005583 CGF.EmitBranch(FinallyEnd);
5584
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005585 CGF.EmitBlock(FinallyRethrow);
Chris Lattner8a569112009-04-22 02:15:23 +00005586 CGF.Builder.CreateCall(ObjCTypes.getUnwindResumeOrRethrowFn(),
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005587 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005588 CGF.Builder.CreateUnreachable();
5589
5590 CGF.EmitBlock(FinallyEnd);
5591}
5592
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005593/// EmitThrowStmt - Generate code for a throw statement.
5594void CGObjCNonFragileABIMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
5595 const ObjCAtThrowStmt &S) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005596 llvm::Value *Exception;
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005597 if (const Expr *ThrowExpr = S.getThrowExpr()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005598 Exception = CGF.EmitScalarExpr(ThrowExpr);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005599 } else {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005600 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
5601 "Unexpected rethrow outside @catch block.");
5602 Exception = CGF.ObjCEHValueStack.back();
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005603 }
5604
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005605 llvm::Value *ExceptionAsObject =
5606 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
5607 llvm::BasicBlock *InvokeDest = CGF.getInvokeDest();
5608 if (InvokeDest) {
5609 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
Chris Lattnerbbccd612009-04-22 02:38:11 +00005610 CGF.Builder.CreateInvoke(ObjCTypes.getExceptionThrowFn(),
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005611 Cont, InvokeDest,
5612 &ExceptionAsObject, &ExceptionAsObject + 1);
5613 CGF.EmitBlock(Cont);
5614 } else
Chris Lattnerbbccd612009-04-22 02:38:11 +00005615 CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(), ExceptionAsObject);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005616 CGF.Builder.CreateUnreachable();
5617
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005618 // Clear the insertion point to indicate we are in unreachable code.
5619 CGF.Builder.ClearInsertionPoint();
5620}
Daniel Dunbare588b992009-03-01 04:46:24 +00005621
5622llvm::Value *
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005623CGObjCNonFragileABIMac::GetInterfaceEHType(const ObjCInterfaceDecl *ID,
5624 bool ForDefinition) {
Daniel Dunbare588b992009-03-01 04:46:24 +00005625 llvm::GlobalVariable * &Entry = EHTypeReferences[ID->getIdentifier()];
Daniel Dunbare588b992009-03-01 04:46:24 +00005626
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005627 // If we don't need a definition, return the entry if found or check
5628 // if we use an external reference.
5629 if (!ForDefinition) {
5630 if (Entry)
5631 return Entry;
Daniel Dunbar7e075cb2009-04-07 06:43:45 +00005632
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005633 // If this type (or a super class) has the __objc_exception__
5634 // attribute, emit an external reference.
5635 if (hasObjCExceptionAttribute(ID))
5636 return Entry =
5637 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5638 llvm::GlobalValue::ExternalLinkage,
5639 0,
5640 (std::string("OBJC_EHTYPE_$_") +
5641 ID->getIdentifier()->getName()),
5642 &CGM.getModule());
5643 }
5644
5645 // Otherwise we need to either make a new entry or fill in the
5646 // initializer.
5647 assert((!Entry || !Entry->hasInitializer()) && "Duplicate EHType definition");
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005648 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbare588b992009-03-01 04:46:24 +00005649 std::string VTableName = "objc_ehtype_vtable";
5650 llvm::GlobalVariable *VTableGV =
5651 CGM.getModule().getGlobalVariable(VTableName);
5652 if (!VTableGV)
5653 VTableGV = new llvm::GlobalVariable(ObjCTypes.Int8PtrTy, false,
5654 llvm::GlobalValue::ExternalLinkage,
5655 0, VTableName, &CGM.getModule());
5656
5657 llvm::Value *VTableIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, 2);
5658
5659 std::vector<llvm::Constant*> Values(3);
5660 Values[0] = llvm::ConstantExpr::getGetElementPtr(VTableGV, &VTableIdx, 1);
5661 Values[1] = GetClassName(ID->getIdentifier());
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005662 Values[2] = GetClassGlobal(ClassName);
Daniel Dunbare588b992009-03-01 04:46:24 +00005663 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.EHTypeTy, Values);
5664
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005665 if (Entry) {
5666 Entry->setInitializer(Init);
5667 } else {
5668 Entry = new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5669 llvm::GlobalValue::WeakAnyLinkage,
5670 Init,
5671 (std::string("OBJC_EHTYPE_$_") +
5672 ID->getIdentifier()->getName()),
5673 &CGM.getModule());
5674 }
5675
Daniel Dunbar04d40782009-04-14 06:00:08 +00005676 if (CGM.getLangOptions().getVisibilityMode() == LangOptions::Hidden)
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005677 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005678 Entry->setAlignment(8);
5679
5680 if (ForDefinition) {
5681 Entry->setSection("__DATA,__objc_const");
5682 Entry->setLinkage(llvm::GlobalValue::ExternalLinkage);
5683 } else {
5684 Entry->setSection("__DATA,__datacoal_nt,coalesced");
5685 }
Daniel Dunbare588b992009-03-01 04:46:24 +00005686
5687 return Entry;
5688}
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005689
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00005690/* *** */
5691
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00005692CodeGen::CGObjCRuntime *
5693CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00005694 return new CGObjCMac(CGM);
5695}
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005696
5697CodeGen::CGObjCRuntime *
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00005698CodeGen::CreateMacNonFragileABIObjCRuntime(CodeGen::CodeGenModule &CGM) {
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00005699 return new CGObjCNonFragileABIMac(CGM);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005700}