blob: dc66fa46b139d0db64a464ad2dcd79b21d7d4621 [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
Daniel Dunbar97776872009-04-22 07:32:20 +000032// Common CGObjCRuntime functions, these don't belong here, but they
33// don't belong in CGObjCRuntime either so we will live with it for
34// now.
35
36uint64_t CGObjCRuntime::ComputeIvarBaseOffset(CodeGen::CodeGenModule &CGM,
37 const ObjCInterfaceDecl *OID,
38 const ObjCIvarDecl *Ivar) {
39 assert(!OID->isForwardDecl() && "Invalid interface decl!");
40 QualType T = CGM.getContext().getObjCInterfaceType(OID);
41 const llvm::StructType *InterfaceTy =
42 cast<llvm::StructType>(CGM.getTypes().ConvertType(T));
43 const llvm::StructLayout *Layout =
44 CGM.getTargetData().getStructLayout(InterfaceTy);
45 const FieldDecl *Field =
46 OID->lookupFieldDeclForIvar(CGM.getContext(), Ivar);
47 if (!Field->isBitField())
48 return Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(Field));
49
50 // FIXME. Must be a better way of getting a bitfield base offset.
51 CodeGenTypes::BitFieldInfo BFI = CGM.getTypes().getBitFieldInfo(Field);
52 // FIXME: The "field no" for bitfields is something completely
53 // different; it is the offset in multiples of the base type size!
54 uint64_t Offset = CGM.getTypes().getLLVMFieldNo(Field);
55 const llvm::Type *Ty =
56 CGM.getTypes().ConvertTypeForMemRecursive(Field->getType());
57 Offset *= CGM.getTypes().getTargetData().getTypePaddedSizeInBits(Ty);
58 return (Offset + BFI.Begin) / 8;
59}
60
61LValue CGObjCRuntime::EmitValueForIvarAtOffset(CodeGen::CodeGenFunction &CGF,
62 const ObjCInterfaceDecl *OID,
63 llvm::Value *BaseValue,
64 const ObjCIvarDecl *Ivar,
65 unsigned CVRQualifiers,
66 llvm::Value *Offset) {
67 // FIXME: For now, we use an implementation based on just computing
68 // the offset and calculating things directly. For optimization
69 // purposes, it would be cleaner to use a GEP on the proper type
70 // since the structure layout is fixed; however for that we need to
71 // be able to walk the class chain for an Ivar.
72 const FieldDecl *Field =
73 OID->lookupFieldDeclForIvar(CGF.CGM.getContext(), Ivar);
74
75 // (char *) BaseValue
76 llvm::Type *I8Ptr = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
77 llvm::Value *V = CGF.Builder.CreateBitCast(BaseValue, I8Ptr);
78 // (char*)BaseValue + Offset_symbol
79 V = CGF.Builder.CreateGEP(V, Offset, "add.ptr");
80 // (type *)((char*)BaseValue + Offset_symbol)
81 const llvm::Type *IvarTy =
82 CGF.CGM.getTypes().ConvertTypeForMem(Ivar->getType());
83 llvm::Type *ptrIvarTy = llvm::PointerType::getUnqual(IvarTy);
84 V = CGF.Builder.CreateBitCast(V, ptrIvarTy);
85
86 if (Ivar->isBitField()) {
87 QualType FieldTy = Field->getType();
88 CodeGenTypes::BitFieldInfo bitFieldInfo =
89 CGF.CGM.getTypes().getBitFieldInfo(Field);
90 return LValue::MakeBitfield(V, bitFieldInfo.Begin % 8, bitFieldInfo.Size,
91 FieldTy->isSignedIntegerType(),
92 FieldTy.getCVRQualifiers()|CVRQualifiers);
93 }
94
95 LValue LV = LValue::MakeAddr(V,
96 Ivar->getType().getCVRQualifiers()|CVRQualifiers,
97 CGF.CGM.getContext().getObjCGCAttrKind(Ivar->getType()));
98 LValue::SetObjCIvar(LV, true);
99 return LV;
100}
101
102///
103
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000104namespace {
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000105
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000106 typedef std::vector<llvm::Constant*> ConstantVector;
107
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000108 // FIXME: We should find a nicer way to make the labels for
109 // metadata, string concatenation is lame.
110
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000111class ObjCCommonTypesHelper {
112protected:
113 CodeGen::CodeGenModule &CGM;
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000114
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000115public:
Fariborz Jahanian0a855d02009-03-23 19:10:40 +0000116 const llvm::Type *ShortTy, *IntTy, *LongTy, *LongLongTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000117 const llvm::Type *Int8PtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000118
Daniel Dunbar2bedbf82008-08-12 05:28:47 +0000119 /// ObjectPtrTy - LLVM type for object handles (typeof(id))
120 const llvm::Type *ObjectPtrTy;
Fariborz Jahanian6d657c42008-11-18 20:18:11 +0000121
122 /// PtrObjectPtrTy - LLVM type for id *
123 const llvm::Type *PtrObjectPtrTy;
124
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000125 /// SelectorPtrTy - LLVM type for selector handles (typeof(SEL))
Daniel Dunbar2bedbf82008-08-12 05:28:47 +0000126 const llvm::Type *SelectorPtrTy;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000127 /// ProtocolPtrTy - LLVM type for external protocol handles
128 /// (typeof(Protocol))
129 const llvm::Type *ExternalProtocolPtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000130
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000131 // SuperCTy - clang type for struct objc_super.
132 QualType SuperCTy;
133 // SuperPtrCTy - clang type for struct objc_super *.
134 QualType SuperPtrCTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000135
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000136 /// SuperTy - LLVM type for struct objc_super.
137 const llvm::StructType *SuperTy;
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000138 /// SuperPtrTy - LLVM type for struct objc_super *.
139 const llvm::Type *SuperPtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000140
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000141 /// PropertyTy - LLVM type for struct objc_property (struct _prop_t
142 /// in GCC parlance).
143 const llvm::StructType *PropertyTy;
144
145 /// PropertyListTy - LLVM type for struct objc_property_list
146 /// (_prop_list_t in GCC parlance).
147 const llvm::StructType *PropertyListTy;
148 /// PropertyListPtrTy - LLVM type for struct objc_property_list*.
149 const llvm::Type *PropertyListPtrTy;
150
151 // MethodTy - LLVM type for struct objc_method.
152 const llvm::StructType *MethodTy;
153
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000154 /// CacheTy - LLVM type for struct objc_cache.
155 const llvm::Type *CacheTy;
156 /// CachePtrTy - LLVM type for struct objc_cache *.
157 const llvm::Type *CachePtrTy;
158
Chris Lattner72db6c32009-04-22 02:44:54 +0000159 llvm::Constant *getGetPropertyFn() {
160 CodeGen::CodeGenTypes &Types = CGM.getTypes();
161 ASTContext &Ctx = CGM.getContext();
162 // id objc_getProperty (id, SEL, ptrdiff_t, bool)
163 llvm::SmallVector<QualType,16> Params;
164 QualType IdType = Ctx.getObjCIdType();
165 QualType SelType = Ctx.getObjCSelType();
166 Params.push_back(IdType);
167 Params.push_back(SelType);
168 Params.push_back(Ctx.LongTy);
169 Params.push_back(Ctx.BoolTy);
170 const llvm::FunctionType *FTy =
171 Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
172 return CGM.CreateRuntimeFunction(FTy, "objc_getProperty");
173 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000174
Chris Lattner72db6c32009-04-22 02:44:54 +0000175 llvm::Constant *getSetPropertyFn() {
176 CodeGen::CodeGenTypes &Types = CGM.getTypes();
177 ASTContext &Ctx = CGM.getContext();
178 // void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool)
179 llvm::SmallVector<QualType,16> Params;
180 QualType IdType = Ctx.getObjCIdType();
181 QualType SelType = Ctx.getObjCSelType();
182 Params.push_back(IdType);
183 Params.push_back(SelType);
184 Params.push_back(Ctx.LongTy);
185 Params.push_back(IdType);
186 Params.push_back(Ctx.BoolTy);
187 Params.push_back(Ctx.BoolTy);
188 const llvm::FunctionType *FTy =
189 Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
190 return CGM.CreateRuntimeFunction(FTy, "objc_setProperty");
191 }
192
193 llvm::Constant *getEnumerationMutationFn() {
194 // void objc_enumerationMutation (id)
195 std::vector<const llvm::Type*> Args;
196 Args.push_back(ObjectPtrTy);
197 llvm::FunctionType *FTy =
198 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
199 return CGM.CreateRuntimeFunction(FTy, "objc_enumerationMutation");
200 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000201
202 /// GcReadWeakFn -- LLVM objc_read_weak (id *src) function.
Chris Lattner72db6c32009-04-22 02:44:54 +0000203 llvm::Constant *getGcReadWeakFn() {
204 // id objc_read_weak (id *)
205 std::vector<const llvm::Type*> Args;
206 Args.push_back(ObjectPtrTy->getPointerTo());
207 llvm::FunctionType *FTy = llvm::FunctionType::get(ObjectPtrTy, Args, false);
208 return CGM.CreateRuntimeFunction(FTy, "objc_read_weak");
209 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000210
211 /// GcAssignWeakFn -- LLVM objc_assign_weak function.
Chris Lattner96508e12009-04-17 22:12:36 +0000212 llvm::Constant *getGcAssignWeakFn() {
213 // id objc_assign_weak (id, id *)
214 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
215 Args.push_back(ObjectPtrTy->getPointerTo());
216 llvm::FunctionType *FTy =
217 llvm::FunctionType::get(ObjectPtrTy, Args, false);
218 return CGM.CreateRuntimeFunction(FTy, "objc_assign_weak");
219 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000220
221 /// GcAssignGlobalFn -- LLVM objc_assign_global function.
Chris Lattnerbbccd612009-04-22 02:38:11 +0000222 llvm::Constant *getGcAssignGlobalFn() {
223 // id objc_assign_global(id, id *)
224 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
225 Args.push_back(ObjectPtrTy->getPointerTo());
226 llvm::FunctionType *FTy = llvm::FunctionType::get(ObjectPtrTy, Args, false);
227 return CGM.CreateRuntimeFunction(FTy, "objc_assign_global");
228 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000229
230 /// GcAssignIvarFn -- LLVM objc_assign_ivar function.
Chris Lattnerbbccd612009-04-22 02:38:11 +0000231 llvm::Constant *getGcAssignIvarFn() {
232 // id objc_assign_ivar(id, id *)
233 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
234 Args.push_back(ObjectPtrTy->getPointerTo());
235 llvm::FunctionType *FTy = llvm::FunctionType::get(ObjectPtrTy, Args, false);
236 return CGM.CreateRuntimeFunction(FTy, "objc_assign_ivar");
237 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000238
239 /// GcAssignStrongCastFn -- LLVM objc_assign_strongCast function.
Chris Lattnerbbccd612009-04-22 02:38:11 +0000240 llvm::Constant *getGcAssignStrongCastFn() {
241 // id objc_assign_global(id, id *)
242 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
243 Args.push_back(ObjectPtrTy->getPointerTo());
244 llvm::FunctionType *FTy = llvm::FunctionType::get(ObjectPtrTy, Args, false);
245 return CGM.CreateRuntimeFunction(FTy, "objc_assign_strongCast");
246 }
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000247
248 /// ExceptionThrowFn - LLVM objc_exception_throw function.
Chris Lattnerbbccd612009-04-22 02:38:11 +0000249 llvm::Constant *getExceptionThrowFn() {
250 // void objc_exception_throw(id)
251 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
252 llvm::FunctionType *FTy =
253 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
254 return CGM.CreateRuntimeFunction(FTy, "objc_exception_throw");
255 }
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000256
Daniel Dunbar1c566672009-02-24 01:43:46 +0000257 /// SyncEnterFn - LLVM object_sync_enter function.
Chris Lattnerb02e53b2009-04-06 16:53:45 +0000258 llvm::Constant *getSyncEnterFn() {
259 // void objc_sync_enter (id)
260 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
261 llvm::FunctionType *FTy =
262 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
263 return CGM.CreateRuntimeFunction(FTy, "objc_sync_enter");
264 }
Daniel Dunbar1c566672009-02-24 01:43:46 +0000265
266 /// SyncExitFn - LLVM object_sync_exit function.
Chris Lattnerbbccd612009-04-22 02:38:11 +0000267 llvm::Constant *getSyncExitFn() {
268 // void objc_sync_exit (id)
269 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
270 llvm::FunctionType *FTy =
271 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
272 return CGM.CreateRuntimeFunction(FTy, "objc_sync_exit");
273 }
Daniel Dunbar1c566672009-02-24 01:43:46 +0000274
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000275 ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm);
276 ~ObjCCommonTypesHelper(){}
277};
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000278
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000279/// ObjCTypesHelper - Helper class that encapsulates lazy
280/// construction of varies types used during ObjC generation.
281class ObjCTypesHelper : public ObjCCommonTypesHelper {
282private:
283
Chris Lattner4176b0c2009-04-22 02:32:31 +0000284 llvm::Constant *getMessageSendFn() {
285 // id objc_msgSend (id, SEL, ...)
286 std::vector<const llvm::Type*> Params;
287 Params.push_back(ObjectPtrTy);
288 Params.push_back(SelectorPtrTy);
289 return
290 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
291 Params, true),
292 "objc_msgSend");
293 }
294
295 llvm::Constant *getMessageSendStretFn() {
296 // id objc_msgSend_stret (id, SEL, ...)
297 std::vector<const llvm::Type*> Params;
298 Params.push_back(ObjectPtrTy);
299 Params.push_back(SelectorPtrTy);
300 return
301 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
302 Params, true),
303 "objc_msgSend_stret");
304
305 }
306
307 llvm::Constant *getMessageSendFpretFn() {
308 // FIXME: This should be long double on x86_64?
309 // [double | long double] objc_msgSend_fpret(id self, SEL op, ...)
310 std::vector<const llvm::Type*> Params;
311 Params.push_back(ObjectPtrTy);
312 Params.push_back(SelectorPtrTy);
313 return
314 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::DoubleTy,
315 Params,
316 true),
317 "objc_msgSend_fpret");
318
319 }
320
321 llvm::Constant *getMessageSendSuperFn() {
322 // id objc_msgSendSuper(struct objc_super *super, SEL op, ...)
323 std::vector<const llvm::Type*> Params;
324 Params.push_back(SuperPtrTy);
325 Params.push_back(SelectorPtrTy);
326 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
327 Params, true),
328 "objc_msgSendSuper");
329 }
330 llvm::Constant *getMessageSendSuperStretFn() {
331 // void objc_msgSendSuper_stret(void * stretAddr, struct objc_super *super,
332 // SEL op, ...)
333 std::vector<const llvm::Type*> Params;
334 Params.push_back(Int8PtrTy);
335 Params.push_back(SuperPtrTy);
336 Params.push_back(SelectorPtrTy);
337 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
338 Params, true),
339 "objc_msgSendSuper_stret");
340 }
341
342 llvm::Constant *getMessageSendSuperFpretFn() {
343 // There is no objc_msgSendSuper_fpret? How can that work?
344 return getMessageSendSuperFn();
345 }
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000346
347public:
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000348 /// SymtabTy - LLVM type for struct objc_symtab.
349 const llvm::StructType *SymtabTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000350 /// SymtabPtrTy - LLVM type for struct objc_symtab *.
351 const llvm::Type *SymtabPtrTy;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000352 /// ModuleTy - LLVM type for struct objc_module.
353 const llvm::StructType *ModuleTy;
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000354
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000355 /// ProtocolTy - LLVM type for struct objc_protocol.
356 const llvm::StructType *ProtocolTy;
357 /// ProtocolPtrTy - LLVM type for struct objc_protocol *.
358 const llvm::Type *ProtocolPtrTy;
359 /// ProtocolExtensionTy - LLVM type for struct
360 /// objc_protocol_extension.
361 const llvm::StructType *ProtocolExtensionTy;
362 /// ProtocolExtensionTy - LLVM type for struct
363 /// objc_protocol_extension *.
364 const llvm::Type *ProtocolExtensionPtrTy;
365 /// MethodDescriptionTy - LLVM type for struct
366 /// objc_method_description.
367 const llvm::StructType *MethodDescriptionTy;
368 /// MethodDescriptionListTy - LLVM type for struct
369 /// objc_method_description_list.
370 const llvm::StructType *MethodDescriptionListTy;
371 /// MethodDescriptionListPtrTy - LLVM type for struct
372 /// objc_method_description_list *.
373 const llvm::Type *MethodDescriptionListPtrTy;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000374 /// ProtocolListTy - LLVM type for struct objc_property_list.
375 const llvm::Type *ProtocolListTy;
376 /// ProtocolListPtrTy - LLVM type for struct objc_property_list*.
377 const llvm::Type *ProtocolListPtrTy;
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000378 /// CategoryTy - LLVM type for struct objc_category.
379 const llvm::StructType *CategoryTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000380 /// ClassTy - LLVM type for struct objc_class.
381 const llvm::StructType *ClassTy;
382 /// ClassPtrTy - LLVM type for struct objc_class *.
383 const llvm::Type *ClassPtrTy;
384 /// ClassExtensionTy - LLVM type for struct objc_class_ext.
385 const llvm::StructType *ClassExtensionTy;
386 /// ClassExtensionPtrTy - LLVM type for struct objc_class_ext *.
387 const llvm::Type *ClassExtensionPtrTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000388 // IvarTy - LLVM type for struct objc_ivar.
389 const llvm::StructType *IvarTy;
390 /// IvarListTy - LLVM type for struct objc_ivar_list.
391 const llvm::Type *IvarListTy;
392 /// IvarListPtrTy - LLVM type for struct objc_ivar_list *.
393 const llvm::Type *IvarListPtrTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000394 /// MethodListTy - LLVM type for struct objc_method_list.
395 const llvm::Type *MethodListTy;
396 /// MethodListPtrTy - LLVM type for struct objc_method_list *.
397 const llvm::Type *MethodListPtrTy;
Anders Carlsson124526b2008-09-09 10:10:21 +0000398
399 /// ExceptionDataTy - LLVM type for struct _objc_exception_data.
400 const llvm::Type *ExceptionDataTy;
401
Anders Carlsson124526b2008-09-09 10:10:21 +0000402 /// ExceptionTryEnterFn - LLVM objc_exception_try_enter function.
Chris Lattner34b02a12009-04-22 02:26:14 +0000403 llvm::Constant *getExceptionTryEnterFn() {
404 std::vector<const llvm::Type*> Params;
405 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
406 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
407 Params, false),
408 "objc_exception_try_enter");
409 }
Anders Carlsson124526b2008-09-09 10:10:21 +0000410
411 /// ExceptionTryExitFn - LLVM objc_exception_try_exit function.
Chris Lattner34b02a12009-04-22 02:26:14 +0000412 llvm::Constant *getExceptionTryExitFn() {
413 std::vector<const llvm::Type*> Params;
414 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
415 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
416 Params, false),
417 "objc_exception_try_exit");
418 }
Anders Carlsson124526b2008-09-09 10:10:21 +0000419
420 /// ExceptionExtractFn - LLVM objc_exception_extract function.
Chris Lattner34b02a12009-04-22 02:26:14 +0000421 llvm::Constant *getExceptionExtractFn() {
422 std::vector<const llvm::Type*> Params;
423 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
424 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
425 Params, false),
426 "objc_exception_extract");
427
428 }
Anders Carlsson124526b2008-09-09 10:10:21 +0000429
430 /// ExceptionMatchFn - LLVM objc_exception_match function.
Chris Lattner34b02a12009-04-22 02:26:14 +0000431 llvm::Constant *getExceptionMatchFn() {
432 std::vector<const llvm::Type*> Params;
433 Params.push_back(ClassPtrTy);
434 Params.push_back(ObjectPtrTy);
435 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
436 Params, false),
437 "objc_exception_match");
438
439 }
Anders Carlsson124526b2008-09-09 10:10:21 +0000440
441 /// SetJmpFn - LLVM _setjmp function.
Chris Lattner34b02a12009-04-22 02:26:14 +0000442 llvm::Constant *getSetJmpFn() {
443 std::vector<const llvm::Type*> Params;
444 Params.push_back(llvm::PointerType::getUnqual(llvm::Type::Int32Ty));
445 return
446 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
447 Params, false),
448 "_setjmp");
449
450 }
Chris Lattner10cac6f2008-11-15 21:26:17 +0000451
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000452public:
453 ObjCTypesHelper(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000454 ~ObjCTypesHelper() {}
Daniel Dunbar5669e572008-10-17 03:24:53 +0000455
456
Chris Lattner74391b42009-03-22 21:03:39 +0000457 llvm::Constant *getSendFn(bool IsSuper) {
Chris Lattner4176b0c2009-04-22 02:32:31 +0000458 return IsSuper ? getMessageSendSuperFn() : getMessageSendFn();
Daniel Dunbar5669e572008-10-17 03:24:53 +0000459 }
460
Chris Lattner74391b42009-03-22 21:03:39 +0000461 llvm::Constant *getSendStretFn(bool IsSuper) {
Chris Lattner4176b0c2009-04-22 02:32:31 +0000462 return IsSuper ? getMessageSendSuperStretFn() : getMessageSendStretFn();
Daniel Dunbar5669e572008-10-17 03:24:53 +0000463 }
464
Chris Lattner74391b42009-03-22 21:03:39 +0000465 llvm::Constant *getSendFpretFn(bool IsSuper) {
Chris Lattner4176b0c2009-04-22 02:32:31 +0000466 return IsSuper ? getMessageSendSuperFpretFn() : getMessageSendFpretFn();
Daniel Dunbar5669e572008-10-17 03:24:53 +0000467 }
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000468};
469
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000470/// ObjCNonFragileABITypesHelper - will have all types needed by objective-c's
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000471/// modern abi
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000472class ObjCNonFragileABITypesHelper : public ObjCCommonTypesHelper {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000473public:
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000474
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000475 // MethodListnfABITy - LLVM for struct _method_list_t
476 const llvm::StructType *MethodListnfABITy;
477
478 // MethodListnfABIPtrTy - LLVM for struct _method_list_t*
479 const llvm::Type *MethodListnfABIPtrTy;
480
481 // ProtocolnfABITy = LLVM for struct _protocol_t
482 const llvm::StructType *ProtocolnfABITy;
483
Daniel Dunbar948e2582009-02-15 07:36:20 +0000484 // ProtocolnfABIPtrTy = LLVM for struct _protocol_t*
485 const llvm::Type *ProtocolnfABIPtrTy;
486
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000487 // ProtocolListnfABITy - LLVM for struct _objc_protocol_list
488 const llvm::StructType *ProtocolListnfABITy;
489
490 // ProtocolListnfABIPtrTy - LLVM for struct _objc_protocol_list*
491 const llvm::Type *ProtocolListnfABIPtrTy;
492
493 // ClassnfABITy - LLVM for struct _class_t
494 const llvm::StructType *ClassnfABITy;
495
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000496 // ClassnfABIPtrTy - LLVM for struct _class_t*
497 const llvm::Type *ClassnfABIPtrTy;
498
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000499 // IvarnfABITy - LLVM for struct _ivar_t
500 const llvm::StructType *IvarnfABITy;
501
502 // IvarListnfABITy - LLVM for struct _ivar_list_t
503 const llvm::StructType *IvarListnfABITy;
504
505 // IvarListnfABIPtrTy = LLVM for struct _ivar_list_t*
506 const llvm::Type *IvarListnfABIPtrTy;
507
508 // ClassRonfABITy - LLVM for struct _class_ro_t
509 const llvm::StructType *ClassRonfABITy;
510
511 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
512 const llvm::Type *ImpnfABITy;
513
514 // CategorynfABITy - LLVM for struct _category_t
515 const llvm::StructType *CategorynfABITy;
516
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000517 // New types for nonfragile abi messaging.
518
519 // MessageRefTy - LLVM for:
520 // struct _message_ref_t {
521 // IMP messenger;
522 // SEL name;
523 // };
524 const llvm::StructType *MessageRefTy;
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000525 // MessageRefCTy - clang type for struct _message_ref_t
526 QualType MessageRefCTy;
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000527
528 // MessageRefPtrTy - LLVM for struct _message_ref_t*
529 const llvm::Type *MessageRefPtrTy;
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000530 // MessageRefCPtrTy - clang type for struct _message_ref_t*
531 QualType MessageRefCPtrTy;
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000532
Fariborz Jahanianef163782009-02-05 01:13:09 +0000533 // MessengerTy - Type of the messenger (shown as IMP above)
534 const llvm::FunctionType *MessengerTy;
535
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000536 // SuperMessageRefTy - LLVM for:
537 // struct _super_message_ref_t {
538 // SUPER_IMP messenger;
539 // SEL name;
540 // };
541 const llvm::StructType *SuperMessageRefTy;
542
543 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
544 const llvm::Type *SuperMessageRefPtrTy;
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000545
Chris Lattner1c02f862009-04-22 02:53:24 +0000546 llvm::Constant *getMessageSendFixupFn() {
547 // id objc_msgSend_fixup(id, struct message_ref_t*, ...)
548 std::vector<const llvm::Type*> Params;
549 Params.push_back(ObjectPtrTy);
550 Params.push_back(MessageRefPtrTy);
551 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
552 Params, true),
553 "objc_msgSend_fixup");
554 }
555
556 llvm::Constant *getMessageSendFpretFixupFn() {
557 // id objc_msgSend_fpret_fixup(id, struct message_ref_t*, ...)
558 std::vector<const llvm::Type*> Params;
559 Params.push_back(ObjectPtrTy);
560 Params.push_back(MessageRefPtrTy);
561 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
562 Params, true),
563 "objc_msgSend_fpret_fixup");
564 }
565
566 llvm::Constant *getMessageSendStretFixupFn() {
567 // id objc_msgSend_stret_fixup(id, struct message_ref_t*, ...)
568 std::vector<const llvm::Type*> Params;
569 Params.push_back(ObjectPtrTy);
570 Params.push_back(MessageRefPtrTy);
571 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
572 Params, true),
573 "objc_msgSend_stret_fixup");
574 }
575
576 llvm::Constant *getMessageSendIdFixupFn() {
577 // id objc_msgSendId_fixup(id, struct message_ref_t*, ...)
578 std::vector<const llvm::Type*> Params;
579 Params.push_back(ObjectPtrTy);
580 Params.push_back(MessageRefPtrTy);
581 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
582 Params, true),
583 "objc_msgSendId_fixup");
584 }
585
586 llvm::Constant *getMessageSendIdStretFixupFn() {
587 // id objc_msgSendId_stret_fixup(id, struct message_ref_t*, ...)
588 std::vector<const llvm::Type*> Params;
589 Params.push_back(ObjectPtrTy);
590 Params.push_back(MessageRefPtrTy);
591 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
592 Params, true),
593 "objc_msgSendId_stret_fixup");
594 }
595 llvm::Constant *getMessageSendSuper2FixupFn() {
596 // id objc_msgSendSuper2_fixup (struct objc_super *,
597 // struct _super_message_ref_t*, ...)
598 std::vector<const llvm::Type*> Params;
599 Params.push_back(SuperPtrTy);
600 Params.push_back(SuperMessageRefPtrTy);
601 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
602 Params, true),
603 "objc_msgSendSuper2_fixup");
604 }
605
606 llvm::Constant *getMessageSendSuper2StretFixupFn() {
607 // id objc_msgSendSuper2_stret_fixup(struct objc_super *,
608 // struct _super_message_ref_t*, ...)
609 std::vector<const llvm::Type*> Params;
610 Params.push_back(SuperPtrTy);
611 Params.push_back(SuperMessageRefPtrTy);
612 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
613 Params, true),
614 "objc_msgSendSuper2_stret_fixup");
615 }
616
617
618
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000619 /// EHPersonalityPtr - LLVM value for an i8* to the Objective-C
620 /// exception personality function.
Chris Lattnerb02e53b2009-04-06 16:53:45 +0000621 llvm::Value *getEHPersonalityPtr() {
622 llvm::Constant *Personality =
623 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
624 std::vector<const llvm::Type*>(),
625 true),
626 "__objc_personality_v0");
627 return llvm::ConstantExpr::getBitCast(Personality, Int8PtrTy);
628 }
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000629
Chris Lattner8a569112009-04-22 02:15:23 +0000630 llvm::Constant *getUnwindResumeOrRethrowFn() {
631 std::vector<const llvm::Type*> Params;
632 Params.push_back(Int8PtrTy);
633 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
634 Params, false),
635 "_Unwind_Resume_or_Rethrow");
636 }
637
638 llvm::Constant *getObjCEndCatchFn() {
639 std::vector<const llvm::Type*> Params;
640 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
641 Params, false),
642 "objc_end_catch");
643
644 }
645
646 llvm::Constant *getObjCBeginCatchFn() {
647 std::vector<const llvm::Type*> Params;
648 Params.push_back(Int8PtrTy);
649 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(Int8PtrTy,
650 Params, false),
651 "objc_begin_catch");
652 }
Daniel Dunbare588b992009-03-01 04:46:24 +0000653
654 const llvm::StructType *EHTypeTy;
655 const llvm::Type *EHTypePtrTy;
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000656
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000657 ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm);
658 ~ObjCNonFragileABITypesHelper(){}
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000659};
660
661class CGObjCCommonMac : public CodeGen::CGObjCRuntime {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000662public:
663 // FIXME - accessibility
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000664 class GC_IVAR {
Fariborz Jahanian820e0202009-03-11 00:07:04 +0000665 public:
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000666 unsigned int ivar_bytepos;
667 unsigned int ivar_size;
668 GC_IVAR() : ivar_bytepos(0), ivar_size(0) {}
669 };
670
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000671 class SKIP_SCAN {
672 public:
673 unsigned int skip;
674 unsigned int scan;
675 SKIP_SCAN() : skip(0), scan(0) {}
676 };
677
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000678protected:
679 CodeGen::CodeGenModule &CGM;
680 // FIXME! May not be needing this after all.
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000681 unsigned ObjCABI;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000682
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000683 // gc ivar layout bitmap calculation helper caches.
684 llvm::SmallVector<GC_IVAR, 16> SkipIvars;
685 llvm::SmallVector<GC_IVAR, 16> IvarsInfo;
686 llvm::SmallVector<SKIP_SCAN, 32> SkipScanIvars;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000687
Daniel Dunbar242d4dc2008-08-25 06:02:07 +0000688 /// LazySymbols - Symbols to generate a lazy reference for. See
689 /// DefinedSymbols and FinishModule().
690 std::set<IdentifierInfo*> LazySymbols;
691
692 /// DefinedSymbols - External symbols which are defined by this
693 /// module. The symbols in this list and LazySymbols are used to add
694 /// special linker symbols which ensure that Objective-C modules are
695 /// linked properly.
696 std::set<IdentifierInfo*> DefinedSymbols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000697
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000698 /// ClassNames - uniqued class names.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000699 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000700
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000701 /// MethodVarNames - uniqued method variable names.
702 llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000703
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000704 /// MethodVarTypes - uniqued method type signatures. We have to use
705 /// a StringMap here because have no other unique reference.
706 llvm::StringMap<llvm::GlobalVariable*> MethodVarTypes;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000707
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000708 /// MethodDefinitions - map of methods which have been defined in
709 /// this translation unit.
710 llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> MethodDefinitions;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000711
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000712 /// PropertyNames - uniqued method variable names.
713 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000714
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000715 /// ClassReferences - uniqued class references.
716 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000717
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000718 /// SelectorReferences - uniqued selector references.
719 llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000720
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000721 /// Protocols - Protocols for which an objc_protocol structure has
722 /// been emitted. Forward declarations are handled by creating an
723 /// empty structure whose initializer is filled in when/if defined.
724 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> Protocols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000725
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000726 /// DefinedProtocols - Protocols which have actually been
727 /// defined. We should not need this, see FIXME in GenerateProtocol.
728 llvm::DenseSet<IdentifierInfo*> DefinedProtocols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000729
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000730 /// DefinedClasses - List of defined classes.
731 std::vector<llvm::GlobalValue*> DefinedClasses;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000732
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000733 /// DefinedCategories - List of defined categories.
734 std::vector<llvm::GlobalValue*> DefinedCategories;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000735
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000736 /// UsedGlobals - List of globals to pack into the llvm.used metadata
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000737 /// to prevent them from being clobbered.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000738 std::vector<llvm::GlobalVariable*> UsedGlobals;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000739
Fariborz Jahanian56210f72009-01-21 23:34:32 +0000740 /// GetNameForMethod - Return a name for the given method.
741 /// \param[out] NameOut - The return value.
742 void GetNameForMethod(const ObjCMethodDecl *OMD,
743 const ObjCContainerDecl *CD,
744 std::string &NameOut);
745
746 /// GetMethodVarName - Return a unique constant for the given
747 /// selector's name. The return value has type char *.
748 llvm::Constant *GetMethodVarName(Selector Sel);
749 llvm::Constant *GetMethodVarName(IdentifierInfo *Ident);
750 llvm::Constant *GetMethodVarName(const std::string &Name);
751
752 /// GetMethodVarType - Return a unique constant for the given
753 /// selector's name. The return value has type char *.
754
755 // FIXME: This is a horrible name.
756 llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D);
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +0000757 llvm::Constant *GetMethodVarType(const FieldDecl *D);
Fariborz Jahanian56210f72009-01-21 23:34:32 +0000758
759 /// GetPropertyName - Return a unique constant for the given
760 /// name. The return value has type char *.
761 llvm::Constant *GetPropertyName(IdentifierInfo *Ident);
762
763 // FIXME: This can be dropped once string functions are unified.
764 llvm::Constant *GetPropertyTypeString(const ObjCPropertyDecl *PD,
765 const Decl *Container);
766
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000767 /// GetClassName - Return a unique constant for the given selector's
768 /// name. The return value has type char *.
769 llvm::Constant *GetClassName(IdentifierInfo *Ident);
770
Fariborz Jahanian21e6f172009-03-11 21:42:00 +0000771 /// GetInterfaceDeclStructLayout - Get layout for ivars of given
772 /// interface declaration.
773 const llvm::StructLayout *GetInterfaceDeclStructLayout(
774 const ObjCInterfaceDecl *ID) const;
775
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000776 /// BuildIvarLayout - Builds ivar layout bitmap for the class
777 /// implementation for the __strong or __weak case.
778 ///
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000779 llvm::Constant *BuildIvarLayout(const ObjCImplementationDecl *OI,
780 bool ForStrongLayout);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000781
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000782 void BuildAggrIvarLayout(const ObjCInterfaceDecl *OI,
783 const llvm::StructLayout *Layout,
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000784 const RecordDecl *RD,
Chris Lattnerf1690852009-03-31 08:48:01 +0000785 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000786 unsigned int BytePos, bool ForStrongLayout,
787 int &Index, int &SkIndex, bool &HasUnion);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000788
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +0000789 /// GetIvarLayoutName - Returns a unique constant for the given
790 /// ivar layout bitmap.
791 llvm::Constant *GetIvarLayoutName(IdentifierInfo *Ident,
792 const ObjCCommonTypesHelper &ObjCTypes);
793
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +0000794 /// EmitPropertyList - Emit the given property list. The return
795 /// value has type PropertyListPtrTy.
796 llvm::Constant *EmitPropertyList(const std::string &Name,
797 const Decl *Container,
798 const ObjCContainerDecl *OCD,
799 const ObjCCommonTypesHelper &ObjCTypes);
800
Fariborz Jahanianda320092009-01-29 19:24:30 +0000801 /// GetProtocolRef - Return a reference to the internal protocol
802 /// description, creating an empty one if it has not been
803 /// defined. The return value has type ProtocolPtrTy.
804 llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +0000805
Chris Lattnercd0ee142009-03-31 08:33:16 +0000806 /// GetFieldBaseOffset - return's field byte offset.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000807 uint64_t GetFieldBaseOffset(const ObjCInterfaceDecl *OI,
808 const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +0000809 const FieldDecl *Field);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000810
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000811 /// CreateMetadataVar - Create a global variable with internal
812 /// linkage for use by the Objective-C runtime.
813 ///
814 /// This is a convenience wrapper which not only creates the
815 /// variable, but also sets the section and alignment and adds the
816 /// global to the UsedGlobals list.
Daniel Dunbar35bd7632009-03-09 20:50:13 +0000817 ///
818 /// \param Name - The variable name.
819 /// \param Init - The variable initializer; this is also used to
820 /// define the type of the variable.
821 /// \param Section - The section the variable should go into, or 0.
822 /// \param Align - The alignment for the variable, or 0.
823 /// \param AddToUsed - Whether the variable should be added to
Daniel Dunbarc1583062009-04-14 17:42:51 +0000824 /// "llvm.used".
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000825 llvm::GlobalVariable *CreateMetadataVar(const std::string &Name,
826 llvm::Constant *Init,
827 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +0000828 unsigned Align,
829 bool AddToUsed);
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000830
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +0000831 /// GetNamedIvarList - Return the list of ivars in the interface
832 /// itself (not including super classes and not including unnamed
833 /// bitfields).
834 ///
835 /// For the non-fragile ABI, this also includes synthesized property
836 /// ivars.
837 void GetNamedIvarList(const ObjCInterfaceDecl *OID,
838 llvm::SmallVector<ObjCIvarDecl*, 16> &Res) const;
839
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000840public:
841 CGObjCCommonMac(CodeGen::CodeGenModule &cgm) : CGM(cgm)
842 { }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000843
Steve Naroff33fdb732009-03-31 16:53:37 +0000844 virtual llvm::Constant *GenerateConstantString(const ObjCStringLiteral *SL);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000845
846 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
847 const ObjCContainerDecl *CD=0);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000848
849 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
850
851 /// GetOrEmitProtocol - Get the protocol object for the given
852 /// declaration, emitting it if necessary. The return value has type
853 /// ProtocolPtrTy.
854 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD)=0;
855
856 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
857 /// object for the given declaration, emitting it if needed. These
858 /// forward references will be filled in with empty bodies if no
859 /// definition is seen. The return value has type ProtocolPtrTy.
860 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD)=0;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000861};
862
863class CGObjCMac : public CGObjCCommonMac {
864private:
865 ObjCTypesHelper ObjCTypes;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000866 /// EmitImageInfo - Emit the image info marker used to encode some module
867 /// level information.
868 void EmitImageInfo();
869
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000870 /// EmitModuleInfo - Another marker encoding module level
871 /// information.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000872 void EmitModuleInfo();
873
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000874 /// EmitModuleSymols - Emit module symbols, the list of defined
875 /// classes and categories. The result has type SymtabPtrTy.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000876 llvm::Constant *EmitModuleSymbols();
877
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000878 /// FinishModule - Write out global data structures at the end of
879 /// processing a translation unit.
880 void FinishModule();
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000881
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000882 /// EmitClassExtension - Generate the class extension structure used
883 /// to store the weak ivar layout and properties. The return value
884 /// has type ClassExtensionPtrTy.
885 llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID);
886
887 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
888 /// for the given class.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000889 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000890 const ObjCInterfaceDecl *ID);
891
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000892 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000893 QualType ResultType,
894 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000895 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000896 QualType Arg0Ty,
897 bool IsSuper,
898 const CallArgList &CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000899
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000900 /// EmitIvarList - Emit the ivar list for the given
901 /// implementation. If ForClass is true the list of class ivars
902 /// (i.e. metaclass ivars) is emitted, otherwise the list of
903 /// interface ivars will be emitted. The return value has type
904 /// IvarListPtrTy.
905 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +0000906 bool ForClass);
907
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000908 /// EmitMetaClass - Emit a forward reference to the class structure
909 /// for the metaclass of the given interface. The return value has
910 /// type ClassPtrTy.
911 llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
912
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000913 /// EmitMetaClass - Emit a class structure for the metaclass of the
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000914 /// given implementation. The return value has type ClassPtrTy.
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000915 llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
916 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000917 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000918 const ConstantVector &Methods);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000919
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000920 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000921
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000922 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000923
924 /// EmitMethodList - Emit the method list for the given
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000925 /// implementation. The return value has type MethodListPtrTy.
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000926 llvm::Constant *EmitMethodList(const std::string &Name,
927 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000928 const ConstantVector &Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000929
930 /// EmitMethodDescList - Emit a method description list for a list of
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000931 /// method declarations.
932 /// - TypeName: The name for the type containing the methods.
933 /// - IsProtocol: True iff these methods are for a protocol.
934 /// - ClassMethds: True iff these are class methods.
935 /// - Required: When true, only "required" methods are
936 /// listed. Similarly, when false only "optional" methods are
937 /// listed. For classes this should always be true.
938 /// - begin, end: The method list to output.
939 ///
940 /// The return value has type MethodDescriptionListPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000941 llvm::Constant *EmitMethodDescList(const std::string &Name,
942 const char *Section,
943 const ConstantVector &Methods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000944
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000945 /// GetOrEmitProtocol - Get the protocol object for the given
946 /// declaration, emitting it if necessary. The return value has type
947 /// ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +0000948 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000949
950 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
951 /// object for the given declaration, emitting it if needed. These
952 /// forward references will be filled in with empty bodies if no
953 /// definition is seen. The return value has type ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +0000954 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000955
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000956 /// EmitProtocolExtension - Generate the protocol extension
957 /// structure used to store optional instance and class methods, and
958 /// protocol properties. The return value has type
959 /// ProtocolExtensionPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000960 llvm::Constant *
961 EmitProtocolExtension(const ObjCProtocolDecl *PD,
962 const ConstantVector &OptInstanceMethods,
963 const ConstantVector &OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000964
965 /// EmitProtocolList - Generate the list of referenced
966 /// protocols. The return value has type ProtocolListPtrTy.
Daniel Dunbardbc93372008-08-21 21:57:41 +0000967 llvm::Constant *EmitProtocolList(const std::string &Name,
968 ObjCProtocolDecl::protocol_iterator begin,
969 ObjCProtocolDecl::protocol_iterator end);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000970
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000971 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
972 /// for the given selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000973 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000974
Fariborz Jahanianda320092009-01-29 19:24:30 +0000975 public:
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000976 CGObjCMac(CodeGen::CodeGenModule &cgm);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000977
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000978 virtual llvm::Function *ModuleInitFunction();
979
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000980 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000981 QualType ResultType,
982 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000983 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000984 bool IsClassMessage,
985 const CallArgList &CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000986
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000987 virtual CodeGen::RValue
988 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000989 QualType ResultType,
990 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000991 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000992 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000993 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000994 bool IsClassMessage,
995 const CallArgList &CallArgs);
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000996
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000997 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000998 const ObjCInterfaceDecl *ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000999
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001000 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001001
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001002 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001003
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001004 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001005
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001006 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001007 const ObjCProtocolDecl *PD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00001008
Chris Lattner74391b42009-03-22 21:03:39 +00001009 virtual llvm::Constant *GetPropertyGetFunction();
1010 virtual llvm::Constant *GetPropertySetFunction();
1011 virtual llvm::Constant *EnumerationMutationFunction();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001012
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001013 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
1014 const Stmt &S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001015 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
1016 const ObjCAtThrowStmt &S);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00001017 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00001018 llvm::Value *AddrWeakObj);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00001019 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
1020 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanian58626502008-11-19 00:59:10 +00001021 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
1022 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00001023 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
1024 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian58626502008-11-19 00:59:10 +00001025 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
1026 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00001027
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00001028 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
1029 QualType ObjectTy,
1030 llvm::Value *BaseValue,
1031 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00001032 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001033 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00001034 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001035 const ObjCIvarDecl *Ivar);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001036};
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001037
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00001038class CGObjCNonFragileABIMac : public CGObjCCommonMac {
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001039private:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00001040 ObjCNonFragileABITypesHelper ObjCTypes;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001041 llvm::GlobalVariable* ObjCEmptyCacheVar;
1042 llvm::GlobalVariable* ObjCEmptyVtableVar;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00001043
Daniel Dunbar11394522009-04-18 08:51:00 +00001044 /// SuperClassReferences - uniqued super class references.
1045 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> SuperClassReferences;
1046
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00001047 /// MetaClassReferences - uniqued meta class references.
1048 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> MetaClassReferences;
Daniel Dunbare588b992009-03-01 04:46:24 +00001049
1050 /// EHTypeReferences - uniqued class ehtype references.
1051 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> EHTypeReferences;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00001052
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001053 /// FinishNonFragileABIModule - Write out global data structures at the end of
1054 /// processing a translation unit.
1055 void FinishNonFragileABIModule();
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001056
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00001057 llvm::GlobalVariable * BuildClassRoTInitializer(unsigned flags,
1058 unsigned InstanceStart,
1059 unsigned InstanceSize,
1060 const ObjCImplementationDecl *ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00001061 llvm::GlobalVariable * BuildClassMetaData(std::string &ClassName,
1062 llvm::Constant *IsAGV,
1063 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +00001064 llvm::Constant *ClassRoGV,
1065 bool HiddenVisibility);
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001066
1067 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
1068
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00001069 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
1070
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001071 /// EmitMethodList - Emit the method list for the given
1072 /// implementation. The return value has type MethodListnfABITy.
1073 llvm::Constant *EmitMethodList(const std::string &Name,
1074 const char *Section,
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00001075 const ConstantVector &Methods);
1076 /// EmitIvarList - Emit the ivar list for the given
1077 /// implementation. If ForClass is true the list of class ivars
1078 /// (i.e. metaclass ivars) is emitted, otherwise the list of
1079 /// interface ivars will be emitted. The return value has type
1080 /// IvarListnfABIPtrTy.
1081 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00001082
Fariborz Jahanianed157d32009-02-10 20:21:06 +00001083 llvm::Constant *EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00001084 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00001085 unsigned long int offset);
1086
Fariborz Jahanianda320092009-01-29 19:24:30 +00001087 /// GetOrEmitProtocol - Get the protocol object for the given
1088 /// declaration, emitting it if necessary. The return value has type
1089 /// ProtocolPtrTy.
1090 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
1091
1092 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
1093 /// object for the given declaration, emitting it if needed. These
1094 /// forward references will be filled in with empty bodies if no
1095 /// definition is seen. The return value has type ProtocolPtrTy.
1096 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
1097
1098 /// EmitProtocolList - Generate the list of referenced
1099 /// protocols. The return value has type ProtocolListPtrTy.
1100 llvm::Constant *EmitProtocolList(const std::string &Name,
1101 ObjCProtocolDecl::protocol_iterator begin,
Fariborz Jahanian46551122009-02-04 00:22:57 +00001102 ObjCProtocolDecl::protocol_iterator end);
1103
1104 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
1105 QualType ResultType,
1106 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00001107 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +00001108 QualType Arg0Ty,
1109 bool IsSuper,
1110 const CallArgList &CallArgs);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00001111
1112 /// GetClassGlobal - Return the global variable for the Objective-C
1113 /// class of the given name.
Fariborz Jahanian0f902942009-04-14 18:41:56 +00001114 llvm::GlobalVariable *GetClassGlobal(const std::string &Name);
1115
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00001116 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
Daniel Dunbar11394522009-04-18 08:51:00 +00001117 /// for the given class reference.
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00001118 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar11394522009-04-18 08:51:00 +00001119 const ObjCInterfaceDecl *ID);
1120
1121 /// EmitSuperClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
1122 /// for the given super class reference.
1123 llvm::Value *EmitSuperClassRef(CGBuilderTy &Builder,
1124 const ObjCInterfaceDecl *ID);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00001125
1126 /// EmitMetaClassRef - Return a Value * of the address of _class_t
1127 /// meta-data
1128 llvm::Value *EmitMetaClassRef(CGBuilderTy &Builder,
1129 const ObjCInterfaceDecl *ID);
1130
Fariborz Jahanianed157d32009-02-10 20:21:06 +00001131 /// ObjCIvarOffsetVariable - Returns the ivar offset variable for
1132 /// the given ivar.
1133 ///
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00001134 llvm::GlobalVariable * ObjCIvarOffsetVariable(
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001135 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +00001136 const ObjCIvarDecl *Ivar);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00001137
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00001138 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
1139 /// for the given selector.
1140 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbare588b992009-03-01 04:46:24 +00001141
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001142 /// GetInterfaceEHType - Get the cached ehtype for the given Objective-C
Daniel Dunbare588b992009-03-01 04:46:24 +00001143 /// interface. The return value has type EHTypePtrTy.
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001144 llvm::Value *GetInterfaceEHType(const ObjCInterfaceDecl *ID,
1145 bool ForDefinition);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00001146
1147 const char *getMetaclassSymbolPrefix() const {
1148 return "OBJC_METACLASS_$_";
1149 }
Daniel Dunbar4ff36842009-03-02 06:08:11 +00001150
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00001151 const char *getClassSymbolPrefix() const {
1152 return "OBJC_CLASS_$_";
1153 }
1154
Daniel Dunbarb02532a2009-04-19 23:41:48 +00001155 void GetClassSizeInfo(const ObjCInterfaceDecl *OID,
1156 uint32_t &InstanceStart,
1157 uint32_t &InstanceSize);
1158
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001159public:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00001160 CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001161 // FIXME. All stubs for now!
1162 virtual llvm::Function *ModuleInitFunction();
1163
1164 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
1165 QualType ResultType,
1166 Selector Sel,
1167 llvm::Value *Receiver,
1168 bool IsClassMessage,
Fariborz Jahanian46551122009-02-04 00:22:57 +00001169 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001170
1171 virtual CodeGen::RValue
1172 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
1173 QualType ResultType,
1174 Selector Sel,
1175 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00001176 bool isCategoryImpl,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001177 llvm::Value *Receiver,
1178 bool IsClassMessage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00001179 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001180
1181 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00001182 const ObjCInterfaceDecl *ID);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001183
1184 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel)
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00001185 { return EmitSelector(Builder, Sel); }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001186
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00001187 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001188
1189 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001190 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00001191 const ObjCProtocolDecl *PD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001192
Chris Lattner74391b42009-03-22 21:03:39 +00001193 virtual llvm::Constant *GetPropertyGetFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00001194 return ObjCTypes.getGetPropertyFn();
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001195 }
Chris Lattner74391b42009-03-22 21:03:39 +00001196 virtual llvm::Constant *GetPropertySetFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00001197 return ObjCTypes.getSetPropertyFn();
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001198 }
Chris Lattner74391b42009-03-22 21:03:39 +00001199 virtual llvm::Constant *EnumerationMutationFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00001200 return ObjCTypes.getEnumerationMutationFn();
Daniel Dunbar28ed0842009-02-16 18:48:45 +00001201 }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001202
1203 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00001204 const Stmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001205 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Anders Carlssonf57c5b22009-02-16 22:59:18 +00001206 const ObjCAtThrowStmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001207 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001208 llvm::Value *AddrWeakObj);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001209 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001210 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001211 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001212 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001213 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001214 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001215 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001216 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00001217 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
1218 QualType ObjectTy,
1219 llvm::Value *BaseValue,
1220 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00001221 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001222 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00001223 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001224 const ObjCIvarDecl *Ivar);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001225};
1226
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001227} // end anonymous namespace
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001228
1229/* *** Helper Functions *** */
1230
1231/// getConstantGEP() - Help routine to construct simple GEPs.
1232static llvm::Constant *getConstantGEP(llvm::Constant *C,
1233 unsigned idx0,
1234 unsigned idx1) {
1235 llvm::Value *Idxs[] = {
1236 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx0),
1237 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx1)
1238 };
1239 return llvm::ConstantExpr::getGetElementPtr(C, Idxs, 2);
1240}
1241
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001242/// hasObjCExceptionAttribute - Return true if this class or any super
1243/// class has the __objc_exception__ attribute.
1244static bool hasObjCExceptionAttribute(const ObjCInterfaceDecl *OID) {
Daniel Dunbarb11fa0d2009-04-13 21:08:27 +00001245 if (OID->hasAttr<ObjCExceptionAttr>())
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001246 return true;
1247 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
1248 return hasObjCExceptionAttribute(Super);
1249 return false;
1250}
1251
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001252/* *** CGObjCMac Public Interface *** */
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001253
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001254CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm),
1255 ObjCTypes(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001256{
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001257 ObjCABI = 1;
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001258 EmitImageInfo();
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001259}
1260
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +00001261/// GetClass - Return a reference to the class for the given interface
1262/// decl.
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001263llvm::Value *CGObjCMac::GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001264 const ObjCInterfaceDecl *ID) {
1265 return EmitClassRef(Builder, ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001266}
1267
1268/// GetSelector - Return the pointer to the unique'd string for this selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001269llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00001270 return EmitSelector(Builder, Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001271}
1272
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001273/// Generate a constant CFString object.
1274/*
1275 struct __builtin_CFString {
1276 const int *isa; // point to __CFConstantStringClassReference
1277 int flags;
1278 const char *str;
1279 long length;
1280 };
1281*/
1282
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001283llvm::Constant *CGObjCCommonMac::GenerateConstantString(
Steve Naroff33fdb732009-03-31 16:53:37 +00001284 const ObjCStringLiteral *SL) {
Steve Naroff8d4141f2009-04-01 13:55:36 +00001285 return CGM.GetAddrOfConstantCFString(SL->getString());
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001286}
1287
1288/// Generates a message send where the super is the receiver. This is
1289/// a message send to self with special delivery semantics indicating
1290/// which class's method should be called.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +00001291CodeGen::RValue
1292CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001293 QualType ResultType,
1294 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001295 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00001296 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001297 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001298 bool IsClassMessage,
Daniel Dunbar46f45b92008-09-09 01:06:48 +00001299 const CodeGen::CallArgList &CallArgs) {
Daniel Dunbare8b470d2008-08-23 04:28:29 +00001300 // Create and init a super structure; this is a (receiver, class)
1301 // pair we will pass to objc_msgSendSuper.
1302 llvm::Value *ObjCSuper =
1303 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
1304 llvm::Value *ReceiverAsObject =
1305 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
1306 CGF.Builder.CreateStore(ReceiverAsObject,
1307 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
Daniel Dunbare8b470d2008-08-23 04:28:29 +00001308
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001309 // If this is a class message the metaclass is passed as the target.
1310 llvm::Value *Target;
1311 if (IsClassMessage) {
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00001312 if (isCategoryImpl) {
1313 // Message sent to 'super' in a class method defined in a category
1314 // implementation requires an odd treatment.
1315 // If we are in a class method, we must retrieve the
1316 // _metaclass_ for the current class, pointed at by
1317 // the class's "isa" pointer. The following assumes that
1318 // isa" is the first ivar in a class (which it must be).
1319 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
1320 Target = CGF.Builder.CreateStructGEP(Target, 0);
1321 Target = CGF.Builder.CreateLoad(Target);
1322 }
1323 else {
1324 llvm::Value *MetaClassPtr = EmitMetaClassRef(Class);
1325 llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1);
1326 llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr);
1327 Target = Super;
1328 }
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001329 } else {
1330 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
1331 }
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001332 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
1333 // and ObjCTypes types.
1334 const llvm::Type *ClassTy =
1335 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001336 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001337 CGF.Builder.CreateStore(Target,
1338 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
1339
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001340 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001341 ObjCSuper, ObjCTypes.SuperPtrCTy,
1342 true, CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001343}
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001344
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001345/// Generate code for a message send expression.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +00001346CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001347 QualType ResultType,
1348 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001349 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001350 bool IsClassMessage,
1351 const CallArgList &CallArgs) {
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001352 llvm::Value *Arg0 =
1353 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy, "tmp");
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001354 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001355 Arg0, CGF.getContext().getObjCIdType(),
1356 false, CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001357}
1358
1359CodeGen::RValue CGObjCMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001360 QualType ResultType,
1361 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001362 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001363 QualType Arg0Ty,
1364 bool IsSuper,
1365 const CallArgList &CallArgs) {
1366 CallArgList ActualArgs;
Daniel Dunbar46f45b92008-09-09 01:06:48 +00001367 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
1368 ActualArgs.push_back(std::make_pair(RValue::get(EmitSelector(CGF.Builder,
1369 Sel)),
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001370 CGF.getContext().getObjCSelType()));
1371 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001372
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001373 CodeGenTypes &Types = CGM.getTypes();
1374 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs);
1375 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo, false);
Daniel Dunbar5669e572008-10-17 03:24:53 +00001376
1377 llvm::Constant *Fn;
Daniel Dunbar88b53962009-02-02 22:03:45 +00001378 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Daniel Dunbar5669e572008-10-17 03:24:53 +00001379 Fn = ObjCTypes.getSendStretFn(IsSuper);
1380 } else if (ResultType->isFloatingType()) {
1381 // FIXME: Sadly, this is wrong. This actually depends on the
1382 // architecture. This happens to be right for x86-32 though.
1383 Fn = ObjCTypes.getSendFpretFn(IsSuper);
1384 } else {
1385 Fn = ObjCTypes.getSendFn(IsSuper);
1386 }
Daniel Dunbar62d5c1b2008-09-10 07:00:50 +00001387 Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy));
Daniel Dunbar88b53962009-02-02 22:03:45 +00001388 return CGF.EmitCall(FnInfo, Fn, ActualArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001389}
1390
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001391llvm::Value *CGObjCMac::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001392 const ObjCProtocolDecl *PD) {
Daniel Dunbarc67876d2008-09-04 04:33:15 +00001393 // FIXME: I don't understand why gcc generates this, or where it is
1394 // resolved. Investigate. Its also wasteful to look this up over and
1395 // over.
1396 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1397
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001398 return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
1399 ObjCTypes.ExternalProtocolPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001400}
1401
Fariborz Jahanianda320092009-01-29 19:24:30 +00001402void CGObjCCommonMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001403 // FIXME: We shouldn't need this, the protocol decl should contain
1404 // enough information to tell us whether this was a declaration or a
1405 // definition.
1406 DefinedProtocols.insert(PD->getIdentifier());
1407
1408 // If we have generated a forward reference to this protocol, emit
1409 // it now. Otherwise do nothing, the protocol objects are lazily
1410 // emitted.
1411 if (Protocols.count(PD->getIdentifier()))
1412 GetOrEmitProtocol(PD);
1413}
1414
Fariborz Jahanianda320092009-01-29 19:24:30 +00001415llvm::Constant *CGObjCCommonMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001416 if (DefinedProtocols.count(PD->getIdentifier()))
1417 return GetOrEmitProtocol(PD);
1418 return GetOrEmitProtocolRef(PD);
1419}
1420
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001421/*
1422 // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions
1423 struct _objc_protocol {
1424 struct _objc_protocol_extension *isa;
1425 char *protocol_name;
1426 struct _objc_protocol_list *protocol_list;
1427 struct _objc__method_prototype_list *instance_methods;
1428 struct _objc__method_prototype_list *class_methods
1429 };
1430
1431 See EmitProtocolExtension().
1432*/
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001433llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
1434 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1435
1436 // Early exit if a defining object has already been generated.
1437 if (Entry && Entry->hasInitializer())
1438 return Entry;
1439
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001440 // FIXME: I don't understand why gcc generates this, or where it is
1441 // resolved. Investigate. Its also wasteful to look this up over and
1442 // over.
1443 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1444
Chris Lattner8ec03f52008-11-24 03:54:41 +00001445 const char *ProtocolName = PD->getNameAsCString();
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001446
1447 // Construct method lists.
1448 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1449 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregor6ab35242009-04-09 21:40:53 +00001450 for (ObjCProtocolDecl::instmeth_iterator
1451 i = PD->instmeth_begin(CGM.getContext()),
1452 e = PD->instmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001453 ObjCMethodDecl *MD = *i;
1454 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1455 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1456 OptInstanceMethods.push_back(C);
1457 } else {
1458 InstanceMethods.push_back(C);
1459 }
1460 }
1461
Douglas Gregor6ab35242009-04-09 21:40:53 +00001462 for (ObjCProtocolDecl::classmeth_iterator
1463 i = PD->classmeth_begin(CGM.getContext()),
1464 e = PD->classmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001465 ObjCMethodDecl *MD = *i;
1466 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1467 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1468 OptClassMethods.push_back(C);
1469 } else {
1470 ClassMethods.push_back(C);
1471 }
1472 }
1473
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001474 std::vector<llvm::Constant*> Values(5);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001475 Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001476 Values[1] = GetClassName(PD->getIdentifier());
Daniel Dunbardbc93372008-08-21 21:57:41 +00001477 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001478 EmitProtocolList("\01L_OBJC_PROTOCOL_REFS_" + PD->getNameAsString(),
Daniel Dunbardbc93372008-08-21 21:57:41 +00001479 PD->protocol_begin(),
1480 PD->protocol_end());
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001481 Values[3] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001482 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_"
1483 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001484 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1485 InstanceMethods);
1486 Values[4] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001487 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_"
1488 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001489 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1490 ClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001491 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
1492 Values);
1493
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001494 if (Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001495 // Already created, fix the linkage and update the initializer.
1496 Entry->setLinkage(llvm::GlobalValue::InternalLinkage);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001497 Entry->setInitializer(Init);
1498 } else {
1499 Entry =
1500 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
1501 llvm::GlobalValue::InternalLinkage,
1502 Init,
1503 std::string("\01L_OBJC_PROTOCOL_")+ProtocolName,
1504 &CGM.getModule());
1505 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001506 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001507 UsedGlobals.push_back(Entry);
1508 // FIXME: Is this necessary? Why only for protocol?
1509 Entry->setAlignment(4);
1510 }
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001511
1512 return Entry;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001513}
1514
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001515llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001516 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1517
1518 if (!Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001519 // We use the initializer as a marker of whether this is a forward
1520 // reference or not. At module finalization we add the empty
1521 // contents for protocols which were referenced but never defined.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001522 Entry =
1523 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001524 llvm::GlobalValue::ExternalLinkage,
1525 0,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001526 "\01L_OBJC_PROTOCOL_" + PD->getNameAsString(),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001527 &CGM.getModule());
1528 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001529 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001530 UsedGlobals.push_back(Entry);
1531 // FIXME: Is this necessary? Why only for protocol?
1532 Entry->setAlignment(4);
1533 }
1534
1535 return Entry;
1536}
1537
1538/*
1539 struct _objc_protocol_extension {
1540 uint32_t size;
1541 struct objc_method_description_list *optional_instance_methods;
1542 struct objc_method_description_list *optional_class_methods;
1543 struct objc_property_list *instance_properties;
1544 };
1545*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001546llvm::Constant *
1547CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
1548 const ConstantVector &OptInstanceMethods,
1549 const ConstantVector &OptClassMethods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001550 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001551 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolExtensionTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001552 std::vector<llvm::Constant*> Values(4);
1553 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001554 Values[1] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001555 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_"
1556 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001557 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1558 OptInstanceMethods);
1559 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001560 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_"
1561 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001562 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1563 OptClassMethods);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001564 Values[3] = EmitPropertyList("\01L_OBJC_$_PROP_PROTO_LIST_" +
1565 PD->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001566 0, PD, ObjCTypes);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001567
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001568 // Return null if no extension bits are used.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001569 if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
1570 Values[3]->isNullValue())
1571 return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
1572
1573 llvm::Constant *Init =
1574 llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001575
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001576 // No special section, but goes in llvm.used
1577 return CreateMetadataVar("\01L_OBJC_PROTOCOLEXT_" + PD->getNameAsString(),
1578 Init,
1579 0, 0, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001580}
1581
1582/*
1583 struct objc_protocol_list {
1584 struct objc_protocol_list *next;
1585 long count;
1586 Protocol *list[];
1587 };
1588*/
Daniel Dunbardbc93372008-08-21 21:57:41 +00001589llvm::Constant *
1590CGObjCMac::EmitProtocolList(const std::string &Name,
1591 ObjCProtocolDecl::protocol_iterator begin,
1592 ObjCProtocolDecl::protocol_iterator end) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001593 std::vector<llvm::Constant*> ProtocolRefs;
1594
Daniel Dunbardbc93372008-08-21 21:57:41 +00001595 for (; begin != end; ++begin)
1596 ProtocolRefs.push_back(GetProtocolRef(*begin));
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001597
1598 // Just return null for empty protocol lists
1599 if (ProtocolRefs.empty())
1600 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1601
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001602 // This list is null terminated.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001603 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
1604
1605 std::vector<llvm::Constant*> Values(3);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001606 // This field is only used by the runtime.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001607 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1608 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
1609 Values[2] =
1610 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
1611 ProtocolRefs.size()),
1612 ProtocolRefs);
1613
1614 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1615 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001616 CreateMetadataVar(Name, Init, "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001617 4, false);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001618 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
1619}
1620
1621/*
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001622 struct _objc_property {
1623 const char * const name;
1624 const char * const attributes;
1625 };
1626
1627 struct _objc_property_list {
1628 uint32_t entsize; // sizeof (struct _objc_property)
1629 uint32_t prop_count;
1630 struct _objc_property[prop_count];
1631 };
1632*/
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001633llvm::Constant *CGObjCCommonMac::EmitPropertyList(const std::string &Name,
1634 const Decl *Container,
1635 const ObjCContainerDecl *OCD,
1636 const ObjCCommonTypesHelper &ObjCTypes) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001637 std::vector<llvm::Constant*> Properties, Prop(2);
Douglas Gregor6ab35242009-04-09 21:40:53 +00001638 for (ObjCContainerDecl::prop_iterator I = OCD->prop_begin(CGM.getContext()),
1639 E = OCD->prop_end(CGM.getContext()); I != E; ++I) {
Steve Naroff93983f82009-01-11 12:47:58 +00001640 const ObjCPropertyDecl *PD = *I;
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001641 Prop[0] = GetPropertyName(PD->getIdentifier());
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00001642 Prop[1] = GetPropertyTypeString(PD, Container);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001643 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
1644 Prop));
1645 }
1646
1647 // Return null for empty list.
1648 if (Properties.empty())
1649 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1650
1651 unsigned PropertySize =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001652 CGM.getTargetData().getTypePaddedSize(ObjCTypes.PropertyTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001653 std::vector<llvm::Constant*> Values(3);
1654 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
1655 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
1656 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
1657 Properties.size());
1658 Values[2] = llvm::ConstantArray::get(AT, Properties);
1659 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1660
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001661 llvm::GlobalVariable *GV =
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001662 CreateMetadataVar(Name, Init,
1663 (ObjCABI == 2) ? "__DATA, __objc_const" :
1664 "__OBJC,__property,regular,no_dead_strip",
1665 (ObjCABI == 2) ? 8 : 4,
1666 true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001667 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.PropertyListPtrTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001668}
1669
1670/*
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001671 struct objc_method_description_list {
1672 int count;
1673 struct objc_method_description list[];
1674 };
1675*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001676llvm::Constant *
1677CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
1678 std::vector<llvm::Constant*> Desc(2);
1679 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1680 ObjCTypes.SelectorPtrTy);
1681 Desc[1] = GetMethodVarType(MD);
1682 return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
1683 Desc);
1684}
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001685
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001686llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name,
1687 const char *Section,
1688 const ConstantVector &Methods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001689 // Return null for empty list.
1690 if (Methods.empty())
1691 return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
1692
1693 std::vector<llvm::Constant*> Values(2);
1694 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1695 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
1696 Methods.size());
1697 Values[1] = llvm::ConstantArray::get(AT, Methods);
1698 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1699
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001700 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001701 return llvm::ConstantExpr::getBitCast(GV,
1702 ObjCTypes.MethodDescriptionListPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001703}
1704
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001705/*
1706 struct _objc_category {
1707 char *category_name;
1708 char *class_name;
1709 struct _objc_method_list *instance_methods;
1710 struct _objc_method_list *class_methods;
1711 struct _objc_protocol_list *protocols;
1712 uint32_t size; // <rdar://4585769>
1713 struct _objc_property_list *instance_properties;
1714 };
1715 */
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001716void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001717 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.CategoryTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001718
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001719 // FIXME: This is poor design, the OCD should have a pointer to the
1720 // category decl. Additionally, note that Category can be null for
1721 // the @implementation w/o an @interface case. Sema should just
1722 // create one for us as it does for @implementation so everyone else
1723 // can live life under a clear blue sky.
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001724 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001725 const ObjCCategoryDecl *Category =
1726 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001727 std::string ExtName(Interface->getNameAsString() + "_" +
1728 OCD->getNameAsString());
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001729
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001730 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1731 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
1732 e = OCD->instmeth_end(); i != e; ++i) {
1733 // Instance methods should always be defined.
1734 InstanceMethods.push_back(GetMethodConstant(*i));
1735 }
1736 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
1737 e = OCD->classmeth_end(); i != e; ++i) {
1738 // Class methods should always be defined.
1739 ClassMethods.push_back(GetMethodConstant(*i));
1740 }
1741
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001742 std::vector<llvm::Constant*> Values(7);
1743 Values[0] = GetClassName(OCD->getIdentifier());
1744 Values[1] = GetClassName(Interface->getIdentifier());
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001745 Values[2] =
1746 EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") +
1747 ExtName,
1748 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001749 InstanceMethods);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001750 Values[3] =
1751 EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName,
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001752 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001753 ClassMethods);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001754 if (Category) {
1755 Values[4] =
1756 EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName,
1757 Category->protocol_begin(),
1758 Category->protocol_end());
1759 } else {
1760 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1761 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001762 Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001763
1764 // If there is no category @interface then there can be no properties.
1765 if (Category) {
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001766 Values[6] = EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001767 OCD, Category, ObjCTypes);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001768 } else {
1769 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1770 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001771
1772 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
1773 Values);
1774
1775 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001776 CreateMetadataVar(std::string("\01L_OBJC_CATEGORY_")+ExtName, Init,
1777 "__OBJC,__category,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001778 4, true);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001779 DefinedCategories.push_back(GV);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001780}
1781
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001782// FIXME: Get from somewhere?
1783enum ClassFlags {
1784 eClassFlags_Factory = 0x00001,
1785 eClassFlags_Meta = 0x00002,
1786 // <rdr://5142207>
1787 eClassFlags_HasCXXStructors = 0x02000,
1788 eClassFlags_Hidden = 0x20000,
1789 eClassFlags_ABI2_Hidden = 0x00010,
1790 eClassFlags_ABI2_HasCXXStructors = 0x00004 // <rdr://4923634>
1791};
1792
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001793/*
1794 struct _objc_class {
1795 Class isa;
1796 Class super_class;
1797 const char *name;
1798 long version;
1799 long info;
1800 long instance_size;
1801 struct _objc_ivar_list *ivars;
1802 struct _objc_method_list *methods;
1803 struct _objc_cache *cache;
1804 struct _objc_protocol_list *protocols;
1805 // Objective-C 1.0 extensions (<rdr://4585769>)
1806 const char *ivar_layout;
1807 struct _objc_class_ext *ext;
1808 };
1809
1810 See EmitClassExtension();
1811 */
1812void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001813 DefinedSymbols.insert(ID->getIdentifier());
1814
Chris Lattner8ec03f52008-11-24 03:54:41 +00001815 std::string ClassName = ID->getNameAsString();
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001816 // FIXME: Gross
1817 ObjCInterfaceDecl *Interface =
1818 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Daniel Dunbardbc93372008-08-21 21:57:41 +00001819 llvm::Constant *Protocols =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001820 EmitProtocolList("\01L_OBJC_CLASS_PROTOCOLS_" + ID->getNameAsString(),
Daniel Dunbardbc93372008-08-21 21:57:41 +00001821 Interface->protocol_begin(),
1822 Interface->protocol_end());
Chris Lattnerb7b58b12009-04-19 06:02:28 +00001823 const llvm::Type *InterfaceTy;
1824 if (Interface->isForwardDecl())
1825 InterfaceTy = llvm::StructType::get(NULL, NULL);
1826 else
1827 InterfaceTy =
Chris Lattner03d9f342009-04-01 06:23:52 +00001828 CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(Interface));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001829 unsigned Flags = eClassFlags_Factory;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001830 unsigned Size = CGM.getTargetData().getTypePaddedSize(InterfaceTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001831
1832 // FIXME: Set CXX-structors flag.
Daniel Dunbar04d40782009-04-14 06:00:08 +00001833 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001834 Flags |= eClassFlags_Hidden;
1835
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001836 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1837 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
1838 e = ID->instmeth_end(); i != e; ++i) {
1839 // Instance methods should always be defined.
1840 InstanceMethods.push_back(GetMethodConstant(*i));
1841 }
1842 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
1843 e = ID->classmeth_end(); i != e; ++i) {
1844 // Class methods should always be defined.
1845 ClassMethods.push_back(GetMethodConstant(*i));
1846 }
1847
1848 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
1849 e = ID->propimpl_end(); i != e; ++i) {
1850 ObjCPropertyImplDecl *PID = *i;
1851
1852 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1853 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1854
1855 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
1856 if (llvm::Constant *C = GetMethodConstant(MD))
1857 InstanceMethods.push_back(C);
1858 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
1859 if (llvm::Constant *C = GetMethodConstant(MD))
1860 InstanceMethods.push_back(C);
1861 }
1862 }
1863
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001864 std::vector<llvm::Constant*> Values(12);
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001865 Values[ 0] = EmitMetaClass(ID, Protocols, InterfaceTy, ClassMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001866 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001867 // Record a reference to the super class.
1868 LazySymbols.insert(Super->getIdentifier());
1869
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001870 Values[ 1] =
1871 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1872 ObjCTypes.ClassPtrTy);
1873 } else {
1874 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1875 }
1876 Values[ 2] = GetClassName(ID->getIdentifier());
1877 // Version is always 0.
1878 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1879 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1880 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001881 Values[ 6] = EmitIvarList(ID, false);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001882 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001883 EmitMethodList("\01L_OBJC_INSTANCE_METHODS_" + ID->getNameAsString(),
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001884 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001885 InstanceMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001886 // cache is always NULL.
1887 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1888 Values[ 9] = Protocols;
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001889 // FIXME: Set ivar_layout
Fariborz Jahanian667423a2009-03-25 22:36:49 +00001890 // Values[10] = BuildIvarLayout(ID, true);
1891 Values[10] = GetIvarLayoutName(0, ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001892 Values[11] = EmitClassExtension(ID);
1893 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1894 Values);
1895
1896 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001897 CreateMetadataVar(std::string("\01L_OBJC_CLASS_")+ClassName, Init,
1898 "__OBJC,__class,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001899 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001900 DefinedClasses.push_back(GV);
1901}
1902
1903llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
1904 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001905 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001906 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001907 unsigned Flags = eClassFlags_Meta;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001908 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001909
Daniel Dunbar04d40782009-04-14 06:00:08 +00001910 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001911 Flags |= eClassFlags_Hidden;
1912
1913 std::vector<llvm::Constant*> Values(12);
1914 // The isa for the metaclass is the root of the hierarchy.
1915 const ObjCInterfaceDecl *Root = ID->getClassInterface();
1916 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
1917 Root = Super;
1918 Values[ 0] =
1919 llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
1920 ObjCTypes.ClassPtrTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001921 // The super class for the metaclass is emitted as the name of the
1922 // super class. The runtime fixes this up to point to the
1923 // *metaclass* for the super class.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001924 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
1925 Values[ 1] =
1926 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1927 ObjCTypes.ClassPtrTy);
1928 } else {
1929 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1930 }
1931 Values[ 2] = GetClassName(ID->getIdentifier());
1932 // Version is always 0.
1933 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1934 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1935 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001936 Values[ 6] = EmitIvarList(ID, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001937 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001938 EmitMethodList("\01L_OBJC_CLASS_METHODS_" + ID->getNameAsString(),
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001939 "__OBJC,__cls_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001940 Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001941 // cache is always NULL.
1942 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1943 Values[ 9] = Protocols;
1944 // ivar_layout for metaclass is always NULL.
1945 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1946 // The class extension is always unused for metaclasses.
1947 Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1948 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1949 Values);
1950
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001951 std::string Name("\01L_OBJC_METACLASS_");
Chris Lattner8ec03f52008-11-24 03:54:41 +00001952 Name += ID->getNameAsCString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001953
1954 // Check for a forward reference.
1955 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
1956 if (GV) {
1957 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1958 "Forward metaclass reference has incorrect type.");
1959 GV->setLinkage(llvm::GlobalValue::InternalLinkage);
1960 GV->setInitializer(Init);
1961 } else {
1962 GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1963 llvm::GlobalValue::InternalLinkage,
1964 Init, Name,
1965 &CGM.getModule());
1966 }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001967 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001968 GV->setAlignment(4);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001969 UsedGlobals.push_back(GV);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001970
1971 return GV;
1972}
1973
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001974llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001975 std::string Name = "\01L_OBJC_METACLASS_" + ID->getNameAsString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001976
1977 // FIXME: Should we look these up somewhere other than the
1978 // module. Its a bit silly since we only generate these while
1979 // processing an implementation, so exactly one pointer would work
1980 // if know when we entered/exitted an implementation block.
1981
1982 // Check for an existing forward reference.
Fariborz Jahanianb0d27942009-01-07 20:11:22 +00001983 // Previously, metaclass with internal linkage may have been defined.
1984 // pass 'true' as 2nd argument so it is returned.
1985 if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true)) {
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001986 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1987 "Forward metaclass reference has incorrect type.");
1988 return GV;
1989 } else {
1990 // Generate as an external reference to keep a consistent
1991 // module. This will be patched up when we emit the metaclass.
1992 return new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1993 llvm::GlobalValue::ExternalLinkage,
1994 0,
1995 Name,
1996 &CGM.getModule());
1997 }
1998}
1999
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002000/*
2001 struct objc_class_ext {
2002 uint32_t size;
2003 const char *weak_ivar_layout;
2004 struct _objc_property_list *properties;
2005 };
2006*/
2007llvm::Constant *
2008CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
2009 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00002010 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassExtensionTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002011
2012 std::vector<llvm::Constant*> Values(3);
2013 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002014 // FIXME: Output weak_ivar_layout string.
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002015 // Values[1] = BuildIvarLayout(ID, false);
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00002016 Values[1] = GetIvarLayoutName(0, ObjCTypes);
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002017 Values[2] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00002018 ID, ID->getClassInterface(), ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002019
2020 // Return null if no extension bits are used.
2021 if (Values[1]->isNullValue() && Values[2]->isNullValue())
2022 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
2023
2024 llvm::Constant *Init =
2025 llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002026 return CreateMetadataVar("\01L_OBJC_CLASSEXT_" + ID->getNameAsString(),
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002027 Init, "__OBJC,__class_ext,regular,no_dead_strip",
2028 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002029}
2030
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00002031/// getInterfaceDeclForIvar - Get the interface declaration node where
2032/// this ivar is declared in.
2033/// FIXME. Ideally, this info should be in the ivar node. But currently
2034/// it is not and prevailing wisdom is that ASTs should not have more
2035/// info than is absolutely needed, even though this info reflects the
2036/// source language.
2037///
2038static const ObjCInterfaceDecl *getInterfaceDeclForIvar(
2039 const ObjCInterfaceDecl *OI,
Douglas Gregor6ab35242009-04-09 21:40:53 +00002040 const ObjCIvarDecl *IVD,
2041 ASTContext &Context) {
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00002042 if (!OI)
2043 return 0;
2044 assert(isa<ObjCInterfaceDecl>(OI) && "OI is not an interface");
2045 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
2046 E = OI->ivar_end(); I != E; ++I)
2047 if ((*I)->getIdentifier() == IVD->getIdentifier())
2048 return OI;
Fariborz Jahanian5a4b4532009-03-31 17:00:52 +00002049 // look into properties.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002050 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(Context),
2051 E = OI->prop_end(Context); I != E; ++I) {
Fariborz Jahanian5a4b4532009-03-31 17:00:52 +00002052 ObjCPropertyDecl *PDecl = (*I);
2053 if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl())
2054 if (IV->getIdentifier() == IVD->getIdentifier())
2055 return OI;
2056 }
Douglas Gregor6ab35242009-04-09 21:40:53 +00002057 return getInterfaceDeclForIvar(OI->getSuperClass(), IVD, Context);
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00002058}
2059
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002060/*
2061 struct objc_ivar {
2062 char *ivar_name;
2063 char *ivar_type;
2064 int ivar_offset;
2065 };
2066
2067 struct objc_ivar_list {
2068 int ivar_count;
2069 struct objc_ivar list[count];
2070 };
2071 */
2072llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002073 bool ForClass) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002074 std::vector<llvm::Constant*> Ivars, Ivar(3);
2075
2076 // When emitting the root class GCC emits ivar entries for the
2077 // actual class structure. It is not clear if we need to follow this
2078 // behavior; for now lets try and get away with not doing it. If so,
2079 // the cleanest solution would be to make up an ObjCInterfaceDecl
2080 // for the class.
2081 if (ForClass)
2082 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002083
2084 ObjCInterfaceDecl *OID =
2085 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002086
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00002087 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
2088 GetNamedIvarList(OID, OIvars);
2089
2090 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
2091 ObjCIvarDecl *IVD = OIvars[i];
Daniel Dunbar3fea0c02009-04-22 08:22:17 +00002092 Ivar[0] = GetMethodVarName(IVD->getIdentifier());
2093 Ivar[1] = GetMethodVarType(IVD);
Daniel Dunbar6c1aac82009-04-20 20:18:54 +00002094 Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy,
Daniel Dunbar97776872009-04-22 07:32:20 +00002095 ComputeIvarBaseOffset(CGM, OID, IVD));
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002096 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002097 }
2098
2099 // Return null for empty list.
2100 if (Ivars.empty())
2101 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
2102
2103 std::vector<llvm::Constant*> Values(2);
2104 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
2105 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
2106 Ivars.size());
2107 Values[1] = llvm::ConstantArray::get(AT, Ivars);
2108 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2109
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002110 llvm::GlobalVariable *GV;
2111 if (ForClass)
2112 GV = CreateMetadataVar("\01L_OBJC_CLASS_VARIABLES_" + ID->getNameAsString(),
Daniel Dunbar58a29122009-03-09 22:18:41 +00002113 Init, "__OBJC,__class_vars,regular,no_dead_strip",
2114 4, true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002115 else
2116 GV = CreateMetadataVar("\01L_OBJC_INSTANCE_VARIABLES_"
2117 + ID->getNameAsString(),
2118 Init, "__OBJC,__instance_vars,regular,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002119 4, true);
2120 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.IvarListPtrTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002121}
2122
2123/*
2124 struct objc_method {
2125 SEL method_name;
2126 char *method_types;
2127 void *method;
2128 };
2129
2130 struct objc_method_list {
2131 struct objc_method_list *obsolete;
2132 int count;
2133 struct objc_method methods_list[count];
2134 };
2135*/
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002136
2137/// GetMethodConstant - Return a struct objc_method constant for the
2138/// given method if it has been defined. The result is null if the
2139/// method has not been defined. The return value has type MethodPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +00002140llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002141 // FIXME: Use DenseMap::lookup
2142 llvm::Function *Fn = MethodDefinitions[MD];
2143 if (!Fn)
2144 return 0;
2145
2146 std::vector<llvm::Constant*> Method(3);
2147 Method[0] =
2148 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
2149 ObjCTypes.SelectorPtrTy);
2150 Method[1] = GetMethodVarType(MD);
2151 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
2152 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
2153}
2154
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002155llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name,
2156 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00002157 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002158 // Return null for empty list.
2159 if (Methods.empty())
2160 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
2161
2162 std::vector<llvm::Constant*> Values(3);
2163 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2164 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
2165 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
2166 Methods.size());
2167 Values[2] = llvm::ConstantArray::get(AT, Methods);
2168 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2169
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002170 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002171 return llvm::ConstantExpr::getBitCast(GV,
2172 ObjCTypes.MethodListPtrTy);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002173}
2174
Fariborz Jahanian493dab72009-01-26 21:38:32 +00002175llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD,
Daniel Dunbarbb36d332009-02-02 21:43:58 +00002176 const ObjCContainerDecl *CD) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002177 std::string Name;
Fariborz Jahanian679a5022009-01-10 21:06:09 +00002178 GetNameForMethod(OMD, CD, Name);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002179
Daniel Dunbar541b63b2009-02-02 23:23:47 +00002180 CodeGenTypes &Types = CGM.getTypes();
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00002181 const llvm::FunctionType *MethodTy =
Daniel Dunbar541b63b2009-02-02 23:23:47 +00002182 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002183 llvm::Function *Method =
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00002184 llvm::Function::Create(MethodTy,
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002185 llvm::GlobalValue::InternalLinkage,
2186 Name,
2187 &CGM.getModule());
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002188 MethodDefinitions.insert(std::make_pair(OMD, Method));
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002189
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002190 return Method;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00002191}
2192
Daniel Dunbar48fa0642009-04-19 02:03:42 +00002193/// GetFieldBaseOffset - return the field's byte offset.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002194uint64_t CGObjCCommonMac::GetFieldBaseOffset(const ObjCInterfaceDecl *OI,
2195 const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +00002196 const FieldDecl *Field) {
Daniel Dunbar97776872009-04-22 07:32:20 +00002197 // Is this a C struct?
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00002198 if (!OI)
2199 return Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(Field));
Daniel Dunbar97776872009-04-22 07:32:20 +00002200 return ComputeIvarBaseOffset(CGM, OI, cast<ObjCIvarDecl>(Field));
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002201}
2202
Daniel Dunbarfd65d372009-03-09 20:09:19 +00002203llvm::GlobalVariable *
2204CGObjCCommonMac::CreateMetadataVar(const std::string &Name,
2205 llvm::Constant *Init,
2206 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +00002207 unsigned Align,
2208 bool AddToUsed) {
Daniel Dunbarfd65d372009-03-09 20:09:19 +00002209 const llvm::Type *Ty = Init->getType();
2210 llvm::GlobalVariable *GV =
2211 new llvm::GlobalVariable(Ty, false,
2212 llvm::GlobalValue::InternalLinkage,
2213 Init,
2214 Name,
2215 &CGM.getModule());
2216 if (Section)
2217 GV->setSection(Section);
Daniel Dunbar35bd7632009-03-09 20:50:13 +00002218 if (Align)
2219 GV->setAlignment(Align);
2220 if (AddToUsed)
Daniel Dunbarfd65d372009-03-09 20:09:19 +00002221 UsedGlobals.push_back(GV);
2222 return GV;
2223}
2224
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00002225llvm::Function *CGObjCMac::ModuleInitFunction() {
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002226 // Abuse this interface function as a place to finalize.
2227 FinishModule();
2228
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00002229 return NULL;
2230}
2231
Chris Lattner74391b42009-03-22 21:03:39 +00002232llvm::Constant *CGObjCMac::GetPropertyGetFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00002233 return ObjCTypes.getGetPropertyFn();
Daniel Dunbar49f66022008-09-24 03:38:44 +00002234}
2235
Chris Lattner74391b42009-03-22 21:03:39 +00002236llvm::Constant *CGObjCMac::GetPropertySetFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00002237 return ObjCTypes.getSetPropertyFn();
Daniel Dunbar49f66022008-09-24 03:38:44 +00002238}
2239
Chris Lattner74391b42009-03-22 21:03:39 +00002240llvm::Constant *CGObjCMac::EnumerationMutationFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00002241 return ObjCTypes.getEnumerationMutationFn();
Anders Carlsson2abd89c2008-08-31 04:05:03 +00002242}
2243
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002244/*
2245
2246Objective-C setjmp-longjmp (sjlj) Exception Handling
2247--
2248
2249The basic framework for a @try-catch-finally is as follows:
2250{
2251 objc_exception_data d;
2252 id _rethrow = null;
Anders Carlsson190d00e2009-02-07 21:26:04 +00002253 bool _call_try_exit = true;
2254
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002255 objc_exception_try_enter(&d);
2256 if (!setjmp(d.jmp_buf)) {
2257 ... try body ...
2258 } else {
2259 // exception path
2260 id _caught = objc_exception_extract(&d);
2261
2262 // enter new try scope for handlers
2263 if (!setjmp(d.jmp_buf)) {
2264 ... match exception and execute catch blocks ...
2265
2266 // fell off end, rethrow.
2267 _rethrow = _caught;
Daniel Dunbar898d5082008-09-30 01:06:03 +00002268 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002269 } else {
2270 // exception in catch block
2271 _rethrow = objc_exception_extract(&d);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002272 _call_try_exit = false;
2273 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002274 }
2275 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00002276 ... jump-through-finally to finally_end ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002277
2278finally:
Anders Carlsson190d00e2009-02-07 21:26:04 +00002279 if (_call_try_exit)
2280 objc_exception_try_exit(&d);
2281
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002282 ... finally block ....
Daniel Dunbar898d5082008-09-30 01:06:03 +00002283 ... dispatch to finally destination ...
2284
2285finally_rethrow:
2286 objc_exception_throw(_rethrow);
2287
2288finally_end:
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002289}
2290
2291This framework differs slightly from the one gcc uses, in that gcc
Daniel Dunbar898d5082008-09-30 01:06:03 +00002292uses _rethrow to determine if objc_exception_try_exit should be called
2293and if the object should be rethrown. This breaks in the face of
2294throwing nil and introduces unnecessary branches.
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002295
2296We specialize this framework for a few particular circumstances:
2297
2298 - If there are no catch blocks, then we avoid emitting the second
2299 exception handling context.
2300
2301 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
2302 e)) we avoid emitting the code to rethrow an uncaught exception.
2303
2304 - FIXME: If there is no @finally block we can do a few more
2305 simplifications.
2306
2307Rethrows and Jumps-Through-Finally
2308--
2309
2310Support for implicit rethrows and jumping through the finally block is
2311handled by storing the current exception-handling context in
2312ObjCEHStack.
2313
Daniel Dunbar898d5082008-09-30 01:06:03 +00002314In order to implement proper @finally semantics, we support one basic
2315mechanism for jumping through the finally block to an arbitrary
2316destination. Constructs which generate exits from a @try or @catch
2317block use this mechanism to implement the proper semantics by chaining
2318jumps, as necessary.
2319
2320This mechanism works like the one used for indirect goto: we
2321arbitrarily assign an ID to each destination and store the ID for the
2322destination in a variable prior to entering the finally block. At the
2323end of the finally block we simply create a switch to the proper
2324destination.
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002325
2326Code gen for @synchronized(expr) stmt;
2327Effectively generating code for:
2328objc_sync_enter(expr);
2329@try stmt @finally { objc_sync_exit(expr); }
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002330*/
2331
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002332void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
2333 const Stmt &S) {
2334 bool isTry = isa<ObjCAtTryStmt>(S);
Daniel Dunbar898d5082008-09-30 01:06:03 +00002335 // Create various blocks we refer to for handling @finally.
Daniel Dunbar55e87422008-11-11 02:29:29 +00002336 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002337 llvm::BasicBlock *FinallyExit = CGF.createBasicBlock("finally.exit");
Daniel Dunbar55e87422008-11-11 02:29:29 +00002338 llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
2339 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
2340 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
Daniel Dunbar1c566672009-02-24 01:43:46 +00002341
2342 // For @synchronized, call objc_sync_enter(sync.expr). The
2343 // evaluation of the expression must occur before we enter the
2344 // @synchronized. We can safely avoid a temp here because jumps into
2345 // @synchronized are illegal & this will dominate uses.
2346 llvm::Value *SyncArg = 0;
2347 if (!isTry) {
2348 SyncArg =
2349 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
2350 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00002351 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar1c566672009-02-24 01:43:46 +00002352 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00002353
2354 // Push an EH context entry, used for handling rethrows and jumps
2355 // through finally.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002356 CGF.PushCleanupBlock(FinallyBlock);
2357
Anders Carlsson273558f2009-02-07 21:37:21 +00002358 CGF.ObjCEHValueStack.push_back(0);
2359
Daniel Dunbar898d5082008-09-30 01:06:03 +00002360 // Allocate memory for the exception data and rethrow pointer.
Anders Carlsson80f25672008-09-09 17:59:25 +00002361 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
2362 "exceptiondata.ptr");
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002363 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
2364 "_rethrow");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002365 llvm::Value *CallTryExitPtr = CGF.CreateTempAlloca(llvm::Type::Int1Ty,
2366 "_call_try_exit");
2367 CGF.Builder.CreateStore(llvm::ConstantInt::getTrue(), CallTryExitPtr);
2368
Anders Carlsson80f25672008-09-09 17:59:25 +00002369 // Enter a new try block and call setjmp.
Chris Lattner34b02a12009-04-22 02:26:14 +00002370 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryEnterFn(), ExceptionData);
Anders Carlsson80f25672008-09-09 17:59:25 +00002371 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
2372 "jmpbufarray");
2373 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
Chris Lattner34b02a12009-04-22 02:26:14 +00002374 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.getSetJmpFn(),
Anders Carlsson80f25672008-09-09 17:59:25 +00002375 JmpBufPtr, "result");
Daniel Dunbar898d5082008-09-30 01:06:03 +00002376
Daniel Dunbar55e87422008-11-11 02:29:29 +00002377 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
2378 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002379 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002380 TryHandler, TryBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002381
2382 // Emit the @try block.
2383 CGF.EmitBlock(TryBlock);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002384 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
2385 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002386 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002387
2388 // Emit the "exception in @try" block.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002389 CGF.EmitBlock(TryHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002390
2391 // Retrieve the exception object. We may emit multiple blocks but
2392 // nothing can cross this so the value is already in SSA form.
Chris Lattner34b02a12009-04-22 02:26:14 +00002393 llvm::Value *Caught =
2394 CGF.Builder.CreateCall(ObjCTypes.getExceptionExtractFn(),
2395 ExceptionData, "caught");
Anders Carlsson273558f2009-02-07 21:37:21 +00002396 CGF.ObjCEHValueStack.back() = Caught;
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002397 if (!isTry)
2398 {
2399 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002400 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002401 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002402 }
2403 else if (const ObjCAtCatchStmt* CatchStmt =
2404 cast<ObjCAtTryStmt>(S).getCatchStmts())
2405 {
Daniel Dunbar55e40722008-09-27 07:03:52 +00002406 // Enter a new exception try block (in case a @catch block throws
2407 // an exception).
Chris Lattner34b02a12009-04-22 02:26:14 +00002408 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryEnterFn(), ExceptionData);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002409
Chris Lattner34b02a12009-04-22 02:26:14 +00002410 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.getSetJmpFn(),
Anders Carlsson80f25672008-09-09 17:59:25 +00002411 JmpBufPtr, "result");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002412 llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw");
Anders Carlsson80f25672008-09-09 17:59:25 +00002413
Daniel Dunbar55e87422008-11-11 02:29:29 +00002414 llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch");
2415 llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler");
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002416 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002417
2418 CGF.EmitBlock(CatchBlock);
2419
Daniel Dunbar55e40722008-09-27 07:03:52 +00002420 // Handle catch list. As a special case we check if everything is
2421 // matched and avoid generating code for falling off the end if
2422 // so.
2423 bool AllMatched = false;
Anders Carlsson80f25672008-09-09 17:59:25 +00002424 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbar55e87422008-11-11 02:29:29 +00002425 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch");
Anders Carlsson80f25672008-09-09 17:59:25 +00002426
Steve Naroff7ba138a2009-03-03 19:52:17 +00002427 const ParmVarDecl *CatchParam = CatchStmt->getCatchParamDecl();
Daniel Dunbar129271a2008-09-27 07:36:24 +00002428 const PointerType *PT = 0;
2429
Anders Carlsson80f25672008-09-09 17:59:25 +00002430 // catch(...) always matches.
Daniel Dunbar55e40722008-09-27 07:03:52 +00002431 if (!CatchParam) {
2432 AllMatched = true;
2433 } else {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002434 PT = CatchParam->getType()->getAsPointerType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002435
Daniel Dunbar97f61d12008-09-27 22:21:14 +00002436 // catch(id e) always matches.
2437 // FIXME: For the time being we also match id<X>; this should
2438 // be rejected by Sema instead.
Steve Naroff389bf462009-02-12 17:52:19 +00002439 if ((PT && CGF.getContext().isObjCIdStructType(PT->getPointeeType())) ||
Steve Naroff7ba138a2009-03-03 19:52:17 +00002440 CatchParam->getType()->isObjCQualifiedIdType())
Daniel Dunbar55e40722008-09-27 07:03:52 +00002441 AllMatched = true;
Anders Carlsson80f25672008-09-09 17:59:25 +00002442 }
2443
Daniel Dunbar55e40722008-09-27 07:03:52 +00002444 if (AllMatched) {
Anders Carlssondde0a942008-09-11 09:15:33 +00002445 if (CatchParam) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002446 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002447 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002448 CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002449 }
Anders Carlsson1452f552008-09-11 08:21:54 +00002450
Anders Carlssondde0a942008-09-11 09:15:33 +00002451 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002452 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002453 break;
2454 }
2455
Daniel Dunbar129271a2008-09-27 07:36:24 +00002456 assert(PT && "Unexpected non-pointer type in @catch");
2457 QualType T = PT->getPointeeType();
Anders Carlsson4b7ff6e2008-09-11 06:35:14 +00002458 const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002459 assert(ObjCType && "Catch parameter must have Objective-C type!");
2460
2461 // Check if the @catch block matches the exception object.
2462 llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl());
2463
Chris Lattner34b02a12009-04-22 02:26:14 +00002464 llvm::Value *Match =
2465 CGF.Builder.CreateCall2(ObjCTypes.getExceptionMatchFn(),
2466 Class, Caught, "match");
Anders Carlsson80f25672008-09-09 17:59:25 +00002467
Daniel Dunbar55e87422008-11-11 02:29:29 +00002468 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched");
Anders Carlsson80f25672008-09-09 17:59:25 +00002469
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002470 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002471 MatchedBlock, NextCatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002472
2473 // Emit the @catch block.
2474 CGF.EmitBlock(MatchedBlock);
Steve Naroff7ba138a2009-03-03 19:52:17 +00002475 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002476 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002477
2478 llvm::Value *Tmp =
Steve Naroff7ba138a2009-03-03 19:52:17 +00002479 CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(CatchParam->getType()),
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002480 "tmp");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002481 CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002482
2483 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002484 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002485
2486 CGF.EmitBlock(NextCatchBlock);
2487 }
2488
Daniel Dunbar55e40722008-09-27 07:03:52 +00002489 if (!AllMatched) {
2490 // None of the handlers caught the exception, so store it to be
2491 // rethrown at the end of the @finally block.
2492 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002493 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002494 }
2495
2496 // Emit the exception handler for the @catch blocks.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002497 CGF.EmitBlock(CatchHandler);
Chris Lattner34b02a12009-04-22 02:26:14 +00002498 CGF.Builder.CreateStore(
2499 CGF.Builder.CreateCall(ObjCTypes.getExceptionExtractFn(),
2500 ExceptionData),
Daniel Dunbar55e40722008-09-27 07:03:52 +00002501 RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002502 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002503 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002504 } else {
Anders Carlsson80f25672008-09-09 17:59:25 +00002505 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002506 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002507 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Anders Carlsson80f25672008-09-09 17:59:25 +00002508 }
2509
Daniel Dunbar898d5082008-09-30 01:06:03 +00002510 // Pop the exception-handling stack entry. It is important to do
2511 // this now, because the code in the @finally block is not in this
2512 // context.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002513 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
2514
Anders Carlsson273558f2009-02-07 21:37:21 +00002515 CGF.ObjCEHValueStack.pop_back();
2516
Anders Carlsson80f25672008-09-09 17:59:25 +00002517 // Emit the @finally block.
2518 CGF.EmitBlock(FinallyBlock);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002519 llvm::Value* CallTryExit = CGF.Builder.CreateLoad(CallTryExitPtr, "tmp");
2520
2521 CGF.Builder.CreateCondBr(CallTryExit, FinallyExit, FinallyNoExit);
2522
2523 CGF.EmitBlock(FinallyExit);
Chris Lattner34b02a12009-04-22 02:26:14 +00002524 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryExitFn(), ExceptionData);
Daniel Dunbar129271a2008-09-27 07:36:24 +00002525
2526 CGF.EmitBlock(FinallyNoExit);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002527 if (isTry) {
2528 if (const ObjCAtFinallyStmt* FinallyStmt =
2529 cast<ObjCAtTryStmt>(S).getFinallyStmt())
2530 CGF.EmitStmt(FinallyStmt->getFinallyBody());
Daniel Dunbar1c566672009-02-24 01:43:46 +00002531 } else {
2532 // Emit objc_sync_exit(expr); as finally's sole statement for
2533 // @synchronized.
Chris Lattnerbbccd612009-04-22 02:38:11 +00002534 CGF.Builder.CreateCall(ObjCTypes.getSyncExitFn(), SyncArg);
Fariborz Jahanianf2878e52008-11-21 19:21:53 +00002535 }
Anders Carlsson80f25672008-09-09 17:59:25 +00002536
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002537 // Emit the switch block
2538 if (Info.SwitchBlock)
2539 CGF.EmitBlock(Info.SwitchBlock);
2540 if (Info.EndBlock)
2541 CGF.EmitBlock(Info.EndBlock);
2542
Daniel Dunbar898d5082008-09-30 01:06:03 +00002543 CGF.EmitBlock(FinallyRethrow);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002544 CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(),
Daniel Dunbar898d5082008-09-30 01:06:03 +00002545 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002546 CGF.Builder.CreateUnreachable();
Daniel Dunbar898d5082008-09-30 01:06:03 +00002547
2548 CGF.EmitBlock(FinallyEnd);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002549}
2550
2551void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar898d5082008-09-30 01:06:03 +00002552 const ObjCAtThrowStmt &S) {
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002553 llvm::Value *ExceptionAsObject;
2554
2555 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2556 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
2557 ExceptionAsObject =
2558 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
2559 } else {
Anders Carlsson273558f2009-02-07 21:37:21 +00002560 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002561 "Unexpected rethrow outside @catch block.");
Anders Carlsson273558f2009-02-07 21:37:21 +00002562 ExceptionAsObject = CGF.ObjCEHValueStack.back();
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002563 }
2564
Chris Lattnerbbccd612009-04-22 02:38:11 +00002565 CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(), ExceptionAsObject);
Anders Carlsson80f25672008-09-09 17:59:25 +00002566 CGF.Builder.CreateUnreachable();
Daniel Dunbara448fb22008-11-11 23:11:34 +00002567
2568 // Clear the insertion point to indicate we are in unreachable code.
2569 CGF.Builder.ClearInsertionPoint();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002570}
2571
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002572/// EmitObjCWeakRead - Code gen for loading value of a __weak
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002573/// object: objc_read_weak (id *src)
2574///
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002575llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002576 llvm::Value *AddrWeakObj)
2577{
Eli Friedman8339b352009-03-07 03:57:15 +00002578 const llvm::Type* DestTy =
2579 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002580 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Chris Lattner72db6c32009-04-22 02:44:54 +00002581 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.getGcReadWeakFn(),
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002582 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00002583 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002584 return read_weak;
2585}
2586
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002587/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
2588/// objc_assign_weak (id src, id *dst)
2589///
2590void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
2591 llvm::Value *src, llvm::Value *dst)
2592{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002593 const llvm::Type * SrcTy = src->getType();
2594 if (!isa<llvm::PointerType>(SrcTy)) {
2595 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2596 assert(Size <= 8 && "does not support size > 8");
2597 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2598 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002599 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2600 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002601 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2602 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattner96508e12009-04-17 22:12:36 +00002603 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002604 src, dst, "weakassign");
2605 return;
2606}
2607
Fariborz Jahanian58626502008-11-19 00:59:10 +00002608/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
2609/// objc_assign_global (id src, id *dst)
2610///
2611void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
2612 llvm::Value *src, llvm::Value *dst)
2613{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002614 const llvm::Type * SrcTy = src->getType();
2615 if (!isa<llvm::PointerType>(SrcTy)) {
2616 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2617 assert(Size <= 8 && "does not support size > 8");
2618 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2619 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002620 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2621 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002622 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2623 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002624 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignGlobalFn(),
Fariborz Jahanian58626502008-11-19 00:59:10 +00002625 src, dst, "globalassign");
2626 return;
2627}
2628
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002629/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
2630/// objc_assign_ivar (id src, id *dst)
2631///
2632void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
2633 llvm::Value *src, llvm::Value *dst)
2634{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002635 const llvm::Type * SrcTy = src->getType();
2636 if (!isa<llvm::PointerType>(SrcTy)) {
2637 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2638 assert(Size <= 8 && "does not support size > 8");
2639 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2640 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002641 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2642 }
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002643 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2644 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002645 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignIvarFn(),
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002646 src, dst, "assignivar");
2647 return;
2648}
2649
Fariborz Jahanian58626502008-11-19 00:59:10 +00002650/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
2651/// objc_assign_strongCast (id src, id *dst)
2652///
2653void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
2654 llvm::Value *src, llvm::Value *dst)
2655{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002656 const llvm::Type * SrcTy = src->getType();
2657 if (!isa<llvm::PointerType>(SrcTy)) {
2658 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2659 assert(Size <= 8 && "does not support size > 8");
2660 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2661 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002662 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2663 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002664 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2665 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002666 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignStrongCastFn(),
Fariborz Jahanian58626502008-11-19 00:59:10 +00002667 src, dst, "weakassign");
2668 return;
2669}
2670
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002671/// EmitObjCValueForIvar - Code Gen for ivar reference.
2672///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002673LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
2674 QualType ObjectTy,
2675 llvm::Value *BaseValue,
2676 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002677 unsigned CVRQualifiers) {
Daniel Dunbar525c9b72009-04-21 01:19:28 +00002678 const ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
Daniel Dunbar97776872009-04-22 07:32:20 +00002679 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
2680 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002681}
2682
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002683llvm::Value *CGObjCMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00002684 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002685 const ObjCIvarDecl *Ivar) {
Daniel Dunbar97776872009-04-22 07:32:20 +00002686 uint64_t Offset = ComputeIvarBaseOffset(CGM, Interface, Ivar);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002687 return llvm::ConstantInt::get(
2688 CGM.getTypes().ConvertType(CGM.getContext().LongTy),
2689 Offset);
2690}
2691
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002692/* *** Private Interface *** */
2693
2694/// EmitImageInfo - Emit the image info marker used to encode some module
2695/// level information.
2696///
2697/// See: <rdr://4810609&4810587&4810587>
2698/// struct IMAGE_INFO {
2699/// unsigned version;
2700/// unsigned flags;
2701/// };
2702enum ImageInfoFlags {
Daniel Dunbarc7c6dc02009-04-20 07:11:47 +00002703 eImageInfo_FixAndContinue = (1 << 0), // FIXME: Not sure what
2704 // this implies.
2705 eImageInfo_GarbageCollected = (1 << 1),
2706 eImageInfo_GCOnly = (1 << 2),
2707 eImageInfo_OptimizedByDyld = (1 << 3), // FIXME: When is this set.
2708
2709 // A flag indicating that the module has no instances of an
2710 // @synthesize of a superclass variable. <rdar://problem/6803242>
2711 eImageInfo_CorrectedSynthesize = (1 << 4)
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002712};
2713
2714void CGObjCMac::EmitImageInfo() {
2715 unsigned version = 0; // Version is unused?
2716 unsigned flags = 0;
2717
2718 // FIXME: Fix and continue?
2719 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
2720 flags |= eImageInfo_GarbageCollected;
2721 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
2722 flags |= eImageInfo_GCOnly;
Daniel Dunbarc7c6dc02009-04-20 07:11:47 +00002723
2724 // We never allow @synthesize of a superclass property.
2725 flags |= eImageInfo_CorrectedSynthesize;
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002726
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002727 // Emitted as int[2];
2728 llvm::Constant *values[2] = {
2729 llvm::ConstantInt::get(llvm::Type::Int32Ty, version),
2730 llvm::ConstantInt::get(llvm::Type::Int32Ty, flags)
2731 };
2732 llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002733
2734 const char *Section;
2735 if (ObjCABI == 1)
2736 Section = "__OBJC, __image_info,regular";
2737 else
2738 Section = "__DATA, __objc_imageinfo, regular, no_dead_strip";
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002739 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002740 CreateMetadataVar("\01L_OBJC_IMAGE_INFO",
2741 llvm::ConstantArray::get(AT, values, 2),
2742 Section,
2743 0,
2744 true);
2745 GV->setConstant(true);
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002746}
2747
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002748
2749// struct objc_module {
2750// unsigned long version;
2751// unsigned long size;
2752// const char *name;
2753// Symtab symtab;
2754// };
2755
2756// FIXME: Get from somewhere
2757static const int ModuleVersion = 7;
2758
2759void CGObjCMac::EmitModuleInfo() {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00002760 uint64_t Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ModuleTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002761
2762 std::vector<llvm::Constant*> Values(4);
2763 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
2764 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002765 // This used to be the filename, now it is unused. <rdr://4327263>
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002766 Values[2] = GetClassName(&CGM.getContext().Idents.get(""));
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002767 Values[3] = EmitModuleSymbols();
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002768 CreateMetadataVar("\01L_OBJC_MODULES",
2769 llvm::ConstantStruct::get(ObjCTypes.ModuleTy, Values),
2770 "__OBJC,__module_info,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00002771 4, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002772}
2773
2774llvm::Constant *CGObjCMac::EmitModuleSymbols() {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002775 unsigned NumClasses = DefinedClasses.size();
2776 unsigned NumCategories = DefinedCategories.size();
2777
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002778 // Return null if no symbols were defined.
2779 if (!NumClasses && !NumCategories)
2780 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
2781
2782 std::vector<llvm::Constant*> Values(5);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002783 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2784 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
2785 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
2786 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
2787
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002788 // The runtime expects exactly the list of defined classes followed
2789 // by the list of defined categories, in a single array.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002790 std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002791 for (unsigned i=0; i<NumClasses; i++)
2792 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
2793 ObjCTypes.Int8PtrTy);
2794 for (unsigned i=0; i<NumCategories; i++)
2795 Symbols[NumClasses + i] =
2796 llvm::ConstantExpr::getBitCast(DefinedCategories[i],
2797 ObjCTypes.Int8PtrTy);
2798
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002799 Values[4] =
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002800 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002801 NumClasses + NumCategories),
2802 Symbols);
2803
2804 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2805
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002806 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002807 CreateMetadataVar("\01L_OBJC_SYMBOLS", Init,
2808 "__OBJC,__symbols,regular,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002809 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002810 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
2811}
2812
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002813llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002814 const ObjCInterfaceDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002815 LazySymbols.insert(ID->getIdentifier());
2816
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002817 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
2818
2819 if (!Entry) {
2820 llvm::Constant *Casted =
2821 llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()),
2822 ObjCTypes.ClassPtrTy);
2823 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002824 CreateMetadataVar("\01L_OBJC_CLASS_REFERENCES_", Casted,
2825 "__OBJC,__cls_refs,literal_pointers,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002826 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002827 }
2828
2829 return Builder.CreateLoad(Entry, false, "tmp");
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002830}
2831
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002832llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002833 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
2834
2835 if (!Entry) {
2836 llvm::Constant *Casted =
2837 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
2838 ObjCTypes.SelectorPtrTy);
2839 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002840 CreateMetadataVar("\01L_OBJC_SELECTOR_REFERENCES_", Casted,
2841 "__OBJC,__message_refs,literal_pointers,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002842 4, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002843 }
2844
2845 return Builder.CreateLoad(Entry, false, "tmp");
2846}
2847
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00002848llvm::Constant *CGObjCCommonMac::GetClassName(IdentifierInfo *Ident) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002849 llvm::GlobalVariable *&Entry = ClassNames[Ident];
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002850
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002851 if (!Entry)
2852 Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
2853 llvm::ConstantArray::get(Ident->getName()),
2854 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00002855 1, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002856
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002857 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002858}
2859
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002860/// GetInterfaceDeclStructLayout - Get layout for ivars of given
2861/// interface declaration.
2862const llvm::StructLayout *CGObjCCommonMac::GetInterfaceDeclStructLayout(
2863 const ObjCInterfaceDecl *OID) const {
Daniel Dunbar24c89912009-04-21 21:41:56 +00002864 assert(!OID->isForwardDecl() && "Invalid interface decl!");
Daniel Dunbar2a031922009-04-22 05:08:15 +00002865 QualType T = CGM.getContext().getObjCInterfaceType(OID);
Daniel Dunbar6c1aac82009-04-20 20:18:54 +00002866 const llvm::StructType *InterfaceTy =
2867 cast<llvm::StructType>(CGM.getTypes().ConvertType(T));
2868 return CGM.getTargetData().getStructLayout(InterfaceTy);
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002869}
2870
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00002871/// GetIvarLayoutName - Returns a unique constant for the given
2872/// ivar layout bitmap.
2873llvm::Constant *CGObjCCommonMac::GetIvarLayoutName(IdentifierInfo *Ident,
2874 const ObjCCommonTypesHelper &ObjCTypes) {
2875 return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2876}
2877
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002878void CGObjCCommonMac::BuildAggrIvarLayout(const ObjCInterfaceDecl *OI,
2879 const llvm::StructLayout *Layout,
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002880 const RecordDecl *RD,
Chris Lattnerf1690852009-03-31 08:48:01 +00002881 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002882 unsigned int BytePos, bool ForStrongLayout,
2883 int &Index, int &SkIndex, bool &HasUnion) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002884 bool IsUnion = (RD && RD->isUnion());
2885 uint64_t MaxUnionIvarSize = 0;
2886 uint64_t MaxSkippedUnionIvarSize = 0;
2887 FieldDecl *MaxField = 0;
2888 FieldDecl *MaxSkippedField = 0;
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002889 FieldDecl *LastFieldBitfield = 0;
2890
Chris Lattnerf1690852009-03-31 08:48:01 +00002891 unsigned base = 0;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002892 if (RecFields.empty())
2893 return;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002894 if (IsUnion)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002895 base = BytePos + GetFieldBaseOffset(OI, Layout, RecFields[0]);
Chris Lattnerf1690852009-03-31 08:48:01 +00002896 unsigned WordSizeInBits = CGM.getContext().Target.getPointerWidth(0);
2897 unsigned ByteSizeInBits = CGM.getContext().Target.getCharWidth();
2898
2899 llvm::SmallVector<FieldDecl*, 16> TmpRecFields;
2900
2901 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002902 FieldDecl *Field = RecFields[i];
2903 // Skip over unnamed or bitfields
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002904 if (!Field->getIdentifier() || Field->isBitField()) {
2905 LastFieldBitfield = Field;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002906 continue;
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002907 }
2908 LastFieldBitfield = 0;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002909 QualType FQT = Field->getType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002910 if (FQT->isRecordType() || FQT->isUnionType()) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002911 if (FQT->isUnionType())
2912 HasUnion = true;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002913 else
2914 assert(FQT->isRecordType() &&
2915 "only union/record is supported for ivar layout bitmap");
2916
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002917 const RecordType *RT = FQT->getAsRecordType();
2918 const RecordDecl *RD = RT->getDecl();
Daniel Dunbarb02532a2009-04-19 23:41:48 +00002919 // FIXME - Find a more efficient way of passing records down.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002920 TmpRecFields.append(RD->field_begin(CGM.getContext()),
2921 RD->field_end(CGM.getContext()));
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00002922 const llvm::Type *Ty = CGM.getTypes().ConvertType(FQT);
2923 const llvm::StructLayout *RecLayout =
2924 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(Ty));
2925
2926 BuildAggrIvarLayout(0, RecLayout, RD, TmpRecFields,
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002927 BytePos + GetFieldBaseOffset(OI, Layout, Field),
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002928 ForStrongLayout, Index, SkIndex,
2929 HasUnion);
Chris Lattnerf1690852009-03-31 08:48:01 +00002930 TmpRecFields.clear();
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002931 continue;
2932 }
Chris Lattnerf1690852009-03-31 08:48:01 +00002933
2934 if (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002935 const ConstantArrayType *CArray =
2936 dyn_cast_or_null<ConstantArrayType>(Array);
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002937 uint64_t ElCount = CArray->getSize().getZExtValue();
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002938 assert(CArray && "only array with know element size is supported");
2939 FQT = CArray->getElementType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002940 while (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
2941 const ConstantArrayType *CArray =
2942 dyn_cast_or_null<ConstantArrayType>(Array);
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002943 ElCount *= CArray->getSize().getZExtValue();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002944 FQT = CArray->getElementType();
2945 }
2946
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002947 assert(!FQT->isUnionType() &&
2948 "layout for array of unions not supported");
2949 if (FQT->isRecordType()) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002950 int OldIndex = Index;
2951 int OldSkIndex = SkIndex;
2952
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002953 // FIXME - Use a common routine with the above!
2954 const RecordType *RT = FQT->getAsRecordType();
2955 const RecordDecl *RD = RT->getDecl();
2956 // FIXME - Find a more efficiant way of passing records down.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002957 TmpRecFields.append(RD->field_begin(CGM.getContext()),
2958 RD->field_end(CGM.getContext()));
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00002959 const llvm::Type *Ty = CGM.getTypes().ConvertType(FQT);
2960 const llvm::StructLayout *RecLayout =
2961 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(Ty));
Chris Lattnerf1690852009-03-31 08:48:01 +00002962
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00002963 BuildAggrIvarLayout(0, RecLayout, RD,
Chris Lattnerf1690852009-03-31 08:48:01 +00002964 TmpRecFields,
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002965 BytePos + GetFieldBaseOffset(OI, Layout, Field),
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002966 ForStrongLayout, Index, SkIndex,
2967 HasUnion);
Chris Lattnerf1690852009-03-31 08:48:01 +00002968 TmpRecFields.clear();
2969
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002970 // Replicate layout information for each array element. Note that
2971 // one element is already done.
2972 uint64_t ElIx = 1;
2973 for (int FirstIndex = Index, FirstSkIndex = SkIndex;
2974 ElIx < ElCount; ElIx++) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002975 uint64_t Size = CGM.getContext().getTypeSize(RT)/ByteSizeInBits;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002976 for (int i = OldIndex+1; i <= FirstIndex; ++i)
2977 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002978 GC_IVAR gcivar;
2979 gcivar.ivar_bytepos = IvarsInfo[i].ivar_bytepos + Size*ElIx;
2980 gcivar.ivar_size = IvarsInfo[i].ivar_size;
2981 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002982 }
2983
Chris Lattnerf1690852009-03-31 08:48:01 +00002984 for (int i = OldSkIndex+1; i <= FirstSkIndex; ++i) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002985 GC_IVAR skivar;
2986 skivar.ivar_bytepos = SkipIvars[i].ivar_bytepos + Size*ElIx;
2987 skivar.ivar_size = SkipIvars[i].ivar_size;
2988 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002989 }
2990 }
2991 continue;
2992 }
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002993 }
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002994 // At this point, we are done with Record/Union and array there of.
2995 // For other arrays we are down to its element type.
2996 QualType::GCAttrTypes GCAttr = QualType::GCNone;
2997 do {
2998 if (FQT.isObjCGCStrong() || FQT.isObjCGCWeak()) {
2999 GCAttr = FQT.isObjCGCStrong() ? QualType::Strong : QualType::Weak;
3000 break;
3001 }
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003002 else if (CGM.getContext().isObjCObjectPointerType(FQT)) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003003 GCAttr = QualType::Strong;
3004 break;
3005 }
3006 else if (const PointerType *PT = FQT->getAsPointerType()) {
3007 FQT = PT->getPointeeType();
3008 }
3009 else {
3010 break;
3011 }
3012 } while (true);
Chris Lattnerf1690852009-03-31 08:48:01 +00003013
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003014 if ((ForStrongLayout && GCAttr == QualType::Strong)
3015 || (!ForStrongLayout && GCAttr == QualType::Weak)) {
3016 if (IsUnion)
3017 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003018 uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType())
3019 / WordSizeInBits;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003020 if (UnionIvarSize > MaxUnionIvarSize)
3021 {
3022 MaxUnionIvarSize = UnionIvarSize;
3023 MaxField = Field;
3024 }
3025 }
3026 else
3027 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003028 GC_IVAR gcivar;
3029 gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field);
3030 gcivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) /
3031 WordSizeInBits;
3032 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003033 }
3034 }
3035 else if ((ForStrongLayout &&
3036 (GCAttr == QualType::GCNone || GCAttr == QualType::Weak))
3037 || (!ForStrongLayout && GCAttr != QualType::Weak)) {
3038 if (IsUnion)
3039 {
3040 uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType());
3041 if (UnionIvarSize > MaxSkippedUnionIvarSize)
3042 {
3043 MaxSkippedUnionIvarSize = UnionIvarSize;
3044 MaxSkippedField = Field;
3045 }
3046 }
3047 else
3048 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003049 GC_IVAR skivar;
3050 skivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field);
3051 skivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) /
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003052 ByteSizeInBits;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003053 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003054 }
3055 }
3056 }
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003057 if (LastFieldBitfield) {
3058 // Last field was a bitfield. Must update skip info.
3059 GC_IVAR skivar;
3060 skivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout,
3061 LastFieldBitfield);
3062 Expr *BitWidth = LastFieldBitfield->getBitWidth();
3063 uint64_t BitFieldSize =
3064 BitWidth->getIntegerConstantExprValue(CGM.getContext()).getZExtValue();
3065 skivar.ivar_size = (BitFieldSize / ByteSizeInBits)
3066 + ((BitFieldSize % ByteSizeInBits) != 0);
3067 SkipIvars.push_back(skivar); ++SkIndex;
3068 }
3069
Chris Lattnerf1690852009-03-31 08:48:01 +00003070 if (MaxField) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003071 GC_IVAR gcivar;
3072 gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, MaxField);
3073 gcivar.ivar_size = MaxUnionIvarSize;
3074 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003075 }
Chris Lattnerf1690852009-03-31 08:48:01 +00003076
3077 if (MaxSkippedField) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003078 GC_IVAR skivar;
3079 skivar.ivar_bytepos = BytePos +
3080 GetFieldBaseOffset(OI, Layout, MaxSkippedField);
3081 skivar.ivar_size = MaxSkippedUnionIvarSize;
3082 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003083 }
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003084}
3085
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003086static int
Chris Lattnerf1690852009-03-31 08:48:01 +00003087IvarBytePosCompare(const void *a, const void *b)
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003088{
3089 unsigned int sa = ((CGObjCCommonMac::GC_IVAR *)a)->ivar_bytepos;
3090 unsigned int sb = ((CGObjCCommonMac::GC_IVAR *)b)->ivar_bytepos;
3091
3092 if (sa < sb)
3093 return -1;
3094 if (sa > sb)
3095 return 1;
3096 return 0;
3097}
3098
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003099/// BuildIvarLayout - Builds ivar layout bitmap for the class
3100/// implementation for the __strong or __weak case.
3101/// The layout map displays which words in ivar list must be skipped
3102/// and which must be scanned by GC (see below). String is built of bytes.
3103/// Each byte is divided up in two nibbles (4-bit each). Left nibble is count
3104/// of words to skip and right nibble is count of words to scan. So, each
3105/// nibble represents up to 15 workds to skip or scan. Skipping the rest is
3106/// represented by a 0x00 byte which also ends the string.
3107/// 1. when ForStrongLayout is true, following ivars are scanned:
3108/// - id, Class
3109/// - object *
3110/// - __strong anything
3111///
3112/// 2. When ForStrongLayout is false, following ivars are scanned:
3113/// - __weak anything
3114///
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003115llvm::Constant *CGObjCCommonMac::BuildIvarLayout(
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003116 const ObjCImplementationDecl *OMD,
3117 bool ForStrongLayout) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003118 int Index = -1;
3119 int SkIndex = -1;
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003120 bool hasUnion = false;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003121 int SkipScan;
3122 unsigned int WordsToScan, WordsToSkip;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003123 const llvm::Type *PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3124 if (CGM.getLangOptions().getGCMode() == LangOptions::NonGC)
3125 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003126
Chris Lattnerf1690852009-03-31 08:48:01 +00003127 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003128 const ObjCInterfaceDecl *OI = OMD->getClassInterface();
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003129 CGM.getContext().CollectObjCIvars(OI, RecFields);
3130 if (RecFields.empty())
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003131 return llvm::Constant::getNullValue(PtrTy);
Chris Lattnerf1690852009-03-31 08:48:01 +00003132
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003133 SkipIvars.clear();
3134 IvarsInfo.clear();
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00003135
3136 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OI);
Chris Lattnerf1690852009-03-31 08:48:01 +00003137 BuildAggrIvarLayout(OI, Layout, 0, RecFields, 0, ForStrongLayout,
3138 Index, SkIndex, hasUnion);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003139 if (Index == -1)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003140 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003141
3142 // Sort on byte position in case we encounterred a union nested in
3143 // the ivar list.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003144 if (hasUnion && !IvarsInfo.empty())
3145 qsort(&IvarsInfo[0], Index+1, sizeof(GC_IVAR), IvarBytePosCompare);
3146 if (hasUnion && !SkipIvars.empty())
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003147 qsort(&SkipIvars[0], Index+1, sizeof(GC_IVAR), IvarBytePosCompare);
3148
3149 // Build the string of skip/scan nibbles
3150 SkipScan = -1;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003151 SkipScanIvars.clear();
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003152 unsigned int WordSize =
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003153 CGM.getTypes().getTargetData().getTypePaddedSize(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003154 if (IvarsInfo[0].ivar_bytepos == 0) {
3155 WordsToSkip = 0;
3156 WordsToScan = IvarsInfo[0].ivar_size;
3157 }
3158 else {
3159 WordsToSkip = IvarsInfo[0].ivar_bytepos/WordSize;
3160 WordsToScan = IvarsInfo[0].ivar_size;
3161 }
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003162 for (unsigned int i=1, Last=IvarsInfo.size(); i != Last; i++)
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003163 {
3164 unsigned int TailPrevGCObjC =
3165 IvarsInfo[i-1].ivar_bytepos + IvarsInfo[i-1].ivar_size * WordSize;
3166 if (IvarsInfo[i].ivar_bytepos == TailPrevGCObjC)
3167 {
3168 // consecutive 'scanned' object pointers.
3169 WordsToScan += IvarsInfo[i].ivar_size;
3170 }
3171 else
3172 {
3173 // Skip over 'gc'able object pointer which lay over each other.
3174 if (TailPrevGCObjC > IvarsInfo[i].ivar_bytepos)
3175 continue;
3176 // Must skip over 1 or more words. We save current skip/scan values
3177 // and start a new pair.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003178 SKIP_SCAN SkScan;
3179 SkScan.skip = WordsToSkip;
3180 SkScan.scan = WordsToScan;
3181 SkipScanIvars.push_back(SkScan); ++SkipScan;
3182
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003183 // Skip the hole.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003184 SkScan.skip = (IvarsInfo[i].ivar_bytepos - TailPrevGCObjC) / WordSize;
3185 SkScan.scan = 0;
3186 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003187 WordsToSkip = 0;
3188 WordsToScan = IvarsInfo[i].ivar_size;
3189 }
3190 }
3191 if (WordsToScan > 0)
3192 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003193 SKIP_SCAN SkScan;
3194 SkScan.skip = WordsToSkip;
3195 SkScan.scan = WordsToScan;
3196 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003197 }
3198
3199 bool BytesSkipped = false;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003200 if (!SkipIvars.empty())
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003201 {
3202 int LastByteSkipped =
3203 SkipIvars[SkIndex].ivar_bytepos + SkipIvars[SkIndex].ivar_size;
3204 int LastByteScanned =
3205 IvarsInfo[Index].ivar_bytepos + IvarsInfo[Index].ivar_size * WordSize;
3206 BytesSkipped = (LastByteSkipped > LastByteScanned);
3207 // Compute number of bytes to skip at the tail end of the last ivar scanned.
3208 if (BytesSkipped)
3209 {
3210 unsigned int TotalWords = (LastByteSkipped + (WordSize -1)) / WordSize;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003211 SKIP_SCAN SkScan;
3212 SkScan.skip = TotalWords - (LastByteScanned/WordSize);
3213 SkScan.scan = 0;
3214 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003215 }
3216 }
3217 // Mini optimization of nibbles such that an 0xM0 followed by 0x0N is produced
3218 // as 0xMN.
3219 for (int i = 0; i <= SkipScan; i++)
3220 {
3221 if ((i < SkipScan) && SkipScanIvars[i].skip && SkipScanIvars[i].scan == 0
3222 && SkipScanIvars[i+1].skip == 0 && SkipScanIvars[i+1].scan) {
3223 // 0xM0 followed by 0x0N detected.
3224 SkipScanIvars[i].scan = SkipScanIvars[i+1].scan;
3225 for (int j = i+1; j < SkipScan; j++)
3226 SkipScanIvars[j] = SkipScanIvars[j+1];
3227 --SkipScan;
3228 }
3229 }
3230
3231 // Generate the string.
3232 std::string BitMap;
3233 for (int i = 0; i <= SkipScan; i++)
3234 {
3235 unsigned char byte;
3236 unsigned int skip_small = SkipScanIvars[i].skip % 0xf;
3237 unsigned int scan_small = SkipScanIvars[i].scan % 0xf;
3238 unsigned int skip_big = SkipScanIvars[i].skip / 0xf;
3239 unsigned int scan_big = SkipScanIvars[i].scan / 0xf;
3240
3241 if (skip_small > 0 || skip_big > 0)
3242 BytesSkipped = true;
3243 // first skip big.
3244 for (unsigned int ix = 0; ix < skip_big; ix++)
3245 BitMap += (unsigned char)(0xf0);
3246
3247 // next (skip small, scan)
3248 if (skip_small)
3249 {
3250 byte = skip_small << 4;
3251 if (scan_big > 0)
3252 {
3253 byte |= 0xf;
3254 --scan_big;
3255 }
3256 else if (scan_small)
3257 {
3258 byte |= scan_small;
3259 scan_small = 0;
3260 }
3261 BitMap += byte;
3262 }
3263 // next scan big
3264 for (unsigned int ix = 0; ix < scan_big; ix++)
3265 BitMap += (unsigned char)(0x0f);
3266 // last scan small
3267 if (scan_small)
3268 {
3269 byte = scan_small;
3270 BitMap += byte;
3271 }
3272 }
3273 // null terminate string.
Fariborz Jahanian667423a2009-03-25 22:36:49 +00003274 unsigned char zero = 0;
3275 BitMap += zero;
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00003276
3277 if (CGM.getLangOptions().ObjCGCBitmapPrint) {
3278 printf("\n%s ivar layout for class '%s': ",
3279 ForStrongLayout ? "strong" : "weak",
3280 OMD->getClassInterface()->getNameAsCString());
3281 const unsigned char *s = (unsigned char*)BitMap.c_str();
3282 for (unsigned i = 0; i < BitMap.size(); i++)
3283 if (!(s[i] & 0xf0))
3284 printf("0x0%x%s", s[i], s[i] != 0 ? ", " : "");
3285 else
3286 printf("0x%x%s", s[i], s[i] != 0 ? ", " : "");
3287 printf("\n");
3288 }
3289
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003290 // if ivar_layout bitmap is all 1 bits (nothing skipped) then use NULL as
3291 // final layout.
3292 if (ForStrongLayout && !BytesSkipped)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003293 return llvm::Constant::getNullValue(PtrTy);
3294 llvm::GlobalVariable * Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
3295 llvm::ConstantArray::get(BitMap.c_str()),
3296 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003297 1, true);
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00003298 return getConstantGEP(Entry, 0, 0);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003299}
3300
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003301llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003302 llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
3303
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003304 // FIXME: Avoid std::string copying.
3305 if (!Entry)
3306 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_NAME_",
3307 llvm::ConstantArray::get(Sel.getAsString()),
3308 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003309 1, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003310
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003311 return getConstantGEP(Entry, 0, 0);
3312}
3313
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003314// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003315llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003316 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
3317}
3318
3319// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003320llvm::Constant *CGObjCCommonMac::GetMethodVarName(const std::string &Name) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003321 return GetMethodVarName(&CGM.getContext().Idents.get(Name));
3322}
3323
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00003324llvm::Constant *CGObjCCommonMac::GetMethodVarType(const FieldDecl *Field) {
Devang Patel7794bb82009-03-04 18:21:39 +00003325 std::string TypeStr;
3326 CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
3327
3328 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003329
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003330 if (!Entry)
3331 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3332 llvm::ConstantArray::get(TypeStr),
3333 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003334 1, true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003335
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003336 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003337}
3338
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003339llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003340 std::string TypeStr;
Daniel Dunbarc45ef602008-08-26 21:51:14 +00003341 CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D),
3342 TypeStr);
Devang Patel7794bb82009-03-04 18:21:39 +00003343
3344 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
3345
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003346 if (!Entry)
3347 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3348 llvm::ConstantArray::get(TypeStr),
3349 "__TEXT,__cstring,cstring_literals",
3350 1, true);
Devang Patel7794bb82009-03-04 18:21:39 +00003351
3352 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003353}
3354
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003355// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003356llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003357 llvm::GlobalVariable *&Entry = PropertyNames[Ident];
3358
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003359 if (!Entry)
3360 Entry = CreateMetadataVar("\01L_OBJC_PROP_NAME_ATTR_",
3361 llvm::ConstantArray::get(Ident->getName()),
3362 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003363 1, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003364
3365 return getConstantGEP(Entry, 0, 0);
3366}
3367
3368// FIXME: Merge into a single cstring creation function.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003369// FIXME: This Decl should be more precise.
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003370llvm::Constant *
3371 CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
3372 const Decl *Container) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003373 std::string TypeStr;
3374 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003375 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
3376}
3377
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003378void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D,
3379 const ObjCContainerDecl *CD,
3380 std::string &NameOut) {
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00003381 NameOut = '\01';
3382 NameOut += (D->isInstanceMethod() ? '-' : '+');
Chris Lattner077bf5e2008-11-24 03:33:13 +00003383 NameOut += '[';
Fariborz Jahanian679a5022009-01-10 21:06:09 +00003384 assert (CD && "Missing container decl in GetNameForMethod");
3385 NameOut += CD->getNameAsString();
Fariborz Jahanian1e9aef32009-04-16 18:34:20 +00003386 if (const ObjCCategoryImplDecl *CID =
3387 dyn_cast<ObjCCategoryImplDecl>(D->getDeclContext())) {
3388 NameOut += '(';
3389 NameOut += CID->getNameAsString();
3390 NameOut+= ')';
3391 }
Chris Lattner077bf5e2008-11-24 03:33:13 +00003392 NameOut += ' ';
3393 NameOut += D->getSelector().getAsString();
3394 NameOut += ']';
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00003395}
3396
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003397void CGObjCMac::FinishModule() {
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003398 EmitModuleInfo();
3399
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003400 // Emit the dummy bodies for any protocols which were referenced but
3401 // never defined.
3402 for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
3403 i = Protocols.begin(), e = Protocols.end(); i != e; ++i) {
3404 if (i->second->hasInitializer())
3405 continue;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003406
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003407 std::vector<llvm::Constant*> Values(5);
3408 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
3409 Values[1] = GetClassName(i->first);
3410 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
3411 Values[3] = Values[4] =
3412 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
3413 i->second->setLinkage(llvm::GlobalValue::InternalLinkage);
3414 i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
3415 Values));
3416 }
3417
3418 std::vector<llvm::Constant*> Used;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003419 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003420 e = UsedGlobals.end(); i != e; ++i) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003421 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003422 }
3423
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003424 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003425 llvm::GlobalValue *GV =
3426 new llvm::GlobalVariable(AT, false,
3427 llvm::GlobalValue::AppendingLinkage,
3428 llvm::ConstantArray::get(AT, Used),
3429 "llvm.used",
3430 &CGM.getModule());
3431
3432 GV->setSection("llvm.metadata");
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003433
3434 // Add assembler directives to add lazy undefined symbol references
3435 // for classes which are referenced but not defined. This is
3436 // important for correct linker interaction.
3437
3438 // FIXME: Uh, this isn't particularly portable.
3439 std::stringstream s;
Anders Carlsson565c99f2008-12-10 02:21:04 +00003440
3441 if (!CGM.getModule().getModuleInlineAsm().empty())
3442 s << "\n";
3443
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003444 for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(),
3445 e = LazySymbols.end(); i != e; ++i) {
3446 s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n";
3447 }
3448 for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(),
3449 e = DefinedSymbols.end(); i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003450 s << "\t.objc_class_name_" << (*i)->getName() << "=0\n"
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003451 << "\t.globl .objc_class_name_" << (*i)->getName() << "\n";
3452 }
Anders Carlsson565c99f2008-12-10 02:21:04 +00003453
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003454 CGM.getModule().appendModuleInlineAsm(s.str());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003455}
3456
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003457CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003458 : CGObjCCommonMac(cgm),
3459 ObjCTypes(cgm)
3460{
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003461 ObjCEmptyCacheVar = ObjCEmptyVtableVar = NULL;
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003462 ObjCABI = 2;
3463}
3464
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003465/* *** */
3466
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003467ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm)
3468: CGM(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003469{
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003470 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3471 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003472
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003473 ShortTy = Types.ConvertType(Ctx.ShortTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003474 IntTy = Types.ConvertType(Ctx.IntTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003475 LongTy = Types.ConvertType(Ctx.LongTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00003476 LongLongTy = Types.ConvertType(Ctx.LongLongTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003477 Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3478
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003479 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00003480 PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003481 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003482
3483 // FIXME: It would be nice to unify this with the opaque type, so
3484 // that the IR comes out a bit cleaner.
3485 const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
3486 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003487
3488 // I'm not sure I like this. The implicit coordination is a bit
3489 // gross. We should solve this in a reasonable fashion because this
3490 // is a pretty common task (match some runtime data structure with
3491 // an LLVM data structure).
3492
3493 // FIXME: This is leaked.
3494 // FIXME: Merge with rewriter code?
3495
3496 // struct _objc_super {
3497 // id self;
3498 // Class cls;
3499 // }
3500 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3501 SourceLocation(),
3502 &Ctx.Idents.get("_objc_super"));
Douglas Gregor6ab35242009-04-09 21:40:53 +00003503 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3504 Ctx.getObjCIdType(), 0, false));
3505 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3506 Ctx.getObjCClassType(), 0, false));
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003507 RD->completeDefinition(Ctx);
3508
3509 SuperCTy = Ctx.getTagDeclType(RD);
3510 SuperPtrCTy = Ctx.getPointerType(SuperCTy);
3511
3512 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003513 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
3514
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003515 // struct _prop_t {
3516 // char *name;
3517 // char *attributes;
3518 // }
Chris Lattner1c02f862009-04-22 02:53:24 +00003519 PropertyTy = llvm::StructType::get(Int8PtrTy, Int8PtrTy, NULL);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003520 CGM.getModule().addTypeName("struct._prop_t",
3521 PropertyTy);
3522
3523 // struct _prop_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003524 // uint32_t entsize; // sizeof(struct _prop_t)
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003525 // uint32_t count_of_properties;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003526 // struct _prop_t prop_list[count_of_properties];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003527 // }
3528 PropertyListTy = llvm::StructType::get(IntTy,
3529 IntTy,
3530 llvm::ArrayType::get(PropertyTy, 0),
3531 NULL);
3532 CGM.getModule().addTypeName("struct._prop_list_t",
3533 PropertyListTy);
3534 // struct _prop_list_t *
3535 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
3536
3537 // struct _objc_method {
3538 // SEL _cmd;
3539 // char *method_type;
3540 // char *_imp;
3541 // }
3542 MethodTy = llvm::StructType::get(SelectorPtrTy,
3543 Int8PtrTy,
3544 Int8PtrTy,
3545 NULL);
3546 CGM.getModule().addTypeName("struct._objc_method", MethodTy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003547
3548 // struct _objc_cache *
3549 CacheTy = llvm::OpaqueType::get();
3550 CGM.getModule().addTypeName("struct._objc_cache", CacheTy);
3551 CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003552}
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003553
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003554ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
3555 : ObjCCommonTypesHelper(cgm)
3556{
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003557 // struct _objc_method_description {
3558 // SEL name;
3559 // char *types;
3560 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003561 MethodDescriptionTy =
3562 llvm::StructType::get(SelectorPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003563 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003564 NULL);
3565 CGM.getModule().addTypeName("struct._objc_method_description",
3566 MethodDescriptionTy);
3567
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003568 // struct _objc_method_description_list {
3569 // int count;
3570 // struct _objc_method_description[1];
3571 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003572 MethodDescriptionListTy =
3573 llvm::StructType::get(IntTy,
3574 llvm::ArrayType::get(MethodDescriptionTy, 0),
3575 NULL);
3576 CGM.getModule().addTypeName("struct._objc_method_description_list",
3577 MethodDescriptionListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003578
3579 // struct _objc_method_description_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003580 MethodDescriptionListPtrTy =
3581 llvm::PointerType::getUnqual(MethodDescriptionListTy);
3582
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003583 // Protocol description structures
3584
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003585 // struct _objc_protocol_extension {
3586 // uint32_t size; // sizeof(struct _objc_protocol_extension)
3587 // struct _objc_method_description_list *optional_instance_methods;
3588 // struct _objc_method_description_list *optional_class_methods;
3589 // struct _objc_property_list *instance_properties;
3590 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003591 ProtocolExtensionTy =
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003592 llvm::StructType::get(IntTy,
3593 MethodDescriptionListPtrTy,
3594 MethodDescriptionListPtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003595 PropertyListPtrTy,
3596 NULL);
3597 CGM.getModule().addTypeName("struct._objc_protocol_extension",
3598 ProtocolExtensionTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003599
3600 // struct _objc_protocol_extension *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003601 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
3602
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003603 // Handle recursive construction of Protocol and ProtocolList types
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003604
3605 llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get();
3606 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3607
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003608 const llvm::Type *T =
3609 llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder),
3610 LongTy,
3611 llvm::ArrayType::get(ProtocolTyHolder, 0),
3612 NULL);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003613 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T);
3614
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003615 // struct _objc_protocol {
3616 // struct _objc_protocol_extension *isa;
3617 // char *protocol_name;
3618 // struct _objc_protocol **_objc_protocol_list;
3619 // struct _objc_method_description_list *instance_methods;
3620 // struct _objc_method_description_list *class_methods;
3621 // }
3622 T = llvm::StructType::get(ProtocolExtensionPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003623 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003624 llvm::PointerType::getUnqual(ProtocolListTyHolder),
3625 MethodDescriptionListPtrTy,
3626 MethodDescriptionListPtrTy,
3627 NULL);
3628 cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T);
3629
3630 ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get());
3631 CGM.getModule().addTypeName("struct._objc_protocol_list",
3632 ProtocolListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003633 // struct _objc_protocol_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003634 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
3635
3636 ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get());
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003637 CGM.getModule().addTypeName("struct._objc_protocol", ProtocolTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003638 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003639
3640 // Class description structures
3641
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003642 // struct _objc_ivar {
3643 // char *ivar_name;
3644 // char *ivar_type;
3645 // int ivar_offset;
3646 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003647 IvarTy = llvm::StructType::get(Int8PtrTy,
3648 Int8PtrTy,
3649 IntTy,
3650 NULL);
3651 CGM.getModule().addTypeName("struct._objc_ivar", IvarTy);
3652
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003653 // struct _objc_ivar_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003654 IvarListTy = llvm::OpaqueType::get();
3655 CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy);
3656 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
3657
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003658 // struct _objc_method_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003659 MethodListTy = llvm::OpaqueType::get();
3660 CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy);
3661 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
3662
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003663 // struct _objc_class_extension *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003664 ClassExtensionTy =
3665 llvm::StructType::get(IntTy,
3666 Int8PtrTy,
3667 PropertyListPtrTy,
3668 NULL);
3669 CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy);
3670 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
3671
3672 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3673
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003674 // struct _objc_class {
3675 // Class isa;
3676 // Class super_class;
3677 // char *name;
3678 // long version;
3679 // long info;
3680 // long instance_size;
3681 // struct _objc_ivar_list *ivars;
3682 // struct _objc_method_list *methods;
3683 // struct _objc_cache *cache;
3684 // struct _objc_protocol_list *protocols;
3685 // char *ivar_layout;
3686 // struct _objc_class_ext *ext;
3687 // };
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003688 T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3689 llvm::PointerType::getUnqual(ClassTyHolder),
3690 Int8PtrTy,
3691 LongTy,
3692 LongTy,
3693 LongTy,
3694 IvarListPtrTy,
3695 MethodListPtrTy,
3696 CachePtrTy,
3697 ProtocolListPtrTy,
3698 Int8PtrTy,
3699 ClassExtensionPtrTy,
3700 NULL);
3701 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T);
3702
3703 ClassTy = cast<llvm::StructType>(ClassTyHolder.get());
3704 CGM.getModule().addTypeName("struct._objc_class", ClassTy);
3705 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
3706
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003707 // struct _objc_category {
3708 // char *category_name;
3709 // char *class_name;
3710 // struct _objc_method_list *instance_method;
3711 // struct _objc_method_list *class_method;
3712 // uint32_t size; // sizeof(struct _objc_category)
3713 // struct _objc_property_list *instance_properties;// category's @property
3714 // }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003715 CategoryTy = llvm::StructType::get(Int8PtrTy,
3716 Int8PtrTy,
3717 MethodListPtrTy,
3718 MethodListPtrTy,
3719 ProtocolListPtrTy,
3720 IntTy,
3721 PropertyListPtrTy,
3722 NULL);
3723 CGM.getModule().addTypeName("struct._objc_category", CategoryTy);
3724
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003725 // Global metadata structures
3726
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003727 // struct _objc_symtab {
3728 // long sel_ref_cnt;
3729 // SEL *refs;
3730 // short cls_def_cnt;
3731 // short cat_def_cnt;
3732 // char *defs[cls_def_cnt + cat_def_cnt];
3733 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003734 SymtabTy = llvm::StructType::get(LongTy,
3735 SelectorPtrTy,
3736 ShortTy,
3737 ShortTy,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003738 llvm::ArrayType::get(Int8PtrTy, 0),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003739 NULL);
3740 CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy);
3741 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
3742
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003743 // struct _objc_module {
3744 // long version;
3745 // long size; // sizeof(struct _objc_module)
3746 // char *name;
3747 // struct _objc_symtab* symtab;
3748 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003749 ModuleTy =
3750 llvm::StructType::get(LongTy,
3751 LongTy,
3752 Int8PtrTy,
3753 SymtabPtrTy,
3754 NULL);
3755 CGM.getModule().addTypeName("struct._objc_module", ModuleTy);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003756
Anders Carlsson2abd89c2008-08-31 04:05:03 +00003757
Anders Carlsson124526b2008-09-09 10:10:21 +00003758 // FIXME: This is the size of the setjmp buffer and should be
3759 // target specific. 18 is what's used on 32-bit X86.
3760 uint64_t SetJmpBufferSize = 18;
3761
3762 // Exceptions
3763 const llvm::Type *StackPtrTy =
Daniel Dunbar10004912008-09-27 06:32:25 +00003764 llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4);
Anders Carlsson124526b2008-09-09 10:10:21 +00003765
3766 ExceptionDataTy =
3767 llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty,
3768 SetJmpBufferSize),
3769 StackPtrTy, NULL);
3770 CGM.getModule().addTypeName("struct._objc_exception_data",
3771 ExceptionDataTy);
3772
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003773}
3774
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003775ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003776: ObjCCommonTypesHelper(cgm)
3777{
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003778 // struct _method_list_t {
3779 // uint32_t entsize; // sizeof(struct _objc_method)
3780 // uint32_t method_count;
3781 // struct _objc_method method_list[method_count];
3782 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003783 MethodListnfABITy = llvm::StructType::get(IntTy,
3784 IntTy,
3785 llvm::ArrayType::get(MethodTy, 0),
3786 NULL);
3787 CGM.getModule().addTypeName("struct.__method_list_t",
3788 MethodListnfABITy);
3789 // struct method_list_t *
3790 MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003791
3792 // struct _protocol_t {
3793 // id isa; // NULL
3794 // const char * const protocol_name;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003795 // const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003796 // const struct method_list_t * const instance_methods;
3797 // const struct method_list_t * const class_methods;
3798 // const struct method_list_t *optionalInstanceMethods;
3799 // const struct method_list_t *optionalClassMethods;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003800 // const struct _prop_list_t * properties;
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003801 // const uint32_t size; // sizeof(struct _protocol_t)
3802 // const uint32_t flags; // = 0
3803 // }
3804
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003805 // Holder for struct _protocol_list_t *
3806 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3807
3808 ProtocolnfABITy = llvm::StructType::get(ObjectPtrTy,
3809 Int8PtrTy,
3810 llvm::PointerType::getUnqual(
3811 ProtocolListTyHolder),
3812 MethodListnfABIPtrTy,
3813 MethodListnfABIPtrTy,
3814 MethodListnfABIPtrTy,
3815 MethodListnfABIPtrTy,
3816 PropertyListPtrTy,
3817 IntTy,
3818 IntTy,
3819 NULL);
3820 CGM.getModule().addTypeName("struct._protocol_t",
3821 ProtocolnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003822
3823 // struct _protocol_t*
3824 ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003825
Fariborz Jahanianda320092009-01-29 19:24:30 +00003826 // struct _protocol_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003827 // long protocol_count; // Note, this is 32/64 bit
Daniel Dunbar948e2582009-02-15 07:36:20 +00003828 // struct _protocol_t *[protocol_count];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003829 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003830 ProtocolListnfABITy = llvm::StructType::get(LongTy,
3831 llvm::ArrayType::get(
Daniel Dunbar948e2582009-02-15 07:36:20 +00003832 ProtocolnfABIPtrTy, 0),
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003833 NULL);
3834 CGM.getModule().addTypeName("struct._objc_protocol_list",
3835 ProtocolListnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003836 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(
3837 ProtocolListnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003838
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003839 // struct _objc_protocol_list*
3840 ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003841
3842 // struct _ivar_t {
3843 // unsigned long int *offset; // pointer to ivar offset location
3844 // char *name;
3845 // char *type;
3846 // uint32_t alignment;
3847 // uint32_t size;
3848 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003849 IvarnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(LongTy),
3850 Int8PtrTy,
3851 Int8PtrTy,
3852 IntTy,
3853 IntTy,
3854 NULL);
3855 CGM.getModule().addTypeName("struct._ivar_t", IvarnfABITy);
3856
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003857 // struct _ivar_list_t {
3858 // uint32 entsize; // sizeof(struct _ivar_t)
3859 // uint32 count;
3860 // struct _iver_t list[count];
3861 // }
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003862 IvarListnfABITy = llvm::StructType::get(IntTy,
3863 IntTy,
3864 llvm::ArrayType::get(
3865 IvarnfABITy, 0),
3866 NULL);
3867 CGM.getModule().addTypeName("struct._ivar_list_t", IvarListnfABITy);
3868
3869 IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003870
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003871 // struct _class_ro_t {
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003872 // uint32_t const flags;
3873 // uint32_t const instanceStart;
3874 // uint32_t const instanceSize;
3875 // uint32_t const reserved; // only when building for 64bit targets
3876 // const uint8_t * const ivarLayout;
3877 // const char *const name;
3878 // const struct _method_list_t * const baseMethods;
3879 // const struct _objc_protocol_list *const baseProtocols;
3880 // const struct _ivar_list_t *const ivars;
3881 // const uint8_t * const weakIvarLayout;
3882 // const struct _prop_list_t * const properties;
3883 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003884
3885 // FIXME. Add 'reserved' field in 64bit abi mode!
3886 ClassRonfABITy = llvm::StructType::get(IntTy,
3887 IntTy,
3888 IntTy,
3889 Int8PtrTy,
3890 Int8PtrTy,
3891 MethodListnfABIPtrTy,
3892 ProtocolListnfABIPtrTy,
3893 IvarListnfABIPtrTy,
3894 Int8PtrTy,
3895 PropertyListPtrTy,
3896 NULL);
3897 CGM.getModule().addTypeName("struct._class_ro_t",
3898 ClassRonfABITy);
3899
3900 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
3901 std::vector<const llvm::Type*> Params;
3902 Params.push_back(ObjectPtrTy);
3903 Params.push_back(SelectorPtrTy);
3904 ImpnfABITy = llvm::PointerType::getUnqual(
3905 llvm::FunctionType::get(ObjectPtrTy, Params, false));
3906
3907 // struct _class_t {
3908 // struct _class_t *isa;
3909 // struct _class_t * const superclass;
3910 // void *cache;
3911 // IMP *vtable;
3912 // struct class_ro_t *ro;
3913 // }
3914
3915 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3916 ClassnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3917 llvm::PointerType::getUnqual(ClassTyHolder),
3918 CachePtrTy,
3919 llvm::PointerType::getUnqual(ImpnfABITy),
3920 llvm::PointerType::getUnqual(
3921 ClassRonfABITy),
3922 NULL);
3923 CGM.getModule().addTypeName("struct._class_t", ClassnfABITy);
3924
3925 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(
3926 ClassnfABITy);
3927
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003928 // LLVM for struct _class_t *
3929 ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy);
3930
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003931 // struct _category_t {
3932 // const char * const name;
3933 // struct _class_t *const cls;
3934 // const struct _method_list_t * const instance_methods;
3935 // const struct _method_list_t * const class_methods;
3936 // const struct _protocol_list_t * const protocols;
3937 // const struct _prop_list_t * const properties;
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003938 // }
3939 CategorynfABITy = llvm::StructType::get(Int8PtrTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003940 ClassnfABIPtrTy,
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003941 MethodListnfABIPtrTy,
3942 MethodListnfABIPtrTy,
3943 ProtocolListnfABIPtrTy,
3944 PropertyListPtrTy,
3945 NULL);
3946 CGM.getModule().addTypeName("struct._category_t", CategorynfABITy);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003947
3948 // New types for nonfragile abi messaging.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003949 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3950 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003951
3952 // MessageRefTy - LLVM for:
3953 // struct _message_ref_t {
3954 // IMP messenger;
3955 // SEL name;
3956 // };
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003957
3958 // First the clang type for struct _message_ref_t
3959 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3960 SourceLocation(),
3961 &Ctx.Idents.get("_message_ref_t"));
Douglas Gregor6ab35242009-04-09 21:40:53 +00003962 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3963 Ctx.VoidPtrTy, 0, false));
3964 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3965 Ctx.getObjCSelType(), 0, false));
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003966 RD->completeDefinition(Ctx);
3967
3968 MessageRefCTy = Ctx.getTagDeclType(RD);
3969 MessageRefCPtrTy = Ctx.getPointerType(MessageRefCTy);
3970 MessageRefTy = cast<llvm::StructType>(Types.ConvertType(MessageRefCTy));
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003971
3972 // MessageRefPtrTy - LLVM for struct _message_ref_t*
3973 MessageRefPtrTy = llvm::PointerType::getUnqual(MessageRefTy);
3974
3975 // SuperMessageRefTy - LLVM for:
3976 // struct _super_message_ref_t {
3977 // SUPER_IMP messenger;
3978 // SEL name;
3979 // };
3980 SuperMessageRefTy = llvm::StructType::get(ImpnfABITy,
3981 SelectorPtrTy,
3982 NULL);
3983 CGM.getModule().addTypeName("struct._super_message_ref_t", SuperMessageRefTy);
3984
3985 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
3986 SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy);
3987
Daniel Dunbare588b992009-03-01 04:46:24 +00003988
3989 // struct objc_typeinfo {
3990 // const void** vtable; // objc_ehtype_vtable + 2
3991 // const char* name; // c++ typeinfo string
3992 // Class cls;
3993 // };
3994 EHTypeTy = llvm::StructType::get(llvm::PointerType::getUnqual(Int8PtrTy),
3995 Int8PtrTy,
3996 ClassnfABIPtrTy,
3997 NULL);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00003998 CGM.getModule().addTypeName("struct._objc_typeinfo", EHTypeTy);
Daniel Dunbare588b992009-03-01 04:46:24 +00003999 EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy);
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00004000}
4001
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004002llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() {
4003 FinishNonFragileABIModule();
4004
4005 return NULL;
4006}
4007
4008void CGObjCNonFragileABIMac::FinishNonFragileABIModule() {
4009 // nonfragile abi has no module definition.
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004010
4011 // Build list of all implemented classe addresses in array
4012 // L_OBJC_LABEL_CLASS_$.
4013 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CLASS_$
4014 // list of 'nonlazy' implementations (defined as those with a +load{}
4015 // method!!).
4016 unsigned NumClasses = DefinedClasses.size();
4017 if (NumClasses) {
4018 std::vector<llvm::Constant*> Symbols(NumClasses);
4019 for (unsigned i=0; i<NumClasses; i++)
4020 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
4021 ObjCTypes.Int8PtrTy);
4022 llvm::Constant* Init =
4023 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
4024 NumClasses),
4025 Symbols);
4026
4027 llvm::GlobalVariable *GV =
4028 new llvm::GlobalVariable(Init->getType(), false,
4029 llvm::GlobalValue::InternalLinkage,
4030 Init,
4031 "\01L_OBJC_LABEL_CLASS_$",
4032 &CGM.getModule());
Daniel Dunbar58a29122009-03-09 22:18:41 +00004033 GV->setAlignment(8);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004034 GV->setSection("__DATA, __objc_classlist, regular, no_dead_strip");
4035 UsedGlobals.push_back(GV);
4036 }
4037
4038 // Build list of all implemented category addresses in array
4039 // L_OBJC_LABEL_CATEGORY_$.
4040 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CATEGORY_$
4041 // list of 'nonlazy' category implementations (defined as those with a +load{}
4042 // method!!).
4043 unsigned NumCategory = DefinedCategories.size();
4044 if (NumCategory) {
4045 std::vector<llvm::Constant*> Symbols(NumCategory);
4046 for (unsigned i=0; i<NumCategory; i++)
4047 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedCategories[i],
4048 ObjCTypes.Int8PtrTy);
4049 llvm::Constant* Init =
4050 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
4051 NumCategory),
4052 Symbols);
4053
4054 llvm::GlobalVariable *GV =
4055 new llvm::GlobalVariable(Init->getType(), false,
4056 llvm::GlobalValue::InternalLinkage,
4057 Init,
4058 "\01L_OBJC_LABEL_CATEGORY_$",
4059 &CGM.getModule());
Daniel Dunbar58a29122009-03-09 22:18:41 +00004060 GV->setAlignment(8);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004061 GV->setSection("__DATA, __objc_catlist, regular, no_dead_strip");
4062 UsedGlobals.push_back(GV);
4063 }
4064
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004065 // static int L_OBJC_IMAGE_INFO[2] = { 0, flags };
4066 // FIXME. flags can be 0 | 1 | 2 | 6. For now just use 0
4067 std::vector<llvm::Constant*> Values(2);
4068 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, 0);
Fariborz Jahanian067986e2009-02-24 21:08:09 +00004069 unsigned int flags = 0;
Fariborz Jahanian66a5c2c2009-02-24 23:34:44 +00004070 // FIXME: Fix and continue?
4071 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
4072 flags |= eImageInfo_GarbageCollected;
4073 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
4074 flags |= eImageInfo_GCOnly;
Fariborz Jahanian067986e2009-02-24 21:08:09 +00004075 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004076 llvm::Constant* Init = llvm::ConstantArray::get(
4077 llvm::ArrayType::get(ObjCTypes.IntTy, 2),
4078 Values);
4079 llvm::GlobalVariable *IMGV =
4080 new llvm::GlobalVariable(Init->getType(), false,
4081 llvm::GlobalValue::InternalLinkage,
4082 Init,
4083 "\01L_OBJC_IMAGE_INFO",
4084 &CGM.getModule());
4085 IMGV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
4086 UsedGlobals.push_back(IMGV);
4087
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004088 std::vector<llvm::Constant*> Used;
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004089
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004090 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
4091 e = UsedGlobals.end(); i != e; ++i) {
4092 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
4093 }
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004094
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004095 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
4096 llvm::GlobalValue *GV =
4097 new llvm::GlobalVariable(AT, false,
4098 llvm::GlobalValue::AppendingLinkage,
4099 llvm::ConstantArray::get(AT, Used),
4100 "llvm.used",
4101 &CGM.getModule());
4102
4103 GV->setSection("llvm.metadata");
4104
4105}
4106
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004107// Metadata flags
4108enum MetaDataDlags {
4109 CLS = 0x0,
4110 CLS_META = 0x1,
4111 CLS_ROOT = 0x2,
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004112 OBJC2_CLS_HIDDEN = 0x10,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004113 CLS_EXCEPTION = 0x20
4114};
4115/// BuildClassRoTInitializer - generate meta-data for:
4116/// struct _class_ro_t {
4117/// uint32_t const flags;
4118/// uint32_t const instanceStart;
4119/// uint32_t const instanceSize;
4120/// uint32_t const reserved; // only when building for 64bit targets
4121/// const uint8_t * const ivarLayout;
4122/// const char *const name;
4123/// const struct _method_list_t * const baseMethods;
Fariborz Jahanianda320092009-01-29 19:24:30 +00004124/// const struct _protocol_list_t *const baseProtocols;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004125/// const struct _ivar_list_t *const ivars;
4126/// const uint8_t * const weakIvarLayout;
4127/// const struct _prop_list_t * const properties;
4128/// }
4129///
4130llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer(
4131 unsigned flags,
4132 unsigned InstanceStart,
4133 unsigned InstanceSize,
4134 const ObjCImplementationDecl *ID) {
4135 std::string ClassName = ID->getNameAsString();
4136 std::vector<llvm::Constant*> Values(10); // 11 for 64bit targets!
4137 Values[ 0] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
4138 Values[ 1] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceStart);
4139 Values[ 2] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceSize);
4140 // FIXME. For 64bit targets add 0 here.
Fariborz Jahanianda320092009-01-29 19:24:30 +00004141 // FIXME. ivarLayout is currently null!
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00004142 // Values[ 3] = (flags & CLS_META) ? GetIvarLayoutName(0, ObjCTypes)
4143 // : BuildIvarLayout(ID, true);
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00004144 Values[ 3] = GetIvarLayoutName(0, ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004145 Values[ 4] = GetClassName(ID->getIdentifier());
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004146 // const struct _method_list_t * const baseMethods;
4147 std::vector<llvm::Constant*> Methods;
4148 std::string MethodListName("\01l_OBJC_$_");
4149 if (flags & CLS_META) {
4150 MethodListName += "CLASS_METHODS_" + ID->getNameAsString();
4151 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
4152 e = ID->classmeth_end(); i != e; ++i) {
4153 // Class methods should always be defined.
4154 Methods.push_back(GetMethodConstant(*i));
4155 }
4156 } else {
4157 MethodListName += "INSTANCE_METHODS_" + ID->getNameAsString();
4158 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
4159 e = ID->instmeth_end(); i != e; ++i) {
4160 // Instance methods should always be defined.
4161 Methods.push_back(GetMethodConstant(*i));
4162 }
Fariborz Jahanian939abce2009-01-28 22:46:49 +00004163 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
4164 e = ID->propimpl_end(); i != e; ++i) {
4165 ObjCPropertyImplDecl *PID = *i;
4166
4167 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize){
4168 ObjCPropertyDecl *PD = PID->getPropertyDecl();
4169
4170 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
4171 if (llvm::Constant *C = GetMethodConstant(MD))
4172 Methods.push_back(C);
4173 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
4174 if (llvm::Constant *C = GetMethodConstant(MD))
4175 Methods.push_back(C);
4176 }
4177 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004178 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004179 Values[ 5] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004180 "__DATA, __objc_const", Methods);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004181
4182 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4183 assert(OID && "CGObjCNonFragileABIMac::BuildClassRoTInitializer");
4184 Values[ 6] = EmitProtocolList("\01l_OBJC_CLASS_PROTOCOLS_$_"
4185 + OID->getNameAsString(),
4186 OID->protocol_begin(),
4187 OID->protocol_end());
4188
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004189 if (flags & CLS_META)
4190 Values[ 7] = llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4191 else
4192 Values[ 7] = EmitIvarList(ID);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004193 // FIXME. weakIvarLayout is currently null.
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00004194 // Values[ 8] = (flags & CLS_META) ? GetIvarLayoutName(0, ObjCTypes)
4195 // : BuildIvarLayout(ID, false);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00004196 Values[ 8] = GetIvarLayoutName(0, ObjCTypes);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004197 if (flags & CLS_META)
4198 Values[ 9] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4199 else
4200 Values[ 9] =
4201 EmitPropertyList(
4202 "\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
4203 ID, ID->getClassInterface(), ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004204 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassRonfABITy,
4205 Values);
4206 llvm::GlobalVariable *CLASS_RO_GV =
4207 new llvm::GlobalVariable(ObjCTypes.ClassRonfABITy, false,
4208 llvm::GlobalValue::InternalLinkage,
4209 Init,
4210 (flags & CLS_META) ?
4211 std::string("\01l_OBJC_METACLASS_RO_$_")+ClassName :
4212 std::string("\01l_OBJC_CLASS_RO_$_")+ClassName,
4213 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004214 CLASS_RO_GV->setAlignment(
4215 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassRonfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004216 CLASS_RO_GV->setSection("__DATA, __objc_const");
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004217 return CLASS_RO_GV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004218
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004219}
4220
4221/// BuildClassMetaData - This routine defines that to-level meta-data
4222/// for the given ClassName for:
4223/// struct _class_t {
4224/// struct _class_t *isa;
4225/// struct _class_t * const superclass;
4226/// void *cache;
4227/// IMP *vtable;
4228/// struct class_ro_t *ro;
4229/// }
4230///
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004231llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassMetaData(
4232 std::string &ClassName,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004233 llvm::Constant *IsAGV,
4234 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004235 llvm::Constant *ClassRoGV,
4236 bool HiddenVisibility) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004237 std::vector<llvm::Constant*> Values(5);
4238 Values[0] = IsAGV;
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004239 Values[1] = SuperClassGV
4240 ? SuperClassGV
4241 : llvm::Constant::getNullValue(ObjCTypes.ClassnfABIPtrTy);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004242 Values[2] = ObjCEmptyCacheVar; // &ObjCEmptyCacheVar
4243 Values[3] = ObjCEmptyVtableVar; // &ObjCEmptyVtableVar
4244 Values[4] = ClassRoGV; // &CLASS_RO_GV
4245 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassnfABITy,
4246 Values);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004247 llvm::GlobalVariable *GV = GetClassGlobal(ClassName);
4248 GV->setInitializer(Init);
Fariborz Jahaniandd0db2a2009-01-31 01:07:39 +00004249 GV->setSection("__DATA, __objc_data");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004250 GV->setAlignment(
4251 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassnfABITy));
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004252 if (HiddenVisibility)
4253 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004254 return GV;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004255}
4256
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004257void CGObjCNonFragileABIMac::GetClassSizeInfo(const ObjCInterfaceDecl *OID,
4258 uint32_t &InstanceStart,
4259 uint32_t &InstanceSize) {
Daniel Dunbar97776872009-04-22 07:32:20 +00004260 // Find first and last (non-padding) ivars in this interface.
4261
4262 // FIXME: Use iterator.
4263 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
4264 GetNamedIvarList(OID, OIvars);
4265
4266 if (OIvars.empty()) {
4267 InstanceStart = InstanceSize = 0;
4268 return;
Daniel Dunbard4ae6c02009-04-22 04:39:47 +00004269 }
Daniel Dunbar97776872009-04-22 07:32:20 +00004270
4271 const ObjCIvarDecl *First = OIvars.front();
4272 const ObjCIvarDecl *Last = OIvars.back();
4273
4274 InstanceStart = ComputeIvarBaseOffset(CGM, OID, First);
4275 const llvm::Type *FieldTy =
4276 CGM.getTypes().ConvertTypeForMem(Last->getType());
4277 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
4278 InstanceSize = ComputeIvarBaseOffset(CGM, OID, Last) + Size;
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004279}
4280
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004281void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) {
4282 std::string ClassName = ID->getNameAsString();
4283 if (!ObjCEmptyCacheVar) {
4284 ObjCEmptyCacheVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004285 ObjCTypes.CacheTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004286 false,
4287 llvm::GlobalValue::ExternalLinkage,
4288 0,
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004289 "_objc_empty_cache",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004290 &CGM.getModule());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004291
4292 ObjCEmptyVtableVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004293 ObjCTypes.ImpnfABITy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004294 false,
4295 llvm::GlobalValue::ExternalLinkage,
4296 0,
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004297 "_objc_empty_vtable",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004298 &CGM.getModule());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004299 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004300 assert(ID->getClassInterface() &&
4301 "CGObjCNonFragileABIMac::GenerateClass - class is 0");
Daniel Dunbar6c1aac82009-04-20 20:18:54 +00004302 // FIXME: Is this correct (that meta class size is never computed)?
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004303 uint32_t InstanceStart =
4304 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassnfABITy);
4305 uint32_t InstanceSize = InstanceStart;
4306 uint32_t flags = CLS_META;
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004307 std::string ObjCMetaClassName(getMetaclassSymbolPrefix());
4308 std::string ObjCClassName(getClassSymbolPrefix());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004309
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004310 llvm::GlobalVariable *SuperClassGV, *IsAGV;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004311
Daniel Dunbar04d40782009-04-14 06:00:08 +00004312 bool classIsHidden =
4313 CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004314 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004315 flags |= OBJC2_CLS_HIDDEN;
4316 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004317 // class is root
4318 flags |= CLS_ROOT;
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004319 SuperClassGV = GetClassGlobal(ObjCClassName + ClassName);
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004320 IsAGV = GetClassGlobal(ObjCMetaClassName + ClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004321 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004322 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004323 const ObjCInterfaceDecl *Root = ID->getClassInterface();
4324 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
4325 Root = Super;
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004326 IsAGV = GetClassGlobal(ObjCMetaClassName + Root->getNameAsString());
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004327 // work on super class metadata symbol.
4328 std::string SuperClassName =
4329 ObjCMetaClassName + ID->getClassInterface()->getSuperClass()->getNameAsString();
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004330 SuperClassGV = GetClassGlobal(SuperClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004331 }
4332 llvm::GlobalVariable *CLASS_RO_GV = BuildClassRoTInitializer(flags,
4333 InstanceStart,
4334 InstanceSize,ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004335 std::string TClassName = ObjCMetaClassName + ClassName;
4336 llvm::GlobalVariable *MetaTClass =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004337 BuildClassMetaData(TClassName, IsAGV, SuperClassGV, CLASS_RO_GV,
4338 classIsHidden);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004339
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004340 // Metadata for the class
4341 flags = CLS;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004342 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004343 flags |= OBJC2_CLS_HIDDEN;
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004344
4345 if (hasObjCExceptionAttribute(ID->getClassInterface()))
4346 flags |= CLS_EXCEPTION;
4347
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004348 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004349 flags |= CLS_ROOT;
4350 SuperClassGV = 0;
Chris Lattnerb7b58b12009-04-19 06:02:28 +00004351 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004352 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004353 std::string RootClassName =
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004354 ID->getClassInterface()->getSuperClass()->getNameAsString();
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004355 SuperClassGV = GetClassGlobal(ObjCClassName + RootClassName);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004356 }
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004357 GetClassSizeInfo(ID->getClassInterface(), InstanceStart, InstanceSize);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004358 CLASS_RO_GV = BuildClassRoTInitializer(flags,
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004359 InstanceStart,
4360 InstanceSize,
4361 ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004362
4363 TClassName = ObjCClassName + ClassName;
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004364 llvm::GlobalVariable *ClassMD =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004365 BuildClassMetaData(TClassName, MetaTClass, SuperClassGV, CLASS_RO_GV,
4366 classIsHidden);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004367 DefinedClasses.push_back(ClassMD);
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004368
4369 // Force the definition of the EHType if necessary.
4370 if (flags & CLS_EXCEPTION)
4371 GetInterfaceEHType(ID->getClassInterface(), true);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004372}
4373
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004374/// GenerateProtocolRef - This routine is called to generate code for
4375/// a protocol reference expression; as in:
4376/// @code
4377/// @protocol(Proto1);
4378/// @endcode
4379/// It generates a weak reference to l_OBJC_PROTOCOL_REFERENCE_$_Proto1
4380/// which will hold address of the protocol meta-data.
4381///
4382llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CGBuilderTy &Builder,
4383 const ObjCProtocolDecl *PD) {
4384
Fariborz Jahanian960cd062009-04-10 18:47:34 +00004385 // This routine is called for @protocol only. So, we must build definition
4386 // of protocol's meta-data (not a reference to it!)
4387 //
4388 llvm::Constant *Init = llvm::ConstantExpr::getBitCast(GetOrEmitProtocol(PD),
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004389 ObjCTypes.ExternalProtocolPtrTy);
4390
4391 std::string ProtocolName("\01l_OBJC_PROTOCOL_REFERENCE_$_");
4392 ProtocolName += PD->getNameAsCString();
4393
4394 llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName);
4395 if (PTGV)
4396 return Builder.CreateLoad(PTGV, false, "tmp");
4397 PTGV = new llvm::GlobalVariable(
4398 Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00004399 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004400 Init,
4401 ProtocolName,
4402 &CGM.getModule());
4403 PTGV->setSection("__DATA, __objc_protorefs, coalesced, no_dead_strip");
4404 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4405 UsedGlobals.push_back(PTGV);
4406 return Builder.CreateLoad(PTGV, false, "tmp");
4407}
4408
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004409/// GenerateCategory - Build metadata for a category implementation.
4410/// struct _category_t {
4411/// const char * const name;
4412/// struct _class_t *const cls;
4413/// const struct _method_list_t * const instance_methods;
4414/// const struct _method_list_t * const class_methods;
4415/// const struct _protocol_list_t * const protocols;
4416/// const struct _prop_list_t * const properties;
4417/// }
4418///
4419void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD)
4420{
4421 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004422 const char *Prefix = "\01l_OBJC_$_CATEGORY_";
4423 std::string ExtCatName(Prefix + Interface->getNameAsString()+
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004424 "_$_" + OCD->getNameAsString());
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004425 std::string ExtClassName(getClassSymbolPrefix() +
4426 Interface->getNameAsString());
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004427
4428 std::vector<llvm::Constant*> Values(6);
4429 Values[0] = GetClassName(OCD->getIdentifier());
4430 // meta-class entry symbol
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004431 llvm::GlobalVariable *ClassGV = GetClassGlobal(ExtClassName);
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004432 Values[1] = ClassGV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004433 std::vector<llvm::Constant*> Methods;
4434 std::string MethodListName(Prefix);
4435 MethodListName += "INSTANCE_METHODS_" + Interface->getNameAsString() +
4436 "_$_" + OCD->getNameAsString();
4437
4438 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
4439 e = OCD->instmeth_end(); i != e; ++i) {
4440 // Instance methods should always be defined.
4441 Methods.push_back(GetMethodConstant(*i));
4442 }
4443
4444 Values[2] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004445 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004446 Methods);
4447
4448 MethodListName = Prefix;
4449 MethodListName += "CLASS_METHODS_" + Interface->getNameAsString() + "_$_" +
4450 OCD->getNameAsString();
4451 Methods.clear();
4452 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
4453 e = OCD->classmeth_end(); i != e; ++i) {
4454 // Class methods should always be defined.
4455 Methods.push_back(GetMethodConstant(*i));
4456 }
4457
4458 Values[3] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004459 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004460 Methods);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004461 const ObjCCategoryDecl *Category =
4462 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Fariborz Jahanian943ed6f2009-02-13 17:52:22 +00004463 if (Category) {
4464 std::string ExtName(Interface->getNameAsString() + "_$_" +
4465 OCD->getNameAsString());
4466 Values[4] = EmitProtocolList("\01l_OBJC_CATEGORY_PROTOCOLS_$_"
4467 + Interface->getNameAsString() + "_$_"
4468 + Category->getNameAsString(),
4469 Category->protocol_begin(),
4470 Category->protocol_end());
4471 Values[5] =
4472 EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
4473 OCD, Category, ObjCTypes);
4474 }
4475 else {
4476 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4477 Values[5] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4478 }
4479
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004480 llvm::Constant *Init =
4481 llvm::ConstantStruct::get(ObjCTypes.CategorynfABITy,
4482 Values);
4483 llvm::GlobalVariable *GCATV
4484 = new llvm::GlobalVariable(ObjCTypes.CategorynfABITy,
4485 false,
4486 llvm::GlobalValue::InternalLinkage,
4487 Init,
4488 ExtCatName,
4489 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004490 GCATV->setAlignment(
4491 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.CategorynfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004492 GCATV->setSection("__DATA, __objc_const");
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004493 UsedGlobals.push_back(GCATV);
4494 DefinedCategories.push_back(GCATV);
4495}
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004496
4497/// GetMethodConstant - Return a struct objc_method constant for the
4498/// given method if it has been defined. The result is null if the
4499/// method has not been defined. The return value has type MethodPtrTy.
4500llvm::Constant *CGObjCNonFragileABIMac::GetMethodConstant(
4501 const ObjCMethodDecl *MD) {
4502 // FIXME: Use DenseMap::lookup
4503 llvm::Function *Fn = MethodDefinitions[MD];
4504 if (!Fn)
4505 return 0;
4506
4507 std::vector<llvm::Constant*> Method(3);
4508 Method[0] =
4509 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4510 ObjCTypes.SelectorPtrTy);
4511 Method[1] = GetMethodVarType(MD);
4512 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
4513 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
4514}
4515
4516/// EmitMethodList - Build meta-data for method declarations
4517/// struct _method_list_t {
4518/// uint32_t entsize; // sizeof(struct _objc_method)
4519/// uint32_t method_count;
4520/// struct _objc_method method_list[method_count];
4521/// }
4522///
4523llvm::Constant *CGObjCNonFragileABIMac::EmitMethodList(
4524 const std::string &Name,
4525 const char *Section,
4526 const ConstantVector &Methods) {
4527 // Return null for empty list.
4528 if (Methods.empty())
4529 return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy);
4530
4531 std::vector<llvm::Constant*> Values(3);
4532 // sizeof(struct _objc_method)
4533 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.MethodTy);
4534 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4535 // method_count
4536 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
4537 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
4538 Methods.size());
4539 Values[2] = llvm::ConstantArray::get(AT, Methods);
4540 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4541
4542 llvm::GlobalVariable *GV =
4543 new llvm::GlobalVariable(Init->getType(), false,
4544 llvm::GlobalValue::InternalLinkage,
4545 Init,
4546 Name,
4547 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004548 GV->setAlignment(
4549 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004550 GV->setSection(Section);
4551 UsedGlobals.push_back(GV);
4552 return llvm::ConstantExpr::getBitCast(GV,
4553 ObjCTypes.MethodListnfABIPtrTy);
4554}
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004555
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004556/// ObjCIvarOffsetVariable - Returns the ivar offset variable for
4557/// the given ivar.
4558///
4559llvm::GlobalVariable * CGObjCNonFragileABIMac::ObjCIvarOffsetVariable(
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004560 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004561 const ObjCIvarDecl *Ivar) {
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00004562 std::string Name = "OBJC_IVAR_$_" +
Douglas Gregor6ab35242009-04-09 21:40:53 +00004563 getInterfaceDeclForIvar(ID, Ivar, CGM.getContext())->getNameAsString() +
4564 '.' + Ivar->getNameAsString();
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004565 llvm::GlobalVariable *IvarOffsetGV =
4566 CGM.getModule().getGlobalVariable(Name);
4567 if (!IvarOffsetGV)
4568 IvarOffsetGV =
4569 new llvm::GlobalVariable(ObjCTypes.LongTy,
4570 false,
4571 llvm::GlobalValue::ExternalLinkage,
4572 0,
4573 Name,
4574 &CGM.getModule());
4575 return IvarOffsetGV;
4576}
4577
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004578llvm::Constant * CGObjCNonFragileABIMac::EmitIvarOffsetVar(
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004579 const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004580 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004581 unsigned long int Offset) {
Daniel Dunbar737c5022009-04-19 00:44:02 +00004582 llvm::GlobalVariable *IvarOffsetGV = ObjCIvarOffsetVariable(ID, Ivar);
4583 IvarOffsetGV->setInitializer(llvm::ConstantInt::get(ObjCTypes.LongTy,
4584 Offset));
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004585 IvarOffsetGV->setAlignment(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004586 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.LongTy));
Daniel Dunbar737c5022009-04-19 00:44:02 +00004587
4588 // FIXME: This matches gcc, but shouldn't the visibility be set on
4589 // the use as well (i.e., in ObjCIvarOffsetVariable).
4590 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
4591 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
4592 CGM.getDeclVisibilityMode(ID) == LangOptions::Hidden)
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004593 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar04d40782009-04-14 06:00:08 +00004594 else
Fariborz Jahanian77c9fd22009-04-06 18:30:00 +00004595 IvarOffsetGV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004596 IvarOffsetGV->setSection("__DATA, __objc_const");
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004597 return IvarOffsetGV;
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004598}
4599
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004600/// EmitIvarList - Emit the ivar list for the given
Daniel Dunbar11394522009-04-18 08:51:00 +00004601/// implementation. The return value has type
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004602/// IvarListnfABIPtrTy.
4603/// struct _ivar_t {
4604/// unsigned long int *offset; // pointer to ivar offset location
4605/// char *name;
4606/// char *type;
4607/// uint32_t alignment;
4608/// uint32_t size;
4609/// }
4610/// struct _ivar_list_t {
4611/// uint32 entsize; // sizeof(struct _ivar_t)
4612/// uint32 count;
4613/// struct _iver_t list[count];
4614/// }
4615///
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004616
4617void CGObjCCommonMac::GetNamedIvarList(const ObjCInterfaceDecl *OID,
4618 llvm::SmallVector<ObjCIvarDecl*, 16> &Res) const {
4619 for (ObjCInterfaceDecl::ivar_iterator I = OID->ivar_begin(),
4620 E = OID->ivar_end(); I != E; ++I) {
4621 // Ignore unnamed bit-fields.
4622 if (!(*I)->getDeclName())
4623 continue;
4624
4625 Res.push_back(*I);
4626 }
4627
4628 for (ObjCInterfaceDecl::prop_iterator I = OID->prop_begin(CGM.getContext()),
4629 E = OID->prop_end(CGM.getContext()); I != E; ++I)
4630 if (ObjCIvarDecl *IV = (*I)->getPropertyIvarDecl())
4631 Res.push_back(IV);
4632}
4633
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004634llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList(
4635 const ObjCImplementationDecl *ID) {
4636
4637 std::vector<llvm::Constant*> Ivars, Ivar(5);
4638
4639 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4640 assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface");
4641
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004642 // FIXME. Consolidate this with similar code in GenerateClass.
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00004643
Daniel Dunbar91636d62009-04-20 00:33:43 +00004644 // Collect declared and synthesized ivars in a small vector.
Fariborz Jahanian18191882009-03-31 18:11:23 +00004645 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004646 GetNamedIvarList(OID, OIvars);
Fariborz Jahanian99eee362009-04-01 19:37:34 +00004647
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004648 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
4649 ObjCIvarDecl *IVD = OIvars[i];
Daniel Dunbar3eec8aa2009-04-20 05:53:40 +00004650 Ivar[0] = EmitIvarOffsetVar(ID->getClassInterface(), IVD,
Daniel Dunbar97776872009-04-22 07:32:20 +00004651 ComputeIvarBaseOffset(CGM, OID, IVD));
Daniel Dunbar3fea0c02009-04-22 08:22:17 +00004652 Ivar[1] = GetMethodVarName(IVD->getIdentifier());
4653 Ivar[2] = GetMethodVarType(IVD);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004654 const llvm::Type *FieldTy =
Daniel Dunbar3fea0c02009-04-22 08:22:17 +00004655 CGM.getTypes().ConvertTypeForMem(IVD->getType());
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004656 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
4657 unsigned Align = CGM.getContext().getPreferredTypeAlign(
Daniel Dunbar3fea0c02009-04-22 08:22:17 +00004658 IVD->getType().getTypePtr()) >> 3;
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004659 Align = llvm::Log2_32(Align);
4660 Ivar[3] = llvm::ConstantInt::get(ObjCTypes.IntTy, Align);
Daniel Dunbar91636d62009-04-20 00:33:43 +00004661 // NOTE. Size of a bitfield does not match gcc's, because of the
4662 // way bitfields are treated special in each. But I am told that
4663 // 'size' for bitfield ivars is ignored by the runtime so it does
4664 // not matter. If it matters, there is enough info to get the
4665 // bitfield right!
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004666 Ivar[4] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4667 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarnfABITy, Ivar));
4668 }
4669 // Return null for empty list.
4670 if (Ivars.empty())
4671 return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4672 std::vector<llvm::Constant*> Values(3);
4673 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.IvarnfABITy);
4674 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4675 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
4676 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarnfABITy,
4677 Ivars.size());
4678 Values[2] = llvm::ConstantArray::get(AT, Ivars);
4679 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4680 const char *Prefix = "\01l_OBJC_$_INSTANCE_VARIABLES_";
4681 llvm::GlobalVariable *GV =
4682 new llvm::GlobalVariable(Init->getType(), false,
4683 llvm::GlobalValue::InternalLinkage,
4684 Init,
4685 Prefix + OID->getNameAsString(),
4686 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004687 GV->setAlignment(
4688 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004689 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004690
4691 UsedGlobals.push_back(GV);
4692 return llvm::ConstantExpr::getBitCast(GV,
4693 ObjCTypes.IvarListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004694}
4695
4696llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef(
4697 const ObjCProtocolDecl *PD) {
4698 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4699
4700 if (!Entry) {
4701 // We use the initializer as a marker of whether this is a forward
4702 // reference or not. At module finalization we add the empty
4703 // contents for protocols which were referenced but never defined.
4704 Entry =
4705 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
4706 llvm::GlobalValue::ExternalLinkage,
4707 0,
4708 "\01l_OBJC_PROTOCOL_$_" + PD->getNameAsString(),
4709 &CGM.getModule());
4710 Entry->setSection("__DATA,__datacoal_nt,coalesced");
4711 UsedGlobals.push_back(Entry);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004712 }
4713
4714 return Entry;
4715}
4716
4717/// GetOrEmitProtocol - Generate the protocol meta-data:
4718/// @code
4719/// struct _protocol_t {
4720/// id isa; // NULL
4721/// const char * const protocol_name;
4722/// const struct _protocol_list_t * protocol_list; // super protocols
4723/// const struct method_list_t * const instance_methods;
4724/// const struct method_list_t * const class_methods;
4725/// const struct method_list_t *optionalInstanceMethods;
4726/// const struct method_list_t *optionalClassMethods;
4727/// const struct _prop_list_t * properties;
4728/// const uint32_t size; // sizeof(struct _protocol_t)
4729/// const uint32_t flags; // = 0
4730/// }
4731/// @endcode
4732///
4733
4734llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol(
4735 const ObjCProtocolDecl *PD) {
4736 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4737
4738 // Early exit if a defining object has already been generated.
4739 if (Entry && Entry->hasInitializer())
4740 return Entry;
4741
4742 const char *ProtocolName = PD->getNameAsCString();
4743
4744 // Construct method lists.
4745 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
4746 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregor6ab35242009-04-09 21:40:53 +00004747 for (ObjCProtocolDecl::instmeth_iterator
4748 i = PD->instmeth_begin(CGM.getContext()),
4749 e = PD->instmeth_end(CGM.getContext());
4750 i != e; ++i) {
Fariborz Jahanianda320092009-01-29 19:24:30 +00004751 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004752 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004753 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4754 OptInstanceMethods.push_back(C);
4755 } else {
4756 InstanceMethods.push_back(C);
4757 }
4758 }
4759
Douglas Gregor6ab35242009-04-09 21:40:53 +00004760 for (ObjCProtocolDecl::classmeth_iterator
4761 i = PD->classmeth_begin(CGM.getContext()),
4762 e = PD->classmeth_end(CGM.getContext());
4763 i != e; ++i) {
Fariborz Jahanianda320092009-01-29 19:24:30 +00004764 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004765 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004766 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4767 OptClassMethods.push_back(C);
4768 } else {
4769 ClassMethods.push_back(C);
4770 }
4771 }
4772
4773 std::vector<llvm::Constant*> Values(10);
4774 // isa is NULL
4775 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ObjectPtrTy);
4776 Values[1] = GetClassName(PD->getIdentifier());
4777 Values[2] = EmitProtocolList(
4778 "\01l_OBJC_$_PROTOCOL_REFS_" + PD->getNameAsString(),
4779 PD->protocol_begin(),
4780 PD->protocol_end());
4781
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004782 Values[3] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004783 + PD->getNameAsString(),
4784 "__DATA, __objc_const",
4785 InstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004786 Values[4] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004787 + PD->getNameAsString(),
4788 "__DATA, __objc_const",
4789 ClassMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004790 Values[5] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004791 + PD->getNameAsString(),
4792 "__DATA, __objc_const",
4793 OptInstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004794 Values[6] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004795 + PD->getNameAsString(),
4796 "__DATA, __objc_const",
4797 OptClassMethods);
4798 Values[7] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + PD->getNameAsString(),
4799 0, PD, ObjCTypes);
4800 uint32_t Size =
4801 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolnfABITy);
4802 Values[8] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4803 Values[9] = llvm::Constant::getNullValue(ObjCTypes.IntTy);
4804 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolnfABITy,
4805 Values);
4806
4807 if (Entry) {
4808 // Already created, fix the linkage and update the initializer.
Mike Stump286acbd2009-03-07 16:33:28 +00004809 Entry->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004810 Entry->setInitializer(Init);
4811 } else {
4812 Entry =
4813 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004814 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004815 Init,
4816 std::string("\01l_OBJC_PROTOCOL_$_")+ProtocolName,
4817 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004818 Entry->setAlignment(
4819 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABITy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004820 Entry->setSection("__DATA,__datacoal_nt,coalesced");
Fariborz Jahanianda320092009-01-29 19:24:30 +00004821 }
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004822 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
4823
4824 // Use this protocol meta-data to build protocol list table in section
4825 // __DATA, __objc_protolist
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004826 llvm::GlobalVariable *PTGV = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004827 ObjCTypes.ProtocolnfABIPtrTy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004828 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004829 Entry,
4830 std::string("\01l_OBJC_LABEL_PROTOCOL_$_")
4831 +ProtocolName,
4832 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004833 PTGV->setAlignment(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004834 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABIPtrTy));
Daniel Dunbar0bf21992009-04-15 02:56:18 +00004835 PTGV->setSection("__DATA, __objc_protolist, coalesced, no_dead_strip");
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004836 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4837 UsedGlobals.push_back(PTGV);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004838 return Entry;
4839}
4840
4841/// EmitProtocolList - Generate protocol list meta-data:
4842/// @code
4843/// struct _protocol_list_t {
4844/// long protocol_count; // Note, this is 32/64 bit
4845/// struct _protocol_t[protocol_count];
4846/// }
4847/// @endcode
4848///
4849llvm::Constant *
4850CGObjCNonFragileABIMac::EmitProtocolList(const std::string &Name,
4851 ObjCProtocolDecl::protocol_iterator begin,
4852 ObjCProtocolDecl::protocol_iterator end) {
4853 std::vector<llvm::Constant*> ProtocolRefs;
4854
Fariborz Jahanianda320092009-01-29 19:24:30 +00004855 // Just return null for empty protocol lists
Daniel Dunbar948e2582009-02-15 07:36:20 +00004856 if (begin == end)
Fariborz Jahanianda320092009-01-29 19:24:30 +00004857 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4858
Daniel Dunbar948e2582009-02-15 07:36:20 +00004859 // FIXME: We shouldn't need to do this lookup here, should we?
Fariborz Jahanianda320092009-01-29 19:24:30 +00004860 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
4861 if (GV)
Daniel Dunbar948e2582009-02-15 07:36:20 +00004862 return llvm::ConstantExpr::getBitCast(GV,
4863 ObjCTypes.ProtocolListnfABIPtrTy);
4864
4865 for (; begin != end; ++begin)
4866 ProtocolRefs.push_back(GetProtocolRef(*begin)); // Implemented???
4867
Fariborz Jahanianda320092009-01-29 19:24:30 +00004868 // This list is null terminated.
4869 ProtocolRefs.push_back(llvm::Constant::getNullValue(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004870 ObjCTypes.ProtocolnfABIPtrTy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004871
4872 std::vector<llvm::Constant*> Values(2);
4873 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
4874 Values[1] =
Daniel Dunbar948e2582009-02-15 07:36:20 +00004875 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolnfABIPtrTy,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004876 ProtocolRefs.size()),
4877 ProtocolRefs);
4878
4879 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4880 GV = new llvm::GlobalVariable(Init->getType(), false,
4881 llvm::GlobalValue::InternalLinkage,
4882 Init,
4883 Name,
4884 &CGM.getModule());
4885 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004886 GV->setAlignment(
4887 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004888 UsedGlobals.push_back(GV);
Daniel Dunbar948e2582009-02-15 07:36:20 +00004889 return llvm::ConstantExpr::getBitCast(GV,
4890 ObjCTypes.ProtocolListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004891}
4892
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004893/// GetMethodDescriptionConstant - This routine build following meta-data:
4894/// struct _objc_method {
4895/// SEL _cmd;
4896/// char *method_type;
4897/// char *_imp;
4898/// }
4899
4900llvm::Constant *
4901CGObjCNonFragileABIMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
4902 std::vector<llvm::Constant*> Desc(3);
4903 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4904 ObjCTypes.SelectorPtrTy);
4905 Desc[1] = GetMethodVarType(MD);
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004906 // Protocol methods have no implementation. So, this entry is always NULL.
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004907 Desc[2] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
4908 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Desc);
4909}
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004910
4911/// EmitObjCValueForIvar - Code Gen for nonfragile ivar reference.
4912/// This code gen. amounts to generating code for:
4913/// @code
4914/// (type *)((char *)base + _OBJC_IVAR_$_.ivar;
4915/// @encode
4916///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004917LValue CGObjCNonFragileABIMac::EmitObjCValueForIvar(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004918 CodeGen::CodeGenFunction &CGF,
4919 QualType ObjectTy,
4920 llvm::Value *BaseValue,
4921 const ObjCIvarDecl *Ivar,
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004922 unsigned CVRQualifiers) {
Daniel Dunbar525c9b72009-04-21 01:19:28 +00004923 const ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
Daniel Dunbar97776872009-04-22 07:32:20 +00004924 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
4925 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004926}
4927
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004928llvm::Value *CGObjCNonFragileABIMac::EmitIvarOffset(
4929 CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00004930 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004931 const ObjCIvarDecl *Ivar) {
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00004932 return CGF.Builder.CreateLoad(ObjCIvarOffsetVariable(Interface, Ivar),
4933 false, "ivar");
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004934}
4935
Fariborz Jahanian46551122009-02-04 00:22:57 +00004936CodeGen::RValue CGObjCNonFragileABIMac::EmitMessageSend(
4937 CodeGen::CodeGenFunction &CGF,
4938 QualType ResultType,
4939 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004940 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +00004941 QualType Arg0Ty,
4942 bool IsSuper,
4943 const CallArgList &CallArgs) {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004944 // FIXME. Even though IsSuper is passes. This function doese not
4945 // handle calls to 'super' receivers.
4946 CodeGenTypes &Types = CGM.getTypes();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004947 llvm::Value *Arg0 = Receiver;
4948 if (!IsSuper)
4949 Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy, "tmp");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004950
4951 // Find the message function name.
Fariborz Jahanianef163782009-02-05 01:13:09 +00004952 // FIXME. This is too much work to get the ABI-specific result type
4953 // needed to find the message name.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004954 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType,
4955 llvm::SmallVector<QualType, 16>());
4956 llvm::Constant *Fn;
4957 std::string Name("\01l_");
4958 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004959#if 0
4960 // unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004961 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
Chris Lattner1c02f862009-04-22 02:53:24 +00004962 Fn = ObjCTypes.getMessageSendIdStretFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004963 // FIXME. Is there a better way of getting these names.
4964 // They are available in RuntimeFunctions vector pair.
4965 Name += "objc_msgSendId_stret_fixup";
4966 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004967 else
4968#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004969 if (IsSuper) {
Chris Lattner1c02f862009-04-22 02:53:24 +00004970 Fn = ObjCTypes.getMessageSendSuper2StretFixupFn();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004971 Name += "objc_msgSendSuper2_stret_fixup";
4972 }
4973 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004974 {
Chris Lattner1c02f862009-04-22 02:53:24 +00004975 Fn = ObjCTypes.getMessageSendStretFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004976 Name += "objc_msgSend_stret_fixup";
4977 }
4978 }
Fariborz Jahanian1a6b3682009-02-05 19:35:43 +00004979 else if (ResultType->isFloatingType() &&
4980 // Selection of frret API only happens in 32bit nonfragile ABI.
4981 CGM.getTargetData().getTypePaddedSize(ObjCTypes.LongTy) == 4) {
Chris Lattner1c02f862009-04-22 02:53:24 +00004982 Fn = ObjCTypes.getMessageSendFpretFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004983 Name += "objc_msgSend_fpret_fixup";
4984 }
4985 else {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004986#if 0
4987// unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004988 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
Chris Lattner1c02f862009-04-22 02:53:24 +00004989 Fn = ObjCTypes.getMessageSendIdFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004990 Name += "objc_msgSendId_fixup";
4991 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004992 else
4993#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004994 if (IsSuper) {
Chris Lattner1c02f862009-04-22 02:53:24 +00004995 Fn = ObjCTypes.getMessageSendSuper2FixupFn();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004996 Name += "objc_msgSendSuper2_fixup";
4997 }
4998 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004999 {
Chris Lattner1c02f862009-04-22 02:53:24 +00005000 Fn = ObjCTypes.getMessageSendFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005001 Name += "objc_msgSend_fixup";
5002 }
5003 }
5004 Name += '_';
5005 std::string SelName(Sel.getAsString());
5006 // Replace all ':' in selector name with '_' ouch!
5007 for(unsigned i = 0; i < SelName.size(); i++)
5008 if (SelName[i] == ':')
5009 SelName[i] = '_';
5010 Name += SelName;
5011 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5012 if (!GV) {
Daniel Dunbar33af70f2009-04-15 19:03:14 +00005013 // Build message ref table entry.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005014 std::vector<llvm::Constant*> Values(2);
5015 Values[0] = Fn;
5016 Values[1] = GetMethodVarName(Sel);
5017 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
5018 GV = new llvm::GlobalVariable(Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00005019 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005020 Init,
5021 Name,
5022 &CGM.getModule());
5023 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbarf59c1a62009-04-15 19:04:46 +00005024 GV->setAlignment(16);
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005025 GV->setSection("__DATA, __objc_msgrefs, coalesced");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005026 }
5027 llvm::Value *Arg1 = CGF.Builder.CreateBitCast(GV, ObjCTypes.MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00005028
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005029 CallArgList ActualArgs;
5030 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
5031 ActualArgs.push_back(std::make_pair(RValue::get(Arg1),
5032 ObjCTypes.MessageRefCPtrTy));
5033 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Fariborz Jahanianef163782009-02-05 01:13:09 +00005034 const CGFunctionInfo &FnInfo1 = Types.getFunctionInfo(ResultType, ActualArgs);
5035 llvm::Value *Callee = CGF.Builder.CreateStructGEP(Arg1, 0);
5036 Callee = CGF.Builder.CreateLoad(Callee);
Fariborz Jahanian3ab75bd2009-02-14 21:25:36 +00005037 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo1, true);
Fariborz Jahanianef163782009-02-05 01:13:09 +00005038 Callee = CGF.Builder.CreateBitCast(Callee,
5039 llvm::PointerType::getUnqual(FTy));
5040 return CGF.EmitCall(FnInfo1, Callee, ActualArgs);
Fariborz Jahanian46551122009-02-04 00:22:57 +00005041}
5042
5043/// Generate code for a message send expression in the nonfragile abi.
5044CodeGen::RValue CGObjCNonFragileABIMac::GenerateMessageSend(
5045 CodeGen::CodeGenFunction &CGF,
5046 QualType ResultType,
5047 Selector Sel,
5048 llvm::Value *Receiver,
5049 bool IsClassMessage,
5050 const CallArgList &CallArgs) {
Fariborz Jahanian46551122009-02-04 00:22:57 +00005051 return EmitMessageSend(CGF, ResultType, Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005052 Receiver, CGF.getContext().getObjCIdType(),
Fariborz Jahanian46551122009-02-04 00:22:57 +00005053 false, CallArgs);
5054}
5055
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005056llvm::GlobalVariable *
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005057CGObjCNonFragileABIMac::GetClassGlobal(const std::string &Name) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005058 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5059
Daniel Dunbardfff2302009-03-02 05:18:14 +00005060 if (!GV) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005061 GV = new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
5062 llvm::GlobalValue::ExternalLinkage,
5063 0, Name, &CGM.getModule());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005064 }
5065
5066 return GV;
5067}
5068
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005069llvm::Value *CGObjCNonFragileABIMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar11394522009-04-18 08:51:00 +00005070 const ObjCInterfaceDecl *ID) {
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005071 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
5072
5073 if (!Entry) {
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005074 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005075 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005076 Entry =
5077 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5078 llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005079 ClassGV,
Daniel Dunbar11394522009-04-18 08:51:00 +00005080 "\01L_OBJC_CLASSLIST_REFERENCES_$_",
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005081 &CGM.getModule());
5082 Entry->setAlignment(
5083 CGM.getTargetData().getPrefTypeAlignment(
5084 ObjCTypes.ClassnfABIPtrTy));
Daniel Dunbar11394522009-04-18 08:51:00 +00005085 Entry->setSection("__DATA, __objc_classrefs, regular, no_dead_strip");
5086 UsedGlobals.push_back(Entry);
5087 }
5088
5089 return Builder.CreateLoad(Entry, false, "tmp");
5090}
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005091
Daniel Dunbar11394522009-04-18 08:51:00 +00005092llvm::Value *
5093CGObjCNonFragileABIMac::EmitSuperClassRef(CGBuilderTy &Builder,
5094 const ObjCInterfaceDecl *ID) {
5095 llvm::GlobalVariable *&Entry = SuperClassReferences[ID->getIdentifier()];
5096
5097 if (!Entry) {
5098 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
5099 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
5100 Entry =
5101 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5102 llvm::GlobalValue::InternalLinkage,
5103 ClassGV,
5104 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5105 &CGM.getModule());
5106 Entry->setAlignment(
5107 CGM.getTargetData().getPrefTypeAlignment(
5108 ObjCTypes.ClassnfABIPtrTy));
5109 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005110 UsedGlobals.push_back(Entry);
5111 }
5112
5113 return Builder.CreateLoad(Entry, false, "tmp");
5114}
5115
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005116/// EmitMetaClassRef - Return a Value * of the address of _class_t
5117/// meta-data
5118///
5119llvm::Value *CGObjCNonFragileABIMac::EmitMetaClassRef(CGBuilderTy &Builder,
5120 const ObjCInterfaceDecl *ID) {
5121 llvm::GlobalVariable * &Entry = MetaClassReferences[ID->getIdentifier()];
5122 if (Entry)
5123 return Builder.CreateLoad(Entry, false, "tmp");
5124
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005125 std::string MetaClassName(getMetaclassSymbolPrefix() + ID->getNameAsString());
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005126 llvm::GlobalVariable *MetaClassGV = GetClassGlobal(MetaClassName);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005127 Entry =
5128 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5129 llvm::GlobalValue::InternalLinkage,
5130 MetaClassGV,
5131 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5132 &CGM.getModule());
5133 Entry->setAlignment(
5134 CGM.getTargetData().getPrefTypeAlignment(
5135 ObjCTypes.ClassnfABIPtrTy));
5136
Daniel Dunbar33af70f2009-04-15 19:03:14 +00005137 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005138 UsedGlobals.push_back(Entry);
5139
5140 return Builder.CreateLoad(Entry, false, "tmp");
5141}
5142
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005143/// GetClass - Return a reference to the class for the given interface
5144/// decl.
5145llvm::Value *CGObjCNonFragileABIMac::GetClass(CGBuilderTy &Builder,
5146 const ObjCInterfaceDecl *ID) {
5147 return EmitClassRef(Builder, ID);
5148}
5149
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005150/// Generates a message send where the super is the receiver. This is
5151/// a message send to self with special delivery semantics indicating
5152/// which class's method should be called.
5153CodeGen::RValue
5154CGObjCNonFragileABIMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
5155 QualType ResultType,
5156 Selector Sel,
5157 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005158 bool isCategoryImpl,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005159 llvm::Value *Receiver,
5160 bool IsClassMessage,
5161 const CodeGen::CallArgList &CallArgs) {
5162 // ...
5163 // Create and init a super structure; this is a (receiver, class)
5164 // pair we will pass to objc_msgSendSuper.
5165 llvm::Value *ObjCSuper =
5166 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
5167
5168 llvm::Value *ReceiverAsObject =
5169 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
5170 CGF.Builder.CreateStore(ReceiverAsObject,
5171 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
5172
5173 // If this is a class message the metaclass is passed as the target.
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005174 llvm::Value *Target;
5175 if (IsClassMessage) {
5176 if (isCategoryImpl) {
5177 // Message sent to "super' in a class method defined in
5178 // a category implementation.
Daniel Dunbar11394522009-04-18 08:51:00 +00005179 Target = EmitClassRef(CGF.Builder, Class);
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005180 Target = CGF.Builder.CreateStructGEP(Target, 0);
5181 Target = CGF.Builder.CreateLoad(Target);
5182 }
5183 else
5184 Target = EmitMetaClassRef(CGF.Builder, Class);
5185 }
5186 else
Daniel Dunbar11394522009-04-18 08:51:00 +00005187 Target = EmitSuperClassRef(CGF.Builder, Class);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005188
5189 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
5190 // and ObjCTypes types.
5191 const llvm::Type *ClassTy =
5192 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
5193 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
5194 CGF.Builder.CreateStore(Target,
5195 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
5196
5197 return EmitMessageSend(CGF, ResultType, Sel,
5198 ObjCSuper, ObjCTypes.SuperPtrCTy,
5199 true, CallArgs);
5200}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005201
5202llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CGBuilderTy &Builder,
5203 Selector Sel) {
5204 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
5205
5206 if (!Entry) {
5207 llvm::Constant *Casted =
5208 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
5209 ObjCTypes.SelectorPtrTy);
5210 Entry =
5211 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
5212 llvm::GlobalValue::InternalLinkage,
5213 Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
5214 &CGM.getModule());
5215 Entry->setSection("__DATA,__objc_selrefs,literal_pointers,no_dead_strip");
5216 UsedGlobals.push_back(Entry);
5217 }
5218
5219 return Builder.CreateLoad(Entry, false, "tmp");
5220}
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005221/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
5222/// objc_assign_ivar (id src, id *dst)
5223///
5224void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
5225 llvm::Value *src, llvm::Value *dst)
5226{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005227 const llvm::Type * SrcTy = src->getType();
5228 if (!isa<llvm::PointerType>(SrcTy)) {
5229 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5230 assert(Size <= 8 && "does not support size > 8");
5231 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5232 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005233 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5234 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005235 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5236 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00005237 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignIvarFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005238 src, dst, "assignivar");
5239 return;
5240}
5241
5242/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
5243/// objc_assign_strongCast (id src, id *dst)
5244///
5245void CGObjCNonFragileABIMac::EmitObjCStrongCastAssign(
5246 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.getGcAssignStrongCastFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005260 src, dst, "weakassign");
5261 return;
5262}
5263
5264/// EmitObjCWeakRead - Code gen for loading value of a __weak
5265/// object: objc_read_weak (id *src)
5266///
5267llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead(
5268 CodeGen::CodeGenFunction &CGF,
5269 llvm::Value *AddrWeakObj)
5270{
Eli Friedman8339b352009-03-07 03:57:15 +00005271 const llvm::Type* DestTy =
5272 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005273 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Chris Lattner72db6c32009-04-22 02:44:54 +00005274 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.getGcReadWeakFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005275 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00005276 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005277 return read_weak;
5278}
5279
5280/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
5281/// objc_assign_weak (id src, id *dst)
5282///
5283void CGObjCNonFragileABIMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
5284 llvm::Value *src, llvm::Value *dst)
5285{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005286 const llvm::Type * SrcTy = src->getType();
5287 if (!isa<llvm::PointerType>(SrcTy)) {
5288 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5289 assert(Size <= 8 && "does not support size > 8");
5290 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5291 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005292 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5293 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005294 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5295 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattner96508e12009-04-17 22:12:36 +00005296 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005297 src, dst, "weakassign");
5298 return;
5299}
5300
5301/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
5302/// objc_assign_global (id src, id *dst)
5303///
5304void CGObjCNonFragileABIMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
5305 llvm::Value *src, llvm::Value *dst)
5306{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005307 const llvm::Type * SrcTy = src->getType();
5308 if (!isa<llvm::PointerType>(SrcTy)) {
5309 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5310 assert(Size <= 8 && "does not support size > 8");
5311 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5312 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005313 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5314 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005315 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5316 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00005317 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignGlobalFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005318 src, dst, "globalassign");
5319 return;
5320}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005321
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005322void
5323CGObjCNonFragileABIMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
5324 const Stmt &S) {
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005325 bool isTry = isa<ObjCAtTryStmt>(S);
5326 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
5327 llvm::BasicBlock *PrevLandingPad = CGF.getInvokeDest();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005328 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005329 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005330 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005331 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
5332
5333 // For @synchronized, call objc_sync_enter(sync.expr). The
5334 // evaluation of the expression must occur before we enter the
5335 // @synchronized. We can safely avoid a temp here because jumps into
5336 // @synchronized are illegal & this will dominate uses.
5337 llvm::Value *SyncArg = 0;
5338 if (!isTry) {
5339 SyncArg =
5340 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
5341 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005342 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005343 }
5344
5345 // Push an EH context entry, used for handling rethrows and jumps
5346 // through finally.
5347 CGF.PushCleanupBlock(FinallyBlock);
5348
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005349 CGF.setInvokeDest(TryHandler);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005350
5351 CGF.EmitBlock(TryBlock);
5352 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
5353 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
5354 CGF.EmitBranchThroughCleanup(FinallyEnd);
5355
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005356 // Emit the exception handler.
5357
5358 CGF.EmitBlock(TryHandler);
5359
5360 llvm::Value *llvm_eh_exception =
5361 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_exception);
5362 llvm::Value *llvm_eh_selector_i64 =
5363 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector_i64);
5364 llvm::Value *llvm_eh_typeid_for_i64 =
5365 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for_i64);
5366 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5367 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(Exc->getType(), "_rethrow");
5368
5369 llvm::SmallVector<llvm::Value*, 8> SelectorArgs;
5370 SelectorArgs.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005371 SelectorArgs.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005372
5373 // Construct the lists of (type, catch body) to handle.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005374 llvm::SmallVector<std::pair<const ParmVarDecl*, const Stmt*>, 8> Handlers;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005375 bool HasCatchAll = false;
5376 if (isTry) {
5377 if (const ObjCAtCatchStmt* CatchStmt =
5378 cast<ObjCAtTryStmt>(S).getCatchStmts()) {
5379 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005380 const ParmVarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
Steve Naroff7ba138a2009-03-03 19:52:17 +00005381 Handlers.push_back(std::make_pair(CatchDecl, CatchStmt->getCatchBody()));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005382
5383 // catch(...) always matches.
Steve Naroff7ba138a2009-03-03 19:52:17 +00005384 if (!CatchDecl) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005385 // Use i8* null here to signal this is a catch all, not a cleanup.
5386 llvm::Value *Null = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
5387 SelectorArgs.push_back(Null);
5388 HasCatchAll = true;
5389 break;
5390 }
5391
Daniel Dunbarede8de92009-03-06 00:01:21 +00005392 if (CGF.getContext().isObjCIdType(CatchDecl->getType()) ||
5393 CatchDecl->getType()->isObjCQualifiedIdType()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005394 llvm::Value *IDEHType =
5395 CGM.getModule().getGlobalVariable("OBJC_EHTYPE_id");
5396 if (!IDEHType)
5397 IDEHType =
5398 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5399 llvm::GlobalValue::ExternalLinkage,
5400 0, "OBJC_EHTYPE_id", &CGM.getModule());
5401 SelectorArgs.push_back(IDEHType);
5402 HasCatchAll = true;
5403 break;
5404 }
5405
5406 // All other types should be Objective-C interface pointer types.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005407 const PointerType *PT = CatchDecl->getType()->getAsPointerType();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005408 assert(PT && "Invalid @catch type.");
5409 const ObjCInterfaceType *IT =
5410 PT->getPointeeType()->getAsObjCInterfaceType();
5411 assert(IT && "Invalid @catch type.");
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005412 llvm::Value *EHType = GetInterfaceEHType(IT->getDecl(), false);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005413 SelectorArgs.push_back(EHType);
5414 }
5415 }
5416 }
5417
5418 // We use a cleanup unless there was already a catch all.
5419 if (!HasCatchAll) {
5420 SelectorArgs.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
Daniel Dunbarede8de92009-03-06 00:01:21 +00005421 Handlers.push_back(std::make_pair((const ParmVarDecl*) 0, (const Stmt*) 0));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005422 }
5423
5424 llvm::Value *Selector =
5425 CGF.Builder.CreateCall(llvm_eh_selector_i64,
5426 SelectorArgs.begin(), SelectorArgs.end(),
5427 "selector");
5428 for (unsigned i = 0, e = Handlers.size(); i != e; ++i) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005429 const ParmVarDecl *CatchParam = Handlers[i].first;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005430 const Stmt *CatchBody = Handlers[i].second;
5431
5432 llvm::BasicBlock *Next = 0;
5433
5434 // The last handler always matches.
5435 if (i + 1 != e) {
5436 assert(CatchParam && "Only last handler can be a catch all.");
5437
5438 llvm::BasicBlock *Match = CGF.createBasicBlock("match");
5439 Next = CGF.createBasicBlock("catch.next");
5440 llvm::Value *Id =
5441 CGF.Builder.CreateCall(llvm_eh_typeid_for_i64,
5442 CGF.Builder.CreateBitCast(SelectorArgs[i+2],
5443 ObjCTypes.Int8PtrTy));
5444 CGF.Builder.CreateCondBr(CGF.Builder.CreateICmpEQ(Selector, Id),
5445 Match, Next);
5446
5447 CGF.EmitBlock(Match);
5448 }
5449
5450 if (CatchBody) {
5451 llvm::BasicBlock *MatchEnd = CGF.createBasicBlock("match.end");
5452 llvm::BasicBlock *MatchHandler = CGF.createBasicBlock("match.handler");
5453
5454 // Cleanups must call objc_end_catch.
5455 //
5456 // FIXME: It seems incorrect for objc_begin_catch to be inside
5457 // this context, but this matches gcc.
5458 CGF.PushCleanupBlock(MatchEnd);
5459 CGF.setInvokeDest(MatchHandler);
5460
5461 llvm::Value *ExcObject =
Chris Lattner8a569112009-04-22 02:15:23 +00005462 CGF.Builder.CreateCall(ObjCTypes.getObjCBeginCatchFn(), Exc);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005463
5464 // Bind the catch parameter if it exists.
5465 if (CatchParam) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005466 ExcObject =
5467 CGF.Builder.CreateBitCast(ExcObject,
5468 CGF.ConvertType(CatchParam->getType()));
5469 // CatchParam is a ParmVarDecl because of the grammar
5470 // construction used to handle this, but for codegen purposes
5471 // we treat this as a local decl.
5472 CGF.EmitLocalBlockVarDecl(*CatchParam);
5473 CGF.Builder.CreateStore(ExcObject, CGF.GetAddrOfLocalVar(CatchParam));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005474 }
5475
5476 CGF.ObjCEHValueStack.push_back(ExcObject);
5477 CGF.EmitStmt(CatchBody);
5478 CGF.ObjCEHValueStack.pop_back();
5479
5480 CGF.EmitBranchThroughCleanup(FinallyEnd);
5481
5482 CGF.EmitBlock(MatchHandler);
5483
5484 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5485 // We are required to emit this call to satisfy LLVM, even
5486 // though we don't use the result.
5487 llvm::SmallVector<llvm::Value*, 8> Args;
5488 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005489 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005490 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5491 0));
5492 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5493 CGF.Builder.CreateStore(Exc, RethrowPtr);
5494 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5495
5496 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5497
5498 CGF.EmitBlock(MatchEnd);
5499
5500 // Unfortunately, we also have to generate another EH frame here
5501 // in case this throws.
5502 llvm::BasicBlock *MatchEndHandler =
5503 CGF.createBasicBlock("match.end.handler");
5504 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
Chris Lattner8a569112009-04-22 02:15:23 +00005505 CGF.Builder.CreateInvoke(ObjCTypes.getObjCEndCatchFn(),
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005506 Cont, MatchEndHandler,
5507 Args.begin(), Args.begin());
5508
5509 CGF.EmitBlock(Cont);
5510 if (Info.SwitchBlock)
5511 CGF.EmitBlock(Info.SwitchBlock);
5512 if (Info.EndBlock)
5513 CGF.EmitBlock(Info.EndBlock);
5514
5515 CGF.EmitBlock(MatchEndHandler);
5516 Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5517 // We are required to emit this call to satisfy LLVM, even
5518 // though we don't use the result.
5519 Args.clear();
5520 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005521 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005522 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5523 0));
5524 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5525 CGF.Builder.CreateStore(Exc, RethrowPtr);
5526 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5527
5528 if (Next)
5529 CGF.EmitBlock(Next);
5530 } else {
5531 assert(!Next && "catchup should be last handler.");
5532
5533 CGF.Builder.CreateStore(Exc, RethrowPtr);
5534 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5535 }
5536 }
5537
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005538 // Pop the cleanup entry, the @finally is outside this cleanup
5539 // scope.
5540 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5541 CGF.setInvokeDest(PrevLandingPad);
5542
5543 CGF.EmitBlock(FinallyBlock);
5544
5545 if (isTry) {
5546 if (const ObjCAtFinallyStmt* FinallyStmt =
5547 cast<ObjCAtTryStmt>(S).getFinallyStmt())
5548 CGF.EmitStmt(FinallyStmt->getFinallyBody());
5549 } else {
5550 // Emit 'objc_sync_exit(expr)' as finally's sole statement for
5551 // @synchronized.
Chris Lattnerbbccd612009-04-22 02:38:11 +00005552 CGF.Builder.CreateCall(ObjCTypes.getSyncExitFn(), SyncArg);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005553 }
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005554
5555 if (Info.SwitchBlock)
5556 CGF.EmitBlock(Info.SwitchBlock);
5557 if (Info.EndBlock)
5558 CGF.EmitBlock(Info.EndBlock);
5559
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005560 // Branch around the rethrow code.
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005561 CGF.EmitBranch(FinallyEnd);
5562
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005563 CGF.EmitBlock(FinallyRethrow);
Chris Lattner8a569112009-04-22 02:15:23 +00005564 CGF.Builder.CreateCall(ObjCTypes.getUnwindResumeOrRethrowFn(),
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005565 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005566 CGF.Builder.CreateUnreachable();
5567
5568 CGF.EmitBlock(FinallyEnd);
5569}
5570
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005571/// EmitThrowStmt - Generate code for a throw statement.
5572void CGObjCNonFragileABIMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
5573 const ObjCAtThrowStmt &S) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005574 llvm::Value *Exception;
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005575 if (const Expr *ThrowExpr = S.getThrowExpr()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005576 Exception = CGF.EmitScalarExpr(ThrowExpr);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005577 } else {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005578 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
5579 "Unexpected rethrow outside @catch block.");
5580 Exception = CGF.ObjCEHValueStack.back();
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005581 }
5582
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005583 llvm::Value *ExceptionAsObject =
5584 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
5585 llvm::BasicBlock *InvokeDest = CGF.getInvokeDest();
5586 if (InvokeDest) {
5587 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
Chris Lattnerbbccd612009-04-22 02:38:11 +00005588 CGF.Builder.CreateInvoke(ObjCTypes.getExceptionThrowFn(),
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005589 Cont, InvokeDest,
5590 &ExceptionAsObject, &ExceptionAsObject + 1);
5591 CGF.EmitBlock(Cont);
5592 } else
Chris Lattnerbbccd612009-04-22 02:38:11 +00005593 CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(), ExceptionAsObject);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005594 CGF.Builder.CreateUnreachable();
5595
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005596 // Clear the insertion point to indicate we are in unreachable code.
5597 CGF.Builder.ClearInsertionPoint();
5598}
Daniel Dunbare588b992009-03-01 04:46:24 +00005599
5600llvm::Value *
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005601CGObjCNonFragileABIMac::GetInterfaceEHType(const ObjCInterfaceDecl *ID,
5602 bool ForDefinition) {
Daniel Dunbare588b992009-03-01 04:46:24 +00005603 llvm::GlobalVariable * &Entry = EHTypeReferences[ID->getIdentifier()];
Daniel Dunbare588b992009-03-01 04:46:24 +00005604
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005605 // If we don't need a definition, return the entry if found or check
5606 // if we use an external reference.
5607 if (!ForDefinition) {
5608 if (Entry)
5609 return Entry;
Daniel Dunbar7e075cb2009-04-07 06:43:45 +00005610
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005611 // If this type (or a super class) has the __objc_exception__
5612 // attribute, emit an external reference.
5613 if (hasObjCExceptionAttribute(ID))
5614 return Entry =
5615 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5616 llvm::GlobalValue::ExternalLinkage,
5617 0,
5618 (std::string("OBJC_EHTYPE_$_") +
5619 ID->getIdentifier()->getName()),
5620 &CGM.getModule());
5621 }
5622
5623 // Otherwise we need to either make a new entry or fill in the
5624 // initializer.
5625 assert((!Entry || !Entry->hasInitializer()) && "Duplicate EHType definition");
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005626 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbare588b992009-03-01 04:46:24 +00005627 std::string VTableName = "objc_ehtype_vtable";
5628 llvm::GlobalVariable *VTableGV =
5629 CGM.getModule().getGlobalVariable(VTableName);
5630 if (!VTableGV)
5631 VTableGV = new llvm::GlobalVariable(ObjCTypes.Int8PtrTy, false,
5632 llvm::GlobalValue::ExternalLinkage,
5633 0, VTableName, &CGM.getModule());
5634
5635 llvm::Value *VTableIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, 2);
5636
5637 std::vector<llvm::Constant*> Values(3);
5638 Values[0] = llvm::ConstantExpr::getGetElementPtr(VTableGV, &VTableIdx, 1);
5639 Values[1] = GetClassName(ID->getIdentifier());
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005640 Values[2] = GetClassGlobal(ClassName);
Daniel Dunbare588b992009-03-01 04:46:24 +00005641 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.EHTypeTy, Values);
5642
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005643 if (Entry) {
5644 Entry->setInitializer(Init);
5645 } else {
5646 Entry = new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5647 llvm::GlobalValue::WeakAnyLinkage,
5648 Init,
5649 (std::string("OBJC_EHTYPE_$_") +
5650 ID->getIdentifier()->getName()),
5651 &CGM.getModule());
5652 }
5653
Daniel Dunbar04d40782009-04-14 06:00:08 +00005654 if (CGM.getLangOptions().getVisibilityMode() == LangOptions::Hidden)
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005655 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005656 Entry->setAlignment(8);
5657
5658 if (ForDefinition) {
5659 Entry->setSection("__DATA,__objc_const");
5660 Entry->setLinkage(llvm::GlobalValue::ExternalLinkage);
5661 } else {
5662 Entry->setSection("__DATA,__datacoal_nt,coalesced");
5663 }
Daniel Dunbare588b992009-03-01 04:46:24 +00005664
5665 return Entry;
5666}
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005667
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00005668/* *** */
5669
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00005670CodeGen::CGObjCRuntime *
5671CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00005672 return new CGObjCMac(CGM);
5673}
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005674
5675CodeGen::CGObjCRuntime *
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00005676CodeGen::CreateMacNonFragileABIObjCRuntime(CodeGen::CodeGenModule &CGM) {
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00005677 return new CGObjCNonFragileABIMac(CGM);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005678}