blob: 140c460c04e84eadd01a6d37dd72ed554708eb3d [file] [log] [blame]
Daniel Dunbar8c85fac2008-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 Dunbar1be1df32008-08-11 21:35:06 +000015
16#include "CodeGenModule.h"
Daniel Dunbarace33292008-08-16 03:19:19 +000017#include "CodeGenFunction.h"
Daniel Dunbardaf4ad42008-08-12 00:12:39 +000018#include "clang/AST/ASTContext.h"
Daniel Dunbarde300732008-08-11 04:54:23 +000019#include "clang/AST/Decl.h"
Daniel Dunbarcffcdac2008-08-13 03:21:16 +000020#include "clang/AST/DeclObjC.h"
Daniel Dunbar1be1df32008-08-11 21:35:06 +000021#include "clang/Basic/LangOptions.h"
22
Daniel Dunbar75de89f2009-02-24 07:47:38 +000023#include "llvm/Intrinsics.h"
Daniel Dunbardaf4ad42008-08-12 00:12:39 +000024#include "llvm/Module.h"
Daniel Dunbar35b777f2008-10-29 22:36:39 +000025#include "llvm/ADT/DenseSet.h"
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +000026#include "llvm/Target/TargetData.h"
Daniel Dunbarace33292008-08-16 03:19:19 +000027#include <sstream>
Daniel Dunbar8c85fac2008-08-11 02:45:11 +000028
29using namespace clang;
Daniel Dunbar0a2da0f2008-09-09 01:06:48 +000030using namespace CodeGen;
Daniel Dunbar8c85fac2008-08-11 02:45:11 +000031
Daniel Dunbar85d37542009-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
Daniel Dunbare5bb23c2009-04-22 09:39:34 +000036const llvm::StructType *
37CGObjCRuntime::GetConcreteClassStruct(CodeGen::CodeGenModule &CGM,
38 const ObjCInterfaceDecl *OID) {
39 assert(!OID->isForwardDecl() && "Invalid interface decl!");
Daniel Dunbarfa6fda42009-04-22 10:28:39 +000040 const RecordDecl *RD = CGM.getContext().addRecordToClass(OID);
41 return cast<llvm::StructType>(CGM.getTypes().ConvertTagDeclType(RD));
Daniel Dunbare5bb23c2009-04-22 09:39:34 +000042}
43
Daniel Dunbarfb65bfb2009-04-22 12:00:04 +000044
45/// LookupFieldDeclForIvar - looks up a field decl in the laid out
46/// storage which matches this 'ivar'.
47///
48static const FieldDecl *LookupFieldDeclForIvar(ASTContext &Context,
49 const ObjCInterfaceDecl *OID,
Daniel Dunbar1af336e2009-04-22 17:43:55 +000050 const ObjCIvarDecl *OIVD,
51 const ObjCInterfaceDecl *&Found) {
Daniel Dunbarfb65bfb2009-04-22 12:00:04 +000052 assert(!OID->isForwardDecl() && "Invalid interface decl!");
53 const RecordDecl *RecordForDecl = Context.addRecordToClass(OID);
54 assert(RecordForDecl && "lookupFieldDeclForIvar no storage for class");
55 DeclContext::lookup_const_result Lookup =
56 RecordForDecl->lookup(Context, OIVD->getDeclName());
Daniel Dunbar1af336e2009-04-22 17:43:55 +000057
58 if (Lookup.first != Lookup.second) {
59 Found = OID;
60 return cast<FieldDecl>(*Lookup.first);
61 }
62
63 // If lookup failed, try the superclass.
64 //
65 // FIXME: This is slow, we shouldn't need to do this.
66 const ObjCInterfaceDecl *Super = OID->getSuperClass();
67 assert(OID && "field decl not found!");
68 return LookupFieldDeclForIvar(Context, Super, OIVD, Found);
Daniel Dunbarfb65bfb2009-04-22 12:00:04 +000069}
70
Daniel Dunbar85d37542009-04-22 07:32:20 +000071uint64_t CGObjCRuntime::ComputeIvarBaseOffset(CodeGen::CodeGenModule &CGM,
72 const ObjCInterfaceDecl *OID,
73 const ObjCIvarDecl *Ivar) {
74 assert(!OID->isForwardDecl() && "Invalid interface decl!");
Daniel Dunbar1af336e2009-04-22 17:43:55 +000075 const ObjCInterfaceDecl *Container;
76 const FieldDecl *Field =
77 LookupFieldDeclForIvar(CGM.getContext(), OID, Ivar, Container);
78 QualType T = CGM.getContext().getObjCInterfaceType(Container);
79 const llvm::StructType *STy = GetConcreteClassStruct(CGM, Container);
Daniel Dunbar85d37542009-04-22 07:32:20 +000080 const llvm::StructLayout *Layout =
Daniel Dunbare5bb23c2009-04-22 09:39:34 +000081 CGM.getTargetData().getStructLayout(STy);
Daniel Dunbar85d37542009-04-22 07:32:20 +000082 if (!Field->isBitField())
83 return Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(Field));
84
85 // FIXME. Must be a better way of getting a bitfield base offset.
86 CodeGenTypes::BitFieldInfo BFI = CGM.getTypes().getBitFieldInfo(Field);
87 // FIXME: The "field no" for bitfields is something completely
88 // different; it is the offset in multiples of the base type size!
89 uint64_t Offset = CGM.getTypes().getLLVMFieldNo(Field);
90 const llvm::Type *Ty =
91 CGM.getTypes().ConvertTypeForMemRecursive(Field->getType());
92 Offset *= CGM.getTypes().getTargetData().getTypePaddedSizeInBits(Ty);
93 return (Offset + BFI.Begin) / 8;
94}
95
96LValue CGObjCRuntime::EmitValueForIvarAtOffset(CodeGen::CodeGenFunction &CGF,
97 const ObjCInterfaceDecl *OID,
98 llvm::Value *BaseValue,
99 const ObjCIvarDecl *Ivar,
100 unsigned CVRQualifiers,
101 llvm::Value *Offset) {
Daniel Dunbarfa6fda42009-04-22 10:28:39 +0000102 // Force generation of the codegen information for this structure.
103 //
104 // FIXME: Remove once we don't use the bit-field lookup map.
105 (void) GetConcreteClassStruct(CGF.CGM, OID);
106
Daniel Dunbar85d37542009-04-22 07:32:20 +0000107 // FIXME: For now, we use an implementation based on just computing
108 // the offset and calculating things directly. For optimization
109 // purposes, it would be cleaner to use a GEP on the proper type
110 // since the structure layout is fixed; however for that we need to
111 // be able to walk the class chain for an Ivar.
Daniel Dunbar1af336e2009-04-22 17:43:55 +0000112 const ObjCInterfaceDecl *Container;
Daniel Dunbar85d37542009-04-22 07:32:20 +0000113 const FieldDecl *Field =
Daniel Dunbar1af336e2009-04-22 17:43:55 +0000114 LookupFieldDeclForIvar(CGF.CGM.getContext(), OID, Ivar, Container);
Daniel Dunbar85d37542009-04-22 07:32:20 +0000115
116 // (char *) BaseValue
117 llvm::Type *I8Ptr = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
118 llvm::Value *V = CGF.Builder.CreateBitCast(BaseValue, I8Ptr);
119 // (char*)BaseValue + Offset_symbol
120 V = CGF.Builder.CreateGEP(V, Offset, "add.ptr");
121 // (type *)((char*)BaseValue + Offset_symbol)
122 const llvm::Type *IvarTy =
123 CGF.CGM.getTypes().ConvertTypeForMem(Ivar->getType());
124 llvm::Type *ptrIvarTy = llvm::PointerType::getUnqual(IvarTy);
125 V = CGF.Builder.CreateBitCast(V, ptrIvarTy);
126
127 if (Ivar->isBitField()) {
128 QualType FieldTy = Field->getType();
129 CodeGenTypes::BitFieldInfo bitFieldInfo =
130 CGF.CGM.getTypes().getBitFieldInfo(Field);
131 return LValue::MakeBitfield(V, bitFieldInfo.Begin % 8, bitFieldInfo.Size,
132 FieldTy->isSignedIntegerType(),
133 FieldTy.getCVRQualifiers()|CVRQualifiers);
134 }
135
136 LValue LV = LValue::MakeAddr(V,
137 Ivar->getType().getCVRQualifiers()|CVRQualifiers,
138 CGF.CGM.getContext().getObjCGCAttrKind(Ivar->getType()));
139 LValue::SetObjCIvar(LV, true);
140 return LV;
141}
142
143///
144
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000145namespace {
Daniel Dunbardaf4ad42008-08-12 00:12:39 +0000146
Daniel Dunbarfe131f02008-08-27 02:31:56 +0000147 typedef std::vector<llvm::Constant*> ConstantVector;
148
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000149 // FIXME: We should find a nicer way to make the labels for
150 // metadata, string concatenation is lame.
151
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000152class ObjCCommonTypesHelper {
153protected:
154 CodeGen::CodeGenModule &CGM;
Daniel Dunbardaf4ad42008-08-12 00:12:39 +0000155
Daniel Dunbardaf4ad42008-08-12 00:12:39 +0000156public:
Fariborz Jahanianad51ca02009-03-23 19:10:40 +0000157 const llvm::Type *ShortTy, *IntTy, *LongTy, *LongLongTy;
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000158 const llvm::Type *Int8PtrTy;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000159
Daniel Dunbar6fa3daf2008-08-12 05:28:47 +0000160 /// ObjectPtrTy - LLVM type for object handles (typeof(id))
161 const llvm::Type *ObjectPtrTy;
Fariborz Jahanianc192d4d2008-11-18 20:18:11 +0000162
163 /// PtrObjectPtrTy - LLVM type for id *
164 const llvm::Type *PtrObjectPtrTy;
165
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +0000166 /// SelectorPtrTy - LLVM type for selector handles (typeof(SEL))
Daniel Dunbar6fa3daf2008-08-12 05:28:47 +0000167 const llvm::Type *SelectorPtrTy;
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000168 /// ProtocolPtrTy - LLVM type for external protocol handles
169 /// (typeof(Protocol))
170 const llvm::Type *ExternalProtocolPtrTy;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000171
Daniel Dunbar0ed60b02008-08-30 03:02:31 +0000172 // SuperCTy - clang type for struct objc_super.
173 QualType SuperCTy;
174 // SuperPtrCTy - clang type for struct objc_super *.
175 QualType SuperPtrCTy;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000176
Daniel Dunbar15245e52008-08-23 04:28:29 +0000177 /// SuperTy - LLVM type for struct objc_super.
178 const llvm::StructType *SuperTy;
Daniel Dunbar87062ff2008-08-23 09:25:55 +0000179 /// SuperPtrTy - LLVM type for struct objc_super *.
180 const llvm::Type *SuperPtrTy;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000181
Fariborz Jahaniand0374812009-01-22 23:02:58 +0000182 /// PropertyTy - LLVM type for struct objc_property (struct _prop_t
183 /// in GCC parlance).
184 const llvm::StructType *PropertyTy;
185
186 /// PropertyListTy - LLVM type for struct objc_property_list
187 /// (_prop_list_t in GCC parlance).
188 const llvm::StructType *PropertyListTy;
189 /// PropertyListPtrTy - LLVM type for struct objc_property_list*.
190 const llvm::Type *PropertyListPtrTy;
191
192 // MethodTy - LLVM type for struct objc_method.
193 const llvm::StructType *MethodTy;
194
Fariborz Jahanian781f2732009-01-23 01:46:23 +0000195 /// CacheTy - LLVM type for struct objc_cache.
196 const llvm::Type *CacheTy;
197 /// CachePtrTy - LLVM type for struct objc_cache *.
198 const llvm::Type *CachePtrTy;
199
Chris Lattnera7ecda42009-04-22 02:44:54 +0000200 llvm::Constant *getGetPropertyFn() {
201 CodeGen::CodeGenTypes &Types = CGM.getTypes();
202 ASTContext &Ctx = CGM.getContext();
203 // id objc_getProperty (id, SEL, ptrdiff_t, bool)
204 llvm::SmallVector<QualType,16> Params;
205 QualType IdType = Ctx.getObjCIdType();
206 QualType SelType = Ctx.getObjCSelType();
207 Params.push_back(IdType);
208 Params.push_back(SelType);
209 Params.push_back(Ctx.LongTy);
210 Params.push_back(Ctx.BoolTy);
211 const llvm::FunctionType *FTy =
212 Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
213 return CGM.CreateRuntimeFunction(FTy, "objc_getProperty");
214 }
Fariborz Jahanian4b161702009-01-22 00:37:21 +0000215
Chris Lattnera7ecda42009-04-22 02:44:54 +0000216 llvm::Constant *getSetPropertyFn() {
217 CodeGen::CodeGenTypes &Types = CGM.getTypes();
218 ASTContext &Ctx = CGM.getContext();
219 // void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool)
220 llvm::SmallVector<QualType,16> Params;
221 QualType IdType = Ctx.getObjCIdType();
222 QualType SelType = Ctx.getObjCSelType();
223 Params.push_back(IdType);
224 Params.push_back(SelType);
225 Params.push_back(Ctx.LongTy);
226 Params.push_back(IdType);
227 Params.push_back(Ctx.BoolTy);
228 Params.push_back(Ctx.BoolTy);
229 const llvm::FunctionType *FTy =
230 Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
231 return CGM.CreateRuntimeFunction(FTy, "objc_setProperty");
232 }
233
234 llvm::Constant *getEnumerationMutationFn() {
235 // void objc_enumerationMutation (id)
236 std::vector<const llvm::Type*> Args;
237 Args.push_back(ObjectPtrTy);
238 llvm::FunctionType *FTy =
239 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
240 return CGM.CreateRuntimeFunction(FTy, "objc_enumerationMutation");
241 }
Fariborz Jahanian4b161702009-01-22 00:37:21 +0000242
243 /// GcReadWeakFn -- LLVM objc_read_weak (id *src) function.
Chris Lattnera7ecda42009-04-22 02:44:54 +0000244 llvm::Constant *getGcReadWeakFn() {
245 // id objc_read_weak (id *)
246 std::vector<const llvm::Type*> Args;
247 Args.push_back(ObjectPtrTy->getPointerTo());
248 llvm::FunctionType *FTy = llvm::FunctionType::get(ObjectPtrTy, Args, false);
249 return CGM.CreateRuntimeFunction(FTy, "objc_read_weak");
250 }
Fariborz Jahanian4b161702009-01-22 00:37:21 +0000251
252 /// GcAssignWeakFn -- LLVM objc_assign_weak function.
Chris Lattner293c1d32009-04-17 22:12:36 +0000253 llvm::Constant *getGcAssignWeakFn() {
254 // id objc_assign_weak (id, id *)
255 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
256 Args.push_back(ObjectPtrTy->getPointerTo());
257 llvm::FunctionType *FTy =
258 llvm::FunctionType::get(ObjectPtrTy, Args, false);
259 return CGM.CreateRuntimeFunction(FTy, "objc_assign_weak");
260 }
Fariborz Jahanian4b161702009-01-22 00:37:21 +0000261
262 /// GcAssignGlobalFn -- LLVM objc_assign_global function.
Chris Lattnerf6ec7e42009-04-22 02:38:11 +0000263 llvm::Constant *getGcAssignGlobalFn() {
264 // id objc_assign_global(id, id *)
265 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
266 Args.push_back(ObjectPtrTy->getPointerTo());
267 llvm::FunctionType *FTy = llvm::FunctionType::get(ObjectPtrTy, Args, false);
268 return CGM.CreateRuntimeFunction(FTy, "objc_assign_global");
269 }
Fariborz Jahanian4b161702009-01-22 00:37:21 +0000270
271 /// GcAssignIvarFn -- LLVM objc_assign_ivar function.
Chris Lattnerf6ec7e42009-04-22 02:38:11 +0000272 llvm::Constant *getGcAssignIvarFn() {
273 // id objc_assign_ivar(id, id *)
274 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
275 Args.push_back(ObjectPtrTy->getPointerTo());
276 llvm::FunctionType *FTy = llvm::FunctionType::get(ObjectPtrTy, Args, false);
277 return CGM.CreateRuntimeFunction(FTy, "objc_assign_ivar");
278 }
Fariborz Jahanian4b161702009-01-22 00:37:21 +0000279
280 /// GcAssignStrongCastFn -- LLVM objc_assign_strongCast function.
Chris Lattnerf6ec7e42009-04-22 02:38:11 +0000281 llvm::Constant *getGcAssignStrongCastFn() {
282 // id objc_assign_global(id, id *)
283 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
284 Args.push_back(ObjectPtrTy->getPointerTo());
285 llvm::FunctionType *FTy = llvm::FunctionType::get(ObjectPtrTy, Args, false);
286 return CGM.CreateRuntimeFunction(FTy, "objc_assign_strongCast");
287 }
Anders Carlsson1cf75362009-02-16 22:59:18 +0000288
289 /// ExceptionThrowFn - LLVM objc_exception_throw function.
Chris Lattnerf6ec7e42009-04-22 02:38:11 +0000290 llvm::Constant *getExceptionThrowFn() {
291 // void objc_exception_throw(id)
292 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
293 llvm::FunctionType *FTy =
294 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
295 return CGM.CreateRuntimeFunction(FTy, "objc_exception_throw");
296 }
Anders Carlsson1cf75362009-02-16 22:59:18 +0000297
Daniel Dunbar34416d62009-02-24 01:43:46 +0000298 /// SyncEnterFn - LLVM object_sync_enter function.
Chris Lattner23e24652009-04-06 16:53:45 +0000299 llvm::Constant *getSyncEnterFn() {
300 // void objc_sync_enter (id)
301 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
302 llvm::FunctionType *FTy =
303 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
304 return CGM.CreateRuntimeFunction(FTy, "objc_sync_enter");
305 }
Daniel Dunbar34416d62009-02-24 01:43:46 +0000306
307 /// SyncExitFn - LLVM object_sync_exit function.
Chris Lattnerf6ec7e42009-04-22 02:38:11 +0000308 llvm::Constant *getSyncExitFn() {
309 // void objc_sync_exit (id)
310 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
311 llvm::FunctionType *FTy =
312 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
313 return CGM.CreateRuntimeFunction(FTy, "objc_sync_exit");
314 }
Daniel Dunbar34416d62009-02-24 01:43:46 +0000315
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000316 ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm);
317 ~ObjCCommonTypesHelper(){}
318};
Daniel Dunbar15245e52008-08-23 04:28:29 +0000319
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000320/// ObjCTypesHelper - Helper class that encapsulates lazy
321/// construction of varies types used during ObjC generation.
322class ObjCTypesHelper : public ObjCCommonTypesHelper {
323private:
324
Chris Lattner61114192009-04-22 02:32:31 +0000325 llvm::Constant *getMessageSendFn() {
326 // id objc_msgSend (id, SEL, ...)
327 std::vector<const llvm::Type*> Params;
328 Params.push_back(ObjectPtrTy);
329 Params.push_back(SelectorPtrTy);
330 return
331 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
332 Params, true),
333 "objc_msgSend");
334 }
335
336 llvm::Constant *getMessageSendStretFn() {
337 // id objc_msgSend_stret (id, SEL, ...)
338 std::vector<const llvm::Type*> Params;
339 Params.push_back(ObjectPtrTy);
340 Params.push_back(SelectorPtrTy);
341 return
342 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
343 Params, true),
344 "objc_msgSend_stret");
345
346 }
347
348 llvm::Constant *getMessageSendFpretFn() {
349 // FIXME: This should be long double on x86_64?
350 // [double | long double] objc_msgSend_fpret(id self, SEL op, ...)
351 std::vector<const llvm::Type*> Params;
352 Params.push_back(ObjectPtrTy);
353 Params.push_back(SelectorPtrTy);
354 return
355 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::DoubleTy,
356 Params,
357 true),
358 "objc_msgSend_fpret");
359
360 }
361
362 llvm::Constant *getMessageSendSuperFn() {
363 // id objc_msgSendSuper(struct objc_super *super, SEL op, ...)
364 std::vector<const llvm::Type*> Params;
365 Params.push_back(SuperPtrTy);
366 Params.push_back(SelectorPtrTy);
367 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
368 Params, true),
369 "objc_msgSendSuper");
370 }
371 llvm::Constant *getMessageSendSuperStretFn() {
372 // void objc_msgSendSuper_stret(void * stretAddr, struct objc_super *super,
373 // SEL op, ...)
374 std::vector<const llvm::Type*> Params;
375 Params.push_back(Int8PtrTy);
376 Params.push_back(SuperPtrTy);
377 Params.push_back(SelectorPtrTy);
378 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
379 Params, true),
380 "objc_msgSendSuper_stret");
381 }
382
383 llvm::Constant *getMessageSendSuperFpretFn() {
384 // There is no objc_msgSendSuper_fpret? How can that work?
385 return getMessageSendSuperFn();
386 }
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000387
388public:
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +0000389 /// SymtabTy - LLVM type for struct objc_symtab.
390 const llvm::StructType *SymtabTy;
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000391 /// SymtabPtrTy - LLVM type for struct objc_symtab *.
392 const llvm::Type *SymtabPtrTy;
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +0000393 /// ModuleTy - LLVM type for struct objc_module.
394 const llvm::StructType *ModuleTy;
Daniel Dunbar5eec6142008-08-12 03:39:23 +0000395
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000396 /// ProtocolTy - LLVM type for struct objc_protocol.
397 const llvm::StructType *ProtocolTy;
398 /// ProtocolPtrTy - LLVM type for struct objc_protocol *.
399 const llvm::Type *ProtocolPtrTy;
400 /// ProtocolExtensionTy - LLVM type for struct
401 /// objc_protocol_extension.
402 const llvm::StructType *ProtocolExtensionTy;
403 /// ProtocolExtensionTy - LLVM type for struct
404 /// objc_protocol_extension *.
405 const llvm::Type *ProtocolExtensionPtrTy;
406 /// MethodDescriptionTy - LLVM type for struct
407 /// objc_method_description.
408 const llvm::StructType *MethodDescriptionTy;
409 /// MethodDescriptionListTy - LLVM type for struct
410 /// objc_method_description_list.
411 const llvm::StructType *MethodDescriptionListTy;
412 /// MethodDescriptionListPtrTy - LLVM type for struct
413 /// objc_method_description_list *.
414 const llvm::Type *MethodDescriptionListPtrTy;
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000415 /// ProtocolListTy - LLVM type for struct objc_property_list.
416 const llvm::Type *ProtocolListTy;
417 /// ProtocolListPtrTy - LLVM type for struct objc_property_list*.
418 const llvm::Type *ProtocolListPtrTy;
Daniel Dunbar4246a8b2008-08-22 20:34:54 +0000419 /// CategoryTy - LLVM type for struct objc_category.
420 const llvm::StructType *CategoryTy;
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000421 /// ClassTy - LLVM type for struct objc_class.
422 const llvm::StructType *ClassTy;
423 /// ClassPtrTy - LLVM type for struct objc_class *.
424 const llvm::Type *ClassPtrTy;
425 /// ClassExtensionTy - LLVM type for struct objc_class_ext.
426 const llvm::StructType *ClassExtensionTy;
427 /// ClassExtensionPtrTy - LLVM type for struct objc_class_ext *.
428 const llvm::Type *ClassExtensionPtrTy;
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000429 // IvarTy - LLVM type for struct objc_ivar.
430 const llvm::StructType *IvarTy;
431 /// IvarListTy - LLVM type for struct objc_ivar_list.
432 const llvm::Type *IvarListTy;
433 /// IvarListPtrTy - LLVM type for struct objc_ivar_list *.
434 const llvm::Type *IvarListPtrTy;
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000435 /// MethodListTy - LLVM type for struct objc_method_list.
436 const llvm::Type *MethodListTy;
437 /// MethodListPtrTy - LLVM type for struct objc_method_list *.
438 const llvm::Type *MethodListPtrTy;
Anders Carlsson9acb0a42008-09-09 10:10:21 +0000439
440 /// ExceptionDataTy - LLVM type for struct _objc_exception_data.
441 const llvm::Type *ExceptionDataTy;
442
Anders Carlsson9acb0a42008-09-09 10:10:21 +0000443 /// ExceptionTryEnterFn - LLVM objc_exception_try_enter function.
Chris Lattnere05d4cb2009-04-22 02:26:14 +0000444 llvm::Constant *getExceptionTryEnterFn() {
445 std::vector<const llvm::Type*> Params;
446 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
447 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
448 Params, false),
449 "objc_exception_try_enter");
450 }
Anders Carlsson9acb0a42008-09-09 10:10:21 +0000451
452 /// ExceptionTryExitFn - LLVM objc_exception_try_exit function.
Chris Lattnere05d4cb2009-04-22 02:26:14 +0000453 llvm::Constant *getExceptionTryExitFn() {
454 std::vector<const llvm::Type*> Params;
455 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
456 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
457 Params, false),
458 "objc_exception_try_exit");
459 }
Anders Carlsson9acb0a42008-09-09 10:10:21 +0000460
461 /// ExceptionExtractFn - LLVM objc_exception_extract function.
Chris Lattnere05d4cb2009-04-22 02:26:14 +0000462 llvm::Constant *getExceptionExtractFn() {
463 std::vector<const llvm::Type*> Params;
464 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
465 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
466 Params, false),
467 "objc_exception_extract");
468
469 }
Anders Carlsson9acb0a42008-09-09 10:10:21 +0000470
471 /// ExceptionMatchFn - LLVM objc_exception_match function.
Chris Lattnere05d4cb2009-04-22 02:26:14 +0000472 llvm::Constant *getExceptionMatchFn() {
473 std::vector<const llvm::Type*> Params;
474 Params.push_back(ClassPtrTy);
475 Params.push_back(ObjectPtrTy);
476 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
477 Params, false),
478 "objc_exception_match");
479
480 }
Anders Carlsson9acb0a42008-09-09 10:10:21 +0000481
482 /// SetJmpFn - LLVM _setjmp function.
Chris Lattnere05d4cb2009-04-22 02:26:14 +0000483 llvm::Constant *getSetJmpFn() {
484 std::vector<const llvm::Type*> Params;
485 Params.push_back(llvm::PointerType::getUnqual(llvm::Type::Int32Ty));
486 return
487 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
488 Params, false),
489 "_setjmp");
490
491 }
Chris Lattnerdd978702008-11-15 21:26:17 +0000492
Daniel Dunbardaf4ad42008-08-12 00:12:39 +0000493public:
494 ObjCTypesHelper(CodeGen::CodeGenModule &cgm);
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000495 ~ObjCTypesHelper() {}
Daniel Dunbaraecef4c2008-10-17 03:24:53 +0000496
497
Chris Lattneraea1aee2009-03-22 21:03:39 +0000498 llvm::Constant *getSendFn(bool IsSuper) {
Chris Lattner61114192009-04-22 02:32:31 +0000499 return IsSuper ? getMessageSendSuperFn() : getMessageSendFn();
Daniel Dunbaraecef4c2008-10-17 03:24:53 +0000500 }
501
Chris Lattneraea1aee2009-03-22 21:03:39 +0000502 llvm::Constant *getSendStretFn(bool IsSuper) {
Chris Lattner61114192009-04-22 02:32:31 +0000503 return IsSuper ? getMessageSendSuperStretFn() : getMessageSendStretFn();
Daniel Dunbaraecef4c2008-10-17 03:24:53 +0000504 }
505
Chris Lattneraea1aee2009-03-22 21:03:39 +0000506 llvm::Constant *getSendFpretFn(bool IsSuper) {
Chris Lattner61114192009-04-22 02:32:31 +0000507 return IsSuper ? getMessageSendSuperFpretFn() : getMessageSendFpretFn();
Daniel Dunbaraecef4c2008-10-17 03:24:53 +0000508 }
Daniel Dunbardaf4ad42008-08-12 00:12:39 +0000509};
510
Fariborz Jahaniand0374812009-01-22 23:02:58 +0000511/// ObjCNonFragileABITypesHelper - will have all types needed by objective-c's
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000512/// modern abi
Fariborz Jahaniand0374812009-01-22 23:02:58 +0000513class ObjCNonFragileABITypesHelper : public ObjCCommonTypesHelper {
Fariborz Jahanianf52110f2009-02-04 20:42:28 +0000514public:
Fariborz Jahanian711e8dd2009-02-03 23:49:23 +0000515
Fariborz Jahanian781f2732009-01-23 01:46:23 +0000516 // MethodListnfABITy - LLVM for struct _method_list_t
517 const llvm::StructType *MethodListnfABITy;
518
519 // MethodListnfABIPtrTy - LLVM for struct _method_list_t*
520 const llvm::Type *MethodListnfABIPtrTy;
521
522 // ProtocolnfABITy = LLVM for struct _protocol_t
523 const llvm::StructType *ProtocolnfABITy;
524
Daniel Dunbar1f42bb02009-02-15 07:36:20 +0000525 // ProtocolnfABIPtrTy = LLVM for struct _protocol_t*
526 const llvm::Type *ProtocolnfABIPtrTy;
527
Fariborz Jahanian781f2732009-01-23 01:46:23 +0000528 // ProtocolListnfABITy - LLVM for struct _objc_protocol_list
529 const llvm::StructType *ProtocolListnfABITy;
530
531 // ProtocolListnfABIPtrTy - LLVM for struct _objc_protocol_list*
532 const llvm::Type *ProtocolListnfABIPtrTy;
533
534 // ClassnfABITy - LLVM for struct _class_t
535 const llvm::StructType *ClassnfABITy;
536
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +0000537 // ClassnfABIPtrTy - LLVM for struct _class_t*
538 const llvm::Type *ClassnfABIPtrTy;
539
Fariborz Jahanian781f2732009-01-23 01:46:23 +0000540 // IvarnfABITy - LLVM for struct _ivar_t
541 const llvm::StructType *IvarnfABITy;
542
543 // IvarListnfABITy - LLVM for struct _ivar_list_t
544 const llvm::StructType *IvarListnfABITy;
545
546 // IvarListnfABIPtrTy = LLVM for struct _ivar_list_t*
547 const llvm::Type *IvarListnfABIPtrTy;
548
549 // ClassRonfABITy - LLVM for struct _class_ro_t
550 const llvm::StructType *ClassRonfABITy;
551
552 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
553 const llvm::Type *ImpnfABITy;
554
555 // CategorynfABITy - LLVM for struct _category_t
556 const llvm::StructType *CategorynfABITy;
557
Fariborz Jahanian711e8dd2009-02-03 23:49:23 +0000558 // New types for nonfragile abi messaging.
559
560 // MessageRefTy - LLVM for:
561 // struct _message_ref_t {
562 // IMP messenger;
563 // SEL name;
564 // };
565 const llvm::StructType *MessageRefTy;
Fariborz Jahanianf52110f2009-02-04 20:42:28 +0000566 // MessageRefCTy - clang type for struct _message_ref_t
567 QualType MessageRefCTy;
Fariborz Jahanian711e8dd2009-02-03 23:49:23 +0000568
569 // MessageRefPtrTy - LLVM for struct _message_ref_t*
570 const llvm::Type *MessageRefPtrTy;
Fariborz Jahanianf52110f2009-02-04 20:42:28 +0000571 // MessageRefCPtrTy - clang type for struct _message_ref_t*
572 QualType MessageRefCPtrTy;
Fariborz Jahanian711e8dd2009-02-03 23:49:23 +0000573
Fariborz Jahanian10d69ea2009-02-05 01:13:09 +0000574 // MessengerTy - Type of the messenger (shown as IMP above)
575 const llvm::FunctionType *MessengerTy;
576
Fariborz Jahanian711e8dd2009-02-03 23:49:23 +0000577 // SuperMessageRefTy - LLVM for:
578 // struct _super_message_ref_t {
579 // SUPER_IMP messenger;
580 // SEL name;
581 // };
582 const llvm::StructType *SuperMessageRefTy;
583
584 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
585 const llvm::Type *SuperMessageRefPtrTy;
Daniel Dunbar75de89f2009-02-24 07:47:38 +0000586
Chris Lattnerada416b2009-04-22 02:53:24 +0000587 llvm::Constant *getMessageSendFixupFn() {
588 // id objc_msgSend_fixup(id, struct message_ref_t*, ...)
589 std::vector<const llvm::Type*> Params;
590 Params.push_back(ObjectPtrTy);
591 Params.push_back(MessageRefPtrTy);
592 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
593 Params, true),
594 "objc_msgSend_fixup");
595 }
596
597 llvm::Constant *getMessageSendFpretFixupFn() {
598 // id objc_msgSend_fpret_fixup(id, struct message_ref_t*, ...)
599 std::vector<const llvm::Type*> Params;
600 Params.push_back(ObjectPtrTy);
601 Params.push_back(MessageRefPtrTy);
602 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
603 Params, true),
604 "objc_msgSend_fpret_fixup");
605 }
606
607 llvm::Constant *getMessageSendStretFixupFn() {
608 // id objc_msgSend_stret_fixup(id, struct message_ref_t*, ...)
609 std::vector<const llvm::Type*> Params;
610 Params.push_back(ObjectPtrTy);
611 Params.push_back(MessageRefPtrTy);
612 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
613 Params, true),
614 "objc_msgSend_stret_fixup");
615 }
616
617 llvm::Constant *getMessageSendIdFixupFn() {
618 // id objc_msgSendId_fixup(id, struct message_ref_t*, ...)
619 std::vector<const llvm::Type*> Params;
620 Params.push_back(ObjectPtrTy);
621 Params.push_back(MessageRefPtrTy);
622 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
623 Params, true),
624 "objc_msgSendId_fixup");
625 }
626
627 llvm::Constant *getMessageSendIdStretFixupFn() {
628 // id objc_msgSendId_stret_fixup(id, struct message_ref_t*, ...)
629 std::vector<const llvm::Type*> Params;
630 Params.push_back(ObjectPtrTy);
631 Params.push_back(MessageRefPtrTy);
632 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
633 Params, true),
634 "objc_msgSendId_stret_fixup");
635 }
636 llvm::Constant *getMessageSendSuper2FixupFn() {
637 // id objc_msgSendSuper2_fixup (struct objc_super *,
638 // struct _super_message_ref_t*, ...)
639 std::vector<const llvm::Type*> Params;
640 Params.push_back(SuperPtrTy);
641 Params.push_back(SuperMessageRefPtrTy);
642 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
643 Params, true),
644 "objc_msgSendSuper2_fixup");
645 }
646
647 llvm::Constant *getMessageSendSuper2StretFixupFn() {
648 // id objc_msgSendSuper2_stret_fixup(struct objc_super *,
649 // struct _super_message_ref_t*, ...)
650 std::vector<const llvm::Type*> Params;
651 Params.push_back(SuperPtrTy);
652 Params.push_back(SuperMessageRefPtrTy);
653 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
654 Params, true),
655 "objc_msgSendSuper2_stret_fixup");
656 }
657
658
659
Daniel Dunbar75de89f2009-02-24 07:47:38 +0000660 /// EHPersonalityPtr - LLVM value for an i8* to the Objective-C
661 /// exception personality function.
Chris Lattner23e24652009-04-06 16:53:45 +0000662 llvm::Value *getEHPersonalityPtr() {
663 llvm::Constant *Personality =
664 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
665 std::vector<const llvm::Type*>(),
666 true),
667 "__objc_personality_v0");
668 return llvm::ConstantExpr::getBitCast(Personality, Int8PtrTy);
669 }
Daniel Dunbar75de89f2009-02-24 07:47:38 +0000670
Chris Lattner93dca5b2009-04-22 02:15:23 +0000671 llvm::Constant *getUnwindResumeOrRethrowFn() {
672 std::vector<const llvm::Type*> Params;
673 Params.push_back(Int8PtrTy);
674 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
675 Params, false),
676 "_Unwind_Resume_or_Rethrow");
677 }
678
679 llvm::Constant *getObjCEndCatchFn() {
680 std::vector<const llvm::Type*> Params;
681 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
682 Params, false),
683 "objc_end_catch");
684
685 }
686
687 llvm::Constant *getObjCBeginCatchFn() {
688 std::vector<const llvm::Type*> Params;
689 Params.push_back(Int8PtrTy);
690 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(Int8PtrTy,
691 Params, false),
692 "objc_begin_catch");
693 }
Daniel Dunbar9c285e72009-03-01 04:46:24 +0000694
695 const llvm::StructType *EHTypeTy;
696 const llvm::Type *EHTypePtrTy;
Daniel Dunbar75de89f2009-02-24 07:47:38 +0000697
Fariborz Jahaniand0374812009-01-22 23:02:58 +0000698 ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm);
699 ~ObjCNonFragileABITypesHelper(){}
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000700};
701
702class CGObjCCommonMac : public CodeGen::CGObjCRuntime {
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +0000703public:
704 // FIXME - accessibility
Fariborz Jahanian37931062009-03-10 16:22:08 +0000705 class GC_IVAR {
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +0000706 public:
Fariborz Jahanian37931062009-03-10 16:22:08 +0000707 unsigned int ivar_bytepos;
708 unsigned int ivar_size;
709 GC_IVAR() : ivar_bytepos(0), ivar_size(0) {}
Daniel Dunbar48445182009-04-23 01:29:05 +0000710
711 // Allow sorting based on byte pos.
712 bool operator<(const GC_IVAR &b) const {
713 return ivar_bytepos < b.ivar_bytepos;
714 }
Fariborz Jahanian37931062009-03-10 16:22:08 +0000715 };
716
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +0000717 class SKIP_SCAN {
718 public:
719 unsigned int skip;
720 unsigned int scan;
721 SKIP_SCAN() : skip(0), scan(0) {}
722 };
723
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000724protected:
725 CodeGen::CodeGenModule &CGM;
726 // FIXME! May not be needing this after all.
Daniel Dunbardaf4ad42008-08-12 00:12:39 +0000727 unsigned ObjCABI;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000728
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +0000729 // gc ivar layout bitmap calculation helper caches.
730 llvm::SmallVector<GC_IVAR, 16> SkipIvars;
731 llvm::SmallVector<GC_IVAR, 16> IvarsInfo;
732 llvm::SmallVector<SKIP_SCAN, 32> SkipScanIvars;
Fariborz Jahanian37931062009-03-10 16:22:08 +0000733
Daniel Dunbar8ede0052008-08-25 06:02:07 +0000734 /// LazySymbols - Symbols to generate a lazy reference for. See
735 /// DefinedSymbols and FinishModule().
736 std::set<IdentifierInfo*> LazySymbols;
737
738 /// DefinedSymbols - External symbols which are defined by this
739 /// module. The symbols in this list and LazySymbols are used to add
740 /// special linker symbols which ensure that Objective-C modules are
741 /// linked properly.
742 std::set<IdentifierInfo*> DefinedSymbols;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000743
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +0000744 /// ClassNames - uniqued class names.
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000745 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassNames;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000746
Daniel Dunbar5eec6142008-08-12 03:39:23 +0000747 /// MethodVarNames - uniqued method variable names.
748 llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000749
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000750 /// MethodVarTypes - uniqued method type signatures. We have to use
751 /// a StringMap here because have no other unique reference.
752 llvm::StringMap<llvm::GlobalVariable*> MethodVarTypes;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000753
Daniel Dunbar12996f52008-08-26 21:51:14 +0000754 /// MethodDefinitions - map of methods which have been defined in
755 /// this translation unit.
756 llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> MethodDefinitions;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000757
Daniel Dunbara6eb6b72008-08-23 00:19:03 +0000758 /// PropertyNames - uniqued method variable names.
759 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000760
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000761 /// ClassReferences - uniqued class references.
762 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000763
Daniel Dunbar5eec6142008-08-12 03:39:23 +0000764 /// SelectorReferences - uniqued selector references.
765 llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000766
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000767 /// Protocols - Protocols for which an objc_protocol structure has
768 /// been emitted. Forward declarations are handled by creating an
769 /// empty structure whose initializer is filled in when/if defined.
770 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> Protocols;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000771
Daniel Dunbar35b777f2008-10-29 22:36:39 +0000772 /// DefinedProtocols - Protocols which have actually been
773 /// defined. We should not need this, see FIXME in GenerateProtocol.
774 llvm::DenseSet<IdentifierInfo*> DefinedProtocols;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000775
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000776 /// DefinedClasses - List of defined classes.
777 std::vector<llvm::GlobalValue*> DefinedClasses;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000778
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000779 /// DefinedCategories - List of defined categories.
780 std::vector<llvm::GlobalValue*> DefinedCategories;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000781
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000782 /// UsedGlobals - List of globals to pack into the llvm.used metadata
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000783 /// to prevent them from being clobbered.
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +0000784 std::vector<llvm::GlobalVariable*> UsedGlobals;
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000785
Fariborz Jahanian32b5ea22009-01-21 23:34:32 +0000786 /// GetNameForMethod - Return a name for the given method.
787 /// \param[out] NameOut - The return value.
788 void GetNameForMethod(const ObjCMethodDecl *OMD,
789 const ObjCContainerDecl *CD,
790 std::string &NameOut);
791
792 /// GetMethodVarName - Return a unique constant for the given
793 /// selector's name. The return value has type char *.
794 llvm::Constant *GetMethodVarName(Selector Sel);
795 llvm::Constant *GetMethodVarName(IdentifierInfo *Ident);
796 llvm::Constant *GetMethodVarName(const std::string &Name);
797
798 /// GetMethodVarType - Return a unique constant for the given
799 /// selector's name. The return value has type char *.
800
801 // FIXME: This is a horrible name.
802 llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D);
Daniel Dunbar356f0742009-04-20 06:54:31 +0000803 llvm::Constant *GetMethodVarType(const FieldDecl *D);
Fariborz Jahanian32b5ea22009-01-21 23:34:32 +0000804
805 /// GetPropertyName - Return a unique constant for the given
806 /// name. The return value has type char *.
807 llvm::Constant *GetPropertyName(IdentifierInfo *Ident);
808
809 // FIXME: This can be dropped once string functions are unified.
810 llvm::Constant *GetPropertyTypeString(const ObjCPropertyDecl *PD,
811 const Decl *Container);
812
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +0000813 /// GetClassName - Return a unique constant for the given selector's
814 /// name. The return value has type char *.
815 llvm::Constant *GetClassName(IdentifierInfo *Ident);
816
Fariborz Jahanian01b3e342009-03-05 22:39:55 +0000817 /// BuildIvarLayout - Builds ivar layout bitmap for the class
818 /// implementation for the __strong or __weak case.
819 ///
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +0000820 llvm::Constant *BuildIvarLayout(const ObjCImplementationDecl *OI,
821 bool ForStrongLayout);
Fariborz Jahanian01b3e342009-03-05 22:39:55 +0000822
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +0000823 void BuildAggrIvarLayout(const ObjCInterfaceDecl *OI,
824 const llvm::StructLayout *Layout,
Fariborz Jahanian37931062009-03-10 16:22:08 +0000825 const RecordDecl *RD,
Chris Lattner9329cf52009-03-31 08:48:01 +0000826 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahanian01b3e342009-03-05 22:39:55 +0000827 unsigned int BytePos, bool ForStrongLayout,
828 int &Index, int &SkIndex, bool &HasUnion);
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +0000829
Fariborz Jahanian7345eba2009-03-05 19:17:31 +0000830 /// GetIvarLayoutName - Returns a unique constant for the given
831 /// ivar layout bitmap.
832 llvm::Constant *GetIvarLayoutName(IdentifierInfo *Ident,
833 const ObjCCommonTypesHelper &ObjCTypes);
834
Fariborz Jahanian7b709bb2009-01-28 22:18:42 +0000835 /// EmitPropertyList - Emit the given property list. The return
836 /// value has type PropertyListPtrTy.
837 llvm::Constant *EmitPropertyList(const std::string &Name,
838 const Decl *Container,
839 const ObjCContainerDecl *OCD,
840 const ObjCCommonTypesHelper &ObjCTypes);
841
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +0000842 /// GetProtocolRef - Return a reference to the internal protocol
843 /// description, creating an empty one if it has not been
844 /// defined. The return value has type ProtocolPtrTy.
845 llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD);
Fariborz Jahaniand65949b2009-03-08 20:18:37 +0000846
Chris Lattnerd391dab2009-03-31 08:33:16 +0000847 /// GetFieldBaseOffset - return's field byte offset.
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +0000848 uint64_t GetFieldBaseOffset(const ObjCInterfaceDecl *OI,
849 const llvm::StructLayout *Layout,
Chris Lattnerd391dab2009-03-31 08:33:16 +0000850 const FieldDecl *Field);
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +0000851
Daniel Dunbarc4594f22009-03-09 20:09:19 +0000852 /// CreateMetadataVar - Create a global variable with internal
853 /// linkage for use by the Objective-C runtime.
854 ///
855 /// This is a convenience wrapper which not only creates the
856 /// variable, but also sets the section and alignment and adds the
857 /// global to the UsedGlobals list.
Daniel Dunbareddddd22009-03-09 20:50:13 +0000858 ///
859 /// \param Name - The variable name.
860 /// \param Init - The variable initializer; this is also used to
861 /// define the type of the variable.
862 /// \param Section - The section the variable should go into, or 0.
863 /// \param Align - The alignment for the variable, or 0.
864 /// \param AddToUsed - Whether the variable should be added to
Daniel Dunbar6b343692009-04-14 17:42:51 +0000865 /// "llvm.used".
Daniel Dunbarc4594f22009-03-09 20:09:19 +0000866 llvm::GlobalVariable *CreateMetadataVar(const std::string &Name,
867 llvm::Constant *Init,
868 const char *Section,
Daniel Dunbareddddd22009-03-09 20:50:13 +0000869 unsigned Align,
870 bool AddToUsed);
Daniel Dunbarc4594f22009-03-09 20:09:19 +0000871
Daniel Dunbar356f0742009-04-20 06:54:31 +0000872 /// GetNamedIvarList - Return the list of ivars in the interface
873 /// itself (not including super classes and not including unnamed
874 /// bitfields).
875 ///
876 /// For the non-fragile ABI, this also includes synthesized property
877 /// ivars.
878 void GetNamedIvarList(const ObjCInterfaceDecl *OID,
879 llvm::SmallVector<ObjCIvarDecl*, 16> &Res) const;
880
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000881public:
882 CGObjCCommonMac(CodeGen::CodeGenModule &cgm) : CGM(cgm)
883 { }
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +0000884
Steve Naroff2c8a08e2009-03-31 16:53:37 +0000885 virtual llvm::Constant *GenerateConstantString(const ObjCStringLiteral *SL);
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +0000886
887 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
888 const ObjCContainerDecl *CD=0);
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +0000889
890 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
891
892 /// GetOrEmitProtocol - Get the protocol object for the given
893 /// declaration, emitting it if necessary. The return value has type
894 /// ProtocolPtrTy.
895 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD)=0;
896
897 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
898 /// object for the given declaration, emitting it if needed. These
899 /// forward references will be filled in with empty bodies if no
900 /// definition is seen. The return value has type ProtocolPtrTy.
901 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD)=0;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000902};
903
904class CGObjCMac : public CGObjCCommonMac {
905private:
906 ObjCTypesHelper ObjCTypes;
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000907 /// EmitImageInfo - Emit the image info marker used to encode some module
908 /// level information.
909 void EmitImageInfo();
910
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +0000911 /// EmitModuleInfo - Another marker encoding module level
912 /// information.
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +0000913 void EmitModuleInfo();
914
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000915 /// EmitModuleSymols - Emit module symbols, the list of defined
916 /// classes and categories. The result has type SymtabPtrTy.
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +0000917 llvm::Constant *EmitModuleSymbols();
918
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000919 /// FinishModule - Write out global data structures at the end of
920 /// processing a translation unit.
921 void FinishModule();
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000922
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000923 /// EmitClassExtension - Generate the class extension structure used
924 /// to store the weak ivar layout and properties. The return value
925 /// has type ClassExtensionPtrTy.
926 llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID);
927
928 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
929 /// for the given class.
Daniel Dunbard916e6e2008-11-01 01:53:16 +0000930 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000931 const ObjCInterfaceDecl *ID);
932
Daniel Dunbar87062ff2008-08-23 09:25:55 +0000933 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbardd851282008-08-30 05:35:15 +0000934 QualType ResultType,
935 Selector Sel,
Daniel Dunbar87062ff2008-08-23 09:25:55 +0000936 llvm::Value *Arg0,
Daniel Dunbar0ed60b02008-08-30 03:02:31 +0000937 QualType Arg0Ty,
938 bool IsSuper,
939 const CallArgList &CallArgs);
Daniel Dunbar87062ff2008-08-23 09:25:55 +0000940
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000941 /// EmitIvarList - Emit the ivar list for the given
942 /// implementation. If ForClass is true the list of class ivars
943 /// (i.e. metaclass ivars) is emitted, otherwise the list of
944 /// interface ivars will be emitted. The return value has type
945 /// IvarListPtrTy.
946 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanianf2a94cd2009-01-28 19:12:34 +0000947 bool ForClass);
948
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +0000949 /// EmitMetaClass - Emit a forward reference to the class structure
950 /// for the metaclass of the given interface. The return value has
951 /// type ClassPtrTy.
952 llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
953
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000954 /// EmitMetaClass - Emit a class structure for the metaclass of the
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +0000955 /// given implementation. The return value has type ClassPtrTy.
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000956 llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
957 llvm::Constant *Protocols,
Daniel Dunbar12996f52008-08-26 21:51:14 +0000958 const llvm::Type *InterfaceTy,
Daniel Dunbarfe131f02008-08-27 02:31:56 +0000959 const ConstantVector &Methods);
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +0000960
Daniel Dunbarfe131f02008-08-27 02:31:56 +0000961 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +0000962
Daniel Dunbarfe131f02008-08-27 02:31:56 +0000963 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000964
965 /// EmitMethodList - Emit the method list for the given
Daniel Dunbar6b57d432008-08-26 08:29:31 +0000966 /// implementation. The return value has type MethodListPtrTy.
Daniel Dunbar4246a8b2008-08-22 20:34:54 +0000967 llvm::Constant *EmitMethodList(const std::string &Name,
968 const char *Section,
Daniel Dunbarfe131f02008-08-27 02:31:56 +0000969 const ConstantVector &Methods);
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000970
971 /// EmitMethodDescList - Emit a method description list for a list of
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000972 /// method declarations.
973 /// - TypeName: The name for the type containing the methods.
974 /// - IsProtocol: True iff these methods are for a protocol.
975 /// - ClassMethds: True iff these are class methods.
976 /// - Required: When true, only "required" methods are
977 /// listed. Similarly, when false only "optional" methods are
978 /// listed. For classes this should always be true.
979 /// - begin, end: The method list to output.
980 ///
981 /// The return value has type MethodDescriptionListPtrTy.
Daniel Dunbarfe131f02008-08-27 02:31:56 +0000982 llvm::Constant *EmitMethodDescList(const std::string &Name,
983 const char *Section,
984 const ConstantVector &Methods);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000985
Daniel Dunbar35b777f2008-10-29 22:36:39 +0000986 /// GetOrEmitProtocol - Get the protocol object for the given
987 /// declaration, emitting it if necessary. The return value has type
988 /// ProtocolPtrTy.
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +0000989 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
Daniel Dunbar35b777f2008-10-29 22:36:39 +0000990
991 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
992 /// object for the given declaration, emitting it if needed. These
993 /// forward references will be filled in with empty bodies if no
994 /// definition is seen. The return value has type ProtocolPtrTy.
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +0000995 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
Daniel Dunbar35b777f2008-10-29 22:36:39 +0000996
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000997 /// EmitProtocolExtension - Generate the protocol extension
998 /// structure used to store optional instance and class methods, and
999 /// protocol properties. The return value has type
1000 /// ProtocolExtensionPtrTy.
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001001 llvm::Constant *
1002 EmitProtocolExtension(const ObjCProtocolDecl *PD,
1003 const ConstantVector &OptInstanceMethods,
1004 const ConstantVector &OptClassMethods);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001005
1006 /// EmitProtocolList - Generate the list of referenced
1007 /// protocols. The return value has type ProtocolListPtrTy.
Daniel Dunbar67e778b2008-08-21 21:57:41 +00001008 llvm::Constant *EmitProtocolList(const std::string &Name,
1009 ObjCProtocolDecl::protocol_iterator begin,
1010 ObjCProtocolDecl::protocol_iterator end);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001011
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001012 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
1013 /// for the given selector.
Daniel Dunbard916e6e2008-11-01 01:53:16 +00001014 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00001015
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00001016 public:
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001017 CGObjCMac(CodeGen::CodeGenModule &cgm);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001018
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00001019 virtual llvm::Function *ModuleInitFunction();
1020
Daniel Dunbara04840b2008-08-23 03:46:30 +00001021 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbardd851282008-08-30 05:35:15 +00001022 QualType ResultType,
1023 Selector Sel,
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +00001024 llvm::Value *Receiver,
Daniel Dunbar0ed60b02008-08-30 03:02:31 +00001025 bool IsClassMessage,
1026 const CallArgList &CallArgs);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001027
Daniel Dunbara04840b2008-08-23 03:46:30 +00001028 virtual CodeGen::RValue
1029 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbardd851282008-08-30 05:35:15 +00001030 QualType ResultType,
1031 Selector Sel,
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +00001032 const ObjCInterfaceDecl *Class,
Fariborz Jahanian17636fa2009-02-28 20:07:56 +00001033 bool isCategoryImpl,
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +00001034 llvm::Value *Receiver,
Daniel Dunbar0ed60b02008-08-30 03:02:31 +00001035 bool IsClassMessage,
1036 const CallArgList &CallArgs);
Daniel Dunbar434627a2008-08-16 00:25:02 +00001037
Daniel Dunbard916e6e2008-11-01 01:53:16 +00001038 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001039 const ObjCInterfaceDecl *ID);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001040
Daniel Dunbard916e6e2008-11-01 01:53:16 +00001041 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001042
Daniel Dunbarac93e472008-08-15 22:20:32 +00001043 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001044
Daniel Dunbarac93e472008-08-15 22:20:32 +00001045 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001046
Daniel Dunbard916e6e2008-11-01 01:53:16 +00001047 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbar84bb85f2008-08-13 00:59:25 +00001048 const ObjCProtocolDecl *PD);
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00001049
Chris Lattneraea1aee2009-03-22 21:03:39 +00001050 virtual llvm::Constant *GetPropertyGetFunction();
1051 virtual llvm::Constant *GetPropertySetFunction();
1052 virtual llvm::Constant *EnumerationMutationFunction();
Anders Carlssonb01a2112008-09-09 10:04:29 +00001053
Fariborz Jahanianfbeda7b2008-11-21 00:49:24 +00001054 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
1055 const Stmt &S);
Anders Carlssonb01a2112008-09-09 10:04:29 +00001056 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
1057 const ObjCAtThrowStmt &S);
Fariborz Jahanian252d87f2008-11-18 22:37:34 +00001058 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian3305ad32008-11-18 21:45:40 +00001059 llvm::Value *AddrWeakObj);
Fariborz Jahanian252d87f2008-11-18 22:37:34 +00001060 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
1061 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanian17958902008-11-19 00:59:10 +00001062 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
1063 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianf310b592008-11-20 19:23:36 +00001064 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
1065 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian17958902008-11-19 00:59:10 +00001066 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
1067 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian4337afe2009-02-02 20:02:29 +00001068
Fariborz Jahanianc912eb72009-02-03 19:03:09 +00001069 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
1070 QualType ObjectTy,
1071 llvm::Value *BaseValue,
1072 const ObjCIvarDecl *Ivar,
Fariborz Jahanianc912eb72009-02-03 19:03:09 +00001073 unsigned CVRQualifiers);
Fariborz Jahanian27cc6662009-02-10 19:02:04 +00001074 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar61e14a62009-04-22 05:08:15 +00001075 const ObjCInterfaceDecl *Interface,
Fariborz Jahanian27cc6662009-02-10 19:02:04 +00001076 const ObjCIvarDecl *Ivar);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001077};
Fariborz Jahanian48543f52009-01-21 22:04:16 +00001078
Fariborz Jahaniand0374812009-01-22 23:02:58 +00001079class CGObjCNonFragileABIMac : public CGObjCCommonMac {
Fariborz Jahanian48543f52009-01-21 22:04:16 +00001080private:
Fariborz Jahaniand0374812009-01-22 23:02:58 +00001081 ObjCNonFragileABITypesHelper ObjCTypes;
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00001082 llvm::GlobalVariable* ObjCEmptyCacheVar;
1083 llvm::GlobalVariable* ObjCEmptyVtableVar;
Daniel Dunbarc0318b22009-03-02 06:08:11 +00001084
Daniel Dunbar3c190812009-04-18 08:51:00 +00001085 /// SuperClassReferences - uniqued super class references.
1086 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> SuperClassReferences;
1087
Fariborz Jahanianf3a44012009-02-06 20:09:23 +00001088 /// MetaClassReferences - uniqued meta class references.
1089 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> MetaClassReferences;
Daniel Dunbar9c285e72009-03-01 04:46:24 +00001090
1091 /// EHTypeReferences - uniqued class ehtype references.
1092 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> EHTypeReferences;
Daniel Dunbarc0318b22009-03-02 06:08:11 +00001093
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00001094 /// FinishNonFragileABIModule - Write out global data structures at the end of
1095 /// processing a translation unit.
1096 void FinishNonFragileABIModule();
Daniel Dunbarc2129532009-04-08 04:21:03 +00001097
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00001098 llvm::GlobalVariable * BuildClassRoTInitializer(unsigned flags,
1099 unsigned InstanceStart,
1100 unsigned InstanceSize,
1101 const ObjCImplementationDecl *ID);
Fariborz Jahanian06726462009-01-24 21:21:53 +00001102 llvm::GlobalVariable * BuildClassMetaData(std::string &ClassName,
1103 llvm::Constant *IsAGV,
1104 llvm::Constant *SuperClassGV,
Fariborz Jahanian51dcacb2009-01-31 00:59:10 +00001105 llvm::Constant *ClassRoGV,
1106 bool HiddenVisibility);
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00001107
1108 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
1109
Fariborz Jahanian151747b2009-01-30 00:46:37 +00001110 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
1111
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00001112 /// EmitMethodList - Emit the method list for the given
1113 /// implementation. The return value has type MethodListnfABITy.
1114 llvm::Constant *EmitMethodList(const std::string &Name,
1115 const char *Section,
Fariborz Jahanian3f1cc562009-01-27 19:38:51 +00001116 const ConstantVector &Methods);
1117 /// EmitIvarList - Emit the ivar list for the given
1118 /// implementation. If ForClass is true the list of class ivars
1119 /// (i.e. metaclass ivars) is emitted, otherwise the list of
1120 /// interface ivars will be emitted. The return value has type
1121 /// IvarListnfABIPtrTy.
1122 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID);
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00001123
Fariborz Jahaniancc00f922009-02-10 20:21:06 +00001124 llvm::Constant *EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,
Fariborz Jahanian150f7732009-01-28 01:36:42 +00001125 const ObjCIvarDecl *Ivar,
Fariborz Jahanian3175ddd2009-01-28 01:05:23 +00001126 unsigned long int offset);
1127
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00001128 /// GetOrEmitProtocol - Get the protocol object for the given
1129 /// declaration, emitting it if necessary. The return value has type
1130 /// ProtocolPtrTy.
1131 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
1132
1133 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
1134 /// object for the given declaration, emitting it if needed. These
1135 /// forward references will be filled in with empty bodies if no
1136 /// definition is seen. The return value has type ProtocolPtrTy.
1137 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
1138
1139 /// EmitProtocolList - Generate the list of referenced
1140 /// protocols. The return value has type ProtocolListPtrTy.
1141 llvm::Constant *EmitProtocolList(const std::string &Name,
1142 ObjCProtocolDecl::protocol_iterator begin,
Fariborz Jahanian7e881162009-02-04 00:22:57 +00001143 ObjCProtocolDecl::protocol_iterator end);
1144
1145 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
1146 QualType ResultType,
1147 Selector Sel,
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00001148 llvm::Value *Receiver,
Fariborz Jahanian7e881162009-02-04 00:22:57 +00001149 QualType Arg0Ty,
1150 bool IsSuper,
1151 const CallArgList &CallArgs);
Daniel Dunbarabbda222009-03-01 04:40:10 +00001152
1153 /// GetClassGlobal - Return the global variable for the Objective-C
1154 /// class of the given name.
Fariborz Jahanianab438842009-04-14 18:41:56 +00001155 llvm::GlobalVariable *GetClassGlobal(const std::string &Name);
1156
Fariborz Jahanian917c0402009-02-05 20:41:40 +00001157 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
Daniel Dunbar3c190812009-04-18 08:51:00 +00001158 /// for the given class reference.
Fariborz Jahanian917c0402009-02-05 20:41:40 +00001159 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar3c190812009-04-18 08:51:00 +00001160 const ObjCInterfaceDecl *ID);
1161
1162 /// EmitSuperClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
1163 /// for the given super class reference.
1164 llvm::Value *EmitSuperClassRef(CGBuilderTy &Builder,
1165 const ObjCInterfaceDecl *ID);
Fariborz Jahanianf3a44012009-02-06 20:09:23 +00001166
1167 /// EmitMetaClassRef - Return a Value * of the address of _class_t
1168 /// meta-data
1169 llvm::Value *EmitMetaClassRef(CGBuilderTy &Builder,
1170 const ObjCInterfaceDecl *ID);
1171
Fariborz Jahaniancc00f922009-02-10 20:21:06 +00001172 /// ObjCIvarOffsetVariable - Returns the ivar offset variable for
1173 /// the given ivar.
1174 ///
Daniel Dunbar07d204a2009-04-19 00:31:15 +00001175 llvm::GlobalVariable * ObjCIvarOffsetVariable(
Fariborz Jahaniana09a5142009-02-12 18:51:23 +00001176 const ObjCInterfaceDecl *ID,
Fariborz Jahaniancc00f922009-02-10 20:21:06 +00001177 const ObjCIvarDecl *Ivar);
Fariborz Jahanian917c0402009-02-05 20:41:40 +00001178
Fariborz Jahanianebb82c62009-02-11 20:51:17 +00001179 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
1180 /// for the given selector.
1181 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbar9c285e72009-03-01 04:46:24 +00001182
Daniel Dunbarc2129532009-04-08 04:21:03 +00001183 /// GetInterfaceEHType - Get the cached ehtype for the given Objective-C
Daniel Dunbar9c285e72009-03-01 04:46:24 +00001184 /// interface. The return value has type EHTypePtrTy.
Daniel Dunbarc2129532009-04-08 04:21:03 +00001185 llvm::Value *GetInterfaceEHType(const ObjCInterfaceDecl *ID,
1186 bool ForDefinition);
Daniel Dunbara2d275d2009-04-07 05:48:37 +00001187
1188 const char *getMetaclassSymbolPrefix() const {
1189 return "OBJC_METACLASS_$_";
1190 }
Daniel Dunbarc0318b22009-03-02 06:08:11 +00001191
Daniel Dunbara2d275d2009-04-07 05:48:37 +00001192 const char *getClassSymbolPrefix() const {
1193 return "OBJC_CLASS_$_";
1194 }
1195
Daniel Dunbarecb5d402009-04-19 23:41:48 +00001196 void GetClassSizeInfo(const ObjCInterfaceDecl *OID,
1197 uint32_t &InstanceStart,
1198 uint32_t &InstanceSize);
1199
Fariborz Jahanian48543f52009-01-21 22:04:16 +00001200public:
Fariborz Jahaniand0374812009-01-22 23:02:58 +00001201 CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00001202 // FIXME. All stubs for now!
1203 virtual llvm::Function *ModuleInitFunction();
1204
1205 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
1206 QualType ResultType,
1207 Selector Sel,
1208 llvm::Value *Receiver,
1209 bool IsClassMessage,
Fariborz Jahanian7e881162009-02-04 00:22:57 +00001210 const CallArgList &CallArgs);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00001211
1212 virtual CodeGen::RValue
1213 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
1214 QualType ResultType,
1215 Selector Sel,
1216 const ObjCInterfaceDecl *Class,
Fariborz Jahanian17636fa2009-02-28 20:07:56 +00001217 bool isCategoryImpl,
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00001218 llvm::Value *Receiver,
1219 bool IsClassMessage,
Fariborz Jahanianf3a44012009-02-06 20:09:23 +00001220 const CallArgList &CallArgs);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00001221
1222 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Fariborz Jahanian917c0402009-02-05 20:41:40 +00001223 const ObjCInterfaceDecl *ID);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00001224
1225 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel)
Fariborz Jahanianebb82c62009-02-11 20:51:17 +00001226 { return EmitSelector(Builder, Sel); }
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00001227
Fariborz Jahanianfe49a092009-01-26 18:32:24 +00001228 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00001229
1230 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00001231 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Fariborz Jahanian5d13ab12009-01-30 18:58:59 +00001232 const ObjCProtocolDecl *PD);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00001233
Chris Lattneraea1aee2009-03-22 21:03:39 +00001234 virtual llvm::Constant *GetPropertyGetFunction() {
Chris Lattnera7ecda42009-04-22 02:44:54 +00001235 return ObjCTypes.getGetPropertyFn();
Fariborz Jahanian27cc6662009-02-10 19:02:04 +00001236 }
Chris Lattneraea1aee2009-03-22 21:03:39 +00001237 virtual llvm::Constant *GetPropertySetFunction() {
Chris Lattnera7ecda42009-04-22 02:44:54 +00001238 return ObjCTypes.getSetPropertyFn();
Fariborz Jahanian27cc6662009-02-10 19:02:04 +00001239 }
Chris Lattneraea1aee2009-03-22 21:03:39 +00001240 virtual llvm::Constant *EnumerationMutationFunction() {
Chris Lattnera7ecda42009-04-22 02:44:54 +00001241 return ObjCTypes.getEnumerationMutationFn();
Daniel Dunbar978d2be2009-02-16 18:48:45 +00001242 }
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00001243
1244 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar75de89f2009-02-24 07:47:38 +00001245 const Stmt &S);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00001246 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Anders Carlsson1cf75362009-02-16 22:59:18 +00001247 const ObjCAtThrowStmt &S);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00001248 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian5eefb432009-02-16 22:52:32 +00001249 llvm::Value *AddrWeakObj);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00001250 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian5eefb432009-02-16 22:52:32 +00001251 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00001252 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian5eefb432009-02-16 22:52:32 +00001253 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00001254 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian5eefb432009-02-16 22:52:32 +00001255 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00001256 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian5eefb432009-02-16 22:52:32 +00001257 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianc912eb72009-02-03 19:03:09 +00001258 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
1259 QualType ObjectTy,
1260 llvm::Value *BaseValue,
1261 const ObjCIvarDecl *Ivar,
Fariborz Jahanianc912eb72009-02-03 19:03:09 +00001262 unsigned CVRQualifiers);
Fariborz Jahanian27cc6662009-02-10 19:02:04 +00001263 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar61e14a62009-04-22 05:08:15 +00001264 const ObjCInterfaceDecl *Interface,
Fariborz Jahanian27cc6662009-02-10 19:02:04 +00001265 const ObjCIvarDecl *Ivar);
Fariborz Jahanian48543f52009-01-21 22:04:16 +00001266};
1267
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001268} // end anonymous namespace
Daniel Dunbardaf4ad42008-08-12 00:12:39 +00001269
1270/* *** Helper Functions *** */
1271
1272/// getConstantGEP() - Help routine to construct simple GEPs.
1273static llvm::Constant *getConstantGEP(llvm::Constant *C,
1274 unsigned idx0,
1275 unsigned idx1) {
1276 llvm::Value *Idxs[] = {
1277 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx0),
1278 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx1)
1279 };
1280 return llvm::ConstantExpr::getGetElementPtr(C, Idxs, 2);
1281}
1282
Daniel Dunbarc2129532009-04-08 04:21:03 +00001283/// hasObjCExceptionAttribute - Return true if this class or any super
1284/// class has the __objc_exception__ attribute.
1285static bool hasObjCExceptionAttribute(const ObjCInterfaceDecl *OID) {
Daniel Dunbar78582862009-04-13 21:08:27 +00001286 if (OID->hasAttr<ObjCExceptionAttr>())
Daniel Dunbarc2129532009-04-08 04:21:03 +00001287 return true;
1288 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
1289 return hasObjCExceptionAttribute(Super);
1290 return false;
1291}
1292
Daniel Dunbardaf4ad42008-08-12 00:12:39 +00001293/* *** CGObjCMac Public Interface *** */
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001294
Fariborz Jahanian48543f52009-01-21 22:04:16 +00001295CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm),
1296 ObjCTypes(cgm)
Daniel Dunbardaf4ad42008-08-12 00:12:39 +00001297{
Fariborz Jahanian48543f52009-01-21 22:04:16 +00001298 ObjCABI = 1;
Daniel Dunbardaf4ad42008-08-12 00:12:39 +00001299 EmitImageInfo();
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001300}
1301
Daniel Dunbar434627a2008-08-16 00:25:02 +00001302/// GetClass - Return a reference to the class for the given interface
1303/// decl.
Daniel Dunbard916e6e2008-11-01 01:53:16 +00001304llvm::Value *CGObjCMac::GetClass(CGBuilderTy &Builder,
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001305 const ObjCInterfaceDecl *ID) {
1306 return EmitClassRef(Builder, ID);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001307}
1308
1309/// GetSelector - Return the pointer to the unique'd string for this selector.
Daniel Dunbard916e6e2008-11-01 01:53:16 +00001310llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar5eec6142008-08-12 03:39:23 +00001311 return EmitSelector(Builder, Sel);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001312}
1313
Daniel Dunbardaf4ad42008-08-12 00:12:39 +00001314/// Generate a constant CFString object.
1315/*
1316 struct __builtin_CFString {
1317 const int *isa; // point to __CFConstantStringClassReference
1318 int flags;
1319 const char *str;
1320 long length;
1321 };
1322*/
1323
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00001324llvm::Constant *CGObjCCommonMac::GenerateConstantString(
Steve Naroff2c8a08e2009-03-31 16:53:37 +00001325 const ObjCStringLiteral *SL) {
Steve Naroff9a744e52009-04-01 13:55:36 +00001326 return CGM.GetAddrOfConstantCFString(SL->getString());
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001327}
1328
1329/// Generates a message send where the super is the receiver. This is
1330/// a message send to self with special delivery semantics indicating
1331/// which class's method should be called.
Daniel Dunbara04840b2008-08-23 03:46:30 +00001332CodeGen::RValue
1333CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbardd851282008-08-30 05:35:15 +00001334 QualType ResultType,
1335 Selector Sel,
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +00001336 const ObjCInterfaceDecl *Class,
Fariborz Jahanian17636fa2009-02-28 20:07:56 +00001337 bool isCategoryImpl,
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +00001338 llvm::Value *Receiver,
Daniel Dunbar0ed60b02008-08-30 03:02:31 +00001339 bool IsClassMessage,
Daniel Dunbar0a2da0f2008-09-09 01:06:48 +00001340 const CodeGen::CallArgList &CallArgs) {
Daniel Dunbar15245e52008-08-23 04:28:29 +00001341 // Create and init a super structure; this is a (receiver, class)
1342 // pair we will pass to objc_msgSendSuper.
1343 llvm::Value *ObjCSuper =
1344 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
1345 llvm::Value *ReceiverAsObject =
1346 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
1347 CGF.Builder.CreateStore(ReceiverAsObject,
1348 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
Daniel Dunbar15245e52008-08-23 04:28:29 +00001349
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +00001350 // If this is a class message the metaclass is passed as the target.
1351 llvm::Value *Target;
1352 if (IsClassMessage) {
Fariborz Jahanian17636fa2009-02-28 20:07:56 +00001353 if (isCategoryImpl) {
1354 // Message sent to 'super' in a class method defined in a category
1355 // implementation requires an odd treatment.
1356 // If we are in a class method, we must retrieve the
1357 // _metaclass_ for the current class, pointed at by
1358 // the class's "isa" pointer. The following assumes that
1359 // isa" is the first ivar in a class (which it must be).
1360 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
1361 Target = CGF.Builder.CreateStructGEP(Target, 0);
1362 Target = CGF.Builder.CreateLoad(Target);
1363 }
1364 else {
1365 llvm::Value *MetaClassPtr = EmitMetaClassRef(Class);
1366 llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1);
1367 llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr);
1368 Target = Super;
1369 }
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +00001370 } else {
1371 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
1372 }
Daniel Dunbar0ed60b02008-08-30 03:02:31 +00001373 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
1374 // and ObjCTypes types.
1375 const llvm::Type *ClassTy =
1376 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
Daniel Dunbar35b777f2008-10-29 22:36:39 +00001377 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +00001378 CGF.Builder.CreateStore(Target,
1379 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
1380
Daniel Dunbardd851282008-08-30 05:35:15 +00001381 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar0ed60b02008-08-30 03:02:31 +00001382 ObjCSuper, ObjCTypes.SuperPtrCTy,
1383 true, CallArgs);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001384}
Daniel Dunbar87062ff2008-08-23 09:25:55 +00001385
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001386/// Generate code for a message send expression.
Daniel Dunbara04840b2008-08-23 03:46:30 +00001387CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbardd851282008-08-30 05:35:15 +00001388 QualType ResultType,
1389 Selector Sel,
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +00001390 llvm::Value *Receiver,
Daniel Dunbar0ed60b02008-08-30 03:02:31 +00001391 bool IsClassMessage,
1392 const CallArgList &CallArgs) {
Daniel Dunbar87062ff2008-08-23 09:25:55 +00001393 llvm::Value *Arg0 =
1394 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy, "tmp");
Daniel Dunbardd851282008-08-30 05:35:15 +00001395 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar0ed60b02008-08-30 03:02:31 +00001396 Arg0, CGF.getContext().getObjCIdType(),
1397 false, CallArgs);
Daniel Dunbar87062ff2008-08-23 09:25:55 +00001398}
1399
1400CodeGen::RValue CGObjCMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbardd851282008-08-30 05:35:15 +00001401 QualType ResultType,
1402 Selector Sel,
Daniel Dunbar87062ff2008-08-23 09:25:55 +00001403 llvm::Value *Arg0,
Daniel Dunbar0ed60b02008-08-30 03:02:31 +00001404 QualType Arg0Ty,
1405 bool IsSuper,
1406 const CallArgList &CallArgs) {
1407 CallArgList ActualArgs;
Daniel Dunbar0a2da0f2008-09-09 01:06:48 +00001408 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
1409 ActualArgs.push_back(std::make_pair(RValue::get(EmitSelector(CGF.Builder,
1410 Sel)),
Daniel Dunbar0ed60b02008-08-30 03:02:31 +00001411 CGF.getContext().getObjCSelType()));
1412 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Daniel Dunbarac93e472008-08-15 22:20:32 +00001413
Daniel Dunbar34bda882009-02-02 23:23:47 +00001414 CodeGenTypes &Types = CGM.getTypes();
1415 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs);
1416 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo, false);
Daniel Dunbaraecef4c2008-10-17 03:24:53 +00001417
1418 llvm::Constant *Fn;
Daniel Dunbar6ee022b2009-02-02 22:03:45 +00001419 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Daniel Dunbaraecef4c2008-10-17 03:24:53 +00001420 Fn = ObjCTypes.getSendStretFn(IsSuper);
1421 } else if (ResultType->isFloatingType()) {
1422 // FIXME: Sadly, this is wrong. This actually depends on the
1423 // architecture. This happens to be right for x86-32 though.
1424 Fn = ObjCTypes.getSendFpretFn(IsSuper);
1425 } else {
1426 Fn = ObjCTypes.getSendFn(IsSuper);
1427 }
Daniel Dunbara9976a22008-09-10 07:00:50 +00001428 Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy));
Daniel Dunbar6ee022b2009-02-02 22:03:45 +00001429 return CGF.EmitCall(FnInfo, Fn, ActualArgs);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001430}
1431
Daniel Dunbard916e6e2008-11-01 01:53:16 +00001432llvm::Value *CGObjCMac::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbar84bb85f2008-08-13 00:59:25 +00001433 const ObjCProtocolDecl *PD) {
Daniel Dunbarb3518152008-09-04 04:33:15 +00001434 // FIXME: I don't understand why gcc generates this, or where it is
1435 // resolved. Investigate. Its also wasteful to look this up over and
1436 // over.
1437 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1438
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001439 return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
1440 ObjCTypes.ExternalProtocolPtrTy);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001441}
1442
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00001443void CGObjCCommonMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
Daniel Dunbar35b777f2008-10-29 22:36:39 +00001444 // FIXME: We shouldn't need this, the protocol decl should contain
1445 // enough information to tell us whether this was a declaration or a
1446 // definition.
1447 DefinedProtocols.insert(PD->getIdentifier());
1448
1449 // If we have generated a forward reference to this protocol, emit
1450 // it now. Otherwise do nothing, the protocol objects are lazily
1451 // emitted.
1452 if (Protocols.count(PD->getIdentifier()))
1453 GetOrEmitProtocol(PD);
1454}
1455
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00001456llvm::Constant *CGObjCCommonMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar35b777f2008-10-29 22:36:39 +00001457 if (DefinedProtocols.count(PD->getIdentifier()))
1458 return GetOrEmitProtocol(PD);
1459 return GetOrEmitProtocolRef(PD);
1460}
1461
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001462/*
1463 // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions
1464 struct _objc_protocol {
1465 struct _objc_protocol_extension *isa;
1466 char *protocol_name;
1467 struct _objc_protocol_list *protocol_list;
1468 struct _objc__method_prototype_list *instance_methods;
1469 struct _objc__method_prototype_list *class_methods
1470 };
1471
1472 See EmitProtocolExtension().
1473*/
Daniel Dunbar35b777f2008-10-29 22:36:39 +00001474llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
1475 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1476
1477 // Early exit if a defining object has already been generated.
1478 if (Entry && Entry->hasInitializer())
1479 return Entry;
1480
Daniel Dunbar8ede0052008-08-25 06:02:07 +00001481 // FIXME: I don't understand why gcc generates this, or where it is
1482 // resolved. Investigate. Its also wasteful to look this up over and
1483 // over.
1484 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1485
Chris Lattnerd120b9e2008-11-24 03:54:41 +00001486 const char *ProtocolName = PD->getNameAsCString();
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001487
1488 // Construct method lists.
1489 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1490 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001491 for (ObjCProtocolDecl::instmeth_iterator
1492 i = PD->instmeth_begin(CGM.getContext()),
1493 e = PD->instmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001494 ObjCMethodDecl *MD = *i;
1495 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1496 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1497 OptInstanceMethods.push_back(C);
1498 } else {
1499 InstanceMethods.push_back(C);
1500 }
1501 }
1502
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001503 for (ObjCProtocolDecl::classmeth_iterator
1504 i = PD->classmeth_begin(CGM.getContext()),
1505 e = PD->classmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001506 ObjCMethodDecl *MD = *i;
1507 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1508 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1509 OptClassMethods.push_back(C);
1510 } else {
1511 ClassMethods.push_back(C);
1512 }
1513 }
1514
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001515 std::vector<llvm::Constant*> Values(5);
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001516 Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001517 Values[1] = GetClassName(PD->getIdentifier());
Daniel Dunbar67e778b2008-08-21 21:57:41 +00001518 Values[2] =
Chris Lattner271d4c22008-11-24 05:29:24 +00001519 EmitProtocolList("\01L_OBJC_PROTOCOL_REFS_" + PD->getNameAsString(),
Daniel Dunbar67e778b2008-08-21 21:57:41 +00001520 PD->protocol_begin(),
1521 PD->protocol_end());
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001522 Values[3] =
Chris Lattner271d4c22008-11-24 05:29:24 +00001523 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_"
1524 + PD->getNameAsString(),
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001525 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1526 InstanceMethods);
1527 Values[4] =
Chris Lattner271d4c22008-11-24 05:29:24 +00001528 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_"
1529 + PD->getNameAsString(),
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001530 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1531 ClassMethods);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001532 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
1533 Values);
1534
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001535 if (Entry) {
Daniel Dunbar35b777f2008-10-29 22:36:39 +00001536 // Already created, fix the linkage and update the initializer.
1537 Entry->setLinkage(llvm::GlobalValue::InternalLinkage);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001538 Entry->setInitializer(Init);
1539 } else {
1540 Entry =
1541 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
1542 llvm::GlobalValue::InternalLinkage,
1543 Init,
1544 std::string("\01L_OBJC_PROTOCOL_")+ProtocolName,
1545 &CGM.getModule());
1546 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar56756c32009-03-09 22:18:41 +00001547 Entry->setAlignment(4);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001548 UsedGlobals.push_back(Entry);
1549 // FIXME: Is this necessary? Why only for protocol?
1550 Entry->setAlignment(4);
1551 }
Daniel Dunbar35b777f2008-10-29 22:36:39 +00001552
1553 return Entry;
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001554}
1555
Daniel Dunbar35b777f2008-10-29 22:36:39 +00001556llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001557 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1558
1559 if (!Entry) {
Daniel Dunbar35b777f2008-10-29 22:36:39 +00001560 // We use the initializer as a marker of whether this is a forward
1561 // reference or not. At module finalization we add the empty
1562 // contents for protocols which were referenced but never defined.
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001563 Entry =
1564 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
Daniel Dunbar35b777f2008-10-29 22:36:39 +00001565 llvm::GlobalValue::ExternalLinkage,
1566 0,
Chris Lattner271d4c22008-11-24 05:29:24 +00001567 "\01L_OBJC_PROTOCOL_" + PD->getNameAsString(),
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001568 &CGM.getModule());
1569 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar56756c32009-03-09 22:18:41 +00001570 Entry->setAlignment(4);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001571 UsedGlobals.push_back(Entry);
1572 // FIXME: Is this necessary? Why only for protocol?
1573 Entry->setAlignment(4);
1574 }
1575
1576 return Entry;
1577}
1578
1579/*
1580 struct _objc_protocol_extension {
1581 uint32_t size;
1582 struct objc_method_description_list *optional_instance_methods;
1583 struct objc_method_description_list *optional_class_methods;
1584 struct objc_property_list *instance_properties;
1585 };
1586*/
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001587llvm::Constant *
1588CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
1589 const ConstantVector &OptInstanceMethods,
1590 const ConstantVector &OptClassMethods) {
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001591 uint64_t Size =
Daniel Dunbard8439f22009-01-12 21:08:18 +00001592 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolExtensionTy);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001593 std::vector<llvm::Constant*> Values(4);
1594 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001595 Values[1] =
Chris Lattner271d4c22008-11-24 05:29:24 +00001596 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_"
1597 + PD->getNameAsString(),
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001598 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1599 OptInstanceMethods);
1600 Values[2] =
Chris Lattner271d4c22008-11-24 05:29:24 +00001601 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_"
1602 + PD->getNameAsString(),
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001603 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1604 OptClassMethods);
Chris Lattner271d4c22008-11-24 05:29:24 +00001605 Values[3] = EmitPropertyList("\01L_OBJC_$_PROP_PROTO_LIST_" +
1606 PD->getNameAsString(),
Fariborz Jahanian7b709bb2009-01-28 22:18:42 +00001607 0, PD, ObjCTypes);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001608
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001609 // Return null if no extension bits are used.
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001610 if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
1611 Values[3]->isNullValue())
1612 return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
1613
1614 llvm::Constant *Init =
1615 llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001616
Daniel Dunbar90d88f92009-03-09 21:49:58 +00001617 // No special section, but goes in llvm.used
1618 return CreateMetadataVar("\01L_OBJC_PROTOCOLEXT_" + PD->getNameAsString(),
1619 Init,
1620 0, 0, true);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001621}
1622
1623/*
1624 struct objc_protocol_list {
1625 struct objc_protocol_list *next;
1626 long count;
1627 Protocol *list[];
1628 };
1629*/
Daniel Dunbar67e778b2008-08-21 21:57:41 +00001630llvm::Constant *
1631CGObjCMac::EmitProtocolList(const std::string &Name,
1632 ObjCProtocolDecl::protocol_iterator begin,
1633 ObjCProtocolDecl::protocol_iterator end) {
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001634 std::vector<llvm::Constant*> ProtocolRefs;
1635
Daniel Dunbar67e778b2008-08-21 21:57:41 +00001636 for (; begin != end; ++begin)
1637 ProtocolRefs.push_back(GetProtocolRef(*begin));
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001638
1639 // Just return null for empty protocol lists
1640 if (ProtocolRefs.empty())
1641 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1642
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001643 // This list is null terminated.
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001644 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
1645
1646 std::vector<llvm::Constant*> Values(3);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001647 // This field is only used by the runtime.
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001648 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1649 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
1650 Values[2] =
1651 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
1652 ProtocolRefs.size()),
1653 ProtocolRefs);
1654
1655 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1656 llvm::GlobalVariable *GV =
Daniel Dunbar90d88f92009-03-09 21:49:58 +00001657 CreateMetadataVar(Name, Init, "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbar56756c32009-03-09 22:18:41 +00001658 4, false);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001659 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
1660}
1661
1662/*
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00001663 struct _objc_property {
1664 const char * const name;
1665 const char * const attributes;
1666 };
1667
1668 struct _objc_property_list {
1669 uint32_t entsize; // sizeof (struct _objc_property)
1670 uint32_t prop_count;
1671 struct _objc_property[prop_count];
1672 };
1673*/
Fariborz Jahanian7b709bb2009-01-28 22:18:42 +00001674llvm::Constant *CGObjCCommonMac::EmitPropertyList(const std::string &Name,
1675 const Decl *Container,
1676 const ObjCContainerDecl *OCD,
1677 const ObjCCommonTypesHelper &ObjCTypes) {
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00001678 std::vector<llvm::Constant*> Properties, Prop(2);
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001679 for (ObjCContainerDecl::prop_iterator I = OCD->prop_begin(CGM.getContext()),
1680 E = OCD->prop_end(CGM.getContext()); I != E; ++I) {
Steve Naroffdcf1e842009-01-11 12:47:58 +00001681 const ObjCPropertyDecl *PD = *I;
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00001682 Prop[0] = GetPropertyName(PD->getIdentifier());
Daniel Dunbar698d6f32008-08-28 04:38:10 +00001683 Prop[1] = GetPropertyTypeString(PD, Container);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00001684 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
1685 Prop));
1686 }
1687
1688 // Return null for empty list.
1689 if (Properties.empty())
1690 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1691
1692 unsigned PropertySize =
Daniel Dunbard8439f22009-01-12 21:08:18 +00001693 CGM.getTargetData().getTypePaddedSize(ObjCTypes.PropertyTy);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00001694 std::vector<llvm::Constant*> Values(3);
1695 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
1696 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
1697 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
1698 Properties.size());
1699 Values[2] = llvm::ConstantArray::get(AT, Properties);
1700 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1701
Daniel Dunbar90d88f92009-03-09 21:49:58 +00001702 llvm::GlobalVariable *GV =
Daniel Dunbar9dfd3a72009-04-15 02:56:18 +00001703 CreateMetadataVar(Name, Init,
1704 (ObjCABI == 2) ? "__DATA, __objc_const" :
1705 "__OBJC,__property,regular,no_dead_strip",
1706 (ObjCABI == 2) ? 8 : 4,
1707 true);
Daniel Dunbar90d88f92009-03-09 21:49:58 +00001708 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.PropertyListPtrTy);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00001709}
1710
1711/*
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001712 struct objc_method_description_list {
1713 int count;
1714 struct objc_method_description list[];
1715 };
1716*/
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001717llvm::Constant *
1718CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
1719 std::vector<llvm::Constant*> Desc(2);
1720 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1721 ObjCTypes.SelectorPtrTy);
1722 Desc[1] = GetMethodVarType(MD);
1723 return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
1724 Desc);
1725}
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001726
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001727llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name,
1728 const char *Section,
1729 const ConstantVector &Methods) {
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001730 // Return null for empty list.
1731 if (Methods.empty())
1732 return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
1733
1734 std::vector<llvm::Constant*> Values(2);
1735 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1736 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
1737 Methods.size());
1738 Values[1] = llvm::ConstantArray::get(AT, Methods);
1739 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1740
Daniel Dunbar9dfd3a72009-04-15 02:56:18 +00001741 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001742 return llvm::ConstantExpr::getBitCast(GV,
1743 ObjCTypes.MethodDescriptionListPtrTy);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001744}
1745
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001746/*
1747 struct _objc_category {
1748 char *category_name;
1749 char *class_name;
1750 struct _objc_method_list *instance_methods;
1751 struct _objc_method_list *class_methods;
1752 struct _objc_protocol_list *protocols;
1753 uint32_t size; // <rdar://4585769>
1754 struct _objc_property_list *instance_properties;
1755 };
1756 */
Daniel Dunbarac93e472008-08-15 22:20:32 +00001757void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Daniel Dunbard8439f22009-01-12 21:08:18 +00001758 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.CategoryTy);
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001759
Daniel Dunbar0cd49032008-08-26 23:03:11 +00001760 // FIXME: This is poor design, the OCD should have a pointer to the
1761 // category decl. Additionally, note that Category can be null for
1762 // the @implementation w/o an @interface case. Sema should just
1763 // create one for us as it does for @implementation so everyone else
1764 // can live life under a clear blue sky.
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001765 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Daniel Dunbar0cd49032008-08-26 23:03:11 +00001766 const ObjCCategoryDecl *Category =
1767 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Chris Lattner271d4c22008-11-24 05:29:24 +00001768 std::string ExtName(Interface->getNameAsString() + "_" +
1769 OCD->getNameAsString());
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001770
Daniel Dunbar12996f52008-08-26 21:51:14 +00001771 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
Douglas Gregorcd19b572009-04-23 01:02:12 +00001772 for (ObjCCategoryImplDecl::instmeth_iterator
1773 i = OCD->instmeth_begin(CGM.getContext()),
1774 e = OCD->instmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbar12996f52008-08-26 21:51:14 +00001775 // Instance methods should always be defined.
1776 InstanceMethods.push_back(GetMethodConstant(*i));
1777 }
Douglas Gregorcd19b572009-04-23 01:02:12 +00001778 for (ObjCCategoryImplDecl::classmeth_iterator
1779 i = OCD->classmeth_begin(CGM.getContext()),
1780 e = OCD->classmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbar12996f52008-08-26 21:51:14 +00001781 // Class methods should always be defined.
1782 ClassMethods.push_back(GetMethodConstant(*i));
1783 }
1784
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001785 std::vector<llvm::Constant*> Values(7);
1786 Values[0] = GetClassName(OCD->getIdentifier());
1787 Values[1] = GetClassName(Interface->getIdentifier());
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00001788 Values[2] =
1789 EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") +
1790 ExtName,
1791 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
Daniel Dunbar12996f52008-08-26 21:51:14 +00001792 InstanceMethods);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00001793 Values[3] =
1794 EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName,
Daniel Dunbar9dfd3a72009-04-15 02:56:18 +00001795 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbar12996f52008-08-26 21:51:14 +00001796 ClassMethods);
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001797 if (Category) {
1798 Values[4] =
1799 EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName,
1800 Category->protocol_begin(),
1801 Category->protocol_end());
1802 } else {
1803 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1804 }
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001805 Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar0cd49032008-08-26 23:03:11 +00001806
1807 // If there is no category @interface then there can be no properties.
1808 if (Category) {
Daniel Dunbar9dfd3a72009-04-15 02:56:18 +00001809 Values[6] = EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
Fariborz Jahanian7b709bb2009-01-28 22:18:42 +00001810 OCD, Category, ObjCTypes);
Daniel Dunbar0cd49032008-08-26 23:03:11 +00001811 } else {
1812 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1813 }
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001814
1815 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
1816 Values);
1817
1818 llvm::GlobalVariable *GV =
Daniel Dunbar90d88f92009-03-09 21:49:58 +00001819 CreateMetadataVar(std::string("\01L_OBJC_CATEGORY_")+ExtName, Init,
1820 "__OBJC,__category,regular,no_dead_strip",
Daniel Dunbar56756c32009-03-09 22:18:41 +00001821 4, true);
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001822 DefinedCategories.push_back(GV);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001823}
1824
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001825// FIXME: Get from somewhere?
1826enum ClassFlags {
1827 eClassFlags_Factory = 0x00001,
1828 eClassFlags_Meta = 0x00002,
1829 // <rdr://5142207>
1830 eClassFlags_HasCXXStructors = 0x02000,
1831 eClassFlags_Hidden = 0x20000,
1832 eClassFlags_ABI2_Hidden = 0x00010,
1833 eClassFlags_ABI2_HasCXXStructors = 0x00004 // <rdr://4923634>
1834};
1835
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001836/*
1837 struct _objc_class {
1838 Class isa;
1839 Class super_class;
1840 const char *name;
1841 long version;
1842 long info;
1843 long instance_size;
1844 struct _objc_ivar_list *ivars;
1845 struct _objc_method_list *methods;
1846 struct _objc_cache *cache;
1847 struct _objc_protocol_list *protocols;
1848 // Objective-C 1.0 extensions (<rdr://4585769>)
1849 const char *ivar_layout;
1850 struct _objc_class_ext *ext;
1851 };
1852
1853 See EmitClassExtension();
1854 */
1855void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
Daniel Dunbar8ede0052008-08-25 06:02:07 +00001856 DefinedSymbols.insert(ID->getIdentifier());
1857
Chris Lattnerd120b9e2008-11-24 03:54:41 +00001858 std::string ClassName = ID->getNameAsString();
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001859 // FIXME: Gross
1860 ObjCInterfaceDecl *Interface =
1861 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Daniel Dunbar67e778b2008-08-21 21:57:41 +00001862 llvm::Constant *Protocols =
Chris Lattner271d4c22008-11-24 05:29:24 +00001863 EmitProtocolList("\01L_OBJC_CLASS_PROTOCOLS_" + ID->getNameAsString(),
Daniel Dunbar67e778b2008-08-21 21:57:41 +00001864 Interface->protocol_begin(),
1865 Interface->protocol_end());
Daniel Dunbare5bb23c2009-04-22 09:39:34 +00001866 const llvm::Type *InterfaceTy = GetConcreteClassStruct(CGM, Interface);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001867 unsigned Flags = eClassFlags_Factory;
Daniel Dunbard8439f22009-01-12 21:08:18 +00001868 unsigned Size = CGM.getTargetData().getTypePaddedSize(InterfaceTy);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001869
1870 // FIXME: Set CXX-structors flag.
Daniel Dunbar8394fda2009-04-14 06:00:08 +00001871 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001872 Flags |= eClassFlags_Hidden;
1873
Daniel Dunbar12996f52008-08-26 21:51:14 +00001874 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
Douglas Gregorcd19b572009-04-23 01:02:12 +00001875 for (ObjCImplementationDecl::instmeth_iterator
1876 i = ID->instmeth_begin(CGM.getContext()),
1877 e = ID->instmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbar12996f52008-08-26 21:51:14 +00001878 // Instance methods should always be defined.
1879 InstanceMethods.push_back(GetMethodConstant(*i));
1880 }
Douglas Gregorcd19b572009-04-23 01:02:12 +00001881 for (ObjCImplementationDecl::classmeth_iterator
1882 i = ID->classmeth_begin(CGM.getContext()),
1883 e = ID->classmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbar12996f52008-08-26 21:51:14 +00001884 // Class methods should always be defined.
1885 ClassMethods.push_back(GetMethodConstant(*i));
1886 }
1887
Douglas Gregorcd19b572009-04-23 01:02:12 +00001888 for (ObjCImplementationDecl::propimpl_iterator
1889 i = ID->propimpl_begin(CGM.getContext()),
1890 e = ID->propimpl_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbar12996f52008-08-26 21:51:14 +00001891 ObjCPropertyImplDecl *PID = *i;
1892
1893 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1894 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1895
1896 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
1897 if (llvm::Constant *C = GetMethodConstant(MD))
1898 InstanceMethods.push_back(C);
1899 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
1900 if (llvm::Constant *C = GetMethodConstant(MD))
1901 InstanceMethods.push_back(C);
1902 }
1903 }
1904
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001905 std::vector<llvm::Constant*> Values(12);
Daniel Dunbar12996f52008-08-26 21:51:14 +00001906 Values[ 0] = EmitMetaClass(ID, Protocols, InterfaceTy, ClassMethods);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001907 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
Daniel Dunbar8ede0052008-08-25 06:02:07 +00001908 // Record a reference to the super class.
1909 LazySymbols.insert(Super->getIdentifier());
1910
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001911 Values[ 1] =
1912 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1913 ObjCTypes.ClassPtrTy);
1914 } else {
1915 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1916 }
1917 Values[ 2] = GetClassName(ID->getIdentifier());
1918 // Version is always 0.
1919 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1920 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1921 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanianf2a94cd2009-01-28 19:12:34 +00001922 Values[ 6] = EmitIvarList(ID, false);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00001923 Values[ 7] =
Chris Lattner271d4c22008-11-24 05:29:24 +00001924 EmitMethodList("\01L_OBJC_INSTANCE_METHODS_" + ID->getNameAsString(),
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00001925 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbar12996f52008-08-26 21:51:14 +00001926 InstanceMethods);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001927 // cache is always NULL.
1928 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1929 Values[ 9] = Protocols;
Fariborz Jahanian31b96492009-04-22 23:00:43 +00001930 Values[10] = BuildIvarLayout(ID, true);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001931 Values[11] = EmitClassExtension(ID);
1932 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1933 Values);
1934
1935 llvm::GlobalVariable *GV =
Daniel Dunbar90d88f92009-03-09 21:49:58 +00001936 CreateMetadataVar(std::string("\01L_OBJC_CLASS_")+ClassName, Init,
1937 "__OBJC,__class,regular,no_dead_strip",
Daniel Dunbar56756c32009-03-09 22:18:41 +00001938 4, true);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001939 DefinedClasses.push_back(GV);
1940}
1941
1942llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
1943 llvm::Constant *Protocols,
Daniel Dunbar12996f52008-08-26 21:51:14 +00001944 const llvm::Type *InterfaceTy,
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001945 const ConstantVector &Methods) {
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001946 unsigned Flags = eClassFlags_Meta;
Daniel Dunbard8439f22009-01-12 21:08:18 +00001947 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassTy);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001948
Daniel Dunbar8394fda2009-04-14 06:00:08 +00001949 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001950 Flags |= eClassFlags_Hidden;
1951
1952 std::vector<llvm::Constant*> Values(12);
1953 // The isa for the metaclass is the root of the hierarchy.
1954 const ObjCInterfaceDecl *Root = ID->getClassInterface();
1955 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
1956 Root = Super;
1957 Values[ 0] =
1958 llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
1959 ObjCTypes.ClassPtrTy);
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001960 // The super class for the metaclass is emitted as the name of the
1961 // super class. The runtime fixes this up to point to the
1962 // *metaclass* for the super class.
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001963 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
1964 Values[ 1] =
1965 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1966 ObjCTypes.ClassPtrTy);
1967 } else {
1968 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1969 }
1970 Values[ 2] = GetClassName(ID->getIdentifier());
1971 // Version is always 0.
1972 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1973 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1974 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanianf2a94cd2009-01-28 19:12:34 +00001975 Values[ 6] = EmitIvarList(ID, true);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00001976 Values[ 7] =
Chris Lattner271d4c22008-11-24 05:29:24 +00001977 EmitMethodList("\01L_OBJC_CLASS_METHODS_" + ID->getNameAsString(),
Daniel Dunbar9dfd3a72009-04-15 02:56:18 +00001978 "__OBJC,__cls_meth,regular,no_dead_strip",
Daniel Dunbar12996f52008-08-26 21:51:14 +00001979 Methods);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001980 // cache is always NULL.
1981 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1982 Values[ 9] = Protocols;
1983 // ivar_layout for metaclass is always NULL.
1984 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1985 // The class extension is always unused for metaclasses.
1986 Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1987 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1988 Values);
1989
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +00001990 std::string Name("\01L_OBJC_METACLASS_");
Chris Lattnerd120b9e2008-11-24 03:54:41 +00001991 Name += ID->getNameAsCString();
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +00001992
1993 // Check for a forward reference.
1994 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
1995 if (GV) {
1996 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1997 "Forward metaclass reference has incorrect type.");
1998 GV->setLinkage(llvm::GlobalValue::InternalLinkage);
1999 GV->setInitializer(Init);
2000 } else {
2001 GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
2002 llvm::GlobalValue::InternalLinkage,
2003 Init, Name,
2004 &CGM.getModule());
2005 }
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002006 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
Daniel Dunbar56756c32009-03-09 22:18:41 +00002007 GV->setAlignment(4);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002008 UsedGlobals.push_back(GV);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002009
2010 return GV;
2011}
2012
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +00002013llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
Chris Lattner271d4c22008-11-24 05:29:24 +00002014 std::string Name = "\01L_OBJC_METACLASS_" + ID->getNameAsString();
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +00002015
2016 // FIXME: Should we look these up somewhere other than the
2017 // module. Its a bit silly since we only generate these while
2018 // processing an implementation, so exactly one pointer would work
2019 // if know when we entered/exitted an implementation block.
2020
2021 // Check for an existing forward reference.
Fariborz Jahanian5fe09f72009-01-07 20:11:22 +00002022 // Previously, metaclass with internal linkage may have been defined.
2023 // pass 'true' as 2nd argument so it is returned.
2024 if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true)) {
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +00002025 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
2026 "Forward metaclass reference has incorrect type.");
2027 return GV;
2028 } else {
2029 // Generate as an external reference to keep a consistent
2030 // module. This will be patched up when we emit the metaclass.
2031 return new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
2032 llvm::GlobalValue::ExternalLinkage,
2033 0,
2034 Name,
2035 &CGM.getModule());
2036 }
2037}
2038
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002039/*
2040 struct objc_class_ext {
2041 uint32_t size;
2042 const char *weak_ivar_layout;
2043 struct _objc_property_list *properties;
2044 };
2045*/
2046llvm::Constant *
2047CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
2048 uint64_t Size =
Daniel Dunbard8439f22009-01-12 21:08:18 +00002049 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassExtensionTy);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002050
2051 std::vector<llvm::Constant*> Values(3);
2052 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Fariborz Jahanian31b96492009-04-22 23:00:43 +00002053 Values[1] = BuildIvarLayout(ID, false);
Daniel Dunbar9dfd3a72009-04-15 02:56:18 +00002054 Values[2] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
Fariborz Jahanian7b709bb2009-01-28 22:18:42 +00002055 ID, ID->getClassInterface(), ObjCTypes);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002056
2057 // Return null if no extension bits are used.
2058 if (Values[1]->isNullValue() && Values[2]->isNullValue())
2059 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
2060
2061 llvm::Constant *Init =
2062 llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
Daniel Dunbar90d88f92009-03-09 21:49:58 +00002063 return CreateMetadataVar("\01L_OBJC_CLASSEXT_" + ID->getNameAsString(),
Daniel Dunbar9dfd3a72009-04-15 02:56:18 +00002064 Init, "__OBJC,__class_ext,regular,no_dead_strip",
2065 4, true);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002066}
2067
Fariborz Jahaniana09a5142009-02-12 18:51:23 +00002068/// getInterfaceDeclForIvar - Get the interface declaration node where
2069/// this ivar is declared in.
2070/// FIXME. Ideally, this info should be in the ivar node. But currently
2071/// it is not and prevailing wisdom is that ASTs should not have more
2072/// info than is absolutely needed, even though this info reflects the
2073/// source language.
2074///
2075static const ObjCInterfaceDecl *getInterfaceDeclForIvar(
2076 const ObjCInterfaceDecl *OI,
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002077 const ObjCIvarDecl *IVD,
2078 ASTContext &Context) {
Fariborz Jahaniana09a5142009-02-12 18:51:23 +00002079 if (!OI)
2080 return 0;
2081 assert(isa<ObjCInterfaceDecl>(OI) && "OI is not an interface");
2082 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
2083 E = OI->ivar_end(); I != E; ++I)
2084 if ((*I)->getIdentifier() == IVD->getIdentifier())
2085 return OI;
Fariborz Jahanian13c22d72009-03-31 17:00:52 +00002086 // look into properties.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002087 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(Context),
2088 E = OI->prop_end(Context); I != E; ++I) {
Fariborz Jahanian13c22d72009-03-31 17:00:52 +00002089 ObjCPropertyDecl *PDecl = (*I);
2090 if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl())
2091 if (IV->getIdentifier() == IVD->getIdentifier())
2092 return OI;
2093 }
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002094 return getInterfaceDeclForIvar(OI->getSuperClass(), IVD, Context);
Fariborz Jahaniana09a5142009-02-12 18:51:23 +00002095}
2096
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002097/*
2098 struct objc_ivar {
2099 char *ivar_name;
2100 char *ivar_type;
2101 int ivar_offset;
2102 };
2103
2104 struct objc_ivar_list {
2105 int ivar_count;
2106 struct objc_ivar list[count];
2107 };
2108 */
2109llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanianf2a94cd2009-01-28 19:12:34 +00002110 bool ForClass) {
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002111 std::vector<llvm::Constant*> Ivars, Ivar(3);
2112
2113 // When emitting the root class GCC emits ivar entries for the
2114 // actual class structure. It is not clear if we need to follow this
2115 // behavior; for now lets try and get away with not doing it. If so,
2116 // the cleanest solution would be to make up an ObjCInterfaceDecl
2117 // for the class.
2118 if (ForClass)
2119 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
Fariborz Jahanianf2a94cd2009-01-28 19:12:34 +00002120
2121 ObjCInterfaceDecl *OID =
2122 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Fariborz Jahanianf2a94cd2009-01-28 19:12:34 +00002123
Daniel Dunbar356f0742009-04-20 06:54:31 +00002124 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
2125 GetNamedIvarList(OID, OIvars);
2126
2127 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
2128 ObjCIvarDecl *IVD = OIvars[i];
Daniel Dunbare42aede2009-04-22 08:22:17 +00002129 Ivar[0] = GetMethodVarName(IVD->getIdentifier());
2130 Ivar[1] = GetMethodVarType(IVD);
Daniel Dunbar72878722009-04-20 20:18:54 +00002131 Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy,
Daniel Dunbar85d37542009-04-22 07:32:20 +00002132 ComputeIvarBaseOffset(CGM, OID, IVD));
Daniel Dunbarc9197cd2008-10-17 20:21:44 +00002133 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002134 }
2135
2136 // Return null for empty list.
2137 if (Ivars.empty())
2138 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
2139
2140 std::vector<llvm::Constant*> Values(2);
2141 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
2142 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
2143 Ivars.size());
2144 Values[1] = llvm::ConstantArray::get(AT, Ivars);
2145 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2146
Daniel Dunbar90d88f92009-03-09 21:49:58 +00002147 llvm::GlobalVariable *GV;
2148 if (ForClass)
2149 GV = CreateMetadataVar("\01L_OBJC_CLASS_VARIABLES_" + ID->getNameAsString(),
Daniel Dunbar56756c32009-03-09 22:18:41 +00002150 Init, "__OBJC,__class_vars,regular,no_dead_strip",
2151 4, true);
Daniel Dunbar90d88f92009-03-09 21:49:58 +00002152 else
2153 GV = CreateMetadataVar("\01L_OBJC_INSTANCE_VARIABLES_"
2154 + ID->getNameAsString(),
2155 Init, "__OBJC,__instance_vars,regular,no_dead_strip",
Daniel Dunbar9dfd3a72009-04-15 02:56:18 +00002156 4, true);
2157 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.IvarListPtrTy);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002158}
2159
2160/*
2161 struct objc_method {
2162 SEL method_name;
2163 char *method_types;
2164 void *method;
2165 };
2166
2167 struct objc_method_list {
2168 struct objc_method_list *obsolete;
2169 int count;
2170 struct objc_method methods_list[count];
2171 };
2172*/
Daniel Dunbar12996f52008-08-26 21:51:14 +00002173
2174/// GetMethodConstant - Return a struct objc_method constant for the
2175/// given method if it has been defined. The result is null if the
2176/// method has not been defined. The return value has type MethodPtrTy.
Daniel Dunbarfe131f02008-08-27 02:31:56 +00002177llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
Daniel Dunbar12996f52008-08-26 21:51:14 +00002178 // FIXME: Use DenseMap::lookup
2179 llvm::Function *Fn = MethodDefinitions[MD];
2180 if (!Fn)
2181 return 0;
2182
2183 std::vector<llvm::Constant*> Method(3);
2184 Method[0] =
2185 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
2186 ObjCTypes.SelectorPtrTy);
2187 Method[1] = GetMethodVarType(MD);
2188 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
2189 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
2190}
2191
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00002192llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name,
2193 const char *Section,
Daniel Dunbarfe131f02008-08-27 02:31:56 +00002194 const ConstantVector &Methods) {
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002195 // Return null for empty list.
2196 if (Methods.empty())
2197 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
2198
2199 std::vector<llvm::Constant*> Values(3);
2200 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2201 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
2202 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
2203 Methods.size());
2204 Values[2] = llvm::ConstantArray::get(AT, Methods);
2205 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2206
Daniel Dunbar9dfd3a72009-04-15 02:56:18 +00002207 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002208 return llvm::ConstantExpr::getBitCast(GV,
2209 ObjCTypes.MethodListPtrTy);
Daniel Dunbarace33292008-08-16 03:19:19 +00002210}
2211
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00002212llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD,
Daniel Dunbar9fc15a82009-02-02 21:43:58 +00002213 const ObjCContainerDecl *CD) {
Daniel Dunbarace33292008-08-16 03:19:19 +00002214 std::string Name;
Fariborz Jahanian0adaa8a2009-01-10 21:06:09 +00002215 GetNameForMethod(OMD, CD, Name);
Daniel Dunbarace33292008-08-16 03:19:19 +00002216
Daniel Dunbar34bda882009-02-02 23:23:47 +00002217 CodeGenTypes &Types = CGM.getTypes();
Daniel Dunbar3ad1f072008-09-10 04:01:49 +00002218 const llvm::FunctionType *MethodTy =
Daniel Dunbar34bda882009-02-02 23:23:47 +00002219 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Daniel Dunbarace33292008-08-16 03:19:19 +00002220 llvm::Function *Method =
Daniel Dunbar3ad1f072008-09-10 04:01:49 +00002221 llvm::Function::Create(MethodTy,
Daniel Dunbarace33292008-08-16 03:19:19 +00002222 llvm::GlobalValue::InternalLinkage,
2223 Name,
2224 &CGM.getModule());
Daniel Dunbar12996f52008-08-26 21:51:14 +00002225 MethodDefinitions.insert(std::make_pair(OMD, Method));
Daniel Dunbarace33292008-08-16 03:19:19 +00002226
Daniel Dunbarace33292008-08-16 03:19:19 +00002227 return Method;
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00002228}
2229
Daniel Dunbar1cfb5192009-04-19 02:03:42 +00002230/// GetFieldBaseOffset - return the field's byte offset.
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002231uint64_t CGObjCCommonMac::GetFieldBaseOffset(const ObjCInterfaceDecl *OI,
2232 const llvm::StructLayout *Layout,
Chris Lattnerd391dab2009-03-31 08:33:16 +00002233 const FieldDecl *Field) {
Daniel Dunbar85d37542009-04-22 07:32:20 +00002234 // Is this a C struct?
Fariborz Jahanian31614742009-04-20 22:03:45 +00002235 if (!OI)
2236 return Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(Field));
Daniel Dunbar85d37542009-04-22 07:32:20 +00002237 return ComputeIvarBaseOffset(CGM, OI, cast<ObjCIvarDecl>(Field));
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002238}
2239
Daniel Dunbarc4594f22009-03-09 20:09:19 +00002240llvm::GlobalVariable *
2241CGObjCCommonMac::CreateMetadataVar(const std::string &Name,
2242 llvm::Constant *Init,
2243 const char *Section,
Daniel Dunbareddddd22009-03-09 20:50:13 +00002244 unsigned Align,
2245 bool AddToUsed) {
Daniel Dunbarc4594f22009-03-09 20:09:19 +00002246 const llvm::Type *Ty = Init->getType();
2247 llvm::GlobalVariable *GV =
2248 new llvm::GlobalVariable(Ty, false,
2249 llvm::GlobalValue::InternalLinkage,
2250 Init,
2251 Name,
2252 &CGM.getModule());
2253 if (Section)
2254 GV->setSection(Section);
Daniel Dunbareddddd22009-03-09 20:50:13 +00002255 if (Align)
2256 GV->setAlignment(Align);
2257 if (AddToUsed)
Daniel Dunbarc4594f22009-03-09 20:09:19 +00002258 UsedGlobals.push_back(GV);
2259 return GV;
2260}
2261
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00002262llvm::Function *CGObjCMac::ModuleInitFunction() {
Daniel Dunbar1be1df32008-08-11 21:35:06 +00002263 // Abuse this interface function as a place to finalize.
2264 FinishModule();
2265
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00002266 return NULL;
2267}
2268
Chris Lattneraea1aee2009-03-22 21:03:39 +00002269llvm::Constant *CGObjCMac::GetPropertyGetFunction() {
Chris Lattnera7ecda42009-04-22 02:44:54 +00002270 return ObjCTypes.getGetPropertyFn();
Daniel Dunbarf7103722008-09-24 03:38:44 +00002271}
2272
Chris Lattneraea1aee2009-03-22 21:03:39 +00002273llvm::Constant *CGObjCMac::GetPropertySetFunction() {
Chris Lattnera7ecda42009-04-22 02:44:54 +00002274 return ObjCTypes.getSetPropertyFn();
Daniel Dunbarf7103722008-09-24 03:38:44 +00002275}
2276
Chris Lattneraea1aee2009-03-22 21:03:39 +00002277llvm::Constant *CGObjCMac::EnumerationMutationFunction() {
Chris Lattnera7ecda42009-04-22 02:44:54 +00002278 return ObjCTypes.getEnumerationMutationFn();
Anders Carlsson58d16242008-08-31 04:05:03 +00002279}
2280
Daniel Dunbar83544842008-09-28 01:03:14 +00002281/*
2282
2283Objective-C setjmp-longjmp (sjlj) Exception Handling
2284--
2285
2286The basic framework for a @try-catch-finally is as follows:
2287{
2288 objc_exception_data d;
2289 id _rethrow = null;
Anders Carlsson8559de12009-02-07 21:26:04 +00002290 bool _call_try_exit = true;
2291
Daniel Dunbar83544842008-09-28 01:03:14 +00002292 objc_exception_try_enter(&d);
2293 if (!setjmp(d.jmp_buf)) {
2294 ... try body ...
2295 } else {
2296 // exception path
2297 id _caught = objc_exception_extract(&d);
2298
2299 // enter new try scope for handlers
2300 if (!setjmp(d.jmp_buf)) {
2301 ... match exception and execute catch blocks ...
2302
2303 // fell off end, rethrow.
2304 _rethrow = _caught;
Daniel Dunbare9900eb2008-09-30 01:06:03 +00002305 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar83544842008-09-28 01:03:14 +00002306 } else {
2307 // exception in catch block
2308 _rethrow = objc_exception_extract(&d);
Anders Carlsson8559de12009-02-07 21:26:04 +00002309 _call_try_exit = false;
2310 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar83544842008-09-28 01:03:14 +00002311 }
2312 }
Daniel Dunbare9900eb2008-09-30 01:06:03 +00002313 ... jump-through-finally to finally_end ...
Daniel Dunbar83544842008-09-28 01:03:14 +00002314
2315finally:
Anders Carlsson8559de12009-02-07 21:26:04 +00002316 if (_call_try_exit)
2317 objc_exception_try_exit(&d);
2318
Daniel Dunbar83544842008-09-28 01:03:14 +00002319 ... finally block ....
Daniel Dunbare9900eb2008-09-30 01:06:03 +00002320 ... dispatch to finally destination ...
2321
2322finally_rethrow:
2323 objc_exception_throw(_rethrow);
2324
2325finally_end:
Daniel Dunbar83544842008-09-28 01:03:14 +00002326}
2327
2328This framework differs slightly from the one gcc uses, in that gcc
Daniel Dunbare9900eb2008-09-30 01:06:03 +00002329uses _rethrow to determine if objc_exception_try_exit should be called
2330and if the object should be rethrown. This breaks in the face of
2331throwing nil and introduces unnecessary branches.
Daniel Dunbar83544842008-09-28 01:03:14 +00002332
2333We specialize this framework for a few particular circumstances:
2334
2335 - If there are no catch blocks, then we avoid emitting the second
2336 exception handling context.
2337
2338 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
2339 e)) we avoid emitting the code to rethrow an uncaught exception.
2340
2341 - FIXME: If there is no @finally block we can do a few more
2342 simplifications.
2343
2344Rethrows and Jumps-Through-Finally
2345--
2346
2347Support for implicit rethrows and jumping through the finally block is
2348handled by storing the current exception-handling context in
2349ObjCEHStack.
2350
Daniel Dunbare9900eb2008-09-30 01:06:03 +00002351In order to implement proper @finally semantics, we support one basic
2352mechanism for jumping through the finally block to an arbitrary
2353destination. Constructs which generate exits from a @try or @catch
2354block use this mechanism to implement the proper semantics by chaining
2355jumps, as necessary.
2356
2357This mechanism works like the one used for indirect goto: we
2358arbitrarily assign an ID to each destination and store the ID for the
2359destination in a variable prior to entering the finally block. At the
2360end of the finally block we simply create a switch to the proper
2361destination.
Fariborz Jahanianfbeda7b2008-11-21 00:49:24 +00002362
2363Code gen for @synchronized(expr) stmt;
2364Effectively generating code for:
2365objc_sync_enter(expr);
2366@try stmt @finally { objc_sync_exit(expr); }
Daniel Dunbar83544842008-09-28 01:03:14 +00002367*/
2368
Fariborz Jahanianfbeda7b2008-11-21 00:49:24 +00002369void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
2370 const Stmt &S) {
2371 bool isTry = isa<ObjCAtTryStmt>(S);
Daniel Dunbare9900eb2008-09-30 01:06:03 +00002372 // Create various blocks we refer to for handling @finally.
Daniel Dunbar72f96552008-11-11 02:29:29 +00002373 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Anders Carlsson8559de12009-02-07 21:26:04 +00002374 llvm::BasicBlock *FinallyExit = CGF.createBasicBlock("finally.exit");
Daniel Dunbar72f96552008-11-11 02:29:29 +00002375 llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
2376 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
2377 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
Daniel Dunbar34416d62009-02-24 01:43:46 +00002378
2379 // For @synchronized, call objc_sync_enter(sync.expr). The
2380 // evaluation of the expression must occur before we enter the
2381 // @synchronized. We can safely avoid a temp here because jumps into
2382 // @synchronized are illegal & this will dominate uses.
2383 llvm::Value *SyncArg = 0;
2384 if (!isTry) {
2385 SyncArg =
2386 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
2387 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattner23e24652009-04-06 16:53:45 +00002388 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar34416d62009-02-24 01:43:46 +00002389 }
Daniel Dunbare9900eb2008-09-30 01:06:03 +00002390
2391 // Push an EH context entry, used for handling rethrows and jumps
2392 // through finally.
Anders Carlsson00ffb962009-02-09 20:38:58 +00002393 CGF.PushCleanupBlock(FinallyBlock);
2394
Anders Carlssonecd81832009-02-07 21:37:21 +00002395 CGF.ObjCEHValueStack.push_back(0);
2396
Daniel Dunbare9900eb2008-09-30 01:06:03 +00002397 // Allocate memory for the exception data and rethrow pointer.
Anders Carlssonfca6c292008-09-09 17:59:25 +00002398 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
2399 "exceptiondata.ptr");
Daniel Dunbar35b777f2008-10-29 22:36:39 +00002400 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
2401 "_rethrow");
Anders Carlsson8559de12009-02-07 21:26:04 +00002402 llvm::Value *CallTryExitPtr = CGF.CreateTempAlloca(llvm::Type::Int1Ty,
2403 "_call_try_exit");
2404 CGF.Builder.CreateStore(llvm::ConstantInt::getTrue(), CallTryExitPtr);
2405
Anders Carlssonfca6c292008-09-09 17:59:25 +00002406 // Enter a new try block and call setjmp.
Chris Lattnere05d4cb2009-04-22 02:26:14 +00002407 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryEnterFn(), ExceptionData);
Anders Carlssonfca6c292008-09-09 17:59:25 +00002408 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
2409 "jmpbufarray");
2410 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
Chris Lattnere05d4cb2009-04-22 02:26:14 +00002411 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.getSetJmpFn(),
Anders Carlssonfca6c292008-09-09 17:59:25 +00002412 JmpBufPtr, "result");
Daniel Dunbare9900eb2008-09-30 01:06:03 +00002413
Daniel Dunbar72f96552008-11-11 02:29:29 +00002414 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
2415 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbarbe56f012008-10-02 17:05:36 +00002416 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
Daniel Dunbar0ac66f72008-09-27 23:30:04 +00002417 TryHandler, TryBlock);
Anders Carlssonfca6c292008-09-09 17:59:25 +00002418
2419 // Emit the @try block.
2420 CGF.EmitBlock(TryBlock);
Fariborz Jahanianfbeda7b2008-11-21 00:49:24 +00002421 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
2422 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
Anders Carlsson00ffb962009-02-09 20:38:58 +00002423 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlssonfca6c292008-09-09 17:59:25 +00002424
2425 // Emit the "exception in @try" block.
Daniel Dunbar0ac66f72008-09-27 23:30:04 +00002426 CGF.EmitBlock(TryHandler);
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00002427
2428 // Retrieve the exception object. We may emit multiple blocks but
2429 // nothing can cross this so the value is already in SSA form.
Chris Lattnere05d4cb2009-04-22 02:26:14 +00002430 llvm::Value *Caught =
2431 CGF.Builder.CreateCall(ObjCTypes.getExceptionExtractFn(),
2432 ExceptionData, "caught");
Anders Carlssonecd81832009-02-07 21:37:21 +00002433 CGF.ObjCEHValueStack.back() = Caught;
Fariborz Jahanianfbeda7b2008-11-21 00:49:24 +00002434 if (!isTry)
2435 {
2436 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson8559de12009-02-07 21:26:04 +00002437 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlsson00ffb962009-02-09 20:38:58 +00002438 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Fariborz Jahanianfbeda7b2008-11-21 00:49:24 +00002439 }
2440 else if (const ObjCAtCatchStmt* CatchStmt =
2441 cast<ObjCAtTryStmt>(S).getCatchStmts())
2442 {
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00002443 // Enter a new exception try block (in case a @catch block throws
2444 // an exception).
Chris Lattnere05d4cb2009-04-22 02:26:14 +00002445 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryEnterFn(), ExceptionData);
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00002446
Chris Lattnere05d4cb2009-04-22 02:26:14 +00002447 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.getSetJmpFn(),
Anders Carlssonfca6c292008-09-09 17:59:25 +00002448 JmpBufPtr, "result");
Daniel Dunbarbe56f012008-10-02 17:05:36 +00002449 llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw");
Anders Carlssonfca6c292008-09-09 17:59:25 +00002450
Daniel Dunbar72f96552008-11-11 02:29:29 +00002451 llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch");
2452 llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler");
Daniel Dunbar0ac66f72008-09-27 23:30:04 +00002453 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
Anders Carlssonfca6c292008-09-09 17:59:25 +00002454
2455 CGF.EmitBlock(CatchBlock);
2456
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00002457 // Handle catch list. As a special case we check if everything is
2458 // matched and avoid generating code for falling off the end if
2459 // so.
2460 bool AllMatched = false;
Anders Carlssonfca6c292008-09-09 17:59:25 +00002461 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbar72f96552008-11-11 02:29:29 +00002462 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch");
Anders Carlssonfca6c292008-09-09 17:59:25 +00002463
Steve Naroff0e8b96a2009-03-03 19:52:17 +00002464 const ParmVarDecl *CatchParam = CatchStmt->getCatchParamDecl();
Daniel Dunbar7a68b452008-09-27 07:36:24 +00002465 const PointerType *PT = 0;
2466
Anders Carlssonfca6c292008-09-09 17:59:25 +00002467 // catch(...) always matches.
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00002468 if (!CatchParam) {
2469 AllMatched = true;
2470 } else {
Steve Naroff0e8b96a2009-03-03 19:52:17 +00002471 PT = CatchParam->getType()->getAsPointerType();
Anders Carlssonfca6c292008-09-09 17:59:25 +00002472
Daniel Dunbard04c9352008-09-27 22:21:14 +00002473 // catch(id e) always matches.
2474 // FIXME: For the time being we also match id<X>; this should
2475 // be rejected by Sema instead.
Steve Naroff17c03822009-02-12 17:52:19 +00002476 if ((PT && CGF.getContext().isObjCIdStructType(PT->getPointeeType())) ||
Steve Naroff0e8b96a2009-03-03 19:52:17 +00002477 CatchParam->getType()->isObjCQualifiedIdType())
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00002478 AllMatched = true;
Anders Carlssonfca6c292008-09-09 17:59:25 +00002479 }
2480
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00002481 if (AllMatched) {
Anders Carlsson75d86732008-09-11 09:15:33 +00002482 if (CatchParam) {
Steve Naroff0e8b96a2009-03-03 19:52:17 +00002483 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbar5aa22bc2008-11-11 23:11:34 +00002484 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Steve Naroff0e8b96a2009-03-03 19:52:17 +00002485 CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlsson75d86732008-09-11 09:15:33 +00002486 }
Anders Carlsson1f4acc32008-09-11 08:21:54 +00002487
Anders Carlsson75d86732008-09-11 09:15:33 +00002488 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlsson00ffb962009-02-09 20:38:58 +00002489 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlssonfca6c292008-09-09 17:59:25 +00002490 break;
2491 }
2492
Daniel Dunbar7a68b452008-09-27 07:36:24 +00002493 assert(PT && "Unexpected non-pointer type in @catch");
2494 QualType T = PT->getPointeeType();
Anders Carlssona4519172008-09-11 06:35:14 +00002495 const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType();
Anders Carlssonfca6c292008-09-09 17:59:25 +00002496 assert(ObjCType && "Catch parameter must have Objective-C type!");
2497
2498 // Check if the @catch block matches the exception object.
2499 llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl());
2500
Chris Lattnere05d4cb2009-04-22 02:26:14 +00002501 llvm::Value *Match =
2502 CGF.Builder.CreateCall2(ObjCTypes.getExceptionMatchFn(),
2503 Class, Caught, "match");
Anders Carlssonfca6c292008-09-09 17:59:25 +00002504
Daniel Dunbar72f96552008-11-11 02:29:29 +00002505 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched");
Anders Carlssonfca6c292008-09-09 17:59:25 +00002506
Daniel Dunbarbe56f012008-10-02 17:05:36 +00002507 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
Daniel Dunbar0ac66f72008-09-27 23:30:04 +00002508 MatchedBlock, NextCatchBlock);
Anders Carlssonfca6c292008-09-09 17:59:25 +00002509
2510 // Emit the @catch block.
2511 CGF.EmitBlock(MatchedBlock);
Steve Naroff0e8b96a2009-03-03 19:52:17 +00002512 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbar5aa22bc2008-11-11 23:11:34 +00002513 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar83544842008-09-28 01:03:14 +00002514
2515 llvm::Value *Tmp =
Steve Naroff0e8b96a2009-03-03 19:52:17 +00002516 CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(CatchParam->getType()),
Daniel Dunbar83544842008-09-28 01:03:14 +00002517 "tmp");
Steve Naroff0e8b96a2009-03-03 19:52:17 +00002518 CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlsson75d86732008-09-11 09:15:33 +00002519
2520 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlsson00ffb962009-02-09 20:38:58 +00002521 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlssonfca6c292008-09-09 17:59:25 +00002522
2523 CGF.EmitBlock(NextCatchBlock);
2524 }
2525
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00002526 if (!AllMatched) {
2527 // None of the handlers caught the exception, so store it to be
2528 // rethrown at the end of the @finally block.
2529 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson00ffb962009-02-09 20:38:58 +00002530 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00002531 }
2532
2533 // Emit the exception handler for the @catch blocks.
Daniel Dunbar0ac66f72008-09-27 23:30:04 +00002534 CGF.EmitBlock(CatchHandler);
Chris Lattnere05d4cb2009-04-22 02:26:14 +00002535 CGF.Builder.CreateStore(
2536 CGF.Builder.CreateCall(ObjCTypes.getExceptionExtractFn(),
2537 ExceptionData),
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00002538 RethrowPtr);
Anders Carlsson8559de12009-02-07 21:26:04 +00002539 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlsson00ffb962009-02-09 20:38:58 +00002540 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00002541 } else {
Anders Carlssonfca6c292008-09-09 17:59:25 +00002542 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson8559de12009-02-07 21:26:04 +00002543 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlsson00ffb962009-02-09 20:38:58 +00002544 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Anders Carlssonfca6c292008-09-09 17:59:25 +00002545 }
2546
Daniel Dunbare9900eb2008-09-30 01:06:03 +00002547 // Pop the exception-handling stack entry. It is important to do
2548 // this now, because the code in the @finally block is not in this
2549 // context.
Anders Carlsson00ffb962009-02-09 20:38:58 +00002550 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
2551
Anders Carlssonecd81832009-02-07 21:37:21 +00002552 CGF.ObjCEHValueStack.pop_back();
2553
Anders Carlssonfca6c292008-09-09 17:59:25 +00002554 // Emit the @finally block.
2555 CGF.EmitBlock(FinallyBlock);
Anders Carlsson8559de12009-02-07 21:26:04 +00002556 llvm::Value* CallTryExit = CGF.Builder.CreateLoad(CallTryExitPtr, "tmp");
2557
2558 CGF.Builder.CreateCondBr(CallTryExit, FinallyExit, FinallyNoExit);
2559
2560 CGF.EmitBlock(FinallyExit);
Chris Lattnere05d4cb2009-04-22 02:26:14 +00002561 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryExitFn(), ExceptionData);
Daniel Dunbar7a68b452008-09-27 07:36:24 +00002562
2563 CGF.EmitBlock(FinallyNoExit);
Fariborz Jahanianfbeda7b2008-11-21 00:49:24 +00002564 if (isTry) {
2565 if (const ObjCAtFinallyStmt* FinallyStmt =
2566 cast<ObjCAtTryStmt>(S).getFinallyStmt())
2567 CGF.EmitStmt(FinallyStmt->getFinallyBody());
Daniel Dunbar34416d62009-02-24 01:43:46 +00002568 } else {
2569 // Emit objc_sync_exit(expr); as finally's sole statement for
2570 // @synchronized.
Chris Lattnerf6ec7e42009-04-22 02:38:11 +00002571 CGF.Builder.CreateCall(ObjCTypes.getSyncExitFn(), SyncArg);
Fariborz Jahanian3895d922008-11-21 19:21:53 +00002572 }
Anders Carlssonfca6c292008-09-09 17:59:25 +00002573
Anders Carlsson00ffb962009-02-09 20:38:58 +00002574 // Emit the switch block
2575 if (Info.SwitchBlock)
2576 CGF.EmitBlock(Info.SwitchBlock);
2577 if (Info.EndBlock)
2578 CGF.EmitBlock(Info.EndBlock);
2579
Daniel Dunbare9900eb2008-09-30 01:06:03 +00002580 CGF.EmitBlock(FinallyRethrow);
Chris Lattnerf6ec7e42009-04-22 02:38:11 +00002581 CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(),
Daniel Dunbare9900eb2008-09-30 01:06:03 +00002582 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbar0ac66f72008-09-27 23:30:04 +00002583 CGF.Builder.CreateUnreachable();
Daniel Dunbare9900eb2008-09-30 01:06:03 +00002584
2585 CGF.EmitBlock(FinallyEnd);
Anders Carlssonb01a2112008-09-09 10:04:29 +00002586}
2587
2588void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbare9900eb2008-09-30 01:06:03 +00002589 const ObjCAtThrowStmt &S) {
Anders Carlsson05d7be72008-09-09 16:16:55 +00002590 llvm::Value *ExceptionAsObject;
2591
2592 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2593 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
2594 ExceptionAsObject =
2595 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
2596 } else {
Anders Carlssonecd81832009-02-07 21:37:21 +00002597 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Daniel Dunbar83544842008-09-28 01:03:14 +00002598 "Unexpected rethrow outside @catch block.");
Anders Carlssonecd81832009-02-07 21:37:21 +00002599 ExceptionAsObject = CGF.ObjCEHValueStack.back();
Anders Carlsson05d7be72008-09-09 16:16:55 +00002600 }
2601
Chris Lattnerf6ec7e42009-04-22 02:38:11 +00002602 CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(), ExceptionAsObject);
Anders Carlssonfca6c292008-09-09 17:59:25 +00002603 CGF.Builder.CreateUnreachable();
Daniel Dunbar5aa22bc2008-11-11 23:11:34 +00002604
2605 // Clear the insertion point to indicate we are in unreachable code.
2606 CGF.Builder.ClearInsertionPoint();
Anders Carlssonb01a2112008-09-09 10:04:29 +00002607}
2608
Fariborz Jahanian252d87f2008-11-18 22:37:34 +00002609/// EmitObjCWeakRead - Code gen for loading value of a __weak
Fariborz Jahanian3305ad32008-11-18 21:45:40 +00002610/// object: objc_read_weak (id *src)
2611///
Fariborz Jahanian252d87f2008-11-18 22:37:34 +00002612llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian3305ad32008-11-18 21:45:40 +00002613 llvm::Value *AddrWeakObj)
2614{
Eli Friedmanf8466232009-03-07 03:57:15 +00002615 const llvm::Type* DestTy =
2616 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahaniand2f661a2008-11-19 17:34:06 +00002617 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Chris Lattnera7ecda42009-04-22 02:44:54 +00002618 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.getGcReadWeakFn(),
Fariborz Jahanian252d87f2008-11-18 22:37:34 +00002619 AddrWeakObj, "weakread");
Eli Friedmanf8466232009-03-07 03:57:15 +00002620 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian3305ad32008-11-18 21:45:40 +00002621 return read_weak;
2622}
2623
Fariborz Jahanian252d87f2008-11-18 22:37:34 +00002624/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
2625/// objc_assign_weak (id src, id *dst)
2626///
2627void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
2628 llvm::Value *src, llvm::Value *dst)
2629{
Fariborz Jahanianad51ca02009-03-23 19:10:40 +00002630 const llvm::Type * SrcTy = src->getType();
2631 if (!isa<llvm::PointerType>(SrcTy)) {
2632 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2633 assert(Size <= 8 && "does not support size > 8");
2634 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2635 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian664da982009-03-13 00:42:52 +00002636 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2637 }
Fariborz Jahaniand2f661a2008-11-19 17:34:06 +00002638 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2639 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattner293c1d32009-04-17 22:12:36 +00002640 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
Fariborz Jahanian252d87f2008-11-18 22:37:34 +00002641 src, dst, "weakassign");
2642 return;
2643}
2644
Fariborz Jahanian17958902008-11-19 00:59:10 +00002645/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
2646/// objc_assign_global (id src, id *dst)
2647///
2648void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
2649 llvm::Value *src, llvm::Value *dst)
2650{
Fariborz Jahanianad51ca02009-03-23 19:10:40 +00002651 const llvm::Type * SrcTy = src->getType();
2652 if (!isa<llvm::PointerType>(SrcTy)) {
2653 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2654 assert(Size <= 8 && "does not support size > 8");
2655 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2656 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian664da982009-03-13 00:42:52 +00002657 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2658 }
Fariborz Jahaniand2f661a2008-11-19 17:34:06 +00002659 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2660 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerf6ec7e42009-04-22 02:38:11 +00002661 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignGlobalFn(),
Fariborz Jahanian17958902008-11-19 00:59:10 +00002662 src, dst, "globalassign");
2663 return;
2664}
2665
Fariborz Jahanianf310b592008-11-20 19:23:36 +00002666/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
2667/// objc_assign_ivar (id src, id *dst)
2668///
2669void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
2670 llvm::Value *src, llvm::Value *dst)
2671{
Fariborz Jahanianad51ca02009-03-23 19:10:40 +00002672 const llvm::Type * SrcTy = src->getType();
2673 if (!isa<llvm::PointerType>(SrcTy)) {
2674 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2675 assert(Size <= 8 && "does not support size > 8");
2676 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2677 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian664da982009-03-13 00:42:52 +00002678 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2679 }
Fariborz Jahanianf310b592008-11-20 19:23:36 +00002680 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2681 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerf6ec7e42009-04-22 02:38:11 +00002682 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignIvarFn(),
Fariborz Jahanianf310b592008-11-20 19:23:36 +00002683 src, dst, "assignivar");
2684 return;
2685}
2686
Fariborz Jahanian17958902008-11-19 00:59:10 +00002687/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
2688/// objc_assign_strongCast (id src, id *dst)
2689///
2690void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
2691 llvm::Value *src, llvm::Value *dst)
2692{
Fariborz Jahanianad51ca02009-03-23 19:10:40 +00002693 const llvm::Type * SrcTy = src->getType();
2694 if (!isa<llvm::PointerType>(SrcTy)) {
2695 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2696 assert(Size <= 8 && "does not support size > 8");
2697 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2698 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian664da982009-03-13 00:42:52 +00002699 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2700 }
Fariborz Jahaniand2f661a2008-11-19 17:34:06 +00002701 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2702 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerf6ec7e42009-04-22 02:38:11 +00002703 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignStrongCastFn(),
Fariborz Jahanian17958902008-11-19 00:59:10 +00002704 src, dst, "weakassign");
2705 return;
2706}
2707
Fariborz Jahanian4337afe2009-02-02 20:02:29 +00002708/// EmitObjCValueForIvar - Code Gen for ivar reference.
2709///
Fariborz Jahanianc912eb72009-02-03 19:03:09 +00002710LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
2711 QualType ObjectTy,
2712 llvm::Value *BaseValue,
2713 const ObjCIvarDecl *Ivar,
Fariborz Jahanianc912eb72009-02-03 19:03:09 +00002714 unsigned CVRQualifiers) {
Daniel Dunbarf5254bd2009-04-21 01:19:28 +00002715 const ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
Daniel Dunbar85d37542009-04-22 07:32:20 +00002716 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
2717 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian4337afe2009-02-02 20:02:29 +00002718}
2719
Fariborz Jahanian27cc6662009-02-10 19:02:04 +00002720llvm::Value *CGObjCMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar61e14a62009-04-22 05:08:15 +00002721 const ObjCInterfaceDecl *Interface,
Fariborz Jahanian27cc6662009-02-10 19:02:04 +00002722 const ObjCIvarDecl *Ivar) {
Daniel Dunbar85d37542009-04-22 07:32:20 +00002723 uint64_t Offset = ComputeIvarBaseOffset(CGM, Interface, Ivar);
Fariborz Jahanian27cc6662009-02-10 19:02:04 +00002724 return llvm::ConstantInt::get(
2725 CGM.getTypes().ConvertType(CGM.getContext().LongTy),
2726 Offset);
2727}
2728
Daniel Dunbar1be1df32008-08-11 21:35:06 +00002729/* *** Private Interface *** */
2730
2731/// EmitImageInfo - Emit the image info marker used to encode some module
2732/// level information.
2733///
2734/// See: <rdr://4810609&4810587&4810587>
2735/// struct IMAGE_INFO {
2736/// unsigned version;
2737/// unsigned flags;
2738/// };
2739enum ImageInfoFlags {
Daniel Dunbarb79f5a92009-04-20 07:11:47 +00002740 eImageInfo_FixAndContinue = (1 << 0), // FIXME: Not sure what
2741 // this implies.
2742 eImageInfo_GarbageCollected = (1 << 1),
2743 eImageInfo_GCOnly = (1 << 2),
2744 eImageInfo_OptimizedByDyld = (1 << 3), // FIXME: When is this set.
2745
2746 // A flag indicating that the module has no instances of an
2747 // @synthesize of a superclass variable. <rdar://problem/6803242>
2748 eImageInfo_CorrectedSynthesize = (1 << 4)
Daniel Dunbar1be1df32008-08-11 21:35:06 +00002749};
2750
2751void CGObjCMac::EmitImageInfo() {
2752 unsigned version = 0; // Version is unused?
2753 unsigned flags = 0;
2754
2755 // FIXME: Fix and continue?
2756 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
2757 flags |= eImageInfo_GarbageCollected;
2758 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
2759 flags |= eImageInfo_GCOnly;
Daniel Dunbarb79f5a92009-04-20 07:11:47 +00002760
2761 // We never allow @synthesize of a superclass property.
2762 flags |= eImageInfo_CorrectedSynthesize;
Daniel Dunbar1be1df32008-08-11 21:35:06 +00002763
Daniel Dunbar1be1df32008-08-11 21:35:06 +00002764 // Emitted as int[2];
2765 llvm::Constant *values[2] = {
2766 llvm::ConstantInt::get(llvm::Type::Int32Ty, version),
2767 llvm::ConstantInt::get(llvm::Type::Int32Ty, flags)
2768 };
2769 llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2);
Daniel Dunbar90d88f92009-03-09 21:49:58 +00002770
2771 const char *Section;
2772 if (ObjCABI == 1)
2773 Section = "__OBJC, __image_info,regular";
2774 else
2775 Section = "__DATA, __objc_imageinfo, regular, no_dead_strip";
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002776 llvm::GlobalVariable *GV =
Daniel Dunbar90d88f92009-03-09 21:49:58 +00002777 CreateMetadataVar("\01L_OBJC_IMAGE_INFO",
2778 llvm::ConstantArray::get(AT, values, 2),
2779 Section,
2780 0,
2781 true);
2782 GV->setConstant(true);
Daniel Dunbar1be1df32008-08-11 21:35:06 +00002783}
2784
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002785
2786// struct objc_module {
2787// unsigned long version;
2788// unsigned long size;
2789// const char *name;
2790// Symtab symtab;
2791// };
2792
2793// FIXME: Get from somewhere
2794static const int ModuleVersion = 7;
2795
2796void CGObjCMac::EmitModuleInfo() {
Daniel Dunbard8439f22009-01-12 21:08:18 +00002797 uint64_t Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ModuleTy);
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002798
2799 std::vector<llvm::Constant*> Values(4);
2800 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
2801 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Daniel Dunbarac93e472008-08-15 22:20:32 +00002802 // This used to be the filename, now it is unused. <rdr://4327263>
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00002803 Values[2] = GetClassName(&CGM.getContext().Idents.get(""));
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002804 Values[3] = EmitModuleSymbols();
Daniel Dunbar90d88f92009-03-09 21:49:58 +00002805 CreateMetadataVar("\01L_OBJC_MODULES",
2806 llvm::ConstantStruct::get(ObjCTypes.ModuleTy, Values),
2807 "__OBJC,__module_info,regular,no_dead_strip",
Daniel Dunbar56756c32009-03-09 22:18:41 +00002808 4, true);
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002809}
2810
2811llvm::Constant *CGObjCMac::EmitModuleSymbols() {
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002812 unsigned NumClasses = DefinedClasses.size();
2813 unsigned NumCategories = DefinedCategories.size();
2814
Daniel Dunbar8ede0052008-08-25 06:02:07 +00002815 // Return null if no symbols were defined.
2816 if (!NumClasses && !NumCategories)
2817 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
2818
2819 std::vector<llvm::Constant*> Values(5);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002820 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2821 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
2822 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
2823 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
2824
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00002825 // The runtime expects exactly the list of defined classes followed
2826 // by the list of defined categories, in a single array.
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002827 std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00002828 for (unsigned i=0; i<NumClasses; i++)
2829 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
2830 ObjCTypes.Int8PtrTy);
2831 for (unsigned i=0; i<NumCategories; i++)
2832 Symbols[NumClasses + i] =
2833 llvm::ConstantExpr::getBitCast(DefinedCategories[i],
2834 ObjCTypes.Int8PtrTy);
2835
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002836 Values[4] =
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00002837 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002838 NumClasses + NumCategories),
2839 Symbols);
2840
2841 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2842
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002843 llvm::GlobalVariable *GV =
Daniel Dunbar90d88f92009-03-09 21:49:58 +00002844 CreateMetadataVar("\01L_OBJC_SYMBOLS", Init,
2845 "__OBJC,__symbols,regular,no_dead_strip",
Daniel Dunbar9dfd3a72009-04-15 02:56:18 +00002846 4, true);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002847 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
2848}
2849
Daniel Dunbard916e6e2008-11-01 01:53:16 +00002850llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002851 const ObjCInterfaceDecl *ID) {
Daniel Dunbar8ede0052008-08-25 06:02:07 +00002852 LazySymbols.insert(ID->getIdentifier());
2853
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002854 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
2855
2856 if (!Entry) {
2857 llvm::Constant *Casted =
2858 llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()),
2859 ObjCTypes.ClassPtrTy);
2860 Entry =
Daniel Dunbar90d88f92009-03-09 21:49:58 +00002861 CreateMetadataVar("\01L_OBJC_CLASS_REFERENCES_", Casted,
2862 "__OBJC,__cls_refs,literal_pointers,no_dead_strip",
Daniel Dunbar9dfd3a72009-04-15 02:56:18 +00002863 4, true);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002864 }
2865
2866 return Builder.CreateLoad(Entry, false, "tmp");
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002867}
2868
Daniel Dunbard916e6e2008-11-01 01:53:16 +00002869llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar5eec6142008-08-12 03:39:23 +00002870 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
2871
2872 if (!Entry) {
2873 llvm::Constant *Casted =
2874 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
2875 ObjCTypes.SelectorPtrTy);
2876 Entry =
Daniel Dunbar90d88f92009-03-09 21:49:58 +00002877 CreateMetadataVar("\01L_OBJC_SELECTOR_REFERENCES_", Casted,
2878 "__OBJC,__message_refs,literal_pointers,no_dead_strip",
Daniel Dunbar9dfd3a72009-04-15 02:56:18 +00002879 4, true);
Daniel Dunbar5eec6142008-08-12 03:39:23 +00002880 }
2881
2882 return Builder.CreateLoad(Entry, false, "tmp");
2883}
2884
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00002885llvm::Constant *CGObjCCommonMac::GetClassName(IdentifierInfo *Ident) {
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00002886 llvm::GlobalVariable *&Entry = ClassNames[Ident];
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002887
Daniel Dunbar90d88f92009-03-09 21:49:58 +00002888 if (!Entry)
2889 Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
2890 llvm::ConstantArray::get(Ident->getName()),
2891 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarfbfd92a2009-04-14 23:14:47 +00002892 1, true);
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002893
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00002894 return getConstantGEP(Entry, 0, 0);
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002895}
2896
Fariborz Jahanian7345eba2009-03-05 19:17:31 +00002897/// GetIvarLayoutName - Returns a unique constant for the given
2898/// ivar layout bitmap.
2899llvm::Constant *CGObjCCommonMac::GetIvarLayoutName(IdentifierInfo *Ident,
2900 const ObjCCommonTypesHelper &ObjCTypes) {
2901 return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2902}
2903
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002904void CGObjCCommonMac::BuildAggrIvarLayout(const ObjCInterfaceDecl *OI,
2905 const llvm::StructLayout *Layout,
Fariborz Jahanian37931062009-03-10 16:22:08 +00002906 const RecordDecl *RD,
Chris Lattner9329cf52009-03-31 08:48:01 +00002907 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahanian01b3e342009-03-05 22:39:55 +00002908 unsigned int BytePos, bool ForStrongLayout,
2909 int &Index, int &SkIndex, bool &HasUnion) {
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00002910 bool IsUnion = (RD && RD->isUnion());
2911 uint64_t MaxUnionIvarSize = 0;
2912 uint64_t MaxSkippedUnionIvarSize = 0;
2913 FieldDecl *MaxField = 0;
2914 FieldDecl *MaxSkippedField = 0;
Fariborz Jahanian7e052812009-04-21 18:33:06 +00002915 FieldDecl *LastFieldBitfield = 0;
2916
Chris Lattner9329cf52009-03-31 08:48:01 +00002917 unsigned base = 0;
Fariborz Jahanian37931062009-03-10 16:22:08 +00002918 if (RecFields.empty())
2919 return;
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00002920 if (IsUnion)
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002921 base = BytePos + GetFieldBaseOffset(OI, Layout, RecFields[0]);
Chris Lattner9329cf52009-03-31 08:48:01 +00002922 unsigned WordSizeInBits = CGM.getContext().Target.getPointerWidth(0);
2923 unsigned ByteSizeInBits = CGM.getContext().Target.getCharWidth();
2924
2925 llvm::SmallVector<FieldDecl*, 16> TmpRecFields;
2926
2927 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian37931062009-03-10 16:22:08 +00002928 FieldDecl *Field = RecFields[i];
2929 // Skip over unnamed or bitfields
Fariborz Jahanian7e052812009-04-21 18:33:06 +00002930 if (!Field->getIdentifier() || Field->isBitField()) {
2931 LastFieldBitfield = Field;
Fariborz Jahanian37931062009-03-10 16:22:08 +00002932 continue;
Fariborz Jahanian7e052812009-04-21 18:33:06 +00002933 }
2934 LastFieldBitfield = 0;
Fariborz Jahanian37931062009-03-10 16:22:08 +00002935 QualType FQT = Field->getType();
Fariborz Jahanian738ee712009-03-25 22:36:49 +00002936 if (FQT->isRecordType() || FQT->isUnionType()) {
Fariborz Jahanian37931062009-03-10 16:22:08 +00002937 if (FQT->isUnionType())
2938 HasUnion = true;
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00002939 else
2940 assert(FQT->isRecordType() &&
2941 "only union/record is supported for ivar layout bitmap");
2942
Fariborz Jahanian37931062009-03-10 16:22:08 +00002943 const RecordType *RT = FQT->getAsRecordType();
2944 const RecordDecl *RD = RT->getDecl();
Daniel Dunbarecb5d402009-04-19 23:41:48 +00002945 // FIXME - Find a more efficient way of passing records down.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002946 TmpRecFields.append(RD->field_begin(CGM.getContext()),
2947 RD->field_end(CGM.getContext()));
Fariborz Jahanian31614742009-04-20 22:03:45 +00002948 const llvm::Type *Ty = CGM.getTypes().ConvertType(FQT);
2949 const llvm::StructLayout *RecLayout =
2950 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(Ty));
2951
2952 BuildAggrIvarLayout(0, RecLayout, RD, TmpRecFields,
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002953 BytePos + GetFieldBaseOffset(OI, Layout, Field),
Fariborz Jahanian37931062009-03-10 16:22:08 +00002954 ForStrongLayout, Index, SkIndex,
2955 HasUnion);
Chris Lattner9329cf52009-03-31 08:48:01 +00002956 TmpRecFields.clear();
Fariborz Jahanian37931062009-03-10 16:22:08 +00002957 continue;
2958 }
Chris Lattner9329cf52009-03-31 08:48:01 +00002959
2960 if (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00002961 const ConstantArrayType *CArray =
2962 dyn_cast_or_null<ConstantArrayType>(Array);
Fariborz Jahanian7e052812009-04-21 18:33:06 +00002963 uint64_t ElCount = CArray->getSize().getZExtValue();
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00002964 assert(CArray && "only array with know element size is supported");
2965 FQT = CArray->getElementType();
Fariborz Jahanian738ee712009-03-25 22:36:49 +00002966 while (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
2967 const ConstantArrayType *CArray =
2968 dyn_cast_or_null<ConstantArrayType>(Array);
Fariborz Jahanian7e052812009-04-21 18:33:06 +00002969 ElCount *= CArray->getSize().getZExtValue();
Fariborz Jahanian738ee712009-03-25 22:36:49 +00002970 FQT = CArray->getElementType();
2971 }
2972
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00002973 assert(!FQT->isUnionType() &&
2974 "layout for array of unions not supported");
2975 if (FQT->isRecordType()) {
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00002976 int OldIndex = Index;
2977 int OldSkIndex = SkIndex;
2978
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00002979 // FIXME - Use a common routine with the above!
2980 const RecordType *RT = FQT->getAsRecordType();
2981 const RecordDecl *RD = RT->getDecl();
2982 // FIXME - Find a more efficiant way of passing records down.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002983 TmpRecFields.append(RD->field_begin(CGM.getContext()),
2984 RD->field_end(CGM.getContext()));
Fariborz Jahanian31614742009-04-20 22:03:45 +00002985 const llvm::Type *Ty = CGM.getTypes().ConvertType(FQT);
2986 const llvm::StructLayout *RecLayout =
2987 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(Ty));
Chris Lattner9329cf52009-03-31 08:48:01 +00002988
Fariborz Jahanian31614742009-04-20 22:03:45 +00002989 BuildAggrIvarLayout(0, RecLayout, RD,
Chris Lattner9329cf52009-03-31 08:48:01 +00002990 TmpRecFields,
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002991 BytePos + GetFieldBaseOffset(OI, Layout, Field),
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00002992 ForStrongLayout, Index, SkIndex,
2993 HasUnion);
Chris Lattner9329cf52009-03-31 08:48:01 +00002994 TmpRecFields.clear();
2995
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00002996 // Replicate layout information for each array element. Note that
2997 // one element is already done.
2998 uint64_t ElIx = 1;
2999 for (int FirstIndex = Index, FirstSkIndex = SkIndex;
3000 ElIx < ElCount; ElIx++) {
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00003001 uint64_t Size = CGM.getContext().getTypeSize(RT)/ByteSizeInBits;
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00003002 for (int i = OldIndex+1; i <= FirstIndex; ++i)
3003 {
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00003004 GC_IVAR gcivar;
3005 gcivar.ivar_bytepos = IvarsInfo[i].ivar_bytepos + Size*ElIx;
3006 gcivar.ivar_size = IvarsInfo[i].ivar_size;
3007 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00003008 }
3009
Chris Lattner9329cf52009-03-31 08:48:01 +00003010 for (int i = OldSkIndex+1; i <= FirstSkIndex; ++i) {
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00003011 GC_IVAR skivar;
3012 skivar.ivar_bytepos = SkipIvars[i].ivar_bytepos + Size*ElIx;
3013 skivar.ivar_size = SkipIvars[i].ivar_size;
3014 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00003015 }
3016 }
3017 continue;
3018 }
Fariborz Jahanian37931062009-03-10 16:22:08 +00003019 }
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00003020 // At this point, we are done with Record/Union and array there of.
3021 // For other arrays we are down to its element type.
3022 QualType::GCAttrTypes GCAttr = QualType::GCNone;
3023 do {
3024 if (FQT.isObjCGCStrong() || FQT.isObjCGCWeak()) {
3025 GCAttr = FQT.isObjCGCStrong() ? QualType::Strong : QualType::Weak;
3026 break;
3027 }
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00003028 else if (CGM.getContext().isObjCObjectPointerType(FQT)) {
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00003029 GCAttr = QualType::Strong;
3030 break;
3031 }
3032 else if (const PointerType *PT = FQT->getAsPointerType()) {
3033 FQT = PT->getPointeeType();
3034 }
3035 else {
3036 break;
3037 }
3038 } while (true);
Chris Lattner9329cf52009-03-31 08:48:01 +00003039
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00003040 if ((ForStrongLayout && GCAttr == QualType::Strong)
3041 || (!ForStrongLayout && GCAttr == QualType::Weak)) {
3042 if (IsUnion)
3043 {
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00003044 uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType())
3045 / WordSizeInBits;
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00003046 if (UnionIvarSize > MaxUnionIvarSize)
3047 {
3048 MaxUnionIvarSize = UnionIvarSize;
3049 MaxField = Field;
3050 }
3051 }
3052 else
3053 {
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00003054 GC_IVAR gcivar;
3055 gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field);
3056 gcivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) /
3057 WordSizeInBits;
3058 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00003059 }
3060 }
3061 else if ((ForStrongLayout &&
3062 (GCAttr == QualType::GCNone || GCAttr == QualType::Weak))
3063 || (!ForStrongLayout && GCAttr != QualType::Weak)) {
3064 if (IsUnion)
3065 {
3066 uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType());
3067 if (UnionIvarSize > MaxSkippedUnionIvarSize)
3068 {
3069 MaxSkippedUnionIvarSize = UnionIvarSize;
3070 MaxSkippedField = Field;
3071 }
3072 }
3073 else
3074 {
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00003075 GC_IVAR skivar;
3076 skivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field);
3077 skivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) /
Fariborz Jahanian7e052812009-04-21 18:33:06 +00003078 ByteSizeInBits;
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00003079 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00003080 }
3081 }
3082 }
Fariborz Jahanian7e052812009-04-21 18:33:06 +00003083 if (LastFieldBitfield) {
3084 // Last field was a bitfield. Must update skip info.
3085 GC_IVAR skivar;
3086 skivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout,
3087 LastFieldBitfield);
3088 Expr *BitWidth = LastFieldBitfield->getBitWidth();
3089 uint64_t BitFieldSize =
3090 BitWidth->getIntegerConstantExprValue(CGM.getContext()).getZExtValue();
3091 skivar.ivar_size = (BitFieldSize / ByteSizeInBits)
3092 + ((BitFieldSize % ByteSizeInBits) != 0);
3093 SkipIvars.push_back(skivar); ++SkIndex;
3094 }
3095
Chris Lattner9329cf52009-03-31 08:48:01 +00003096 if (MaxField) {
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00003097 GC_IVAR gcivar;
3098 gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, MaxField);
3099 gcivar.ivar_size = MaxUnionIvarSize;
3100 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00003101 }
Chris Lattner9329cf52009-03-31 08:48:01 +00003102
3103 if (MaxSkippedField) {
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00003104 GC_IVAR skivar;
3105 skivar.ivar_bytepos = BytePos +
3106 GetFieldBaseOffset(OI, Layout, MaxSkippedField);
3107 skivar.ivar_size = MaxSkippedUnionIvarSize;
3108 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahanian37931062009-03-10 16:22:08 +00003109 }
Fariborz Jahanian01b3e342009-03-05 22:39:55 +00003110}
3111
3112/// BuildIvarLayout - Builds ivar layout bitmap for the class
3113/// implementation for the __strong or __weak case.
3114/// The layout map displays which words in ivar list must be skipped
3115/// and which must be scanned by GC (see below). String is built of bytes.
3116/// Each byte is divided up in two nibbles (4-bit each). Left nibble is count
3117/// of words to skip and right nibble is count of words to scan. So, each
3118/// nibble represents up to 15 workds to skip or scan. Skipping the rest is
3119/// represented by a 0x00 byte which also ends the string.
3120/// 1. when ForStrongLayout is true, following ivars are scanned:
3121/// - id, Class
3122/// - object *
3123/// - __strong anything
3124///
3125/// 2. When ForStrongLayout is false, following ivars are scanned:
3126/// - __weak anything
3127///
Fariborz Jahanian37931062009-03-10 16:22:08 +00003128llvm::Constant *CGObjCCommonMac::BuildIvarLayout(
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00003129 const ObjCImplementationDecl *OMD,
3130 bool ForStrongLayout) {
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00003131 int Index = -1;
3132 int SkIndex = -1;
Fariborz Jahanian01b3e342009-03-05 22:39:55 +00003133 bool hasUnion = false;
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00003134 int SkipScan;
3135 unsigned int WordsToScan, WordsToSkip;
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00003136 const llvm::Type *PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3137 if (CGM.getLangOptions().getGCMode() == LangOptions::NonGC)
3138 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahanian01b3e342009-03-05 22:39:55 +00003139
Chris Lattner9329cf52009-03-31 08:48:01 +00003140 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00003141 const ObjCInterfaceDecl *OI = OMD->getClassInterface();
Fariborz Jahanian01b3e342009-03-05 22:39:55 +00003142 CGM.getContext().CollectObjCIvars(OI, RecFields);
3143 if (RecFields.empty())
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00003144 return llvm::Constant::getNullValue(PtrTy);
Chris Lattner9329cf52009-03-31 08:48:01 +00003145
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00003146 SkipIvars.clear();
3147 IvarsInfo.clear();
Fariborz Jahanian6d49ab62009-03-11 21:42:00 +00003148
Daniel Dunbare5bb23c2009-04-22 09:39:34 +00003149 const llvm::StructLayout *Layout =
3150 CGM.getTargetData().getStructLayout(GetConcreteClassStruct(CGM, OI));
Chris Lattner9329cf52009-03-31 08:48:01 +00003151 BuildAggrIvarLayout(OI, Layout, 0, RecFields, 0, ForStrongLayout,
3152 Index, SkIndex, hasUnion);
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00003153 if (Index == -1)
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00003154 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00003155
3156 // Sort on byte position in case we encounterred a union nested in
3157 // the ivar list.
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00003158 if (hasUnion && !IvarsInfo.empty())
Daniel Dunbar48445182009-04-23 01:29:05 +00003159 std::sort(IvarsInfo.begin(), IvarsInfo.end());
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00003160 if (hasUnion && !SkipIvars.empty())
Daniel Dunbar48445182009-04-23 01:29:05 +00003161 std::sort(SkipIvars.begin(), SkipIvars.end());
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00003162
3163 // Build the string of skip/scan nibbles
3164 SkipScan = -1;
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00003165 SkipScanIvars.clear();
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00003166 unsigned int WordSize =
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00003167 CGM.getTypes().getTargetData().getTypePaddedSize(PtrTy);
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00003168 if (IvarsInfo[0].ivar_bytepos == 0) {
3169 WordsToSkip = 0;
3170 WordsToScan = IvarsInfo[0].ivar_size;
3171 }
3172 else {
3173 WordsToSkip = IvarsInfo[0].ivar_bytepos/WordSize;
3174 WordsToScan = IvarsInfo[0].ivar_size;
3175 }
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00003176 for (unsigned int i=1, Last=IvarsInfo.size(); i != Last; i++)
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00003177 {
3178 unsigned int TailPrevGCObjC =
3179 IvarsInfo[i-1].ivar_bytepos + IvarsInfo[i-1].ivar_size * WordSize;
3180 if (IvarsInfo[i].ivar_bytepos == TailPrevGCObjC)
3181 {
3182 // consecutive 'scanned' object pointers.
3183 WordsToScan += IvarsInfo[i].ivar_size;
3184 }
3185 else
3186 {
3187 // Skip over 'gc'able object pointer which lay over each other.
3188 if (TailPrevGCObjC > IvarsInfo[i].ivar_bytepos)
3189 continue;
3190 // Must skip over 1 or more words. We save current skip/scan values
3191 // and start a new pair.
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00003192 SKIP_SCAN SkScan;
3193 SkScan.skip = WordsToSkip;
3194 SkScan.scan = WordsToScan;
3195 SkipScanIvars.push_back(SkScan); ++SkipScan;
3196
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00003197 // Skip the hole.
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00003198 SkScan.skip = (IvarsInfo[i].ivar_bytepos - TailPrevGCObjC) / WordSize;
3199 SkScan.scan = 0;
3200 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00003201 WordsToSkip = 0;
3202 WordsToScan = IvarsInfo[i].ivar_size;
3203 }
3204 }
3205 if (WordsToScan > 0)
3206 {
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00003207 SKIP_SCAN SkScan;
3208 SkScan.skip = WordsToSkip;
3209 SkScan.scan = WordsToScan;
3210 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00003211 }
3212
3213 bool BytesSkipped = false;
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00003214 if (!SkipIvars.empty())
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00003215 {
3216 int LastByteSkipped =
3217 SkipIvars[SkIndex].ivar_bytepos + SkipIvars[SkIndex].ivar_size;
3218 int LastByteScanned =
3219 IvarsInfo[Index].ivar_bytepos + IvarsInfo[Index].ivar_size * WordSize;
3220 BytesSkipped = (LastByteSkipped > LastByteScanned);
3221 // Compute number of bytes to skip at the tail end of the last ivar scanned.
3222 if (BytesSkipped)
3223 {
3224 unsigned int TotalWords = (LastByteSkipped + (WordSize -1)) / WordSize;
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00003225 SKIP_SCAN SkScan;
3226 SkScan.skip = TotalWords - (LastByteScanned/WordSize);
3227 SkScan.scan = 0;
3228 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00003229 }
3230 }
3231 // Mini optimization of nibbles such that an 0xM0 followed by 0x0N is produced
3232 // as 0xMN.
3233 for (int i = 0; i <= SkipScan; i++)
3234 {
3235 if ((i < SkipScan) && SkipScanIvars[i].skip && SkipScanIvars[i].scan == 0
3236 && SkipScanIvars[i+1].skip == 0 && SkipScanIvars[i+1].scan) {
3237 // 0xM0 followed by 0x0N detected.
3238 SkipScanIvars[i].scan = SkipScanIvars[i+1].scan;
3239 for (int j = i+1; j < SkipScan; j++)
3240 SkipScanIvars[j] = SkipScanIvars[j+1];
3241 --SkipScan;
3242 }
3243 }
3244
3245 // Generate the string.
3246 std::string BitMap;
3247 for (int i = 0; i <= SkipScan; i++)
3248 {
3249 unsigned char byte;
3250 unsigned int skip_small = SkipScanIvars[i].skip % 0xf;
3251 unsigned int scan_small = SkipScanIvars[i].scan % 0xf;
3252 unsigned int skip_big = SkipScanIvars[i].skip / 0xf;
3253 unsigned int scan_big = SkipScanIvars[i].scan / 0xf;
3254
3255 if (skip_small > 0 || skip_big > 0)
3256 BytesSkipped = true;
3257 // first skip big.
3258 for (unsigned int ix = 0; ix < skip_big; ix++)
3259 BitMap += (unsigned char)(0xf0);
3260
3261 // next (skip small, scan)
3262 if (skip_small)
3263 {
3264 byte = skip_small << 4;
3265 if (scan_big > 0)
3266 {
3267 byte |= 0xf;
3268 --scan_big;
3269 }
3270 else if (scan_small)
3271 {
3272 byte |= scan_small;
3273 scan_small = 0;
3274 }
3275 BitMap += byte;
3276 }
3277 // next scan big
3278 for (unsigned int ix = 0; ix < scan_big; ix++)
3279 BitMap += (unsigned char)(0x0f);
3280 // last scan small
3281 if (scan_small)
3282 {
3283 byte = scan_small;
3284 BitMap += byte;
3285 }
3286 }
3287 // null terminate string.
Fariborz Jahanian738ee712009-03-25 22:36:49 +00003288 unsigned char zero = 0;
3289 BitMap += zero;
Fariborz Jahanian31614742009-04-20 22:03:45 +00003290
3291 if (CGM.getLangOptions().ObjCGCBitmapPrint) {
3292 printf("\n%s ivar layout for class '%s': ",
3293 ForStrongLayout ? "strong" : "weak",
3294 OMD->getClassInterface()->getNameAsCString());
3295 const unsigned char *s = (unsigned char*)BitMap.c_str();
3296 for (unsigned i = 0; i < BitMap.size(); i++)
3297 if (!(s[i] & 0xf0))
3298 printf("0x0%x%s", s[i], s[i] != 0 ? ", " : "");
3299 else
3300 printf("0x%x%s", s[i], s[i] != 0 ? ", " : "");
3301 printf("\n");
3302 }
3303
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00003304 // if ivar_layout bitmap is all 1 bits (nothing skipped) then use NULL as
3305 // final layout.
3306 if (ForStrongLayout && !BytesSkipped)
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00003307 return llvm::Constant::getNullValue(PtrTy);
3308 llvm::GlobalVariable * Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
3309 llvm::ConstantArray::get(BitMap.c_str()),
3310 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarfbfd92a2009-04-14 23:14:47 +00003311 1, true);
Fariborz Jahanian31614742009-04-20 22:03:45 +00003312 return getConstantGEP(Entry, 0, 0);
Fariborz Jahanian01b3e342009-03-05 22:39:55 +00003313}
3314
Fariborz Jahanian32b5ea22009-01-21 23:34:32 +00003315llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) {
Daniel Dunbar5eec6142008-08-12 03:39:23 +00003316 llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
3317
Daniel Dunbar90d88f92009-03-09 21:49:58 +00003318 // FIXME: Avoid std::string copying.
3319 if (!Entry)
3320 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_NAME_",
3321 llvm::ConstantArray::get(Sel.getAsString()),
3322 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarfbfd92a2009-04-14 23:14:47 +00003323 1, true);
Daniel Dunbar5eec6142008-08-12 03:39:23 +00003324
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003325 return getConstantGEP(Entry, 0, 0);
3326}
3327
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003328// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian32b5ea22009-01-21 23:34:32 +00003329llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) {
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003330 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
3331}
3332
3333// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian32b5ea22009-01-21 23:34:32 +00003334llvm::Constant *CGObjCCommonMac::GetMethodVarName(const std::string &Name) {
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003335 return GetMethodVarName(&CGM.getContext().Idents.get(Name));
3336}
3337
Daniel Dunbar356f0742009-04-20 06:54:31 +00003338llvm::Constant *CGObjCCommonMac::GetMethodVarType(const FieldDecl *Field) {
Devang Patel593a07a2009-03-04 18:21:39 +00003339 std::string TypeStr;
3340 CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
3341
3342 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003343
Daniel Dunbar90d88f92009-03-09 21:49:58 +00003344 if (!Entry)
3345 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3346 llvm::ConstantArray::get(TypeStr),
3347 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarfbfd92a2009-04-14 23:14:47 +00003348 1, true);
Daniel Dunbar90d88f92009-03-09 21:49:58 +00003349
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003350 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar5eec6142008-08-12 03:39:23 +00003351}
3352
Fariborz Jahanian32b5ea22009-01-21 23:34:32 +00003353llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D) {
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003354 std::string TypeStr;
Daniel Dunbar12996f52008-08-26 21:51:14 +00003355 CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D),
3356 TypeStr);
Devang Patel593a07a2009-03-04 18:21:39 +00003357
3358 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
3359
Daniel Dunbarfbfd92a2009-04-14 23:14:47 +00003360 if (!Entry)
3361 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3362 llvm::ConstantArray::get(TypeStr),
3363 "__TEXT,__cstring,cstring_literals",
3364 1, true);
Devang Patel593a07a2009-03-04 18:21:39 +00003365
3366 return getConstantGEP(Entry, 0, 0);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003367}
3368
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00003369// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian32b5ea22009-01-21 23:34:32 +00003370llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) {
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00003371 llvm::GlobalVariable *&Entry = PropertyNames[Ident];
3372
Daniel Dunbar90d88f92009-03-09 21:49:58 +00003373 if (!Entry)
3374 Entry = CreateMetadataVar("\01L_OBJC_PROP_NAME_ATTR_",
3375 llvm::ConstantArray::get(Ident->getName()),
3376 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarfbfd92a2009-04-14 23:14:47 +00003377 1, true);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00003378
3379 return getConstantGEP(Entry, 0, 0);
3380}
3381
3382// FIXME: Merge into a single cstring creation function.
Daniel Dunbar698d6f32008-08-28 04:38:10 +00003383// FIXME: This Decl should be more precise.
Daniel Dunbar90d88f92009-03-09 21:49:58 +00003384llvm::Constant *
3385 CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
3386 const Decl *Container) {
Daniel Dunbar698d6f32008-08-28 04:38:10 +00003387 std::string TypeStr;
3388 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00003389 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
3390}
3391
Fariborz Jahanian32b5ea22009-01-21 23:34:32 +00003392void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D,
3393 const ObjCContainerDecl *CD,
3394 std::string &NameOut) {
Daniel Dunbara2d275d2009-04-07 05:48:37 +00003395 NameOut = '\01';
3396 NameOut += (D->isInstanceMethod() ? '-' : '+');
Chris Lattner3a8f2942008-11-24 03:33:13 +00003397 NameOut += '[';
Fariborz Jahanian0adaa8a2009-01-10 21:06:09 +00003398 assert (CD && "Missing container decl in GetNameForMethod");
3399 NameOut += CD->getNameAsString();
Fariborz Jahanian6e4b7372009-04-16 18:34:20 +00003400 if (const ObjCCategoryImplDecl *CID =
3401 dyn_cast<ObjCCategoryImplDecl>(D->getDeclContext())) {
3402 NameOut += '(';
3403 NameOut += CID->getNameAsString();
3404 NameOut+= ')';
3405 }
Chris Lattner3a8f2942008-11-24 03:33:13 +00003406 NameOut += ' ';
3407 NameOut += D->getSelector().getAsString();
3408 NameOut += ']';
Daniel Dunbarace33292008-08-16 03:19:19 +00003409}
3410
Daniel Dunbar1be1df32008-08-11 21:35:06 +00003411void CGObjCMac::FinishModule() {
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00003412 EmitModuleInfo();
3413
Daniel Dunbar35b777f2008-10-29 22:36:39 +00003414 // Emit the dummy bodies for any protocols which were referenced but
3415 // never defined.
3416 for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
3417 i = Protocols.begin(), e = Protocols.end(); i != e; ++i) {
3418 if (i->second->hasInitializer())
3419 continue;
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00003420
Daniel Dunbar35b777f2008-10-29 22:36:39 +00003421 std::vector<llvm::Constant*> Values(5);
3422 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
3423 Values[1] = GetClassName(i->first);
3424 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
3425 Values[3] = Values[4] =
3426 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
3427 i->second->setLinkage(llvm::GlobalValue::InternalLinkage);
3428 i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
3429 Values));
3430 }
3431
3432 std::vector<llvm::Constant*> Used;
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00003433 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
Daniel Dunbar1be1df32008-08-11 21:35:06 +00003434 e = UsedGlobals.end(); i != e; ++i) {
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003435 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
Daniel Dunbar1be1df32008-08-11 21:35:06 +00003436 }
3437
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003438 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
Daniel Dunbar1be1df32008-08-11 21:35:06 +00003439 llvm::GlobalValue *GV =
3440 new llvm::GlobalVariable(AT, false,
3441 llvm::GlobalValue::AppendingLinkage,
3442 llvm::ConstantArray::get(AT, Used),
3443 "llvm.used",
3444 &CGM.getModule());
3445
3446 GV->setSection("llvm.metadata");
Daniel Dunbar8ede0052008-08-25 06:02:07 +00003447
3448 // Add assembler directives to add lazy undefined symbol references
3449 // for classes which are referenced but not defined. This is
3450 // important for correct linker interaction.
3451
3452 // FIXME: Uh, this isn't particularly portable.
3453 std::stringstream s;
Anders Carlsson63f98352008-12-10 02:21:04 +00003454
3455 if (!CGM.getModule().getModuleInlineAsm().empty())
3456 s << "\n";
3457
Daniel Dunbar8ede0052008-08-25 06:02:07 +00003458 for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(),
3459 e = LazySymbols.end(); i != e; ++i) {
3460 s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n";
3461 }
3462 for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(),
3463 e = DefinedSymbols.end(); i != e; ++i) {
Daniel Dunbar698d6f32008-08-28 04:38:10 +00003464 s << "\t.objc_class_name_" << (*i)->getName() << "=0\n"
Daniel Dunbar8ede0052008-08-25 06:02:07 +00003465 << "\t.globl .objc_class_name_" << (*i)->getName() << "\n";
3466 }
Anders Carlsson63f98352008-12-10 02:21:04 +00003467
Daniel Dunbar8ede0052008-08-25 06:02:07 +00003468 CGM.getModule().appendModuleInlineAsm(s.str());
Daniel Dunbar1be1df32008-08-11 21:35:06 +00003469}
3470
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003471CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm)
Fariborz Jahanian48543f52009-01-21 22:04:16 +00003472 : CGObjCCommonMac(cgm),
3473 ObjCTypes(cgm)
3474{
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00003475 ObjCEmptyCacheVar = ObjCEmptyVtableVar = NULL;
Fariborz Jahanian48543f52009-01-21 22:04:16 +00003476 ObjCABI = 2;
3477}
3478
Daniel Dunbar1be1df32008-08-11 21:35:06 +00003479/* *** */
3480
Fariborz Jahanian48543f52009-01-21 22:04:16 +00003481ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm)
3482: CGM(cgm)
Daniel Dunbardaf4ad42008-08-12 00:12:39 +00003483{
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00003484 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3485 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanian48543f52009-01-21 22:04:16 +00003486
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003487 ShortTy = Types.ConvertType(Ctx.ShortTy);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003488 IntTy = Types.ConvertType(Ctx.IntTy);
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00003489 LongTy = Types.ConvertType(Ctx.LongTy);
Fariborz Jahanianad51ca02009-03-23 19:10:40 +00003490 LongLongTy = Types.ConvertType(Ctx.LongLongTy);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003491 Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3492
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00003493 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
Fariborz Jahanianc192d4d2008-11-18 20:18:11 +00003494 PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00003495 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003496
3497 // FIXME: It would be nice to unify this with the opaque type, so
3498 // that the IR comes out a bit cleaner.
3499 const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
3500 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
Fariborz Jahanian48543f52009-01-21 22:04:16 +00003501
3502 // I'm not sure I like this. The implicit coordination is a bit
3503 // gross. We should solve this in a reasonable fashion because this
3504 // is a pretty common task (match some runtime data structure with
3505 // an LLVM data structure).
3506
3507 // FIXME: This is leaked.
3508 // FIXME: Merge with rewriter code?
3509
3510 // struct _objc_super {
3511 // id self;
3512 // Class cls;
3513 // }
3514 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3515 SourceLocation(),
3516 &Ctx.Idents.get("_objc_super"));
Douglas Gregorc55b0b02009-04-09 21:40:53 +00003517 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3518 Ctx.getObjCIdType(), 0, false));
3519 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3520 Ctx.getObjCClassType(), 0, false));
Fariborz Jahanian48543f52009-01-21 22:04:16 +00003521 RD->completeDefinition(Ctx);
3522
3523 SuperCTy = Ctx.getTagDeclType(RD);
3524 SuperPtrCTy = Ctx.getPointerType(SuperCTy);
3525
3526 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
Fariborz Jahanian4b161702009-01-22 00:37:21 +00003527 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
3528
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003529 // struct _prop_t {
3530 // char *name;
3531 // char *attributes;
3532 // }
Chris Lattnerada416b2009-04-22 02:53:24 +00003533 PropertyTy = llvm::StructType::get(Int8PtrTy, Int8PtrTy, NULL);
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003534 CGM.getModule().addTypeName("struct._prop_t",
3535 PropertyTy);
3536
3537 // struct _prop_list_t {
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003538 // uint32_t entsize; // sizeof(struct _prop_t)
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003539 // uint32_t count_of_properties;
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003540 // struct _prop_t prop_list[count_of_properties];
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003541 // }
3542 PropertyListTy = llvm::StructType::get(IntTy,
3543 IntTy,
3544 llvm::ArrayType::get(PropertyTy, 0),
3545 NULL);
3546 CGM.getModule().addTypeName("struct._prop_list_t",
3547 PropertyListTy);
3548 // struct _prop_list_t *
3549 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
3550
3551 // struct _objc_method {
3552 // SEL _cmd;
3553 // char *method_type;
3554 // char *_imp;
3555 // }
3556 MethodTy = llvm::StructType::get(SelectorPtrTy,
3557 Int8PtrTy,
3558 Int8PtrTy,
3559 NULL);
3560 CGM.getModule().addTypeName("struct._objc_method", MethodTy);
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003561
3562 // struct _objc_cache *
3563 CacheTy = llvm::OpaqueType::get();
3564 CGM.getModule().addTypeName("struct._objc_cache", CacheTy);
3565 CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
Fariborz Jahanian48543f52009-01-21 22:04:16 +00003566}
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00003567
Fariborz Jahanian48543f52009-01-21 22:04:16 +00003568ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
3569 : ObjCCommonTypesHelper(cgm)
3570{
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003571 // struct _objc_method_description {
3572 // SEL name;
3573 // char *types;
3574 // }
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003575 MethodDescriptionTy =
3576 llvm::StructType::get(SelectorPtrTy,
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003577 Int8PtrTy,
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003578 NULL);
3579 CGM.getModule().addTypeName("struct._objc_method_description",
3580 MethodDescriptionTy);
3581
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003582 // struct _objc_method_description_list {
3583 // int count;
3584 // struct _objc_method_description[1];
3585 // }
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003586 MethodDescriptionListTy =
3587 llvm::StructType::get(IntTy,
3588 llvm::ArrayType::get(MethodDescriptionTy, 0),
3589 NULL);
3590 CGM.getModule().addTypeName("struct._objc_method_description_list",
3591 MethodDescriptionListTy);
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003592
3593 // struct _objc_method_description_list *
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003594 MethodDescriptionListPtrTy =
3595 llvm::PointerType::getUnqual(MethodDescriptionListTy);
3596
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003597 // Protocol description structures
3598
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003599 // struct _objc_protocol_extension {
3600 // uint32_t size; // sizeof(struct _objc_protocol_extension)
3601 // struct _objc_method_description_list *optional_instance_methods;
3602 // struct _objc_method_description_list *optional_class_methods;
3603 // struct _objc_property_list *instance_properties;
3604 // }
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003605 ProtocolExtensionTy =
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003606 llvm::StructType::get(IntTy,
3607 MethodDescriptionListPtrTy,
3608 MethodDescriptionListPtrTy,
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003609 PropertyListPtrTy,
3610 NULL);
3611 CGM.getModule().addTypeName("struct._objc_protocol_extension",
3612 ProtocolExtensionTy);
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003613
3614 // struct _objc_protocol_extension *
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003615 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
3616
Daniel Dunbar35b777f2008-10-29 22:36:39 +00003617 // Handle recursive construction of Protocol and ProtocolList types
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003618
3619 llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get();
3620 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3621
Fariborz Jahanian48543f52009-01-21 22:04:16 +00003622 const llvm::Type *T =
3623 llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder),
3624 LongTy,
3625 llvm::ArrayType::get(ProtocolTyHolder, 0),
3626 NULL);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003627 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T);
3628
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003629 // struct _objc_protocol {
3630 // struct _objc_protocol_extension *isa;
3631 // char *protocol_name;
3632 // struct _objc_protocol **_objc_protocol_list;
3633 // struct _objc_method_description_list *instance_methods;
3634 // struct _objc_method_description_list *class_methods;
3635 // }
3636 T = llvm::StructType::get(ProtocolExtensionPtrTy,
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003637 Int8PtrTy,
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003638 llvm::PointerType::getUnqual(ProtocolListTyHolder),
3639 MethodDescriptionListPtrTy,
3640 MethodDescriptionListPtrTy,
3641 NULL);
3642 cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T);
3643
3644 ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get());
3645 CGM.getModule().addTypeName("struct._objc_protocol_list",
3646 ProtocolListTy);
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003647 // struct _objc_protocol_list *
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003648 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
3649
3650 ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get());
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003651 CGM.getModule().addTypeName("struct._objc_protocol", ProtocolTy);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003652 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003653
3654 // Class description structures
3655
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003656 // struct _objc_ivar {
3657 // char *ivar_name;
3658 // char *ivar_type;
3659 // int ivar_offset;
3660 // }
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003661 IvarTy = llvm::StructType::get(Int8PtrTy,
3662 Int8PtrTy,
3663 IntTy,
3664 NULL);
3665 CGM.getModule().addTypeName("struct._objc_ivar", IvarTy);
3666
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003667 // struct _objc_ivar_list *
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003668 IvarListTy = llvm::OpaqueType::get();
3669 CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy);
3670 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
3671
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003672 // struct _objc_method_list *
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003673 MethodListTy = llvm::OpaqueType::get();
3674 CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy);
3675 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
3676
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003677 // struct _objc_class_extension *
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003678 ClassExtensionTy =
3679 llvm::StructType::get(IntTy,
3680 Int8PtrTy,
3681 PropertyListPtrTy,
3682 NULL);
3683 CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy);
3684 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
3685
3686 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3687
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003688 // struct _objc_class {
3689 // Class isa;
3690 // Class super_class;
3691 // char *name;
3692 // long version;
3693 // long info;
3694 // long instance_size;
3695 // struct _objc_ivar_list *ivars;
3696 // struct _objc_method_list *methods;
3697 // struct _objc_cache *cache;
3698 // struct _objc_protocol_list *protocols;
3699 // char *ivar_layout;
3700 // struct _objc_class_ext *ext;
3701 // };
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003702 T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3703 llvm::PointerType::getUnqual(ClassTyHolder),
3704 Int8PtrTy,
3705 LongTy,
3706 LongTy,
3707 LongTy,
3708 IvarListPtrTy,
3709 MethodListPtrTy,
3710 CachePtrTy,
3711 ProtocolListPtrTy,
3712 Int8PtrTy,
3713 ClassExtensionPtrTy,
3714 NULL);
3715 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T);
3716
3717 ClassTy = cast<llvm::StructType>(ClassTyHolder.get());
3718 CGM.getModule().addTypeName("struct._objc_class", ClassTy);
3719 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
3720
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003721 // struct _objc_category {
3722 // char *category_name;
3723 // char *class_name;
3724 // struct _objc_method_list *instance_method;
3725 // struct _objc_method_list *class_method;
3726 // uint32_t size; // sizeof(struct _objc_category)
3727 // struct _objc_property_list *instance_properties;// category's @property
3728 // }
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00003729 CategoryTy = llvm::StructType::get(Int8PtrTy,
3730 Int8PtrTy,
3731 MethodListPtrTy,
3732 MethodListPtrTy,
3733 ProtocolListPtrTy,
3734 IntTy,
3735 PropertyListPtrTy,
3736 NULL);
3737 CGM.getModule().addTypeName("struct._objc_category", CategoryTy);
3738
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003739 // Global metadata structures
3740
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003741 // struct _objc_symtab {
3742 // long sel_ref_cnt;
3743 // SEL *refs;
3744 // short cls_def_cnt;
3745 // short cat_def_cnt;
3746 // char *defs[cls_def_cnt + cat_def_cnt];
3747 // }
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003748 SymtabTy = llvm::StructType::get(LongTy,
3749 SelectorPtrTy,
3750 ShortTy,
3751 ShortTy,
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00003752 llvm::ArrayType::get(Int8PtrTy, 0),
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003753 NULL);
3754 CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy);
3755 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
3756
Fariborz Jahanian4b161702009-01-22 00:37:21 +00003757 // struct _objc_module {
3758 // long version;
3759 // long size; // sizeof(struct _objc_module)
3760 // char *name;
3761 // struct _objc_symtab* symtab;
3762 // }
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003763 ModuleTy =
3764 llvm::StructType::get(LongTy,
3765 LongTy,
3766 Int8PtrTy,
3767 SymtabPtrTy,
3768 NULL);
3769 CGM.getModule().addTypeName("struct._objc_module", ModuleTy);
Daniel Dunbar87062ff2008-08-23 09:25:55 +00003770
Anders Carlsson58d16242008-08-31 04:05:03 +00003771
Anders Carlsson9acb0a42008-09-09 10:10:21 +00003772 // FIXME: This is the size of the setjmp buffer and should be
3773 // target specific. 18 is what's used on 32-bit X86.
3774 uint64_t SetJmpBufferSize = 18;
3775
3776 // Exceptions
3777 const llvm::Type *StackPtrTy =
Daniel Dunbar1c5e4632008-09-27 06:32:25 +00003778 llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4);
Anders Carlsson9acb0a42008-09-09 10:10:21 +00003779
3780 ExceptionDataTy =
3781 llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty,
3782 SetJmpBufferSize),
3783 StackPtrTy, NULL);
3784 CGM.getModule().addTypeName("struct._objc_exception_data",
3785 ExceptionDataTy);
3786
Daniel Dunbardaf4ad42008-08-12 00:12:39 +00003787}
3788
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003789ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm)
Fariborz Jahanian48543f52009-01-21 22:04:16 +00003790: ObjCCommonTypesHelper(cgm)
3791{
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003792 // struct _method_list_t {
3793 // uint32_t entsize; // sizeof(struct _objc_method)
3794 // uint32_t method_count;
3795 // struct _objc_method method_list[method_count];
3796 // }
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003797 MethodListnfABITy = llvm::StructType::get(IntTy,
3798 IntTy,
3799 llvm::ArrayType::get(MethodTy, 0),
3800 NULL);
3801 CGM.getModule().addTypeName("struct.__method_list_t",
3802 MethodListnfABITy);
3803 // struct method_list_t *
3804 MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy);
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003805
3806 // struct _protocol_t {
3807 // id isa; // NULL
3808 // const char * const protocol_name;
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003809 // const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003810 // const struct method_list_t * const instance_methods;
3811 // const struct method_list_t * const class_methods;
3812 // const struct method_list_t *optionalInstanceMethods;
3813 // const struct method_list_t *optionalClassMethods;
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003814 // const struct _prop_list_t * properties;
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003815 // const uint32_t size; // sizeof(struct _protocol_t)
3816 // const uint32_t flags; // = 0
3817 // }
3818
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003819 // Holder for struct _protocol_list_t *
3820 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3821
3822 ProtocolnfABITy = llvm::StructType::get(ObjectPtrTy,
3823 Int8PtrTy,
3824 llvm::PointerType::getUnqual(
3825 ProtocolListTyHolder),
3826 MethodListnfABIPtrTy,
3827 MethodListnfABIPtrTy,
3828 MethodListnfABIPtrTy,
3829 MethodListnfABIPtrTy,
3830 PropertyListPtrTy,
3831 IntTy,
3832 IntTy,
3833 NULL);
3834 CGM.getModule().addTypeName("struct._protocol_t",
3835 ProtocolnfABITy);
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00003836
3837 // struct _protocol_t*
3838 ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy);
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003839
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00003840 // struct _protocol_list_t {
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003841 // long protocol_count; // Note, this is 32/64 bit
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00003842 // struct _protocol_t *[protocol_count];
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003843 // }
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003844 ProtocolListnfABITy = llvm::StructType::get(LongTy,
3845 llvm::ArrayType::get(
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00003846 ProtocolnfABIPtrTy, 0),
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003847 NULL);
3848 CGM.getModule().addTypeName("struct._objc_protocol_list",
3849 ProtocolListnfABITy);
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00003850 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(
3851 ProtocolListnfABITy);
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003852
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003853 // struct _objc_protocol_list*
3854 ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy);
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003855
3856 // struct _ivar_t {
3857 // unsigned long int *offset; // pointer to ivar offset location
3858 // char *name;
3859 // char *type;
3860 // uint32_t alignment;
3861 // uint32_t size;
3862 // }
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003863 IvarnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(LongTy),
3864 Int8PtrTy,
3865 Int8PtrTy,
3866 IntTy,
3867 IntTy,
3868 NULL);
3869 CGM.getModule().addTypeName("struct._ivar_t", IvarnfABITy);
3870
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003871 // struct _ivar_list_t {
3872 // uint32 entsize; // sizeof(struct _ivar_t)
3873 // uint32 count;
3874 // struct _iver_t list[count];
3875 // }
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00003876 IvarListnfABITy = llvm::StructType::get(IntTy,
3877 IntTy,
3878 llvm::ArrayType::get(
3879 IvarnfABITy, 0),
3880 NULL);
3881 CGM.getModule().addTypeName("struct._ivar_list_t", IvarListnfABITy);
3882
3883 IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy);
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003884
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003885 // struct _class_ro_t {
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003886 // uint32_t const flags;
3887 // uint32_t const instanceStart;
3888 // uint32_t const instanceSize;
3889 // uint32_t const reserved; // only when building for 64bit targets
3890 // const uint8_t * const ivarLayout;
3891 // const char *const name;
3892 // const struct _method_list_t * const baseMethods;
3893 // const struct _objc_protocol_list *const baseProtocols;
3894 // const struct _ivar_list_t *const ivars;
3895 // const uint8_t * const weakIvarLayout;
3896 // const struct _prop_list_t * const properties;
3897 // }
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003898
3899 // FIXME. Add 'reserved' field in 64bit abi mode!
3900 ClassRonfABITy = llvm::StructType::get(IntTy,
3901 IntTy,
3902 IntTy,
3903 Int8PtrTy,
3904 Int8PtrTy,
3905 MethodListnfABIPtrTy,
3906 ProtocolListnfABIPtrTy,
3907 IvarListnfABIPtrTy,
3908 Int8PtrTy,
3909 PropertyListPtrTy,
3910 NULL);
3911 CGM.getModule().addTypeName("struct._class_ro_t",
3912 ClassRonfABITy);
3913
3914 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
3915 std::vector<const llvm::Type*> Params;
3916 Params.push_back(ObjectPtrTy);
3917 Params.push_back(SelectorPtrTy);
3918 ImpnfABITy = llvm::PointerType::getUnqual(
3919 llvm::FunctionType::get(ObjectPtrTy, Params, false));
3920
3921 // struct _class_t {
3922 // struct _class_t *isa;
3923 // struct _class_t * const superclass;
3924 // void *cache;
3925 // IMP *vtable;
3926 // struct class_ro_t *ro;
3927 // }
3928
3929 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3930 ClassnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3931 llvm::PointerType::getUnqual(ClassTyHolder),
3932 CachePtrTy,
3933 llvm::PointerType::getUnqual(ImpnfABITy),
3934 llvm::PointerType::getUnqual(
3935 ClassRonfABITy),
3936 NULL);
3937 CGM.getModule().addTypeName("struct._class_t", ClassnfABITy);
3938
3939 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(
3940 ClassnfABITy);
3941
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00003942 // LLVM for struct _class_t *
3943 ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy);
3944
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003945 // struct _category_t {
3946 // const char * const name;
3947 // struct _class_t *const cls;
3948 // const struct _method_list_t * const instance_methods;
3949 // const struct _method_list_t * const class_methods;
3950 // const struct _protocol_list_t * const protocols;
3951 // const struct _prop_list_t * const properties;
Fariborz Jahanianb9459b72009-01-23 17:41:22 +00003952 // }
3953 CategorynfABITy = llvm::StructType::get(Int8PtrTy,
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00003954 ClassnfABIPtrTy,
Fariborz Jahanianb9459b72009-01-23 17:41:22 +00003955 MethodListnfABIPtrTy,
3956 MethodListnfABIPtrTy,
3957 ProtocolListnfABIPtrTy,
3958 PropertyListPtrTy,
3959 NULL);
3960 CGM.getModule().addTypeName("struct._category_t", CategorynfABITy);
Fariborz Jahanian711e8dd2009-02-03 23:49:23 +00003961
3962 // New types for nonfragile abi messaging.
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00003963 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3964 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanian711e8dd2009-02-03 23:49:23 +00003965
3966 // MessageRefTy - LLVM for:
3967 // struct _message_ref_t {
3968 // IMP messenger;
3969 // SEL name;
3970 // };
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00003971
3972 // First the clang type for struct _message_ref_t
3973 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3974 SourceLocation(),
3975 &Ctx.Idents.get("_message_ref_t"));
Douglas Gregorc55b0b02009-04-09 21:40:53 +00003976 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3977 Ctx.VoidPtrTy, 0, false));
3978 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3979 Ctx.getObjCSelType(), 0, false));
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00003980 RD->completeDefinition(Ctx);
3981
3982 MessageRefCTy = Ctx.getTagDeclType(RD);
3983 MessageRefCPtrTy = Ctx.getPointerType(MessageRefCTy);
3984 MessageRefTy = cast<llvm::StructType>(Types.ConvertType(MessageRefCTy));
Fariborz Jahanian711e8dd2009-02-03 23:49:23 +00003985
3986 // MessageRefPtrTy - LLVM for struct _message_ref_t*
3987 MessageRefPtrTy = llvm::PointerType::getUnqual(MessageRefTy);
3988
3989 // SuperMessageRefTy - LLVM for:
3990 // struct _super_message_ref_t {
3991 // SUPER_IMP messenger;
3992 // SEL name;
3993 // };
3994 SuperMessageRefTy = llvm::StructType::get(ImpnfABITy,
3995 SelectorPtrTy,
3996 NULL);
3997 CGM.getModule().addTypeName("struct._super_message_ref_t", SuperMessageRefTy);
3998
3999 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
4000 SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy);
4001
Daniel Dunbar9c285e72009-03-01 04:46:24 +00004002
4003 // struct objc_typeinfo {
4004 // const void** vtable; // objc_ehtype_vtable + 2
4005 // const char* name; // c++ typeinfo string
4006 // Class cls;
4007 // };
4008 EHTypeTy = llvm::StructType::get(llvm::PointerType::getUnqual(Int8PtrTy),
4009 Int8PtrTy,
4010 ClassnfABIPtrTy,
4011 NULL);
Daniel Dunbarc0318b22009-03-02 06:08:11 +00004012 CGM.getModule().addTypeName("struct._objc_typeinfo", EHTypeTy);
Daniel Dunbar9c285e72009-03-01 04:46:24 +00004013 EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy);
Daniel Dunbardaf4ad42008-08-12 00:12:39 +00004014}
4015
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00004016llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() {
4017 FinishNonFragileABIModule();
4018
4019 return NULL;
4020}
4021
4022void CGObjCNonFragileABIMac::FinishNonFragileABIModule() {
4023 // nonfragile abi has no module definition.
Fariborz Jahanian11c93dd2009-01-30 20:55:31 +00004024
4025 // Build list of all implemented classe addresses in array
4026 // L_OBJC_LABEL_CLASS_$.
4027 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CLASS_$
4028 // list of 'nonlazy' implementations (defined as those with a +load{}
4029 // method!!).
4030 unsigned NumClasses = DefinedClasses.size();
4031 if (NumClasses) {
4032 std::vector<llvm::Constant*> Symbols(NumClasses);
4033 for (unsigned i=0; i<NumClasses; i++)
4034 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
4035 ObjCTypes.Int8PtrTy);
4036 llvm::Constant* Init =
4037 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
4038 NumClasses),
4039 Symbols);
4040
4041 llvm::GlobalVariable *GV =
4042 new llvm::GlobalVariable(Init->getType(), false,
4043 llvm::GlobalValue::InternalLinkage,
4044 Init,
4045 "\01L_OBJC_LABEL_CLASS_$",
4046 &CGM.getModule());
Daniel Dunbar56756c32009-03-09 22:18:41 +00004047 GV->setAlignment(8);
Fariborz Jahanian11c93dd2009-01-30 20:55:31 +00004048 GV->setSection("__DATA, __objc_classlist, regular, no_dead_strip");
4049 UsedGlobals.push_back(GV);
4050 }
4051
4052 // Build list of all implemented category addresses in array
4053 // L_OBJC_LABEL_CATEGORY_$.
4054 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CATEGORY_$
4055 // list of 'nonlazy' category implementations (defined as those with a +load{}
4056 // method!!).
4057 unsigned NumCategory = DefinedCategories.size();
4058 if (NumCategory) {
4059 std::vector<llvm::Constant*> Symbols(NumCategory);
4060 for (unsigned i=0; i<NumCategory; i++)
4061 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedCategories[i],
4062 ObjCTypes.Int8PtrTy);
4063 llvm::Constant* Init =
4064 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
4065 NumCategory),
4066 Symbols);
4067
4068 llvm::GlobalVariable *GV =
4069 new llvm::GlobalVariable(Init->getType(), false,
4070 llvm::GlobalValue::InternalLinkage,
4071 Init,
4072 "\01L_OBJC_LABEL_CATEGORY_$",
4073 &CGM.getModule());
Daniel Dunbar56756c32009-03-09 22:18:41 +00004074 GV->setAlignment(8);
Fariborz Jahanian11c93dd2009-01-30 20:55:31 +00004075 GV->setSection("__DATA, __objc_catlist, regular, no_dead_strip");
4076 UsedGlobals.push_back(GV);
4077 }
4078
Fariborz Jahanian5b2f5502009-01-30 22:07:48 +00004079 // static int L_OBJC_IMAGE_INFO[2] = { 0, flags };
4080 // FIXME. flags can be 0 | 1 | 2 | 6. For now just use 0
4081 std::vector<llvm::Constant*> Values(2);
4082 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, 0);
Fariborz Jahanian4d7933a2009-02-24 21:08:09 +00004083 unsigned int flags = 0;
Fariborz Jahanian27f58962009-02-24 23:34:44 +00004084 // FIXME: Fix and continue?
4085 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
4086 flags |= eImageInfo_GarbageCollected;
4087 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
4088 flags |= eImageInfo_GCOnly;
Fariborz Jahanian4d7933a2009-02-24 21:08:09 +00004089 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
Fariborz Jahanian5b2f5502009-01-30 22:07:48 +00004090 llvm::Constant* Init = llvm::ConstantArray::get(
4091 llvm::ArrayType::get(ObjCTypes.IntTy, 2),
4092 Values);
4093 llvm::GlobalVariable *IMGV =
4094 new llvm::GlobalVariable(Init->getType(), false,
4095 llvm::GlobalValue::InternalLinkage,
4096 Init,
4097 "\01L_OBJC_IMAGE_INFO",
4098 &CGM.getModule());
4099 IMGV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
Daniel Dunbarac277992009-04-23 08:03:21 +00004100 IMGV->setConstant(true);
Fariborz Jahanian5b2f5502009-01-30 22:07:48 +00004101 UsedGlobals.push_back(IMGV);
4102
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00004103 std::vector<llvm::Constant*> Used;
Fariborz Jahanianab438842009-04-14 18:41:56 +00004104
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00004105 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
4106 e = UsedGlobals.end(); i != e; ++i) {
4107 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
4108 }
Fariborz Jahanianab438842009-04-14 18:41:56 +00004109
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00004110 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
4111 llvm::GlobalValue *GV =
4112 new llvm::GlobalVariable(AT, false,
4113 llvm::GlobalValue::AppendingLinkage,
4114 llvm::ConstantArray::get(AT, Used),
4115 "llvm.used",
4116 &CGM.getModule());
4117
4118 GV->setSection("llvm.metadata");
4119
4120}
4121
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004122// Metadata flags
4123enum MetaDataDlags {
4124 CLS = 0x0,
4125 CLS_META = 0x1,
4126 CLS_ROOT = 0x2,
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00004127 OBJC2_CLS_HIDDEN = 0x10,
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004128 CLS_EXCEPTION = 0x20
4129};
4130/// BuildClassRoTInitializer - generate meta-data for:
4131/// struct _class_ro_t {
4132/// uint32_t const flags;
4133/// uint32_t const instanceStart;
4134/// uint32_t const instanceSize;
4135/// uint32_t const reserved; // only when building for 64bit targets
4136/// const uint8_t * const ivarLayout;
4137/// const char *const name;
4138/// const struct _method_list_t * const baseMethods;
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004139/// const struct _protocol_list_t *const baseProtocols;
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004140/// const struct _ivar_list_t *const ivars;
4141/// const uint8_t * const weakIvarLayout;
4142/// const struct _prop_list_t * const properties;
4143/// }
4144///
4145llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer(
4146 unsigned flags,
4147 unsigned InstanceStart,
4148 unsigned InstanceSize,
4149 const ObjCImplementationDecl *ID) {
4150 std::string ClassName = ID->getNameAsString();
4151 std::vector<llvm::Constant*> Values(10); // 11 for 64bit targets!
4152 Values[ 0] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
4153 Values[ 1] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceStart);
4154 Values[ 2] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceSize);
4155 // FIXME. For 64bit targets add 0 here.
Fariborz Jahanian31b96492009-04-22 23:00:43 +00004156 Values[ 3] = (flags & CLS_META) ? GetIvarLayoutName(0, ObjCTypes)
4157 : BuildIvarLayout(ID, true);
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004158 Values[ 4] = GetClassName(ID->getIdentifier());
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00004159 // const struct _method_list_t * const baseMethods;
4160 std::vector<llvm::Constant*> Methods;
4161 std::string MethodListName("\01l_OBJC_$_");
4162 if (flags & CLS_META) {
4163 MethodListName += "CLASS_METHODS_" + ID->getNameAsString();
Douglas Gregorcd19b572009-04-23 01:02:12 +00004164 for (ObjCImplementationDecl::classmeth_iterator
4165 i = ID->classmeth_begin(CGM.getContext()),
4166 e = ID->classmeth_end(CGM.getContext()); i != e; ++i) {
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00004167 // Class methods should always be defined.
4168 Methods.push_back(GetMethodConstant(*i));
4169 }
4170 } else {
4171 MethodListName += "INSTANCE_METHODS_" + ID->getNameAsString();
Douglas Gregorcd19b572009-04-23 01:02:12 +00004172 for (ObjCImplementationDecl::instmeth_iterator
4173 i = ID->instmeth_begin(CGM.getContext()),
4174 e = ID->instmeth_end(CGM.getContext()); i != e; ++i) {
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00004175 // Instance methods should always be defined.
4176 Methods.push_back(GetMethodConstant(*i));
4177 }
Douglas Gregorcd19b572009-04-23 01:02:12 +00004178 for (ObjCImplementationDecl::propimpl_iterator
4179 i = ID->propimpl_begin(CGM.getContext()),
4180 e = ID->propimpl_end(CGM.getContext()); i != e; ++i) {
Fariborz Jahanian78355ec2009-01-28 22:46:49 +00004181 ObjCPropertyImplDecl *PID = *i;
4182
4183 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize){
4184 ObjCPropertyDecl *PD = PID->getPropertyDecl();
4185
4186 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
4187 if (llvm::Constant *C = GetMethodConstant(MD))
4188 Methods.push_back(C);
4189 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
4190 if (llvm::Constant *C = GetMethodConstant(MD))
4191 Methods.push_back(C);
4192 }
4193 }
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00004194 }
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00004195 Values[ 5] = EmitMethodList(MethodListName,
Fariborz Jahanian3175ddd2009-01-28 01:05:23 +00004196 "__DATA, __objc_const", Methods);
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004197
4198 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4199 assert(OID && "CGObjCNonFragileABIMac::BuildClassRoTInitializer");
4200 Values[ 6] = EmitProtocolList("\01l_OBJC_CLASS_PROTOCOLS_$_"
4201 + OID->getNameAsString(),
4202 OID->protocol_begin(),
4203 OID->protocol_end());
4204
Fariborz Jahanian3f1cc562009-01-27 19:38:51 +00004205 if (flags & CLS_META)
4206 Values[ 7] = llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4207 else
4208 Values[ 7] = EmitIvarList(ID);
Fariborz Jahanian31b96492009-04-22 23:00:43 +00004209 Values[ 8] = (flags & CLS_META) ? GetIvarLayoutName(0, ObjCTypes)
4210 : BuildIvarLayout(ID, false);
Fariborz Jahanian7b709bb2009-01-28 22:18:42 +00004211 if (flags & CLS_META)
4212 Values[ 9] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4213 else
4214 Values[ 9] =
4215 EmitPropertyList(
4216 "\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
4217 ID, ID->getClassInterface(), ObjCTypes);
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004218 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassRonfABITy,
4219 Values);
4220 llvm::GlobalVariable *CLASS_RO_GV =
4221 new llvm::GlobalVariable(ObjCTypes.ClassRonfABITy, false,
4222 llvm::GlobalValue::InternalLinkage,
4223 Init,
4224 (flags & CLS_META) ?
4225 std::string("\01l_OBJC_METACLASS_RO_$_")+ClassName :
4226 std::string("\01l_OBJC_CLASS_RO_$_")+ClassName,
4227 &CGM.getModule());
Fariborz Jahanian2d6ecb22009-01-31 02:43:27 +00004228 CLASS_RO_GV->setAlignment(
4229 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassRonfABITy));
Fariborz Jahanian3175ddd2009-01-28 01:05:23 +00004230 CLASS_RO_GV->setSection("__DATA, __objc_const");
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004231 return CLASS_RO_GV;
Fariborz Jahanianc98c87b2009-01-26 22:58:07 +00004232
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004233}
4234
4235/// BuildClassMetaData - This routine defines that to-level meta-data
4236/// for the given ClassName for:
4237/// struct _class_t {
4238/// struct _class_t *isa;
4239/// struct _class_t * const superclass;
4240/// void *cache;
4241/// IMP *vtable;
4242/// struct class_ro_t *ro;
4243/// }
4244///
Fariborz Jahanian06726462009-01-24 21:21:53 +00004245llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassMetaData(
4246 std::string &ClassName,
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004247 llvm::Constant *IsAGV,
4248 llvm::Constant *SuperClassGV,
Fariborz Jahanian51dcacb2009-01-31 00:59:10 +00004249 llvm::Constant *ClassRoGV,
4250 bool HiddenVisibility) {
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004251 std::vector<llvm::Constant*> Values(5);
4252 Values[0] = IsAGV;
Fariborz Jahanian06726462009-01-24 21:21:53 +00004253 Values[1] = SuperClassGV
4254 ? SuperClassGV
4255 : llvm::Constant::getNullValue(ObjCTypes.ClassnfABIPtrTy);
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004256 Values[2] = ObjCEmptyCacheVar; // &ObjCEmptyCacheVar
4257 Values[3] = ObjCEmptyVtableVar; // &ObjCEmptyVtableVar
4258 Values[4] = ClassRoGV; // &CLASS_RO_GV
4259 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassnfABITy,
4260 Values);
Daniel Dunbarabbda222009-03-01 04:40:10 +00004261 llvm::GlobalVariable *GV = GetClassGlobal(ClassName);
4262 GV->setInitializer(Init);
Fariborz Jahanian7c891592009-01-31 01:07:39 +00004263 GV->setSection("__DATA, __objc_data");
Fariborz Jahanian2d6ecb22009-01-31 02:43:27 +00004264 GV->setAlignment(
4265 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassnfABITy));
Fariborz Jahanian51dcacb2009-01-31 00:59:10 +00004266 if (HiddenVisibility)
4267 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahanian06726462009-01-24 21:21:53 +00004268 return GV;
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004269}
4270
Daniel Dunbarecb5d402009-04-19 23:41:48 +00004271void CGObjCNonFragileABIMac::GetClassSizeInfo(const ObjCInterfaceDecl *OID,
4272 uint32_t &InstanceStart,
4273 uint32_t &InstanceSize) {
Daniel Dunbar85d37542009-04-22 07:32:20 +00004274 // Find first and last (non-padding) ivars in this interface.
4275
4276 // FIXME: Use iterator.
4277 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
4278 GetNamedIvarList(OID, OIvars);
4279
4280 if (OIvars.empty()) {
4281 InstanceStart = InstanceSize = 0;
4282 return;
Daniel Dunbare0edb2e2009-04-22 04:39:47 +00004283 }
Daniel Dunbar85d37542009-04-22 07:32:20 +00004284
4285 const ObjCIvarDecl *First = OIvars.front();
4286 const ObjCIvarDecl *Last = OIvars.back();
4287
4288 InstanceStart = ComputeIvarBaseOffset(CGM, OID, First);
4289 const llvm::Type *FieldTy =
4290 CGM.getTypes().ConvertTypeForMem(Last->getType());
4291 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
Fariborz Jahanian31b96492009-04-22 23:00:43 +00004292// FIXME. This breaks compatibility with llvm-gcc-4.2 (but makes it compatible
4293// with gcc-4.2). We postpone this for now.
4294#if 0
4295 if (Last->isBitField()) {
4296 Expr *BitWidth = Last->getBitWidth();
4297 uint64_t BitFieldSize =
4298 BitWidth->getIntegerConstantExprValue(CGM.getContext()).getZExtValue();
4299 Size = (BitFieldSize / 8) + ((BitFieldSize % 8) != 0);
4300 }
4301#endif
Daniel Dunbar85d37542009-04-22 07:32:20 +00004302 InstanceSize = ComputeIvarBaseOffset(CGM, OID, Last) + Size;
Daniel Dunbarecb5d402009-04-19 23:41:48 +00004303}
4304
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00004305void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) {
4306 std::string ClassName = ID->getNameAsString();
4307 if (!ObjCEmptyCacheVar) {
4308 ObjCEmptyCacheVar = new llvm::GlobalVariable(
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00004309 ObjCTypes.CacheTy,
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00004310 false,
4311 llvm::GlobalValue::ExternalLinkage,
4312 0,
Daniel Dunbara2d275d2009-04-07 05:48:37 +00004313 "_objc_empty_cache",
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00004314 &CGM.getModule());
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00004315
4316 ObjCEmptyVtableVar = new llvm::GlobalVariable(
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00004317 ObjCTypes.ImpnfABITy,
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00004318 false,
4319 llvm::GlobalValue::ExternalLinkage,
4320 0,
Daniel Dunbara2d275d2009-04-07 05:48:37 +00004321 "_objc_empty_vtable",
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00004322 &CGM.getModule());
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00004323 }
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00004324 assert(ID->getClassInterface() &&
4325 "CGObjCNonFragileABIMac::GenerateClass - class is 0");
Daniel Dunbar72878722009-04-20 20:18:54 +00004326 // FIXME: Is this correct (that meta class size is never computed)?
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004327 uint32_t InstanceStart =
4328 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassnfABITy);
4329 uint32_t InstanceSize = InstanceStart;
4330 uint32_t flags = CLS_META;
Daniel Dunbara2d275d2009-04-07 05:48:37 +00004331 std::string ObjCMetaClassName(getMetaclassSymbolPrefix());
4332 std::string ObjCClassName(getClassSymbolPrefix());
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00004333
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004334 llvm::GlobalVariable *SuperClassGV, *IsAGV;
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00004335
Daniel Dunbar8394fda2009-04-14 06:00:08 +00004336 bool classIsHidden =
4337 CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden;
Fariborz Jahanian51dcacb2009-01-31 00:59:10 +00004338 if (classIsHidden)
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00004339 flags |= OBJC2_CLS_HIDDEN;
4340 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004341 // class is root
4342 flags |= CLS_ROOT;
Daniel Dunbarabbda222009-03-01 04:40:10 +00004343 SuperClassGV = GetClassGlobal(ObjCClassName + ClassName);
Fariborz Jahanianab438842009-04-14 18:41:56 +00004344 IsAGV = GetClassGlobal(ObjCMetaClassName + ClassName);
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004345 } else {
Fariborz Jahanian06726462009-01-24 21:21:53 +00004346 // Has a root. Current class is not a root.
Fariborz Jahanian514c63b2009-02-26 18:23:47 +00004347 const ObjCInterfaceDecl *Root = ID->getClassInterface();
4348 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
4349 Root = Super;
Fariborz Jahanianab438842009-04-14 18:41:56 +00004350 IsAGV = GetClassGlobal(ObjCMetaClassName + Root->getNameAsString());
Fariborz Jahanian514c63b2009-02-26 18:23:47 +00004351 // work on super class metadata symbol.
4352 std::string SuperClassName =
4353 ObjCMetaClassName + ID->getClassInterface()->getSuperClass()->getNameAsString();
Fariborz Jahanianab438842009-04-14 18:41:56 +00004354 SuperClassGV = GetClassGlobal(SuperClassName);
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004355 }
4356 llvm::GlobalVariable *CLASS_RO_GV = BuildClassRoTInitializer(flags,
4357 InstanceStart,
4358 InstanceSize,ID);
Fariborz Jahanian06726462009-01-24 21:21:53 +00004359 std::string TClassName = ObjCMetaClassName + ClassName;
4360 llvm::GlobalVariable *MetaTClass =
Fariborz Jahanian51dcacb2009-01-31 00:59:10 +00004361 BuildClassMetaData(TClassName, IsAGV, SuperClassGV, CLASS_RO_GV,
4362 classIsHidden);
Daniel Dunbara2d275d2009-04-07 05:48:37 +00004363
Fariborz Jahanian06726462009-01-24 21:21:53 +00004364 // Metadata for the class
4365 flags = CLS;
Fariborz Jahanian51dcacb2009-01-31 00:59:10 +00004366 if (classIsHidden)
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00004367 flags |= OBJC2_CLS_HIDDEN;
Daniel Dunbarc2129532009-04-08 04:21:03 +00004368
4369 if (hasObjCExceptionAttribute(ID->getClassInterface()))
4370 flags |= CLS_EXCEPTION;
4371
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00004372 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian06726462009-01-24 21:21:53 +00004373 flags |= CLS_ROOT;
4374 SuperClassGV = 0;
Chris Lattner9fe470d2009-04-19 06:02:28 +00004375 } else {
Fariborz Jahanian06726462009-01-24 21:21:53 +00004376 // Has a root. Current class is not a root.
Fariborz Jahanian514c63b2009-02-26 18:23:47 +00004377 std::string RootClassName =
Fariborz Jahanian06726462009-01-24 21:21:53 +00004378 ID->getClassInterface()->getSuperClass()->getNameAsString();
Daniel Dunbarabbda222009-03-01 04:40:10 +00004379 SuperClassGV = GetClassGlobal(ObjCClassName + RootClassName);
Fariborz Jahanian06726462009-01-24 21:21:53 +00004380 }
Daniel Dunbarecb5d402009-04-19 23:41:48 +00004381 GetClassSizeInfo(ID->getClassInterface(), InstanceStart, InstanceSize);
Fariborz Jahanian06726462009-01-24 21:21:53 +00004382 CLASS_RO_GV = BuildClassRoTInitializer(flags,
Fariborz Jahanianddd2fdd2009-01-24 23:43:01 +00004383 InstanceStart,
4384 InstanceSize,
4385 ID);
Fariborz Jahanian06726462009-01-24 21:21:53 +00004386
4387 TClassName = ObjCClassName + ClassName;
Fariborz Jahanian11c93dd2009-01-30 20:55:31 +00004388 llvm::GlobalVariable *ClassMD =
Fariborz Jahanian51dcacb2009-01-31 00:59:10 +00004389 BuildClassMetaData(TClassName, MetaTClass, SuperClassGV, CLASS_RO_GV,
4390 classIsHidden);
Fariborz Jahanian11c93dd2009-01-30 20:55:31 +00004391 DefinedClasses.push_back(ClassMD);
Daniel Dunbarc2129532009-04-08 04:21:03 +00004392
4393 // Force the definition of the EHType if necessary.
4394 if (flags & CLS_EXCEPTION)
4395 GetInterfaceEHType(ID->getClassInterface(), true);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00004396}
4397
Fariborz Jahanian5d13ab12009-01-30 18:58:59 +00004398/// GenerateProtocolRef - This routine is called to generate code for
4399/// a protocol reference expression; as in:
4400/// @code
4401/// @protocol(Proto1);
4402/// @endcode
4403/// It generates a weak reference to l_OBJC_PROTOCOL_REFERENCE_$_Proto1
4404/// which will hold address of the protocol meta-data.
4405///
4406llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CGBuilderTy &Builder,
4407 const ObjCProtocolDecl *PD) {
4408
Fariborz Jahaniand3243322009-04-10 18:47:34 +00004409 // This routine is called for @protocol only. So, we must build definition
4410 // of protocol's meta-data (not a reference to it!)
4411 //
4412 llvm::Constant *Init = llvm::ConstantExpr::getBitCast(GetOrEmitProtocol(PD),
Fariborz Jahanian5d13ab12009-01-30 18:58:59 +00004413 ObjCTypes.ExternalProtocolPtrTy);
4414
4415 std::string ProtocolName("\01l_OBJC_PROTOCOL_REFERENCE_$_");
4416 ProtocolName += PD->getNameAsCString();
4417
4418 llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName);
4419 if (PTGV)
4420 return Builder.CreateLoad(PTGV, false, "tmp");
4421 PTGV = new llvm::GlobalVariable(
4422 Init->getType(), false,
Mike Stump36dbf222009-03-07 16:33:28 +00004423 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian5d13ab12009-01-30 18:58:59 +00004424 Init,
4425 ProtocolName,
4426 &CGM.getModule());
4427 PTGV->setSection("__DATA, __objc_protorefs, coalesced, no_dead_strip");
4428 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4429 UsedGlobals.push_back(PTGV);
4430 return Builder.CreateLoad(PTGV, false, "tmp");
4431}
4432
Fariborz Jahanianfe49a092009-01-26 18:32:24 +00004433/// GenerateCategory - Build metadata for a category implementation.
4434/// struct _category_t {
4435/// const char * const name;
4436/// struct _class_t *const cls;
4437/// const struct _method_list_t * const instance_methods;
4438/// const struct _method_list_t * const class_methods;
4439/// const struct _protocol_list_t * const protocols;
4440/// const struct _prop_list_t * const properties;
4441/// }
4442///
4443void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD)
4444{
4445 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Fariborz Jahanianc98c87b2009-01-26 22:58:07 +00004446 const char *Prefix = "\01l_OBJC_$_CATEGORY_";
4447 std::string ExtCatName(Prefix + Interface->getNameAsString()+
Fariborz Jahanianfe49a092009-01-26 18:32:24 +00004448 "_$_" + OCD->getNameAsString());
Daniel Dunbara2d275d2009-04-07 05:48:37 +00004449 std::string ExtClassName(getClassSymbolPrefix() +
4450 Interface->getNameAsString());
Fariborz Jahanianfe49a092009-01-26 18:32:24 +00004451
4452 std::vector<llvm::Constant*> Values(6);
4453 Values[0] = GetClassName(OCD->getIdentifier());
4454 // meta-class entry symbol
Daniel Dunbarabbda222009-03-01 04:40:10 +00004455 llvm::GlobalVariable *ClassGV = GetClassGlobal(ExtClassName);
Fariborz Jahanianfe49a092009-01-26 18:32:24 +00004456 Values[1] = ClassGV;
Fariborz Jahanianc98c87b2009-01-26 22:58:07 +00004457 std::vector<llvm::Constant*> Methods;
4458 std::string MethodListName(Prefix);
4459 MethodListName += "INSTANCE_METHODS_" + Interface->getNameAsString() +
4460 "_$_" + OCD->getNameAsString();
4461
Douglas Gregorcd19b572009-04-23 01:02:12 +00004462 for (ObjCCategoryImplDecl::instmeth_iterator
4463 i = OCD->instmeth_begin(CGM.getContext()),
4464 e = OCD->instmeth_end(CGM.getContext()); i != e; ++i) {
Fariborz Jahanianc98c87b2009-01-26 22:58:07 +00004465 // Instance methods should always be defined.
4466 Methods.push_back(GetMethodConstant(*i));
4467 }
4468
4469 Values[2] = EmitMethodList(MethodListName,
Fariborz Jahanian3175ddd2009-01-28 01:05:23 +00004470 "__DATA, __objc_const",
Fariborz Jahanianc98c87b2009-01-26 22:58:07 +00004471 Methods);
4472
4473 MethodListName = Prefix;
4474 MethodListName += "CLASS_METHODS_" + Interface->getNameAsString() + "_$_" +
4475 OCD->getNameAsString();
4476 Methods.clear();
Douglas Gregorcd19b572009-04-23 01:02:12 +00004477 for (ObjCCategoryImplDecl::classmeth_iterator
4478 i = OCD->classmeth_begin(CGM.getContext()),
4479 e = OCD->classmeth_end(CGM.getContext()); i != e; ++i) {
Fariborz Jahanianc98c87b2009-01-26 22:58:07 +00004480 // Class methods should always be defined.
4481 Methods.push_back(GetMethodConstant(*i));
4482 }
4483
4484 Values[3] = EmitMethodList(MethodListName,
Fariborz Jahanian3175ddd2009-01-28 01:05:23 +00004485 "__DATA, __objc_const",
Fariborz Jahanianc98c87b2009-01-26 22:58:07 +00004486 Methods);
Fariborz Jahanian7b709bb2009-01-28 22:18:42 +00004487 const ObjCCategoryDecl *Category =
4488 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Fariborz Jahanian8c7904b2009-02-13 17:52:22 +00004489 if (Category) {
4490 std::string ExtName(Interface->getNameAsString() + "_$_" +
4491 OCD->getNameAsString());
4492 Values[4] = EmitProtocolList("\01l_OBJC_CATEGORY_PROTOCOLS_$_"
4493 + Interface->getNameAsString() + "_$_"
4494 + Category->getNameAsString(),
4495 Category->protocol_begin(),
4496 Category->protocol_end());
4497 Values[5] =
4498 EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
4499 OCD, Category, ObjCTypes);
4500 }
4501 else {
4502 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4503 Values[5] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4504 }
4505
Fariborz Jahanianfe49a092009-01-26 18:32:24 +00004506 llvm::Constant *Init =
4507 llvm::ConstantStruct::get(ObjCTypes.CategorynfABITy,
4508 Values);
4509 llvm::GlobalVariable *GCATV
4510 = new llvm::GlobalVariable(ObjCTypes.CategorynfABITy,
4511 false,
4512 llvm::GlobalValue::InternalLinkage,
4513 Init,
4514 ExtCatName,
4515 &CGM.getModule());
Fariborz Jahanian2d6ecb22009-01-31 02:43:27 +00004516 GCATV->setAlignment(
4517 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.CategorynfABITy));
Fariborz Jahanian3175ddd2009-01-28 01:05:23 +00004518 GCATV->setSection("__DATA, __objc_const");
Fariborz Jahanianfe49a092009-01-26 18:32:24 +00004519 UsedGlobals.push_back(GCATV);
4520 DefinedCategories.push_back(GCATV);
4521}
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00004522
4523/// GetMethodConstant - Return a struct objc_method constant for the
4524/// given method if it has been defined. The result is null if the
4525/// method has not been defined. The return value has type MethodPtrTy.
4526llvm::Constant *CGObjCNonFragileABIMac::GetMethodConstant(
4527 const ObjCMethodDecl *MD) {
4528 // FIXME: Use DenseMap::lookup
4529 llvm::Function *Fn = MethodDefinitions[MD];
4530 if (!Fn)
4531 return 0;
4532
4533 std::vector<llvm::Constant*> Method(3);
4534 Method[0] =
4535 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4536 ObjCTypes.SelectorPtrTy);
4537 Method[1] = GetMethodVarType(MD);
4538 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
4539 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
4540}
4541
4542/// EmitMethodList - Build meta-data for method declarations
4543/// struct _method_list_t {
4544/// uint32_t entsize; // sizeof(struct _objc_method)
4545/// uint32_t method_count;
4546/// struct _objc_method method_list[method_count];
4547/// }
4548///
4549llvm::Constant *CGObjCNonFragileABIMac::EmitMethodList(
4550 const std::string &Name,
4551 const char *Section,
4552 const ConstantVector &Methods) {
4553 // Return null for empty list.
4554 if (Methods.empty())
4555 return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy);
4556
4557 std::vector<llvm::Constant*> Values(3);
4558 // sizeof(struct _objc_method)
4559 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.MethodTy);
4560 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4561 // method_count
4562 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
4563 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
4564 Methods.size());
4565 Values[2] = llvm::ConstantArray::get(AT, Methods);
4566 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4567
4568 llvm::GlobalVariable *GV =
4569 new llvm::GlobalVariable(Init->getType(), false,
4570 llvm::GlobalValue::InternalLinkage,
4571 Init,
4572 Name,
4573 &CGM.getModule());
Fariborz Jahanian2d6ecb22009-01-31 02:43:27 +00004574 GV->setAlignment(
4575 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00004576 GV->setSection(Section);
4577 UsedGlobals.push_back(GV);
4578 return llvm::ConstantExpr::getBitCast(GV,
4579 ObjCTypes.MethodListnfABIPtrTy);
4580}
Fariborz Jahanian3f1cc562009-01-27 19:38:51 +00004581
Fariborz Jahaniancc00f922009-02-10 20:21:06 +00004582/// ObjCIvarOffsetVariable - Returns the ivar offset variable for
4583/// the given ivar.
4584///
4585llvm::GlobalVariable * CGObjCNonFragileABIMac::ObjCIvarOffsetVariable(
Fariborz Jahaniana09a5142009-02-12 18:51:23 +00004586 const ObjCInterfaceDecl *ID,
Fariborz Jahaniancc00f922009-02-10 20:21:06 +00004587 const ObjCIvarDecl *Ivar) {
Daniel Dunbar07d204a2009-04-19 00:31:15 +00004588 std::string Name = "OBJC_IVAR_$_" +
Douglas Gregorc55b0b02009-04-09 21:40:53 +00004589 getInterfaceDeclForIvar(ID, Ivar, CGM.getContext())->getNameAsString() +
4590 '.' + Ivar->getNameAsString();
Fariborz Jahaniancc00f922009-02-10 20:21:06 +00004591 llvm::GlobalVariable *IvarOffsetGV =
4592 CGM.getModule().getGlobalVariable(Name);
4593 if (!IvarOffsetGV)
4594 IvarOffsetGV =
4595 new llvm::GlobalVariable(ObjCTypes.LongTy,
4596 false,
4597 llvm::GlobalValue::ExternalLinkage,
4598 0,
4599 Name,
4600 &CGM.getModule());
4601 return IvarOffsetGV;
4602}
4603
Fariborz Jahanian3175ddd2009-01-28 01:05:23 +00004604llvm::Constant * CGObjCNonFragileABIMac::EmitIvarOffsetVar(
Fariborz Jahaniancc00f922009-02-10 20:21:06 +00004605 const ObjCInterfaceDecl *ID,
Fariborz Jahanian150f7732009-01-28 01:36:42 +00004606 const ObjCIvarDecl *Ivar,
Fariborz Jahanian3175ddd2009-01-28 01:05:23 +00004607 unsigned long int Offset) {
Daniel Dunbar0438ff42009-04-19 00:44:02 +00004608 llvm::GlobalVariable *IvarOffsetGV = ObjCIvarOffsetVariable(ID, Ivar);
4609 IvarOffsetGV->setInitializer(llvm::ConstantInt::get(ObjCTypes.LongTy,
4610 Offset));
Fariborz Jahanian2d6ecb22009-01-31 02:43:27 +00004611 IvarOffsetGV->setAlignment(
Fariborz Jahanian55343922009-02-03 00:09:52 +00004612 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.LongTy));
Daniel Dunbar0438ff42009-04-19 00:44:02 +00004613
4614 // FIXME: This matches gcc, but shouldn't the visibility be set on
4615 // the use as well (i.e., in ObjCIvarOffsetVariable).
4616 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
4617 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
4618 CGM.getDeclVisibilityMode(ID) == LangOptions::Hidden)
Fariborz Jahanian150f7732009-01-28 01:36:42 +00004619 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar8394fda2009-04-14 06:00:08 +00004620 else
Fariborz Jahanian745fd892009-04-06 18:30:00 +00004621 IvarOffsetGV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Fariborz Jahanian3175ddd2009-01-28 01:05:23 +00004622 IvarOffsetGV->setSection("__DATA, __objc_const");
Fariborz Jahanian55343922009-02-03 00:09:52 +00004623 return IvarOffsetGV;
Fariborz Jahanian3175ddd2009-01-28 01:05:23 +00004624}
4625
Fariborz Jahanian3f1cc562009-01-27 19:38:51 +00004626/// EmitIvarList - Emit the ivar list for the given
Daniel Dunbar3c190812009-04-18 08:51:00 +00004627/// implementation. The return value has type
Fariborz Jahanian3f1cc562009-01-27 19:38:51 +00004628/// IvarListnfABIPtrTy.
4629/// struct _ivar_t {
4630/// unsigned long int *offset; // pointer to ivar offset location
4631/// char *name;
4632/// char *type;
4633/// uint32_t alignment;
4634/// uint32_t size;
4635/// }
4636/// struct _ivar_list_t {
4637/// uint32 entsize; // sizeof(struct _ivar_t)
4638/// uint32 count;
4639/// struct _iver_t list[count];
4640/// }
4641///
Daniel Dunbar356f0742009-04-20 06:54:31 +00004642
4643void CGObjCCommonMac::GetNamedIvarList(const ObjCInterfaceDecl *OID,
4644 llvm::SmallVector<ObjCIvarDecl*, 16> &Res) const {
4645 for (ObjCInterfaceDecl::ivar_iterator I = OID->ivar_begin(),
4646 E = OID->ivar_end(); I != E; ++I) {
4647 // Ignore unnamed bit-fields.
4648 if (!(*I)->getDeclName())
4649 continue;
4650
4651 Res.push_back(*I);
4652 }
4653
4654 for (ObjCInterfaceDecl::prop_iterator I = OID->prop_begin(CGM.getContext()),
4655 E = OID->prop_end(CGM.getContext()); I != E; ++I)
4656 if (ObjCIvarDecl *IV = (*I)->getPropertyIvarDecl())
4657 Res.push_back(IV);
4658}
4659
Fariborz Jahanian3f1cc562009-01-27 19:38:51 +00004660llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList(
4661 const ObjCImplementationDecl *ID) {
4662
4663 std::vector<llvm::Constant*> Ivars, Ivar(5);
4664
4665 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4666 assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface");
4667
Fariborz Jahanian3175ddd2009-01-28 01:05:23 +00004668 // FIXME. Consolidate this with similar code in GenerateClass.
Fariborz Jahanianf2a94cd2009-01-28 19:12:34 +00004669
Daniel Dunbar1748ac32009-04-20 00:33:43 +00004670 // Collect declared and synthesized ivars in a small vector.
Fariborz Jahanianfbf44642009-03-31 18:11:23 +00004671 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
Daniel Dunbar356f0742009-04-20 06:54:31 +00004672 GetNamedIvarList(OID, OIvars);
Fariborz Jahanian84c45692009-04-01 19:37:34 +00004673
Daniel Dunbar356f0742009-04-20 06:54:31 +00004674 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
4675 ObjCIvarDecl *IVD = OIvars[i];
Daniel Dunbard73f5f22009-04-20 05:53:40 +00004676 Ivar[0] = EmitIvarOffsetVar(ID->getClassInterface(), IVD,
Daniel Dunbar85d37542009-04-22 07:32:20 +00004677 ComputeIvarBaseOffset(CGM, OID, IVD));
Daniel Dunbare42aede2009-04-22 08:22:17 +00004678 Ivar[1] = GetMethodVarName(IVD->getIdentifier());
4679 Ivar[2] = GetMethodVarType(IVD);
Fariborz Jahanian3f1cc562009-01-27 19:38:51 +00004680 const llvm::Type *FieldTy =
Daniel Dunbare42aede2009-04-22 08:22:17 +00004681 CGM.getTypes().ConvertTypeForMem(IVD->getType());
Fariborz Jahanian3f1cc562009-01-27 19:38:51 +00004682 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
4683 unsigned Align = CGM.getContext().getPreferredTypeAlign(
Daniel Dunbare42aede2009-04-22 08:22:17 +00004684 IVD->getType().getTypePtr()) >> 3;
Fariborz Jahanian3f1cc562009-01-27 19:38:51 +00004685 Align = llvm::Log2_32(Align);
4686 Ivar[3] = llvm::ConstantInt::get(ObjCTypes.IntTy, Align);
Daniel Dunbar1748ac32009-04-20 00:33:43 +00004687 // NOTE. Size of a bitfield does not match gcc's, because of the
4688 // way bitfields are treated special in each. But I am told that
4689 // 'size' for bitfield ivars is ignored by the runtime so it does
4690 // not matter. If it matters, there is enough info to get the
4691 // bitfield right!
Fariborz Jahanian3f1cc562009-01-27 19:38:51 +00004692 Ivar[4] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4693 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarnfABITy, Ivar));
4694 }
4695 // Return null for empty list.
4696 if (Ivars.empty())
4697 return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4698 std::vector<llvm::Constant*> Values(3);
4699 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.IvarnfABITy);
4700 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4701 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
4702 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarnfABITy,
4703 Ivars.size());
4704 Values[2] = llvm::ConstantArray::get(AT, Ivars);
4705 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4706 const char *Prefix = "\01l_OBJC_$_INSTANCE_VARIABLES_";
4707 llvm::GlobalVariable *GV =
4708 new llvm::GlobalVariable(Init->getType(), false,
4709 llvm::GlobalValue::InternalLinkage,
4710 Init,
4711 Prefix + OID->getNameAsString(),
4712 &CGM.getModule());
Fariborz Jahanian2d6ecb22009-01-31 02:43:27 +00004713 GV->setAlignment(
4714 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian3175ddd2009-01-28 01:05:23 +00004715 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian3f1cc562009-01-27 19:38:51 +00004716
4717 UsedGlobals.push_back(GV);
4718 return llvm::ConstantExpr::getBitCast(GV,
4719 ObjCTypes.IvarListnfABIPtrTy);
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004720}
4721
4722llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef(
4723 const ObjCProtocolDecl *PD) {
4724 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4725
4726 if (!Entry) {
4727 // We use the initializer as a marker of whether this is a forward
4728 // reference or not. At module finalization we add the empty
4729 // contents for protocols which were referenced but never defined.
4730 Entry =
4731 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
4732 llvm::GlobalValue::ExternalLinkage,
4733 0,
4734 "\01l_OBJC_PROTOCOL_$_" + PD->getNameAsString(),
4735 &CGM.getModule());
4736 Entry->setSection("__DATA,__datacoal_nt,coalesced");
4737 UsedGlobals.push_back(Entry);
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004738 }
4739
4740 return Entry;
4741}
4742
4743/// GetOrEmitProtocol - Generate the protocol meta-data:
4744/// @code
4745/// struct _protocol_t {
4746/// id isa; // NULL
4747/// const char * const protocol_name;
4748/// const struct _protocol_list_t * protocol_list; // super protocols
4749/// const struct method_list_t * const instance_methods;
4750/// const struct method_list_t * const class_methods;
4751/// const struct method_list_t *optionalInstanceMethods;
4752/// const struct method_list_t *optionalClassMethods;
4753/// const struct _prop_list_t * properties;
4754/// const uint32_t size; // sizeof(struct _protocol_t)
4755/// const uint32_t flags; // = 0
4756/// }
4757/// @endcode
4758///
4759
4760llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol(
4761 const ObjCProtocolDecl *PD) {
4762 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4763
4764 // Early exit if a defining object has already been generated.
4765 if (Entry && Entry->hasInitializer())
4766 return Entry;
4767
4768 const char *ProtocolName = PD->getNameAsCString();
4769
4770 // Construct method lists.
4771 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
4772 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00004773 for (ObjCProtocolDecl::instmeth_iterator
4774 i = PD->instmeth_begin(CGM.getContext()),
4775 e = PD->instmeth_end(CGM.getContext());
4776 i != e; ++i) {
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004777 ObjCMethodDecl *MD = *i;
Fariborz Jahanian151747b2009-01-30 00:46:37 +00004778 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004779 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4780 OptInstanceMethods.push_back(C);
4781 } else {
4782 InstanceMethods.push_back(C);
4783 }
4784 }
4785
Douglas Gregorc55b0b02009-04-09 21:40:53 +00004786 for (ObjCProtocolDecl::classmeth_iterator
4787 i = PD->classmeth_begin(CGM.getContext()),
4788 e = PD->classmeth_end(CGM.getContext());
4789 i != e; ++i) {
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004790 ObjCMethodDecl *MD = *i;
Fariborz Jahanian151747b2009-01-30 00:46:37 +00004791 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004792 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4793 OptClassMethods.push_back(C);
4794 } else {
4795 ClassMethods.push_back(C);
4796 }
4797 }
4798
4799 std::vector<llvm::Constant*> Values(10);
4800 // isa is NULL
4801 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ObjectPtrTy);
4802 Values[1] = GetClassName(PD->getIdentifier());
4803 Values[2] = EmitProtocolList(
4804 "\01l_OBJC_$_PROTOCOL_REFS_" + PD->getNameAsString(),
4805 PD->protocol_begin(),
4806 PD->protocol_end());
4807
Fariborz Jahanian151747b2009-01-30 00:46:37 +00004808 Values[3] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_"
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004809 + PD->getNameAsString(),
4810 "__DATA, __objc_const",
4811 InstanceMethods);
Fariborz Jahanian151747b2009-01-30 00:46:37 +00004812 Values[4] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_"
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004813 + PD->getNameAsString(),
4814 "__DATA, __objc_const",
4815 ClassMethods);
Fariborz Jahanian151747b2009-01-30 00:46:37 +00004816 Values[5] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_"
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004817 + PD->getNameAsString(),
4818 "__DATA, __objc_const",
4819 OptInstanceMethods);
Fariborz Jahanian151747b2009-01-30 00:46:37 +00004820 Values[6] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_"
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004821 + PD->getNameAsString(),
4822 "__DATA, __objc_const",
4823 OptClassMethods);
4824 Values[7] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + PD->getNameAsString(),
4825 0, PD, ObjCTypes);
4826 uint32_t Size =
4827 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolnfABITy);
4828 Values[8] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4829 Values[9] = llvm::Constant::getNullValue(ObjCTypes.IntTy);
4830 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolnfABITy,
4831 Values);
4832
4833 if (Entry) {
4834 // Already created, fix the linkage and update the initializer.
Mike Stump36dbf222009-03-07 16:33:28 +00004835 Entry->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004836 Entry->setInitializer(Init);
4837 } else {
4838 Entry =
4839 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
Mike Stump36dbf222009-03-07 16:33:28 +00004840 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004841 Init,
4842 std::string("\01l_OBJC_PROTOCOL_$_")+ProtocolName,
4843 &CGM.getModule());
Fariborz Jahanian2d6ecb22009-01-31 02:43:27 +00004844 Entry->setAlignment(
4845 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABITy));
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004846 Entry->setSection("__DATA,__datacoal_nt,coalesced");
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004847 }
Fariborz Jahanianfd02a662009-01-29 20:10:59 +00004848 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
4849
4850 // Use this protocol meta-data to build protocol list table in section
4851 // __DATA, __objc_protolist
Fariborz Jahanianfd02a662009-01-29 20:10:59 +00004852 llvm::GlobalVariable *PTGV = new llvm::GlobalVariable(
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00004853 ObjCTypes.ProtocolnfABIPtrTy, false,
Mike Stump36dbf222009-03-07 16:33:28 +00004854 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanianfd02a662009-01-29 20:10:59 +00004855 Entry,
4856 std::string("\01l_OBJC_LABEL_PROTOCOL_$_")
4857 +ProtocolName,
4858 &CGM.getModule());
Fariborz Jahanian2d6ecb22009-01-31 02:43:27 +00004859 PTGV->setAlignment(
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00004860 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABIPtrTy));
Daniel Dunbar9dfd3a72009-04-15 02:56:18 +00004861 PTGV->setSection("__DATA, __objc_protolist, coalesced, no_dead_strip");
Fariborz Jahanianfd02a662009-01-29 20:10:59 +00004862 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4863 UsedGlobals.push_back(PTGV);
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004864 return Entry;
4865}
4866
4867/// EmitProtocolList - Generate protocol list meta-data:
4868/// @code
4869/// struct _protocol_list_t {
4870/// long protocol_count; // Note, this is 32/64 bit
4871/// struct _protocol_t[protocol_count];
4872/// }
4873/// @endcode
4874///
4875llvm::Constant *
4876CGObjCNonFragileABIMac::EmitProtocolList(const std::string &Name,
4877 ObjCProtocolDecl::protocol_iterator begin,
4878 ObjCProtocolDecl::protocol_iterator end) {
4879 std::vector<llvm::Constant*> ProtocolRefs;
4880
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004881 // Just return null for empty protocol lists
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00004882 if (begin == end)
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004883 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4884
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00004885 // FIXME: We shouldn't need to do this lookup here, should we?
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004886 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
4887 if (GV)
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00004888 return llvm::ConstantExpr::getBitCast(GV,
4889 ObjCTypes.ProtocolListnfABIPtrTy);
4890
4891 for (; begin != end; ++begin)
4892 ProtocolRefs.push_back(GetProtocolRef(*begin)); // Implemented???
4893
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004894 // This list is null terminated.
4895 ProtocolRefs.push_back(llvm::Constant::getNullValue(
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00004896 ObjCTypes.ProtocolnfABIPtrTy));
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004897
4898 std::vector<llvm::Constant*> Values(2);
4899 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
4900 Values[1] =
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00004901 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolnfABIPtrTy,
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004902 ProtocolRefs.size()),
4903 ProtocolRefs);
4904
4905 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4906 GV = new llvm::GlobalVariable(Init->getType(), false,
4907 llvm::GlobalValue::InternalLinkage,
4908 Init,
4909 Name,
4910 &CGM.getModule());
4911 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian2d6ecb22009-01-31 02:43:27 +00004912 GV->setAlignment(
4913 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004914 UsedGlobals.push_back(GV);
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00004915 return llvm::ConstantExpr::getBitCast(GV,
4916 ObjCTypes.ProtocolListnfABIPtrTy);
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004917}
4918
Fariborz Jahanian151747b2009-01-30 00:46:37 +00004919/// GetMethodDescriptionConstant - This routine build following meta-data:
4920/// struct _objc_method {
4921/// SEL _cmd;
4922/// char *method_type;
4923/// char *_imp;
4924/// }
4925
4926llvm::Constant *
4927CGObjCNonFragileABIMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
4928 std::vector<llvm::Constant*> Desc(3);
4929 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4930 ObjCTypes.SelectorPtrTy);
4931 Desc[1] = GetMethodVarType(MD);
Fariborz Jahanian5d13ab12009-01-30 18:58:59 +00004932 // Protocol methods have no implementation. So, this entry is always NULL.
Fariborz Jahanian151747b2009-01-30 00:46:37 +00004933 Desc[2] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
4934 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Desc);
4935}
Fariborz Jahanian55343922009-02-03 00:09:52 +00004936
4937/// EmitObjCValueForIvar - Code Gen for nonfragile ivar reference.
4938/// This code gen. amounts to generating code for:
4939/// @code
4940/// (type *)((char *)base + _OBJC_IVAR_$_.ivar;
4941/// @encode
4942///
Fariborz Jahanianc912eb72009-02-03 19:03:09 +00004943LValue CGObjCNonFragileABIMac::EmitObjCValueForIvar(
Fariborz Jahanian55343922009-02-03 00:09:52 +00004944 CodeGen::CodeGenFunction &CGF,
4945 QualType ObjectTy,
4946 llvm::Value *BaseValue,
4947 const ObjCIvarDecl *Ivar,
Fariborz Jahanian55343922009-02-03 00:09:52 +00004948 unsigned CVRQualifiers) {
Daniel Dunbarf5254bd2009-04-21 01:19:28 +00004949 const ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
Daniel Dunbar85d37542009-04-22 07:32:20 +00004950 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
4951 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian55343922009-02-03 00:09:52 +00004952}
4953
Fariborz Jahanian27cc6662009-02-10 19:02:04 +00004954llvm::Value *CGObjCNonFragileABIMac::EmitIvarOffset(
4955 CodeGen::CodeGenFunction &CGF,
Daniel Dunbar61e14a62009-04-22 05:08:15 +00004956 const ObjCInterfaceDecl *Interface,
Fariborz Jahanian27cc6662009-02-10 19:02:04 +00004957 const ObjCIvarDecl *Ivar) {
Daniel Dunbar07d204a2009-04-19 00:31:15 +00004958 return CGF.Builder.CreateLoad(ObjCIvarOffsetVariable(Interface, Ivar),
4959 false, "ivar");
Fariborz Jahanian27cc6662009-02-10 19:02:04 +00004960}
4961
Fariborz Jahanian7e881162009-02-04 00:22:57 +00004962CodeGen::RValue CGObjCNonFragileABIMac::EmitMessageSend(
4963 CodeGen::CodeGenFunction &CGF,
4964 QualType ResultType,
4965 Selector Sel,
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00004966 llvm::Value *Receiver,
Fariborz Jahanian7e881162009-02-04 00:22:57 +00004967 QualType Arg0Ty,
4968 bool IsSuper,
4969 const CallArgList &CallArgs) {
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00004970 // FIXME. Even though IsSuper is passes. This function doese not
4971 // handle calls to 'super' receivers.
4972 CodeGenTypes &Types = CGM.getTypes();
Fariborz Jahanianf3a44012009-02-06 20:09:23 +00004973 llvm::Value *Arg0 = Receiver;
4974 if (!IsSuper)
4975 Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy, "tmp");
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00004976
4977 // Find the message function name.
Fariborz Jahanian10d69ea2009-02-05 01:13:09 +00004978 // FIXME. This is too much work to get the ABI-specific result type
4979 // needed to find the message name.
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00004980 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType,
4981 llvm::SmallVector<QualType, 16>());
4982 llvm::Constant *Fn;
4983 std::string Name("\01l_");
4984 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Fariborz Jahanian13ab25e2009-02-05 18:00:27 +00004985#if 0
4986 // unlike what is documented. gcc never generates this API!!
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00004987 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
Chris Lattnerada416b2009-04-22 02:53:24 +00004988 Fn = ObjCTypes.getMessageSendIdStretFixupFn();
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00004989 // FIXME. Is there a better way of getting these names.
4990 // They are available in RuntimeFunctions vector pair.
4991 Name += "objc_msgSendId_stret_fixup";
4992 }
Fariborz Jahanian13ab25e2009-02-05 18:00:27 +00004993 else
4994#endif
Fariborz Jahanianf3a44012009-02-06 20:09:23 +00004995 if (IsSuper) {
Chris Lattnerada416b2009-04-22 02:53:24 +00004996 Fn = ObjCTypes.getMessageSendSuper2StretFixupFn();
Fariborz Jahanianf3a44012009-02-06 20:09:23 +00004997 Name += "objc_msgSendSuper2_stret_fixup";
4998 }
4999 else
Fariborz Jahanian13ab25e2009-02-05 18:00:27 +00005000 {
Chris Lattnerada416b2009-04-22 02:53:24 +00005001 Fn = ObjCTypes.getMessageSendStretFixupFn();
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00005002 Name += "objc_msgSend_stret_fixup";
5003 }
5004 }
Fariborz Jahanianbea03192009-02-05 19:35:43 +00005005 else if (ResultType->isFloatingType() &&
5006 // Selection of frret API only happens in 32bit nonfragile ABI.
5007 CGM.getTargetData().getTypePaddedSize(ObjCTypes.LongTy) == 4) {
Chris Lattnerada416b2009-04-22 02:53:24 +00005008 Fn = ObjCTypes.getMessageSendFpretFixupFn();
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00005009 Name += "objc_msgSend_fpret_fixup";
5010 }
5011 else {
Fariborz Jahanian13ab25e2009-02-05 18:00:27 +00005012#if 0
5013// unlike what is documented. gcc never generates this API!!
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00005014 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
Chris Lattnerada416b2009-04-22 02:53:24 +00005015 Fn = ObjCTypes.getMessageSendIdFixupFn();
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00005016 Name += "objc_msgSendId_fixup";
5017 }
Fariborz Jahanian13ab25e2009-02-05 18:00:27 +00005018 else
5019#endif
Fariborz Jahanianf3a44012009-02-06 20:09:23 +00005020 if (IsSuper) {
Chris Lattnerada416b2009-04-22 02:53:24 +00005021 Fn = ObjCTypes.getMessageSendSuper2FixupFn();
Fariborz Jahanianf3a44012009-02-06 20:09:23 +00005022 Name += "objc_msgSendSuper2_fixup";
5023 }
5024 else
Fariborz Jahanian13ab25e2009-02-05 18:00:27 +00005025 {
Chris Lattnerada416b2009-04-22 02:53:24 +00005026 Fn = ObjCTypes.getMessageSendFixupFn();
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00005027 Name += "objc_msgSend_fixup";
5028 }
5029 }
5030 Name += '_';
5031 std::string SelName(Sel.getAsString());
5032 // Replace all ':' in selector name with '_' ouch!
5033 for(unsigned i = 0; i < SelName.size(); i++)
5034 if (SelName[i] == ':')
5035 SelName[i] = '_';
5036 Name += SelName;
5037 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5038 if (!GV) {
Daniel Dunbar4993e292009-04-15 19:03:14 +00005039 // Build message ref table entry.
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00005040 std::vector<llvm::Constant*> Values(2);
5041 Values[0] = Fn;
5042 Values[1] = GetMethodVarName(Sel);
5043 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
5044 GV = new llvm::GlobalVariable(Init->getType(), false,
Mike Stump36dbf222009-03-07 16:33:28 +00005045 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00005046 Init,
5047 Name,
5048 &CGM.getModule());
5049 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbara405f782009-04-15 19:04:46 +00005050 GV->setAlignment(16);
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00005051 GV->setSection("__DATA, __objc_msgrefs, coalesced");
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00005052 }
5053 llvm::Value *Arg1 = CGF.Builder.CreateBitCast(GV, ObjCTypes.MessageRefPtrTy);
Fariborz Jahanian10d69ea2009-02-05 01:13:09 +00005054
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00005055 CallArgList ActualArgs;
5056 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
5057 ActualArgs.push_back(std::make_pair(RValue::get(Arg1),
5058 ObjCTypes.MessageRefCPtrTy));
5059 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Fariborz Jahanian10d69ea2009-02-05 01:13:09 +00005060 const CGFunctionInfo &FnInfo1 = Types.getFunctionInfo(ResultType, ActualArgs);
5061 llvm::Value *Callee = CGF.Builder.CreateStructGEP(Arg1, 0);
5062 Callee = CGF.Builder.CreateLoad(Callee);
Fariborz Jahanianf3c17752009-02-14 21:25:36 +00005063 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo1, true);
Fariborz Jahanian10d69ea2009-02-05 01:13:09 +00005064 Callee = CGF.Builder.CreateBitCast(Callee,
5065 llvm::PointerType::getUnqual(FTy));
5066 return CGF.EmitCall(FnInfo1, Callee, ActualArgs);
Fariborz Jahanian7e881162009-02-04 00:22:57 +00005067}
5068
5069/// Generate code for a message send expression in the nonfragile abi.
5070CodeGen::RValue CGObjCNonFragileABIMac::GenerateMessageSend(
5071 CodeGen::CodeGenFunction &CGF,
5072 QualType ResultType,
5073 Selector Sel,
5074 llvm::Value *Receiver,
5075 bool IsClassMessage,
5076 const CallArgList &CallArgs) {
Fariborz Jahanian7e881162009-02-04 00:22:57 +00005077 return EmitMessageSend(CGF, ResultType, Sel,
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00005078 Receiver, CGF.getContext().getObjCIdType(),
Fariborz Jahanian7e881162009-02-04 00:22:57 +00005079 false, CallArgs);
5080}
5081
Daniel Dunbarabbda222009-03-01 04:40:10 +00005082llvm::GlobalVariable *
Fariborz Jahanianab438842009-04-14 18:41:56 +00005083CGObjCNonFragileABIMac::GetClassGlobal(const std::string &Name) {
Daniel Dunbarabbda222009-03-01 04:40:10 +00005084 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5085
Daniel Dunbar66b47512009-03-02 05:18:14 +00005086 if (!GV) {
Daniel Dunbarabbda222009-03-01 04:40:10 +00005087 GV = new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
5088 llvm::GlobalValue::ExternalLinkage,
5089 0, Name, &CGM.getModule());
Daniel Dunbarabbda222009-03-01 04:40:10 +00005090 }
5091
5092 return GV;
5093}
5094
Fariborz Jahanian917c0402009-02-05 20:41:40 +00005095llvm::Value *CGObjCNonFragileABIMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar3c190812009-04-18 08:51:00 +00005096 const ObjCInterfaceDecl *ID) {
Fariborz Jahanian917c0402009-02-05 20:41:40 +00005097 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
5098
5099 if (!Entry) {
Daniel Dunbara2d275d2009-04-07 05:48:37 +00005100 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbarabbda222009-03-01 04:40:10 +00005101 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
Fariborz Jahanian917c0402009-02-05 20:41:40 +00005102 Entry =
5103 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5104 llvm::GlobalValue::InternalLinkage,
Fariborz Jahanianf3a44012009-02-06 20:09:23 +00005105 ClassGV,
Daniel Dunbar3c190812009-04-18 08:51:00 +00005106 "\01L_OBJC_CLASSLIST_REFERENCES_$_",
Fariborz Jahanian917c0402009-02-05 20:41:40 +00005107 &CGM.getModule());
5108 Entry->setAlignment(
5109 CGM.getTargetData().getPrefTypeAlignment(
5110 ObjCTypes.ClassnfABIPtrTy));
Daniel Dunbar3c190812009-04-18 08:51:00 +00005111 Entry->setSection("__DATA, __objc_classrefs, regular, no_dead_strip");
5112 UsedGlobals.push_back(Entry);
5113 }
5114
5115 return Builder.CreateLoad(Entry, false, "tmp");
5116}
Fariborz Jahanian917c0402009-02-05 20:41:40 +00005117
Daniel Dunbar3c190812009-04-18 08:51:00 +00005118llvm::Value *
5119CGObjCNonFragileABIMac::EmitSuperClassRef(CGBuilderTy &Builder,
5120 const ObjCInterfaceDecl *ID) {
5121 llvm::GlobalVariable *&Entry = SuperClassReferences[ID->getIdentifier()];
5122
5123 if (!Entry) {
5124 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
5125 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
5126 Entry =
5127 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5128 llvm::GlobalValue::InternalLinkage,
5129 ClassGV,
5130 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5131 &CGM.getModule());
5132 Entry->setAlignment(
5133 CGM.getTargetData().getPrefTypeAlignment(
5134 ObjCTypes.ClassnfABIPtrTy));
5135 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanian917c0402009-02-05 20:41:40 +00005136 UsedGlobals.push_back(Entry);
5137 }
5138
5139 return Builder.CreateLoad(Entry, false, "tmp");
5140}
5141
Fariborz Jahanianf3a44012009-02-06 20:09:23 +00005142/// EmitMetaClassRef - Return a Value * of the address of _class_t
5143/// meta-data
5144///
5145llvm::Value *CGObjCNonFragileABIMac::EmitMetaClassRef(CGBuilderTy &Builder,
5146 const ObjCInterfaceDecl *ID) {
5147 llvm::GlobalVariable * &Entry = MetaClassReferences[ID->getIdentifier()];
5148 if (Entry)
5149 return Builder.CreateLoad(Entry, false, "tmp");
5150
Daniel Dunbara2d275d2009-04-07 05:48:37 +00005151 std::string MetaClassName(getMetaclassSymbolPrefix() + ID->getNameAsString());
Fariborz Jahanianab438842009-04-14 18:41:56 +00005152 llvm::GlobalVariable *MetaClassGV = GetClassGlobal(MetaClassName);
Fariborz Jahanianf3a44012009-02-06 20:09:23 +00005153 Entry =
5154 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5155 llvm::GlobalValue::InternalLinkage,
5156 MetaClassGV,
5157 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5158 &CGM.getModule());
5159 Entry->setAlignment(
5160 CGM.getTargetData().getPrefTypeAlignment(
5161 ObjCTypes.ClassnfABIPtrTy));
5162
Daniel Dunbar4993e292009-04-15 19:03:14 +00005163 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanianf3a44012009-02-06 20:09:23 +00005164 UsedGlobals.push_back(Entry);
5165
5166 return Builder.CreateLoad(Entry, false, "tmp");
5167}
5168
Fariborz Jahanian917c0402009-02-05 20:41:40 +00005169/// GetClass - Return a reference to the class for the given interface
5170/// decl.
5171llvm::Value *CGObjCNonFragileABIMac::GetClass(CGBuilderTy &Builder,
5172 const ObjCInterfaceDecl *ID) {
5173 return EmitClassRef(Builder, ID);
5174}
5175
Fariborz Jahanianf3a44012009-02-06 20:09:23 +00005176/// Generates a message send where the super is the receiver. This is
5177/// a message send to self with special delivery semantics indicating
5178/// which class's method should be called.
5179CodeGen::RValue
5180CGObjCNonFragileABIMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
5181 QualType ResultType,
5182 Selector Sel,
5183 const ObjCInterfaceDecl *Class,
Fariborz Jahanian17636fa2009-02-28 20:07:56 +00005184 bool isCategoryImpl,
Fariborz Jahanianf3a44012009-02-06 20:09:23 +00005185 llvm::Value *Receiver,
5186 bool IsClassMessage,
5187 const CodeGen::CallArgList &CallArgs) {
5188 // ...
5189 // Create and init a super structure; this is a (receiver, class)
5190 // pair we will pass to objc_msgSendSuper.
5191 llvm::Value *ObjCSuper =
5192 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
5193
5194 llvm::Value *ReceiverAsObject =
5195 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
5196 CGF.Builder.CreateStore(ReceiverAsObject,
5197 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
5198
5199 // If this is a class message the metaclass is passed as the target.
Fariborz Jahanian17636fa2009-02-28 20:07:56 +00005200 llvm::Value *Target;
5201 if (IsClassMessage) {
5202 if (isCategoryImpl) {
5203 // Message sent to "super' in a class method defined in
5204 // a category implementation.
Daniel Dunbar3c190812009-04-18 08:51:00 +00005205 Target = EmitClassRef(CGF.Builder, Class);
Fariborz Jahanian17636fa2009-02-28 20:07:56 +00005206 Target = CGF.Builder.CreateStructGEP(Target, 0);
5207 Target = CGF.Builder.CreateLoad(Target);
5208 }
5209 else
5210 Target = EmitMetaClassRef(CGF.Builder, Class);
5211 }
5212 else
Daniel Dunbar3c190812009-04-18 08:51:00 +00005213 Target = EmitSuperClassRef(CGF.Builder, Class);
Fariborz Jahanianf3a44012009-02-06 20:09:23 +00005214
5215 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
5216 // and ObjCTypes types.
5217 const llvm::Type *ClassTy =
5218 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
5219 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
5220 CGF.Builder.CreateStore(Target,
5221 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
5222
5223 return EmitMessageSend(CGF, ResultType, Sel,
5224 ObjCSuper, ObjCTypes.SuperPtrCTy,
5225 true, CallArgs);
5226}
Fariborz Jahanianebb82c62009-02-11 20:51:17 +00005227
5228llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CGBuilderTy &Builder,
5229 Selector Sel) {
5230 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
5231
5232 if (!Entry) {
5233 llvm::Constant *Casted =
5234 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
5235 ObjCTypes.SelectorPtrTy);
5236 Entry =
5237 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
5238 llvm::GlobalValue::InternalLinkage,
5239 Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
5240 &CGM.getModule());
5241 Entry->setSection("__DATA,__objc_selrefs,literal_pointers,no_dead_strip");
5242 UsedGlobals.push_back(Entry);
5243 }
5244
5245 return Builder.CreateLoad(Entry, false, "tmp");
5246}
Fariborz Jahanian5eefb432009-02-16 22:52:32 +00005247/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
5248/// objc_assign_ivar (id src, id *dst)
5249///
5250void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
5251 llvm::Value *src, llvm::Value *dst)
5252{
Fariborz Jahanianad51ca02009-03-23 19:10:40 +00005253 const llvm::Type * SrcTy = src->getType();
5254 if (!isa<llvm::PointerType>(SrcTy)) {
5255 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5256 assert(Size <= 8 && "does not support size > 8");
5257 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5258 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian664da982009-03-13 00:42:52 +00005259 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5260 }
Fariborz Jahanian5eefb432009-02-16 22:52:32 +00005261 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5262 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerf6ec7e42009-04-22 02:38:11 +00005263 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignIvarFn(),
Fariborz Jahanian5eefb432009-02-16 22:52:32 +00005264 src, dst, "assignivar");
5265 return;
5266}
5267
5268/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
5269/// objc_assign_strongCast (id src, id *dst)
5270///
5271void CGObjCNonFragileABIMac::EmitObjCStrongCastAssign(
5272 CodeGen::CodeGenFunction &CGF,
5273 llvm::Value *src, llvm::Value *dst)
5274{
Fariborz Jahanianad51ca02009-03-23 19:10:40 +00005275 const llvm::Type * SrcTy = src->getType();
5276 if (!isa<llvm::PointerType>(SrcTy)) {
5277 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5278 assert(Size <= 8 && "does not support size > 8");
5279 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5280 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian664da982009-03-13 00:42:52 +00005281 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5282 }
Fariborz Jahanian5eefb432009-02-16 22:52:32 +00005283 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5284 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerf6ec7e42009-04-22 02:38:11 +00005285 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignStrongCastFn(),
Fariborz Jahanian5eefb432009-02-16 22:52:32 +00005286 src, dst, "weakassign");
5287 return;
5288}
5289
5290/// EmitObjCWeakRead - Code gen for loading value of a __weak
5291/// object: objc_read_weak (id *src)
5292///
5293llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead(
5294 CodeGen::CodeGenFunction &CGF,
5295 llvm::Value *AddrWeakObj)
5296{
Eli Friedmanf8466232009-03-07 03:57:15 +00005297 const llvm::Type* DestTy =
5298 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahanian5eefb432009-02-16 22:52:32 +00005299 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Chris Lattnera7ecda42009-04-22 02:44:54 +00005300 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.getGcReadWeakFn(),
Fariborz Jahanian5eefb432009-02-16 22:52:32 +00005301 AddrWeakObj, "weakread");
Eli Friedmanf8466232009-03-07 03:57:15 +00005302 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian5eefb432009-02-16 22:52:32 +00005303 return read_weak;
5304}
5305
5306/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
5307/// objc_assign_weak (id src, id *dst)
5308///
5309void CGObjCNonFragileABIMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
5310 llvm::Value *src, llvm::Value *dst)
5311{
Fariborz Jahanianad51ca02009-03-23 19:10:40 +00005312 const llvm::Type * SrcTy = src->getType();
5313 if (!isa<llvm::PointerType>(SrcTy)) {
5314 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5315 assert(Size <= 8 && "does not support size > 8");
5316 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5317 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian664da982009-03-13 00:42:52 +00005318 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5319 }
Fariborz Jahanian5eefb432009-02-16 22:52:32 +00005320 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5321 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattner293c1d32009-04-17 22:12:36 +00005322 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
Fariborz Jahanian5eefb432009-02-16 22:52:32 +00005323 src, dst, "weakassign");
5324 return;
5325}
5326
5327/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
5328/// objc_assign_global (id src, id *dst)
5329///
5330void CGObjCNonFragileABIMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
5331 llvm::Value *src, llvm::Value *dst)
5332{
Fariborz Jahanianad51ca02009-03-23 19:10:40 +00005333 const llvm::Type * SrcTy = src->getType();
5334 if (!isa<llvm::PointerType>(SrcTy)) {
5335 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5336 assert(Size <= 8 && "does not support size > 8");
5337 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5338 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian664da982009-03-13 00:42:52 +00005339 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5340 }
Fariborz Jahanian5eefb432009-02-16 22:52:32 +00005341 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5342 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerf6ec7e42009-04-22 02:38:11 +00005343 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignGlobalFn(),
Fariborz Jahanian5eefb432009-02-16 22:52:32 +00005344 src, dst, "globalassign");
5345 return;
5346}
Fariborz Jahanianebb82c62009-02-11 20:51:17 +00005347
Daniel Dunbar75de89f2009-02-24 07:47:38 +00005348void
5349CGObjCNonFragileABIMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
5350 const Stmt &S) {
Daniel Dunbar75de89f2009-02-24 07:47:38 +00005351 bool isTry = isa<ObjCAtTryStmt>(S);
5352 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
5353 llvm::BasicBlock *PrevLandingPad = CGF.getInvokeDest();
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005354 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar75de89f2009-02-24 07:47:38 +00005355 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005356 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
Daniel Dunbar75de89f2009-02-24 07:47:38 +00005357 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
5358
5359 // For @synchronized, call objc_sync_enter(sync.expr). The
5360 // evaluation of the expression must occur before we enter the
5361 // @synchronized. We can safely avoid a temp here because jumps into
5362 // @synchronized are illegal & this will dominate uses.
5363 llvm::Value *SyncArg = 0;
5364 if (!isTry) {
5365 SyncArg =
5366 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
5367 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattner23e24652009-04-06 16:53:45 +00005368 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar75de89f2009-02-24 07:47:38 +00005369 }
5370
5371 // Push an EH context entry, used for handling rethrows and jumps
5372 // through finally.
5373 CGF.PushCleanupBlock(FinallyBlock);
5374
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005375 CGF.setInvokeDest(TryHandler);
Daniel Dunbar75de89f2009-02-24 07:47:38 +00005376
5377 CGF.EmitBlock(TryBlock);
5378 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
5379 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
5380 CGF.EmitBranchThroughCleanup(FinallyEnd);
5381
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005382 // Emit the exception handler.
5383
5384 CGF.EmitBlock(TryHandler);
5385
5386 llvm::Value *llvm_eh_exception =
5387 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_exception);
5388 llvm::Value *llvm_eh_selector_i64 =
5389 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector_i64);
5390 llvm::Value *llvm_eh_typeid_for_i64 =
5391 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for_i64);
5392 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5393 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(Exc->getType(), "_rethrow");
5394
5395 llvm::SmallVector<llvm::Value*, 8> SelectorArgs;
5396 SelectorArgs.push_back(Exc);
Chris Lattner23e24652009-04-06 16:53:45 +00005397 SelectorArgs.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005398
5399 // Construct the lists of (type, catch body) to handle.
Daniel Dunbar0098e7a2009-03-06 00:01:21 +00005400 llvm::SmallVector<std::pair<const ParmVarDecl*, const Stmt*>, 8> Handlers;
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005401 bool HasCatchAll = false;
5402 if (isTry) {
5403 if (const ObjCAtCatchStmt* CatchStmt =
5404 cast<ObjCAtTryStmt>(S).getCatchStmts()) {
5405 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbar0098e7a2009-03-06 00:01:21 +00005406 const ParmVarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
Steve Naroff0e8b96a2009-03-03 19:52:17 +00005407 Handlers.push_back(std::make_pair(CatchDecl, CatchStmt->getCatchBody()));
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005408
5409 // catch(...) always matches.
Steve Naroff0e8b96a2009-03-03 19:52:17 +00005410 if (!CatchDecl) {
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005411 // Use i8* null here to signal this is a catch all, not a cleanup.
5412 llvm::Value *Null = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
5413 SelectorArgs.push_back(Null);
5414 HasCatchAll = true;
5415 break;
5416 }
5417
Daniel Dunbar0098e7a2009-03-06 00:01:21 +00005418 if (CGF.getContext().isObjCIdType(CatchDecl->getType()) ||
5419 CatchDecl->getType()->isObjCQualifiedIdType()) {
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005420 llvm::Value *IDEHType =
5421 CGM.getModule().getGlobalVariable("OBJC_EHTYPE_id");
5422 if (!IDEHType)
5423 IDEHType =
5424 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5425 llvm::GlobalValue::ExternalLinkage,
5426 0, "OBJC_EHTYPE_id", &CGM.getModule());
5427 SelectorArgs.push_back(IDEHType);
5428 HasCatchAll = true;
5429 break;
5430 }
5431
5432 // All other types should be Objective-C interface pointer types.
Daniel Dunbar0098e7a2009-03-06 00:01:21 +00005433 const PointerType *PT = CatchDecl->getType()->getAsPointerType();
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005434 assert(PT && "Invalid @catch type.");
5435 const ObjCInterfaceType *IT =
5436 PT->getPointeeType()->getAsObjCInterfaceType();
5437 assert(IT && "Invalid @catch type.");
Daniel Dunbarc2129532009-04-08 04:21:03 +00005438 llvm::Value *EHType = GetInterfaceEHType(IT->getDecl(), false);
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005439 SelectorArgs.push_back(EHType);
5440 }
5441 }
5442 }
5443
5444 // We use a cleanup unless there was already a catch all.
5445 if (!HasCatchAll) {
5446 SelectorArgs.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
Daniel Dunbar0098e7a2009-03-06 00:01:21 +00005447 Handlers.push_back(std::make_pair((const ParmVarDecl*) 0, (const Stmt*) 0));
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005448 }
5449
5450 llvm::Value *Selector =
5451 CGF.Builder.CreateCall(llvm_eh_selector_i64,
5452 SelectorArgs.begin(), SelectorArgs.end(),
5453 "selector");
5454 for (unsigned i = 0, e = Handlers.size(); i != e; ++i) {
Daniel Dunbar0098e7a2009-03-06 00:01:21 +00005455 const ParmVarDecl *CatchParam = Handlers[i].first;
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005456 const Stmt *CatchBody = Handlers[i].second;
5457
5458 llvm::BasicBlock *Next = 0;
5459
5460 // The last handler always matches.
5461 if (i + 1 != e) {
5462 assert(CatchParam && "Only last handler can be a catch all.");
5463
5464 llvm::BasicBlock *Match = CGF.createBasicBlock("match");
5465 Next = CGF.createBasicBlock("catch.next");
5466 llvm::Value *Id =
5467 CGF.Builder.CreateCall(llvm_eh_typeid_for_i64,
5468 CGF.Builder.CreateBitCast(SelectorArgs[i+2],
5469 ObjCTypes.Int8PtrTy));
5470 CGF.Builder.CreateCondBr(CGF.Builder.CreateICmpEQ(Selector, Id),
5471 Match, Next);
5472
5473 CGF.EmitBlock(Match);
5474 }
5475
5476 if (CatchBody) {
5477 llvm::BasicBlock *MatchEnd = CGF.createBasicBlock("match.end");
5478 llvm::BasicBlock *MatchHandler = CGF.createBasicBlock("match.handler");
5479
5480 // Cleanups must call objc_end_catch.
5481 //
5482 // FIXME: It seems incorrect for objc_begin_catch to be inside
5483 // this context, but this matches gcc.
5484 CGF.PushCleanupBlock(MatchEnd);
5485 CGF.setInvokeDest(MatchHandler);
5486
5487 llvm::Value *ExcObject =
Chris Lattner93dca5b2009-04-22 02:15:23 +00005488 CGF.Builder.CreateCall(ObjCTypes.getObjCBeginCatchFn(), Exc);
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005489
5490 // Bind the catch parameter if it exists.
5491 if (CatchParam) {
Daniel Dunbar0098e7a2009-03-06 00:01:21 +00005492 ExcObject =
5493 CGF.Builder.CreateBitCast(ExcObject,
5494 CGF.ConvertType(CatchParam->getType()));
5495 // CatchParam is a ParmVarDecl because of the grammar
5496 // construction used to handle this, but for codegen purposes
5497 // we treat this as a local decl.
5498 CGF.EmitLocalBlockVarDecl(*CatchParam);
5499 CGF.Builder.CreateStore(ExcObject, CGF.GetAddrOfLocalVar(CatchParam));
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005500 }
5501
5502 CGF.ObjCEHValueStack.push_back(ExcObject);
5503 CGF.EmitStmt(CatchBody);
5504 CGF.ObjCEHValueStack.pop_back();
5505
5506 CGF.EmitBranchThroughCleanup(FinallyEnd);
5507
5508 CGF.EmitBlock(MatchHandler);
5509
5510 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5511 // We are required to emit this call to satisfy LLVM, even
5512 // though we don't use the result.
5513 llvm::SmallVector<llvm::Value*, 8> Args;
5514 Args.push_back(Exc);
Chris Lattner23e24652009-04-06 16:53:45 +00005515 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005516 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5517 0));
5518 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5519 CGF.Builder.CreateStore(Exc, RethrowPtr);
5520 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5521
5522 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5523
5524 CGF.EmitBlock(MatchEnd);
5525
5526 // Unfortunately, we also have to generate another EH frame here
5527 // in case this throws.
5528 llvm::BasicBlock *MatchEndHandler =
5529 CGF.createBasicBlock("match.end.handler");
5530 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
Chris Lattner93dca5b2009-04-22 02:15:23 +00005531 CGF.Builder.CreateInvoke(ObjCTypes.getObjCEndCatchFn(),
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005532 Cont, MatchEndHandler,
5533 Args.begin(), Args.begin());
5534
5535 CGF.EmitBlock(Cont);
5536 if (Info.SwitchBlock)
5537 CGF.EmitBlock(Info.SwitchBlock);
5538 if (Info.EndBlock)
5539 CGF.EmitBlock(Info.EndBlock);
5540
5541 CGF.EmitBlock(MatchEndHandler);
5542 Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5543 // We are required to emit this call to satisfy LLVM, even
5544 // though we don't use the result.
5545 Args.clear();
5546 Args.push_back(Exc);
Chris Lattner23e24652009-04-06 16:53:45 +00005547 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005548 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5549 0));
5550 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5551 CGF.Builder.CreateStore(Exc, RethrowPtr);
5552 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5553
5554 if (Next)
5555 CGF.EmitBlock(Next);
5556 } else {
5557 assert(!Next && "catchup should be last handler.");
5558
5559 CGF.Builder.CreateStore(Exc, RethrowPtr);
5560 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5561 }
5562 }
5563
Daniel Dunbar75de89f2009-02-24 07:47:38 +00005564 // Pop the cleanup entry, the @finally is outside this cleanup
5565 // scope.
5566 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5567 CGF.setInvokeDest(PrevLandingPad);
5568
5569 CGF.EmitBlock(FinallyBlock);
5570
5571 if (isTry) {
5572 if (const ObjCAtFinallyStmt* FinallyStmt =
5573 cast<ObjCAtTryStmt>(S).getFinallyStmt())
5574 CGF.EmitStmt(FinallyStmt->getFinallyBody());
5575 } else {
5576 // Emit 'objc_sync_exit(expr)' as finally's sole statement for
5577 // @synchronized.
Chris Lattnerf6ec7e42009-04-22 02:38:11 +00005578 CGF.Builder.CreateCall(ObjCTypes.getSyncExitFn(), SyncArg);
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005579 }
Daniel Dunbar75de89f2009-02-24 07:47:38 +00005580
5581 if (Info.SwitchBlock)
5582 CGF.EmitBlock(Info.SwitchBlock);
5583 if (Info.EndBlock)
5584 CGF.EmitBlock(Info.EndBlock);
5585
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005586 // Branch around the rethrow code.
Daniel Dunbar75de89f2009-02-24 07:47:38 +00005587 CGF.EmitBranch(FinallyEnd);
5588
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005589 CGF.EmitBlock(FinallyRethrow);
Chris Lattner93dca5b2009-04-22 02:15:23 +00005590 CGF.Builder.CreateCall(ObjCTypes.getUnwindResumeOrRethrowFn(),
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005591 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbar75de89f2009-02-24 07:47:38 +00005592 CGF.Builder.CreateUnreachable();
5593
5594 CGF.EmitBlock(FinallyEnd);
5595}
5596
Anders Carlsson1cf75362009-02-16 22:59:18 +00005597/// EmitThrowStmt - Generate code for a throw statement.
5598void CGObjCNonFragileABIMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
5599 const ObjCAtThrowStmt &S) {
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005600 llvm::Value *Exception;
Anders Carlsson1cf75362009-02-16 22:59:18 +00005601 if (const Expr *ThrowExpr = S.getThrowExpr()) {
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005602 Exception = CGF.EmitScalarExpr(ThrowExpr);
Anders Carlsson1cf75362009-02-16 22:59:18 +00005603 } else {
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005604 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
5605 "Unexpected rethrow outside @catch block.");
5606 Exception = CGF.ObjCEHValueStack.back();
Anders Carlsson1cf75362009-02-16 22:59:18 +00005607 }
5608
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005609 llvm::Value *ExceptionAsObject =
5610 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
5611 llvm::BasicBlock *InvokeDest = CGF.getInvokeDest();
5612 if (InvokeDest) {
5613 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
Chris Lattnerf6ec7e42009-04-22 02:38:11 +00005614 CGF.Builder.CreateInvoke(ObjCTypes.getExceptionThrowFn(),
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005615 Cont, InvokeDest,
5616 &ExceptionAsObject, &ExceptionAsObject + 1);
5617 CGF.EmitBlock(Cont);
5618 } else
Chris Lattnerf6ec7e42009-04-22 02:38:11 +00005619 CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(), ExceptionAsObject);
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005620 CGF.Builder.CreateUnreachable();
5621
Anders Carlsson1cf75362009-02-16 22:59:18 +00005622 // Clear the insertion point to indicate we are in unreachable code.
5623 CGF.Builder.ClearInsertionPoint();
5624}
Daniel Dunbar9c285e72009-03-01 04:46:24 +00005625
5626llvm::Value *
Daniel Dunbarc2129532009-04-08 04:21:03 +00005627CGObjCNonFragileABIMac::GetInterfaceEHType(const ObjCInterfaceDecl *ID,
5628 bool ForDefinition) {
Daniel Dunbar9c285e72009-03-01 04:46:24 +00005629 llvm::GlobalVariable * &Entry = EHTypeReferences[ID->getIdentifier()];
Daniel Dunbar9c285e72009-03-01 04:46:24 +00005630
Daniel Dunbarc2129532009-04-08 04:21:03 +00005631 // If we don't need a definition, return the entry if found or check
5632 // if we use an external reference.
5633 if (!ForDefinition) {
5634 if (Entry)
5635 return Entry;
Daniel Dunbarafac9be2009-04-07 06:43:45 +00005636
Daniel Dunbarc2129532009-04-08 04:21:03 +00005637 // If this type (or a super class) has the __objc_exception__
5638 // attribute, emit an external reference.
5639 if (hasObjCExceptionAttribute(ID))
5640 return Entry =
5641 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5642 llvm::GlobalValue::ExternalLinkage,
5643 0,
5644 (std::string("OBJC_EHTYPE_$_") +
5645 ID->getIdentifier()->getName()),
5646 &CGM.getModule());
5647 }
5648
5649 // Otherwise we need to either make a new entry or fill in the
5650 // initializer.
5651 assert((!Entry || !Entry->hasInitializer()) && "Duplicate EHType definition");
Daniel Dunbara2d275d2009-04-07 05:48:37 +00005652 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbar9c285e72009-03-01 04:46:24 +00005653 std::string VTableName = "objc_ehtype_vtable";
5654 llvm::GlobalVariable *VTableGV =
5655 CGM.getModule().getGlobalVariable(VTableName);
5656 if (!VTableGV)
5657 VTableGV = new llvm::GlobalVariable(ObjCTypes.Int8PtrTy, false,
5658 llvm::GlobalValue::ExternalLinkage,
5659 0, VTableName, &CGM.getModule());
5660
5661 llvm::Value *VTableIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, 2);
5662
5663 std::vector<llvm::Constant*> Values(3);
5664 Values[0] = llvm::ConstantExpr::getGetElementPtr(VTableGV, &VTableIdx, 1);
5665 Values[1] = GetClassName(ID->getIdentifier());
Fariborz Jahanianab438842009-04-14 18:41:56 +00005666 Values[2] = GetClassGlobal(ClassName);
Daniel Dunbar9c285e72009-03-01 04:46:24 +00005667 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.EHTypeTy, Values);
5668
Daniel Dunbarc2129532009-04-08 04:21:03 +00005669 if (Entry) {
5670 Entry->setInitializer(Init);
5671 } else {
5672 Entry = new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5673 llvm::GlobalValue::WeakAnyLinkage,
5674 Init,
5675 (std::string("OBJC_EHTYPE_$_") +
5676 ID->getIdentifier()->getName()),
5677 &CGM.getModule());
5678 }
5679
Daniel Dunbar8394fda2009-04-14 06:00:08 +00005680 if (CGM.getLangOptions().getVisibilityMode() == LangOptions::Hidden)
Daniel Dunbara2d275d2009-04-07 05:48:37 +00005681 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbarc2129532009-04-08 04:21:03 +00005682 Entry->setAlignment(8);
5683
5684 if (ForDefinition) {
5685 Entry->setSection("__DATA,__objc_const");
5686 Entry->setLinkage(llvm::GlobalValue::ExternalLinkage);
5687 } else {
5688 Entry->setSection("__DATA,__datacoal_nt,coalesced");
5689 }
Daniel Dunbar9c285e72009-03-01 04:46:24 +00005690
5691 return Entry;
5692}
Anders Carlsson1cf75362009-02-16 22:59:18 +00005693
Daniel Dunbardaf4ad42008-08-12 00:12:39 +00005694/* *** */
5695
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00005696CodeGen::CGObjCRuntime *
5697CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00005698 return new CGObjCMac(CGM);
5699}
Fariborz Jahanian48543f52009-01-21 22:04:16 +00005700
5701CodeGen::CGObjCRuntime *
Fariborz Jahaniand0374812009-01-22 23:02:58 +00005702CodeGen::CreateMacNonFragileABIObjCRuntime(CodeGen::CodeGenModule &CGM) {
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00005703 return new CGObjCNonFragileABIMac(CGM);
Fariborz Jahanian48543f52009-01-21 22:04:16 +00005704}